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
9,400
hyperhq/runv
hypervisor/fanout.go
CreateFanout
func CreateFanout(upstream chan *types.VmResponse, size int, block bool) *Fanout { fo := &Fanout{ size: size, upstream: upstream, clients: []chan *types.VmResponse{}, closeSignal: make(chan *types.VmResponse, 1), running: !block, lock: sync.RWMutex{}, } if !block { fo.start() } return fo }
go
func CreateFanout(upstream chan *types.VmResponse, size int, block bool) *Fanout { fo := &Fanout{ size: size, upstream: upstream, clients: []chan *types.VmResponse{}, closeSignal: make(chan *types.VmResponse, 1), running: !block, lock: sync.RWMutex{}, } if !block { fo.start() } return fo }
[ "func", "CreateFanout", "(", "upstream", "chan", "*", "types", ".", "VmResponse", ",", "size", "int", ",", "block", "bool", ")", "*", "Fanout", "{", "fo", ":=", "&", "Fanout", "{", "size", ":", "size", ",", "upstream", ":", "upstream", ",", "clients", ":", "[", "]", "chan", "*", "types", ".", "VmResponse", "{", "}", ",", "closeSignal", ":", "make", "(", "chan", "*", "types", ".", "VmResponse", ",", "1", ")", ",", "running", ":", "!", "block", ",", "lock", ":", "sync", ".", "RWMutex", "{", "}", ",", "}", "\n\n", "if", "!", "block", "{", "fo", ".", "start", "(", ")", "\n", "}", "\n\n", "return", "fo", "\n", "}" ]
// CreateFanout create a new fanout, and if it is non-blocked, it will start // the fanout goroutine at once, otherwise it will start the goroutine when it // get the first client
[ "CreateFanout", "create", "a", "new", "fanout", "and", "if", "it", "is", "non", "-", "blocked", "it", "will", "start", "the", "fanout", "goroutine", "at", "once", "otherwise", "it", "will", "start", "the", "goroutine", "when", "it", "get", "the", "first", "client" ]
10eb6877d5df825f4438f69864a9256f9694741d
https://github.com/hyperhq/runv/blob/10eb6877d5df825f4438f69864a9256f9694741d/hypervisor/fanout.go#L22-L37
9,401
hyperhq/runv
cli/spec.go
loadProcessConfig
func loadProcessConfig(path string) (*specs.Process, error) { f, err := os.Open(path) if err != nil { if os.IsNotExist(err) { return nil, fmt.Errorf("JSON configuration file for %s not found", path) } return nil, err } defer f.Close() var s *specs.Process if err := json.NewDecoder(f).Decode(&s); err != nil { return nil, err } return s, nil }
go
func loadProcessConfig(path string) (*specs.Process, error) { f, err := os.Open(path) if err != nil { if os.IsNotExist(err) { return nil, fmt.Errorf("JSON configuration file for %s not found", path) } return nil, err } defer f.Close() var s *specs.Process if err := json.NewDecoder(f).Decode(&s); err != nil { return nil, err } return s, nil }
[ "func", "loadProcessConfig", "(", "path", "string", ")", "(", "*", "specs", ".", "Process", ",", "error", ")", "{", "f", ",", "err", ":=", "os", ".", "Open", "(", "path", ")", "\n", "if", "err", "!=", "nil", "{", "if", "os", ".", "IsNotExist", "(", "err", ")", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "path", ")", "\n", "}", "\n", "return", "nil", ",", "err", "\n", "}", "\n", "defer", "f", ".", "Close", "(", ")", "\n", "var", "s", "*", "specs", ".", "Process", "\n", "if", "err", ":=", "json", ".", "NewDecoder", "(", "f", ")", ".", "Decode", "(", "&", "s", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "return", "s", ",", "nil", "\n", "}" ]
// loadProcessConfig loads the process configuration from the provided path.
[ "loadProcessConfig", "loads", "the", "process", "configuration", "from", "the", "provided", "path", "." ]
10eb6877d5df825f4438f69864a9256f9694741d
https://github.com/hyperhq/runv/blob/10eb6877d5df825f4438f69864a9256f9694741d/cli/spec.go#L114-L128
9,402
hyperhq/runv
cli/filesystem.go
preCreateDirs
func preCreateDirs(rootfs string) error { dirs := []string{ "proc", "sys", "dev", "lib/modules", } for _, dir := range dirs { err := createIfNotExists(filepath.Join(rootfs, dir), true) if err != nil { return err } } return nil }
go
func preCreateDirs(rootfs string) error { dirs := []string{ "proc", "sys", "dev", "lib/modules", } for _, dir := range dirs { err := createIfNotExists(filepath.Join(rootfs, dir), true) if err != nil { return err } } return nil }
[ "func", "preCreateDirs", "(", "rootfs", "string", ")", "error", "{", "dirs", ":=", "[", "]", "string", "{", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ",", "}", "\n", "for", "_", ",", "dir", ":=", "range", "dirs", "{", "err", ":=", "createIfNotExists", "(", "filepath", ".", "Join", "(", "rootfs", ",", "dir", ")", ",", "true", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// preCreateDirs creates necessary dirs for hyperstart
[ "preCreateDirs", "creates", "necessary", "dirs", "for", "hyperstart" ]
10eb6877d5df825f4438f69864a9256f9694741d
https://github.com/hyperhq/runv/blob/10eb6877d5df825f4438f69864a9256f9694741d/cli/filesystem.go#L104-L118
9,403
hyperhq/runv
hypervisor/network.go
allInterfaces
func (nc *NetworkContext) allInterfaces() (nics []*InterfaceCreated) { nc.slotLock.Lock() defer nc.slotLock.Unlock() for _, v := range nc.eth { if v != nil { nics = append(nics, v) } } return }
go
func (nc *NetworkContext) allInterfaces() (nics []*InterfaceCreated) { nc.slotLock.Lock() defer nc.slotLock.Unlock() for _, v := range nc.eth { if v != nil { nics = append(nics, v) } } return }
[ "func", "(", "nc", "*", "NetworkContext", ")", "allInterfaces", "(", ")", "(", "nics", "[", "]", "*", "InterfaceCreated", ")", "{", "nc", ".", "slotLock", ".", "Lock", "(", ")", "\n", "defer", "nc", ".", "slotLock", ".", "Unlock", "(", ")", "\n\n", "for", "_", ",", "v", ":=", "range", "nc", ".", "eth", "{", "if", "v", "!=", "nil", "{", "nics", "=", "append", "(", "nics", ",", "v", ")", "\n", "}", "\n", "}", "\n", "return", "\n", "}" ]
// allInterfaces return all the network interfaces except loop
[ "allInterfaces", "return", "all", "the", "network", "interfaces", "except", "loop" ]
10eb6877d5df825f4438f69864a9256f9694741d
https://github.com/hyperhq/runv/blob/10eb6877d5df825f4438f69864a9256f9694741d/hypervisor/network.go#L223-L233
9,404
hyperhq/runv
cli/sandbox.go
lockSandbox
func lockSandbox(sandboxPath string) (*os.File, error) { lockFilePath := filepath.Join(sandboxPath, "sandbox.lock") lockFile, err := os.OpenFile(lockFilePath, os.O_RDWR|os.O_CREATE, 0755) if err != nil { return nil, err } err = syscall.Flock(int(lockFile.Fd()), syscall.LOCK_EX) if err != nil { lockFile.Close() return nil, err } return lockFile, nil }
go
func lockSandbox(sandboxPath string) (*os.File, error) { lockFilePath := filepath.Join(sandboxPath, "sandbox.lock") lockFile, err := os.OpenFile(lockFilePath, os.O_RDWR|os.O_CREATE, 0755) if err != nil { return nil, err } err = syscall.Flock(int(lockFile.Fd()), syscall.LOCK_EX) if err != nil { lockFile.Close() return nil, err } return lockFile, nil }
[ "func", "lockSandbox", "(", "sandboxPath", "string", ")", "(", "*", "os", ".", "File", ",", "error", ")", "{", "lockFilePath", ":=", "filepath", ".", "Join", "(", "sandboxPath", ",", "\"", "\"", ")", "\n\n", "lockFile", ",", "err", ":=", "os", ".", "OpenFile", "(", "lockFilePath", ",", "os", ".", "O_RDWR", "|", "os", ".", "O_CREATE", ",", "0755", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "err", "=", "syscall", ".", "Flock", "(", "int", "(", "lockFile", ".", "Fd", "(", ")", ")", ",", "syscall", ".", "LOCK_EX", ")", "\n", "if", "err", "!=", "nil", "{", "lockFile", ".", "Close", "(", ")", "\n", "return", "nil", ",", "err", "\n", "}", "\n\n", "return", "lockFile", ",", "nil", "\n", "}" ]
// lock locks the sandbox to prevent it from being accessed by other processes.
[ "lock", "locks", "the", "sandbox", "to", "prevent", "it", "from", "being", "accessed", "by", "other", "processes", "." ]
10eb6877d5df825f4438f69864a9256f9694741d
https://github.com/hyperhq/runv/blob/10eb6877d5df825f4438f69864a9256f9694741d/cli/sandbox.go#L257-L272
9,405
hyperhq/runv
cli/sandbox.go
unlockSandbox
func unlockSandbox(lockFile *os.File) error { if lockFile == nil { return fmt.Errorf("lockFile cannot be empty") } err := syscall.Flock(int(lockFile.Fd()), syscall.LOCK_UN) if err != nil { return err } lockFile.Close() return nil }
go
func unlockSandbox(lockFile *os.File) error { if lockFile == nil { return fmt.Errorf("lockFile cannot be empty") } err := syscall.Flock(int(lockFile.Fd()), syscall.LOCK_UN) if err != nil { return err } lockFile.Close() return nil }
[ "func", "unlockSandbox", "(", "lockFile", "*", "os", ".", "File", ")", "error", "{", "if", "lockFile", "==", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n\n", "err", ":=", "syscall", ".", "Flock", "(", "int", "(", "lockFile", ".", "Fd", "(", ")", ")", ",", "syscall", ".", "LOCK_UN", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "lockFile", ".", "Close", "(", ")", "\n\n", "return", "nil", "\n", "}" ]
// unlock unlocks the sandbox to allow it being accessed by other processes.
[ "unlock", "unlocks", "the", "sandbox", "to", "allow", "it", "being", "accessed", "by", "other", "processes", "." ]
10eb6877d5df825f4438f69864a9256f9694741d
https://github.com/hyperhq/runv/blob/10eb6877d5df825f4438f69864a9256f9694741d/cli/sandbox.go#L275-L288
9,406
hyperhq/runv
hypervisor/context.go
SendVmEvent
func (ctx *VmContext) SendVmEvent(ev VmEvent) error { ctx.lock.RLock() defer ctx.lock.RUnlock() if ctx.handler == nil { return fmt.Errorf("VmContext(%s): event handler already shutdown.", ctx.Id) } ctx.Hub <- ev return nil }
go
func (ctx *VmContext) SendVmEvent(ev VmEvent) error { ctx.lock.RLock() defer ctx.lock.RUnlock() if ctx.handler == nil { return fmt.Errorf("VmContext(%s): event handler already shutdown.", ctx.Id) } ctx.Hub <- ev return nil }
[ "func", "(", "ctx", "*", "VmContext", ")", "SendVmEvent", "(", "ev", "VmEvent", ")", "error", "{", "ctx", ".", "lock", ".", "RLock", "(", ")", "\n", "defer", "ctx", ".", "lock", ".", "RUnlock", "(", ")", "\n\n", "if", "ctx", ".", "handler", "==", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "ctx", ".", "Id", ")", "\n", "}", "\n\n", "ctx", ".", "Hub", "<-", "ev", "\n\n", "return", "nil", "\n", "}" ]
// SendVmEvent enqueues a VmEvent onto the context. Returns an error if there is // no handler associated with the context. VmEvent handling happens in a // separate goroutine, so this is thread-safe and asynchronous.
[ "SendVmEvent", "enqueues", "a", "VmEvent", "onto", "the", "context", ".", "Returns", "an", "error", "if", "there", "is", "no", "handler", "associated", "with", "the", "context", ".", "VmEvent", "handling", "happens", "in", "a", "separate", "goroutine", "so", "this", "is", "thread", "-", "safe", "and", "asynchronous", "." ]
10eb6877d5df825f4438f69864a9256f9694741d
https://github.com/hyperhq/runv/blob/10eb6877d5df825f4438f69864a9256f9694741d/hypervisor/context.go#L145-L156
9,407
hyperhq/runv
lib/telnet/conn.go
ReadByte
func (c *Conn) ReadByte() (b byte, err error) { retry := true for retry && err == nil { b, retry, err = c.tryReadByte() } return }
go
func (c *Conn) ReadByte() (b byte, err error) { retry := true for retry && err == nil { b, retry, err = c.tryReadByte() } return }
[ "func", "(", "c", "*", "Conn", ")", "ReadByte", "(", ")", "(", "b", "byte", ",", "err", "error", ")", "{", "retry", ":=", "true", "\n", "for", "retry", "&&", "err", "==", "nil", "{", "b", ",", "retry", ",", "err", "=", "c", ".", "tryReadByte", "(", ")", "\n", "}", "\n", "return", "\n", "}" ]
// ReadByte works like bufio.ReadByte
[ "ReadByte", "works", "like", "bufio", ".", "ReadByte" ]
10eb6877d5df825f4438f69864a9256f9694741d
https://github.com/hyperhq/runv/blob/10eb6877d5df825f4438f69864a9256f9694741d/lib/telnet/conn.go#L207-L213
9,408
hyperhq/runv
lib/telnet/conn.go
ReadRune
func (c *Conn) ReadRune() (r rune, size int, err error) { loop: r, size, err = c.r.ReadRune() if err != nil { return } if r != unicode.ReplacementChar || size != 1 { // Properly readed rune return } // Bad rune err = c.r.UnreadRune() if err != nil { return } // Read telnet command or escaped IAC _, retry, err := c.tryReadByte() if err != nil { return } if retry { // This bad rune was a beginning of telnet command. Try read next rune. goto loop } // Return escaped IAC as unicode.ReplacementChar return }
go
func (c *Conn) ReadRune() (r rune, size int, err error) { loop: r, size, err = c.r.ReadRune() if err != nil { return } if r != unicode.ReplacementChar || size != 1 { // Properly readed rune return } // Bad rune err = c.r.UnreadRune() if err != nil { return } // Read telnet command or escaped IAC _, retry, err := c.tryReadByte() if err != nil { return } if retry { // This bad rune was a beginning of telnet command. Try read next rune. goto loop } // Return escaped IAC as unicode.ReplacementChar return }
[ "func", "(", "c", "*", "Conn", ")", "ReadRune", "(", ")", "(", "r", "rune", ",", "size", "int", ",", "err", "error", ")", "{", "loop", ":", "r", ",", "size", ",", "err", "=", "c", ".", "r", ".", "ReadRune", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\n", "}", "\n", "if", "r", "!=", "unicode", ".", "ReplacementChar", "||", "size", "!=", "1", "{", "// Properly readed rune", "return", "\n", "}", "\n", "// Bad rune", "err", "=", "c", ".", "r", ".", "UnreadRune", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\n", "}", "\n", "// Read telnet command or escaped IAC", "_", ",", "retry", ",", "err", ":=", "c", ".", "tryReadByte", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\n", "}", "\n", "if", "retry", "{", "// This bad rune was a beginning of telnet command. Try read next rune.", "goto", "loop", "\n", "}", "\n", "// Return escaped IAC as unicode.ReplacementChar", "return", "\n", "}" ]
// ReadRune works like bufio.ReadRune
[ "ReadRune", "works", "like", "bufio", ".", "ReadRune" ]
10eb6877d5df825f4438f69864a9256f9694741d
https://github.com/hyperhq/runv/blob/10eb6877d5df825f4438f69864a9256f9694741d/lib/telnet/conn.go#L216-L242
9,409
hyperhq/runv
lib/telnet/conn.go
Read
func (c *Conn) Read(buf []byte) (int, error) { var n int for n < len(buf) { b, err := c.ReadByte() if err != nil { return n, err } //log.Printf("char: %d %q", b, b) buf[n] = b n++ if c.r.Buffered() == 0 { // Try don't block if can return some data break } } return n, nil }
go
func (c *Conn) Read(buf []byte) (int, error) { var n int for n < len(buf) { b, err := c.ReadByte() if err != nil { return n, err } //log.Printf("char: %d %q", b, b) buf[n] = b n++ if c.r.Buffered() == 0 { // Try don't block if can return some data break } } return n, nil }
[ "func", "(", "c", "*", "Conn", ")", "Read", "(", "buf", "[", "]", "byte", ")", "(", "int", ",", "error", ")", "{", "var", "n", "int", "\n", "for", "n", "<", "len", "(", "buf", ")", "{", "b", ",", "err", ":=", "c", ".", "ReadByte", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "n", ",", "err", "\n", "}", "\n", "//log.Printf(\"char: %d %q\", b, b)", "buf", "[", "n", "]", "=", "b", "\n", "n", "++", "\n", "if", "c", ".", "r", ".", "Buffered", "(", ")", "==", "0", "{", "// Try don't block if can return some data", "break", "\n", "}", "\n", "}", "\n", "return", "n", ",", "nil", "\n", "}" ]
// Read is for implement an io.Reader interface
[ "Read", "is", "for", "implement", "an", "io", ".", "Reader", "interface" ]
10eb6877d5df825f4438f69864a9256f9694741d
https://github.com/hyperhq/runv/blob/10eb6877d5df825f4438f69864a9256f9694741d/lib/telnet/conn.go#L245-L261
9,410
hyperhq/runv
lib/telnet/conn.go
ReadBytes
func (c *Conn) ReadBytes(delim byte) ([]byte, error) { var line []byte for { b, err := c.ReadByte() if err != nil { return nil, err } line = append(line, b) if b == delim { break } } return line, nil }
go
func (c *Conn) ReadBytes(delim byte) ([]byte, error) { var line []byte for { b, err := c.ReadByte() if err != nil { return nil, err } line = append(line, b) if b == delim { break } } return line, nil }
[ "func", "(", "c", "*", "Conn", ")", "ReadBytes", "(", "delim", "byte", ")", "(", "[", "]", "byte", ",", "error", ")", "{", "var", "line", "[", "]", "byte", "\n", "for", "{", "b", ",", "err", ":=", "c", ".", "ReadByte", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "line", "=", "append", "(", "line", ",", "b", ")", "\n", "if", "b", "==", "delim", "{", "break", "\n", "}", "\n", "}", "\n", "return", "line", ",", "nil", "\n", "}" ]
// ReadBytes works like bufio.ReadBytes
[ "ReadBytes", "works", "like", "bufio", ".", "ReadBytes" ]
10eb6877d5df825f4438f69864a9256f9694741d
https://github.com/hyperhq/runv/blob/10eb6877d5df825f4438f69864a9256f9694741d/lib/telnet/conn.go#L264-L277
9,411
hyperhq/runv
lib/telnet/conn.go
SkipBytes
func (c *Conn) SkipBytes(delim byte) error { for { b, err := c.ReadByte() if err != nil { return err } if b == delim { break } } return nil }
go
func (c *Conn) SkipBytes(delim byte) error { for { b, err := c.ReadByte() if err != nil { return err } if b == delim { break } } return nil }
[ "func", "(", "c", "*", "Conn", ")", "SkipBytes", "(", "delim", "byte", ")", "error", "{", "for", "{", "b", ",", "err", ":=", "c", ".", "ReadByte", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "if", "b", "==", "delim", "{", "break", "\n", "}", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// SkipBytes works like ReadBytes but skips all read data.
[ "SkipBytes", "works", "like", "ReadBytes", "but", "skips", "all", "read", "data", "." ]
10eb6877d5df825f4438f69864a9256f9694741d
https://github.com/hyperhq/runv/blob/10eb6877d5df825f4438f69864a9256f9694741d/lib/telnet/conn.go#L280-L291
9,412
hyperhq/runv
lib/telnet/conn.go
ReadString
func (c *Conn) ReadString(delim byte) (string, error) { bytes, err := c.ReadBytes(delim) return string(bytes), err }
go
func (c *Conn) ReadString(delim byte) (string, error) { bytes, err := c.ReadBytes(delim) return string(bytes), err }
[ "func", "(", "c", "*", "Conn", ")", "ReadString", "(", "delim", "byte", ")", "(", "string", ",", "error", ")", "{", "bytes", ",", "err", ":=", "c", ".", "ReadBytes", "(", "delim", ")", "\n", "return", "string", "(", "bytes", ")", ",", "err", "\n", "}" ]
// ReadString works like bufio.ReadString
[ "ReadString", "works", "like", "bufio", ".", "ReadString" ]
10eb6877d5df825f4438f69864a9256f9694741d
https://github.com/hyperhq/runv/blob/10eb6877d5df825f4438f69864a9256f9694741d/lib/telnet/conn.go#L294-L297
9,413
hyperhq/runv
lib/telnet/conn.go
ReadUntilIndex
func (c *Conn) ReadUntilIndex(delims ...string) ([]byte, int, error) { return c.readUntil(true, delims...) }
go
func (c *Conn) ReadUntilIndex(delims ...string) ([]byte, int, error) { return c.readUntil(true, delims...) }
[ "func", "(", "c", "*", "Conn", ")", "ReadUntilIndex", "(", "delims", "...", "string", ")", "(", "[", "]", "byte", ",", "int", ",", "error", ")", "{", "return", "c", ".", "readUntil", "(", "true", ",", "delims", "...", ")", "\n", "}" ]
// ReadUntilIndex reads from connection until one of delimiters occurs. Returns // read data and an index of delimiter or error.
[ "ReadUntilIndex", "reads", "from", "connection", "until", "one", "of", "delimiters", "occurs", ".", "Returns", "read", "data", "and", "an", "index", "of", "delimiter", "or", "error", "." ]
10eb6877d5df825f4438f69864a9256f9694741d
https://github.com/hyperhq/runv/blob/10eb6877d5df825f4438f69864a9256f9694741d/lib/telnet/conn.go#L334-L336
9,414
hyperhq/runv
lib/telnet/conn.go
ReadUntil
func (c *Conn) ReadUntil(delims ...string) ([]byte, error) { d, _, err := c.readUntil(true, delims...) return d, err }
go
func (c *Conn) ReadUntil(delims ...string) ([]byte, error) { d, _, err := c.readUntil(true, delims...) return d, err }
[ "func", "(", "c", "*", "Conn", ")", "ReadUntil", "(", "delims", "...", "string", ")", "(", "[", "]", "byte", ",", "error", ")", "{", "d", ",", "_", ",", "err", ":=", "c", ".", "readUntil", "(", "true", ",", "delims", "...", ")", "\n", "return", "d", ",", "err", "\n", "}" ]
// ReadUntil works like ReadUntilIndex but don't return a delimiter index.
[ "ReadUntil", "works", "like", "ReadUntilIndex", "but", "don", "t", "return", "a", "delimiter", "index", "." ]
10eb6877d5df825f4438f69864a9256f9694741d
https://github.com/hyperhq/runv/blob/10eb6877d5df825f4438f69864a9256f9694741d/lib/telnet/conn.go#L339-L342
9,415
hyperhq/runv
lib/telnet/conn.go
SkipUntilIndex
func (c *Conn) SkipUntilIndex(delims ...string) (int, error) { _, i, err := c.readUntil(false, delims...) return i, err }
go
func (c *Conn) SkipUntilIndex(delims ...string) (int, error) { _, i, err := c.readUntil(false, delims...) return i, err }
[ "func", "(", "c", "*", "Conn", ")", "SkipUntilIndex", "(", "delims", "...", "string", ")", "(", "int", ",", "error", ")", "{", "_", ",", "i", ",", "err", ":=", "c", ".", "readUntil", "(", "false", ",", "delims", "...", ")", "\n", "return", "i", ",", "err", "\n", "}" ]
// SkipUntilIndex works like ReadUntilIndex but skips all read data.
[ "SkipUntilIndex", "works", "like", "ReadUntilIndex", "but", "skips", "all", "read", "data", "." ]
10eb6877d5df825f4438f69864a9256f9694741d
https://github.com/hyperhq/runv/blob/10eb6877d5df825f4438f69864a9256f9694741d/lib/telnet/conn.go#L345-L348
9,416
hyperhq/runv
lib/telnet/conn.go
SkipUntil
func (c *Conn) SkipUntil(delims ...string) error { _, _, err := c.readUntil(false, delims...) return err }
go
func (c *Conn) SkipUntil(delims ...string) error { _, _, err := c.readUntil(false, delims...) return err }
[ "func", "(", "c", "*", "Conn", ")", "SkipUntil", "(", "delims", "...", "string", ")", "error", "{", "_", ",", "_", ",", "err", ":=", "c", ".", "readUntil", "(", "false", ",", "delims", "...", ")", "\n", "return", "err", "\n", "}" ]
// SkipUntil works like ReadUntil but skips all read data.
[ "SkipUntil", "works", "like", "ReadUntil", "but", "skips", "all", "read", "data", "." ]
10eb6877d5df825f4438f69864a9256f9694741d
https://github.com/hyperhq/runv/blob/10eb6877d5df825f4438f69864a9256f9694741d/lib/telnet/conn.go#L351-L354
9,417
hyperhq/runv
lib/telnet/conn.go
Write
func (c *Conn) Write(buf []byte) (int, error) { search := "\xff" if c.unixWriteMode { search = "\xff\n" } var ( n int err error ) for len(buf) > 0 { var k int i := bytes.IndexAny(buf, search) if i == -1 { k, err = c.Conn.Write(buf) n += k break } k, err = c.Conn.Write(buf[:i]) n += k if err != nil { break } switch buf[i] { case LF: k, err = c.Conn.Write([]byte{CR, LF}) case cmdIAC: k, err = c.Conn.Write([]byte{cmdIAC, cmdIAC}) } n += k if err != nil { break } buf = buf[i+1:] } return n, err }
go
func (c *Conn) Write(buf []byte) (int, error) { search := "\xff" if c.unixWriteMode { search = "\xff\n" } var ( n int err error ) for len(buf) > 0 { var k int i := bytes.IndexAny(buf, search) if i == -1 { k, err = c.Conn.Write(buf) n += k break } k, err = c.Conn.Write(buf[:i]) n += k if err != nil { break } switch buf[i] { case LF: k, err = c.Conn.Write([]byte{CR, LF}) case cmdIAC: k, err = c.Conn.Write([]byte{cmdIAC, cmdIAC}) } n += k if err != nil { break } buf = buf[i+1:] } return n, err }
[ "func", "(", "c", "*", "Conn", ")", "Write", "(", "buf", "[", "]", "byte", ")", "(", "int", ",", "error", ")", "{", "search", ":=", "\"", "\\xff", "\"", "\n", "if", "c", ".", "unixWriteMode", "{", "search", "=", "\"", "\\xff", "\\n", "\"", "\n", "}", "\n", "var", "(", "n", "int", "\n", "err", "error", "\n", ")", "\n", "for", "len", "(", "buf", ")", ">", "0", "{", "var", "k", "int", "\n", "i", ":=", "bytes", ".", "IndexAny", "(", "buf", ",", "search", ")", "\n", "if", "i", "==", "-", "1", "{", "k", ",", "err", "=", "c", ".", "Conn", ".", "Write", "(", "buf", ")", "\n", "n", "+=", "k", "\n", "break", "\n", "}", "\n", "k", ",", "err", "=", "c", ".", "Conn", ".", "Write", "(", "buf", "[", ":", "i", "]", ")", "\n", "n", "+=", "k", "\n", "if", "err", "!=", "nil", "{", "break", "\n", "}", "\n", "switch", "buf", "[", "i", "]", "{", "case", "LF", ":", "k", ",", "err", "=", "c", ".", "Conn", ".", "Write", "(", "[", "]", "byte", "{", "CR", ",", "LF", "}", ")", "\n", "case", "cmdIAC", ":", "k", ",", "err", "=", "c", ".", "Conn", ".", "Write", "(", "[", "]", "byte", "{", "cmdIAC", ",", "cmdIAC", "}", ")", "\n", "}", "\n", "n", "+=", "k", "\n", "if", "err", "!=", "nil", "{", "break", "\n", "}", "\n", "buf", "=", "buf", "[", "i", "+", "1", ":", "]", "\n", "}", "\n", "return", "n", ",", "err", "\n", "}" ]
// Write is for implement an io.Writer interface
[ "Write", "is", "for", "implement", "an", "io", ".", "Writer", "interface" ]
10eb6877d5df825f4438f69864a9256f9694741d
https://github.com/hyperhq/runv/blob/10eb6877d5df825f4438f69864a9256f9694741d/lib/telnet/conn.go#L357-L392
9,418
hyperhq/runv
hypervisor/vm.go
AssociateVm
func AssociateVm(vmId string, data []byte) (*Vm, error) { var ( PodEvent = make(chan VmEvent, 128) Status = make(chan *types.VmResponse, 128) err error ) vm := newVm(vmId, 0, 0) vm.ctx, err = VmAssociate(vm.Id, PodEvent, Status, data) if err != nil { vm.Log(ERROR, "cannot associate with vm: %v", err) return nil, err } vm.clients = CreateFanout(Status, 128, false) return vm, nil }
go
func AssociateVm(vmId string, data []byte) (*Vm, error) { var ( PodEvent = make(chan VmEvent, 128) Status = make(chan *types.VmResponse, 128) err error ) vm := newVm(vmId, 0, 0) vm.ctx, err = VmAssociate(vm.Id, PodEvent, Status, data) if err != nil { vm.Log(ERROR, "cannot associate with vm: %v", err) return nil, err } vm.clients = CreateFanout(Status, 128, false) return vm, nil }
[ "func", "AssociateVm", "(", "vmId", "string", ",", "data", "[", "]", "byte", ")", "(", "*", "Vm", ",", "error", ")", "{", "var", "(", "PodEvent", "=", "make", "(", "chan", "VmEvent", ",", "128", ")", "\n", "Status", "=", "make", "(", "chan", "*", "types", ".", "VmResponse", ",", "128", ")", "\n", "err", "error", "\n", ")", "\n\n", "vm", ":=", "newVm", "(", "vmId", ",", "0", ",", "0", ")", "\n", "vm", ".", "ctx", ",", "err", "=", "VmAssociate", "(", "vm", ".", "Id", ",", "PodEvent", ",", "Status", ",", "data", ")", "\n", "if", "err", "!=", "nil", "{", "vm", ".", "Log", "(", "ERROR", ",", "\"", "\"", ",", "err", ")", "\n", "return", "nil", ",", "err", "\n", "}", "\n\n", "vm", ".", "clients", "=", "CreateFanout", "(", "Status", ",", "128", ",", "false", ")", "\n", "return", "vm", ",", "nil", "\n", "}" ]
// This function will only be invoked during daemon start
[ "This", "function", "will", "only", "be", "invoked", "during", "daemon", "start" ]
10eb6877d5df825f4438f69864a9256f9694741d
https://github.com/hyperhq/runv/blob/10eb6877d5df825f4438f69864a9256f9694741d/hypervisor/vm.go#L83-L99
9,419
hyperhq/runv
cli/network.go
setupNetworkNsTrap
func setupNetworkNsTrap(netNs2Containerd func(NetlinkUpdate)) { // Subscribe for links change event chLink := make(chan netlink.LinkUpdate) doneLink := make(chan struct{}) defer close(doneLink) if err := netlink.LinkSubscribe(chLink, doneLink); err != nil { glog.Fatal(err) } // Subscribe for addresses change event chAddr := make(chan netlink.AddrUpdate) doneAddr := make(chan struct{}) defer close(doneAddr) if err := netlink.AddrSubscribe(chAddr, doneAddr); err != nil { glog.Fatal(err) } // Subscribe for route change event chRoute := make(chan netlink.RouteUpdate) doneRoute := make(chan struct{}) defer close(doneRoute) if err := netlink.RouteSubscribe(chRoute, doneRoute); err != nil { glog.Fatal(err) } for { select { case updateLink := <-chLink: handleLink(updateLink, netNs2Containerd) case updateAddr := <-chAddr: handleAddr(updateAddr, netNs2Containerd) case updateRoute := <-chRoute: handleRoute(updateRoute, netNs2Containerd) } } }
go
func setupNetworkNsTrap(netNs2Containerd func(NetlinkUpdate)) { // Subscribe for links change event chLink := make(chan netlink.LinkUpdate) doneLink := make(chan struct{}) defer close(doneLink) if err := netlink.LinkSubscribe(chLink, doneLink); err != nil { glog.Fatal(err) } // Subscribe for addresses change event chAddr := make(chan netlink.AddrUpdate) doneAddr := make(chan struct{}) defer close(doneAddr) if err := netlink.AddrSubscribe(chAddr, doneAddr); err != nil { glog.Fatal(err) } // Subscribe for route change event chRoute := make(chan netlink.RouteUpdate) doneRoute := make(chan struct{}) defer close(doneRoute) if err := netlink.RouteSubscribe(chRoute, doneRoute); err != nil { glog.Fatal(err) } for { select { case updateLink := <-chLink: handleLink(updateLink, netNs2Containerd) case updateAddr := <-chAddr: handleAddr(updateAddr, netNs2Containerd) case updateRoute := <-chRoute: handleRoute(updateRoute, netNs2Containerd) } } }
[ "func", "setupNetworkNsTrap", "(", "netNs2Containerd", "func", "(", "NetlinkUpdate", ")", ")", "{", "// Subscribe for links change event", "chLink", ":=", "make", "(", "chan", "netlink", ".", "LinkUpdate", ")", "\n", "doneLink", ":=", "make", "(", "chan", "struct", "{", "}", ")", "\n", "defer", "close", "(", "doneLink", ")", "\n", "if", "err", ":=", "netlink", ".", "LinkSubscribe", "(", "chLink", ",", "doneLink", ")", ";", "err", "!=", "nil", "{", "glog", ".", "Fatal", "(", "err", ")", "\n", "}", "\n\n", "// Subscribe for addresses change event", "chAddr", ":=", "make", "(", "chan", "netlink", ".", "AddrUpdate", ")", "\n", "doneAddr", ":=", "make", "(", "chan", "struct", "{", "}", ")", "\n", "defer", "close", "(", "doneAddr", ")", "\n", "if", "err", ":=", "netlink", ".", "AddrSubscribe", "(", "chAddr", ",", "doneAddr", ")", ";", "err", "!=", "nil", "{", "glog", ".", "Fatal", "(", "err", ")", "\n", "}", "\n\n", "// Subscribe for route change event", "chRoute", ":=", "make", "(", "chan", "netlink", ".", "RouteUpdate", ")", "\n", "doneRoute", ":=", "make", "(", "chan", "struct", "{", "}", ")", "\n", "defer", "close", "(", "doneRoute", ")", "\n", "if", "err", ":=", "netlink", ".", "RouteSubscribe", "(", "chRoute", ",", "doneRoute", ")", ";", "err", "!=", "nil", "{", "glog", ".", "Fatal", "(", "err", ")", "\n", "}", "\n\n", "for", "{", "select", "{", "case", "updateLink", ":=", "<-", "chLink", ":", "handleLink", "(", "updateLink", ",", "netNs2Containerd", ")", "\n", "case", "updateAddr", ":=", "<-", "chAddr", ":", "handleAddr", "(", "updateAddr", ",", "netNs2Containerd", ")", "\n", "case", "updateRoute", ":=", "<-", "chRoute", ":", "handleRoute", "(", "updateRoute", ",", "netNs2Containerd", ")", "\n", "}", "\n", "}", "\n", "}" ]
// This function should be put into the main process or somewhere that can be // use to init the network namespace trap.
[ "This", "function", "should", "be", "put", "into", "the", "main", "process", "or", "somewhere", "that", "can", "be", "use", "to", "init", "the", "network", "namespace", "trap", "." ]
10eb6877d5df825f4438f69864a9256f9694741d
https://github.com/hyperhq/runv/blob/10eb6877d5df825f4438f69864a9256f9694741d/cli/network.go#L501-L536
9,420
hyperhq/runv
cli/list.go
fatal
func fatal(err error) { // make sure the error is written to the logger fmt.Fprintln(os.Stderr, err) os.Exit(1) }
go
func fatal(err error) { // make sure the error is written to the logger fmt.Fprintln(os.Stderr, err) os.Exit(1) }
[ "func", "fatal", "(", "err", "error", ")", "{", "// make sure the error is written to the logger", "fmt", ".", "Fprintln", "(", "os", ".", "Stderr", ",", "err", ")", "\n", "os", ".", "Exit", "(", "1", ")", "\n", "}" ]
// fatal prints the error's details if it is a runv specific error type // then exits the program with an exit status of 1.
[ "fatal", "prints", "the", "error", "s", "details", "if", "it", "is", "a", "runv", "specific", "error", "type", "then", "exits", "the", "program", "with", "an", "exit", "status", "of", "1", "." ]
10eb6877d5df825f4438f69864a9256f9694741d
https://github.com/hyperhq/runv/blob/10eb6877d5df825f4438f69864a9256f9694741d/cli/list.go#L142-L146
9,421
hyperhq/runv
hypervisor/errors.go
NewSpecError
func NewSpecError(id, cause string) *CommonError { return &CommonError{ errType: ET_SPEC, contextId: id, cause: "spec error: " + cause, } }
go
func NewSpecError(id, cause string) *CommonError { return &CommonError{ errType: ET_SPEC, contextId: id, cause: "spec error: " + cause, } }
[ "func", "NewSpecError", "(", "id", ",", "cause", "string", ")", "*", "CommonError", "{", "return", "&", "CommonError", "{", "errType", ":", "ET_SPEC", ",", "contextId", ":", "id", ",", "cause", ":", "\"", "\"", "+", "cause", ",", "}", "\n", "}" ]
// Error in spec, which is either mistake format or content inconsistency, and // is checked when elements are being added to Sandbox.
[ "Error", "in", "spec", "which", "is", "either", "mistake", "format", "or", "content", "inconsistency", "and", "is", "checked", "when", "elements", "are", "being", "added", "to", "Sandbox", "." ]
10eb6877d5df825f4438f69864a9256f9694741d
https://github.com/hyperhq/runv/blob/10eb6877d5df825f4438f69864a9256f9694741d/hypervisor/errors.go#L44-L50
9,422
hyperhq/runv
hypervisor/kvmtool/lkvm_arm64.go
getGicInfo
func getGicInfo() (info string) { gicinfo, err := os.Open("/proc/interrupts") if err != nil { return "unknown" } defer gicinfo.Close() scanner := bufio.NewScanner(gicinfo) for scanner.Scan() { newline := scanner.Text() list := strings.Fields(newline) for _, item := range list { if strings.EqualFold(item, "GICv2") { return "gicv2" } else if strings.EqualFold(item, "GICv3") || strings.EqualFold(item, "GICv4") { return "gicv3" } } } return "unknown" }
go
func getGicInfo() (info string) { gicinfo, err := os.Open("/proc/interrupts") if err != nil { return "unknown" } defer gicinfo.Close() scanner := bufio.NewScanner(gicinfo) for scanner.Scan() { newline := scanner.Text() list := strings.Fields(newline) for _, item := range list { if strings.EqualFold(item, "GICv2") { return "gicv2" } else if strings.EqualFold(item, "GICv3") || strings.EqualFold(item, "GICv4") { return "gicv3" } } } return "unknown" }
[ "func", "getGicInfo", "(", ")", "(", "info", "string", ")", "{", "gicinfo", ",", "err", ":=", "os", ".", "Open", "(", "\"", "\"", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\"", "\"", "\n", "}", "\n\n", "defer", "gicinfo", ".", "Close", "(", ")", "\n\n", "scanner", ":=", "bufio", ".", "NewScanner", "(", "gicinfo", ")", "\n", "for", "scanner", ".", "Scan", "(", ")", "{", "newline", ":=", "scanner", ".", "Text", "(", ")", "\n", "list", ":=", "strings", ".", "Fields", "(", "newline", ")", "\n\n", "for", "_", ",", "item", ":=", "range", "list", "{", "if", "strings", ".", "EqualFold", "(", "item", ",", "\"", "\"", ")", "{", "return", "\"", "\"", "\n", "}", "else", "if", "strings", ".", "EqualFold", "(", "item", ",", "\"", "\"", ")", "||", "strings", ".", "EqualFold", "(", "item", ",", "\"", "\"", ")", "{", "return", "\"", "\"", "\n", "}", "\n", "}", "\n", "}", "\n\n", "return", "\"", "\"", "\n", "}" ]
// On ARM platform, we have different gic interrupt controllers. // We have to detect the correct gic chip to set parameter for lkvm.
[ "On", "ARM", "platform", "we", "have", "different", "gic", "interrupt", "controllers", ".", "We", "have", "to", "detect", "the", "correct", "gic", "chip", "to", "set", "parameter", "for", "lkvm", "." ]
10eb6877d5df825f4438f69864a9256f9694741d
https://github.com/hyperhq/runv/blob/10eb6877d5df825f4438f69864a9256f9694741d/hypervisor/kvmtool/lkvm_arm64.go#L13-L37
9,423
hyperhq/runv
template/template.go
NewVmFromTemplate
func (t *TemplateVmConfig) NewVmFromTemplate(vmName string) (*hypervisor.Vm, error) { return hypervisor.GetVm(vmName, t.BootConfigFromTemplate(), false) }
go
func (t *TemplateVmConfig) NewVmFromTemplate(vmName string) (*hypervisor.Vm, error) { return hypervisor.GetVm(vmName, t.BootConfigFromTemplate(), false) }
[ "func", "(", "t", "*", "TemplateVmConfig", ")", "NewVmFromTemplate", "(", "vmName", "string", ")", "(", "*", "hypervisor", ".", "Vm", ",", "error", ")", "{", "return", "hypervisor", ".", "GetVm", "(", "vmName", ",", "t", ".", "BootConfigFromTemplate", "(", ")", ",", "false", ")", "\n", "}" ]
// boot vm from template, the returned vm is paused
[ "boot", "vm", "from", "template", "the", "returned", "vm", "is", "paused" ]
10eb6877d5df825f4438f69864a9256f9694741d
https://github.com/hyperhq/runv/blob/10eb6877d5df825f4438f69864a9256f9694741d/template/template.go#L113-L115
9,424
hyperhq/runv
cli/process.go
NewProcessList
func NewProcessList(root, name string) (*ProcessList, error) { f, err := os.OpenFile(filepath.Join(root, name, processJSON), os.O_RDWR|os.O_CREATE, 0644) if err != nil { return nil, err } if err = syscall.Flock(int(f.Fd()), syscall.LOCK_SH); err != nil { f.Close() return nil, fmt.Errorf("Placing LOCK_SH lock on process json file failed: %s", err.Error()) } return &ProcessList{file: f}, nil }
go
func NewProcessList(root, name string) (*ProcessList, error) { f, err := os.OpenFile(filepath.Join(root, name, processJSON), os.O_RDWR|os.O_CREATE, 0644) if err != nil { return nil, err } if err = syscall.Flock(int(f.Fd()), syscall.LOCK_SH); err != nil { f.Close() return nil, fmt.Errorf("Placing LOCK_SH lock on process json file failed: %s", err.Error()) } return &ProcessList{file: f}, nil }
[ "func", "NewProcessList", "(", "root", ",", "name", "string", ")", "(", "*", "ProcessList", ",", "error", ")", "{", "f", ",", "err", ":=", "os", ".", "OpenFile", "(", "filepath", ".", "Join", "(", "root", ",", "name", ",", "processJSON", ")", ",", "os", ".", "O_RDWR", "|", "os", ".", "O_CREATE", ",", "0644", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "if", "err", "=", "syscall", ".", "Flock", "(", "int", "(", "f", ".", "Fd", "(", ")", ")", ",", "syscall", ".", "LOCK_SH", ")", ";", "err", "!=", "nil", "{", "f", ".", "Close", "(", ")", "\n", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ".", "Error", "(", ")", ")", "\n", "}", "\n\n", "return", "&", "ProcessList", "{", "file", ":", "f", "}", ",", "nil", "\n", "}" ]
// Return locked processlist, which needs to be released by caller after using
[ "Return", "locked", "processlist", "which", "needs", "to", "be", "released", "by", "caller", "after", "using" ]
10eb6877d5df825f4438f69864a9256f9694741d
https://github.com/hyperhq/runv/blob/10eb6877d5df825f4438f69864a9256f9694741d/cli/process.go#L29-L41
9,425
hyperhq/runv
agent/proxy/proxy.go
NewServer
func NewServer(address string, json agent.SandboxAgent) (*grpc.Server, error) { s := grpc.NewServer() jp := &jsonProxy{ json: json, self: s, } kagenta.RegisterAgentServiceServer(s, jp) healthServer := health.NewServer() grpc_health_v1.RegisterHealthServer(s, healthServer) return s, nil }
go
func NewServer(address string, json agent.SandboxAgent) (*grpc.Server, error) { s := grpc.NewServer() jp := &jsonProxy{ json: json, self: s, } kagenta.RegisterAgentServiceServer(s, jp) healthServer := health.NewServer() grpc_health_v1.RegisterHealthServer(s, healthServer) return s, nil }
[ "func", "NewServer", "(", "address", "string", ",", "json", "agent", ".", "SandboxAgent", ")", "(", "*", "grpc", ".", "Server", ",", "error", ")", "{", "s", ":=", "grpc", ".", "NewServer", "(", ")", "\n", "jp", ":=", "&", "jsonProxy", "{", "json", ":", "json", ",", "self", ":", "s", ",", "}", "\n", "kagenta", ".", "RegisterAgentServiceServer", "(", "s", ",", "jp", ")", "\n", "healthServer", ":=", "health", ".", "NewServer", "(", ")", "\n", "grpc_health_v1", ".", "RegisterHealthServer", "(", "s", ",", "healthServer", ")", "\n", "return", "s", ",", "nil", "\n", "}" ]
// NewServer initializes a brand new grpc server with registered grpc services
[ "NewServer", "initializes", "a", "brand", "new", "grpc", "server", "with", "registered", "grpc", "services" ]
10eb6877d5df825f4438f69864a9256f9694741d
https://github.com/hyperhq/runv/blob/10eb6877d5df825f4438f69864a9256f9694741d/agent/proxy/proxy.go#L222-L232
9,426
denisbrodbeck/machineid
id_windows.go
machineID
func machineID() (string, error) { k, err := registry.OpenKey(registry.LOCAL_MACHINE, `SOFTWARE\Microsoft\Cryptography`, registry.QUERY_VALUE|registry.WOW64_64KEY) if err != nil { return "", err } defer k.Close() s, _, err := k.GetStringValue("MachineGuid") if err != nil { return "", err } return s, nil }
go
func machineID() (string, error) { k, err := registry.OpenKey(registry.LOCAL_MACHINE, `SOFTWARE\Microsoft\Cryptography`, registry.QUERY_VALUE|registry.WOW64_64KEY) if err != nil { return "", err } defer k.Close() s, _, err := k.GetStringValue("MachineGuid") if err != nil { return "", err } return s, nil }
[ "func", "machineID", "(", ")", "(", "string", ",", "error", ")", "{", "k", ",", "err", ":=", "registry", ".", "OpenKey", "(", "registry", ".", "LOCAL_MACHINE", ",", "`SOFTWARE\\Microsoft\\Cryptography`", ",", "registry", ".", "QUERY_VALUE", "|", "registry", ".", "WOW64_64KEY", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "err", "\n", "}", "\n", "defer", "k", ".", "Close", "(", ")", "\n\n", "s", ",", "_", ",", "err", ":=", "k", ".", "GetStringValue", "(", "\"", "\"", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "err", "\n", "}", "\n", "return", "s", ",", "nil", "\n", "}" ]
// machineID returns the key MachineGuid in registry `HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Cryptography`. // If there is an error running the commad an empty string is returned.
[ "machineID", "returns", "the", "key", "MachineGuid", "in", "registry", "HKEY_LOCAL_MACHINE", "\\", "SOFTWARE", "\\", "Microsoft", "\\", "Cryptography", ".", "If", "there", "is", "an", "error", "running", "the", "commad", "an", "empty", "string", "is", "returned", "." ]
f07179bb15a0bec252453468aa607c670f5c12b5
https://github.com/denisbrodbeck/machineid/blob/f07179bb15a0bec252453468aa607c670f5c12b5/id_windows.go#L11-L23
9,427
denisbrodbeck/machineid
id.go
ProtectedID
func ProtectedID(appID string) (string, error) { id, err := ID() if err != nil { return "", fmt.Errorf("machineid: %v", err) } return protect(appID, id), nil }
go
func ProtectedID(appID string) (string, error) { id, err := ID() if err != nil { return "", fmt.Errorf("machineid: %v", err) } return protect(appID, id), nil }
[ "func", "ProtectedID", "(", "appID", "string", ")", "(", "string", ",", "error", ")", "{", "id", ",", "err", ":=", "ID", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n", "return", "protect", "(", "appID", ",", "id", ")", ",", "nil", "\n", "}" ]
// ProtectedID returns a hashed version of the machine ID in a cryptographically secure way, // using a fixed, application-specific key. // Internally, this function calculates HMAC-SHA256 of the application ID, keyed by the machine ID.
[ "ProtectedID", "returns", "a", "hashed", "version", "of", "the", "machine", "ID", "in", "a", "cryptographically", "secure", "way", "using", "a", "fixed", "application", "-", "specific", "key", ".", "Internally", "this", "function", "calculates", "HMAC", "-", "SHA256", "of", "the", "application", "ID", "keyed", "by", "the", "machine", "ID", "." ]
f07179bb15a0bec252453468aa607c670f5c12b5
https://github.com/denisbrodbeck/machineid/blob/f07179bb15a0bec252453468aa607c670f5c12b5/id.go#L39-L45
9,428
denisbrodbeck/machineid
id_darwin.go
machineID
func machineID() (string, error) { buf := &bytes.Buffer{} err := run(buf, os.Stderr, "ioreg", "-rd1", "-c", "IOPlatformExpertDevice") if err != nil { return "", err } id, err := extractID(buf.String()) if err != nil { return "", err } return trim(id), nil }
go
func machineID() (string, error) { buf := &bytes.Buffer{} err := run(buf, os.Stderr, "ioreg", "-rd1", "-c", "IOPlatformExpertDevice") if err != nil { return "", err } id, err := extractID(buf.String()) if err != nil { return "", err } return trim(id), nil }
[ "func", "machineID", "(", ")", "(", "string", ",", "error", ")", "{", "buf", ":=", "&", "bytes", ".", "Buffer", "{", "}", "\n", "err", ":=", "run", "(", "buf", ",", "os", ".", "Stderr", ",", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "err", "\n", "}", "\n", "id", ",", "err", ":=", "extractID", "(", "buf", ".", "String", "(", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "err", "\n", "}", "\n", "return", "trim", "(", "id", ")", ",", "nil", "\n", "}" ]
// machineID returns the uuid returned by `ioreg -rd1 -c IOPlatformExpertDevice`. // If there is an error running the commad an empty string is returned.
[ "machineID", "returns", "the", "uuid", "returned", "by", "ioreg", "-", "rd1", "-", "c", "IOPlatformExpertDevice", ".", "If", "there", "is", "an", "error", "running", "the", "commad", "an", "empty", "string", "is", "returned", "." ]
f07179bb15a0bec252453468aa607c670f5c12b5
https://github.com/denisbrodbeck/machineid/blob/f07179bb15a0bec252453468aa607c670f5c12b5/id_darwin.go#L14-L25
9,429
denisbrodbeck/machineid
helper.go
run
func run(stdout, stderr io.Writer, cmd string, args ...string) error { c := exec.Command(cmd, args...) c.Stdin = os.Stdin c.Stdout = stdout c.Stderr = stderr return c.Run() }
go
func run(stdout, stderr io.Writer, cmd string, args ...string) error { c := exec.Command(cmd, args...) c.Stdin = os.Stdin c.Stdout = stdout c.Stderr = stderr return c.Run() }
[ "func", "run", "(", "stdout", ",", "stderr", "io", ".", "Writer", ",", "cmd", "string", ",", "args", "...", "string", ")", "error", "{", "c", ":=", "exec", ".", "Command", "(", "cmd", ",", "args", "...", ")", "\n", "c", ".", "Stdin", "=", "os", ".", "Stdin", "\n", "c", ".", "Stdout", "=", "stdout", "\n", "c", ".", "Stderr", "=", "stderr", "\n", "return", "c", ".", "Run", "(", ")", "\n", "}" ]
// run wraps `exec.Command` with easy access to stdout and stderr.
[ "run", "wraps", "exec", ".", "Command", "with", "easy", "access", "to", "stdout", "and", "stderr", "." ]
f07179bb15a0bec252453468aa607c670f5c12b5
https://github.com/denisbrodbeck/machineid/blob/f07179bb15a0bec252453468aa607c670f5c12b5/helper.go#L15-L21
9,430
denisbrodbeck/machineid
helper.go
protect
func protect(appID, id string) string { mac := hmac.New(sha256.New, []byte(id)) mac.Write([]byte(appID)) return hex.EncodeToString(mac.Sum(nil)) }
go
func protect(appID, id string) string { mac := hmac.New(sha256.New, []byte(id)) mac.Write([]byte(appID)) return hex.EncodeToString(mac.Sum(nil)) }
[ "func", "protect", "(", "appID", ",", "id", "string", ")", "string", "{", "mac", ":=", "hmac", ".", "New", "(", "sha256", ".", "New", ",", "[", "]", "byte", "(", "id", ")", ")", "\n", "mac", ".", "Write", "(", "[", "]", "byte", "(", "appID", ")", ")", "\n", "return", "hex", ".", "EncodeToString", "(", "mac", ".", "Sum", "(", "nil", ")", ")", "\n", "}" ]
// protect calculates HMAC-SHA256 of the application ID, keyed by the machine ID and returns a hex-encoded string.
[ "protect", "calculates", "HMAC", "-", "SHA256", "of", "the", "application", "ID", "keyed", "by", "the", "machine", "ID", "and", "returns", "a", "hex", "-", "encoded", "string", "." ]
f07179bb15a0bec252453468aa607c670f5c12b5
https://github.com/denisbrodbeck/machineid/blob/f07179bb15a0bec252453468aa607c670f5c12b5/helper.go#L24-L28
9,431
preichenberger/go-coinbasepro
client.go
Headers
func (c *Client) Headers(method, url, timestamp, data string) (map[string]string, error) { h := make(map[string]string) h["CB-ACCESS-KEY"] = c.Key h["CB-ACCESS-PASSPHRASE"] = c.Passphrase h["CB-ACCESS-TIMESTAMP"] = timestamp message := fmt.Sprintf( "%s%s%s%s", timestamp, method, url, data, ) sig, err := generateSig(message, c.Secret) if err != nil { return nil, err } h["CB-ACCESS-SIGN"] = sig return h, nil }
go
func (c *Client) Headers(method, url, timestamp, data string) (map[string]string, error) { h := make(map[string]string) h["CB-ACCESS-KEY"] = c.Key h["CB-ACCESS-PASSPHRASE"] = c.Passphrase h["CB-ACCESS-TIMESTAMP"] = timestamp message := fmt.Sprintf( "%s%s%s%s", timestamp, method, url, data, ) sig, err := generateSig(message, c.Secret) if err != nil { return nil, err } h["CB-ACCESS-SIGN"] = sig return h, nil }
[ "func", "(", "c", "*", "Client", ")", "Headers", "(", "method", ",", "url", ",", "timestamp", ",", "data", "string", ")", "(", "map", "[", "string", "]", "string", ",", "error", ")", "{", "h", ":=", "make", "(", "map", "[", "string", "]", "string", ")", "\n", "h", "[", "\"", "\"", "]", "=", "c", ".", "Key", "\n", "h", "[", "\"", "\"", "]", "=", "c", ".", "Passphrase", "\n", "h", "[", "\"", "\"", "]", "=", "timestamp", "\n\n", "message", ":=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "timestamp", ",", "method", ",", "url", ",", "data", ",", ")", "\n\n", "sig", ",", "err", ":=", "generateSig", "(", "message", ",", "c", ".", "Secret", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "h", "[", "\"", "\"", "]", "=", "sig", "\n", "return", "h", ",", "nil", "\n", "}" ]
// Headers generates a map that can be used as headers to authenticate a request
[ "Headers", "generates", "a", "map", "that", "can", "be", "used", "as", "headers", "to", "authenticate", "a", "request" ]
b6b44f4eca43ccf9e10750adfaf8511609968757
https://github.com/preichenberger/go-coinbasepro/blob/b6b44f4eca43ccf9e10750adfaf8511609968757/client.go#L166-L186
9,432
maxbrunsfeld/counterfeiter
generator/fake.go
NewFake
func NewFake(fakeMode FakeMode, targetName string, packagePath string, fakeName string, destinationPackage string, workingDir string) (*Fake, error) { f := &Fake{ TargetName: targetName, TargetPackage: packagePath, Name: fakeName, Mode: fakeMode, DestinationPackage: destinationPackage, Imports: newImports(), } f.Imports.Add("sync", "sync") err := f.loadPackages(workingDir) if err != nil { return nil, err } // TODO: Package mode here err = f.findPackage() if err != nil { return nil, err } if f.IsInterface() || f.Mode == Package { f.loadMethods() } if f.IsFunction() { err = f.loadMethodForFunction() if err != nil { return nil, err } } return f, nil }
go
func NewFake(fakeMode FakeMode, targetName string, packagePath string, fakeName string, destinationPackage string, workingDir string) (*Fake, error) { f := &Fake{ TargetName: targetName, TargetPackage: packagePath, Name: fakeName, Mode: fakeMode, DestinationPackage: destinationPackage, Imports: newImports(), } f.Imports.Add("sync", "sync") err := f.loadPackages(workingDir) if err != nil { return nil, err } // TODO: Package mode here err = f.findPackage() if err != nil { return nil, err } if f.IsInterface() || f.Mode == Package { f.loadMethods() } if f.IsFunction() { err = f.loadMethodForFunction() if err != nil { return nil, err } } return f, nil }
[ "func", "NewFake", "(", "fakeMode", "FakeMode", ",", "targetName", "string", ",", "packagePath", "string", ",", "fakeName", "string", ",", "destinationPackage", "string", ",", "workingDir", "string", ")", "(", "*", "Fake", ",", "error", ")", "{", "f", ":=", "&", "Fake", "{", "TargetName", ":", "targetName", ",", "TargetPackage", ":", "packagePath", ",", "Name", ":", "fakeName", ",", "Mode", ":", "fakeMode", ",", "DestinationPackage", ":", "destinationPackage", ",", "Imports", ":", "newImports", "(", ")", ",", "}", "\n\n", "f", ".", "Imports", ".", "Add", "(", "\"", "\"", ",", "\"", "\"", ")", "\n", "err", ":=", "f", ".", "loadPackages", "(", "workingDir", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "// TODO: Package mode here", "err", "=", "f", ".", "findPackage", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "if", "f", ".", "IsInterface", "(", ")", "||", "f", ".", "Mode", "==", "Package", "{", "f", ".", "loadMethods", "(", ")", "\n", "}", "\n", "if", "f", ".", "IsFunction", "(", ")", "{", "err", "=", "f", ".", "loadMethodForFunction", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "}", "\n", "return", "f", ",", "nil", "\n", "}" ]
// NewFake returns a Fake that loads the package and finds the interface or the // function.
[ "NewFake", "returns", "a", "Fake", "that", "loads", "the", "package", "and", "finds", "the", "interface", "or", "the", "function", "." ]
f7bde7cbdb1288611466a0d715b1bbc956519eb1
https://github.com/maxbrunsfeld/counterfeiter/blob/f7bde7cbdb1288611466a0d715b1bbc956519eb1/generator/fake.go#L51-L83
9,433
maxbrunsfeld/counterfeiter
generator/fake.go
IsInterface
func (f *Fake) IsInterface() bool { if f.Target == nil || f.Target.Type() == nil { return false } return types.IsInterface(f.Target.Type()) }
go
func (f *Fake) IsInterface() bool { if f.Target == nil || f.Target.Type() == nil { return false } return types.IsInterface(f.Target.Type()) }
[ "func", "(", "f", "*", "Fake", ")", "IsInterface", "(", ")", "bool", "{", "if", "f", ".", "Target", "==", "nil", "||", "f", ".", "Target", ".", "Type", "(", ")", "==", "nil", "{", "return", "false", "\n", "}", "\n", "return", "types", ".", "IsInterface", "(", "f", ".", "Target", ".", "Type", "(", ")", ")", "\n", "}" ]
// IsInterface indicates whether the fake is for an interface.
[ "IsInterface", "indicates", "whether", "the", "fake", "is", "for", "an", "interface", "." ]
f7bde7cbdb1288611466a0d715b1bbc956519eb1
https://github.com/maxbrunsfeld/counterfeiter/blob/f7bde7cbdb1288611466a0d715b1bbc956519eb1/generator/fake.go#L86-L91
9,434
maxbrunsfeld/counterfeiter
generator/fake.go
IsFunction
func (f *Fake) IsFunction() bool { if f.Target == nil || f.Target.Type() == nil || f.Target.Type().Underlying() == nil { return false } _, ok := f.Target.Type().Underlying().(*types.Signature) return ok }
go
func (f *Fake) IsFunction() bool { if f.Target == nil || f.Target.Type() == nil || f.Target.Type().Underlying() == nil { return false } _, ok := f.Target.Type().Underlying().(*types.Signature) return ok }
[ "func", "(", "f", "*", "Fake", ")", "IsFunction", "(", ")", "bool", "{", "if", "f", ".", "Target", "==", "nil", "||", "f", ".", "Target", ".", "Type", "(", ")", "==", "nil", "||", "f", ".", "Target", ".", "Type", "(", ")", ".", "Underlying", "(", ")", "==", "nil", "{", "return", "false", "\n", "}", "\n", "_", ",", "ok", ":=", "f", ".", "Target", ".", "Type", "(", ")", ".", "Underlying", "(", ")", ".", "(", "*", "types", ".", "Signature", ")", "\n", "return", "ok", "\n", "}" ]
// IsFunction indicates whether the fake is for a function..
[ "IsFunction", "indicates", "whether", "the", "fake", "is", "for", "a", "function", ".." ]
f7bde7cbdb1288611466a0d715b1bbc956519eb1
https://github.com/maxbrunsfeld/counterfeiter/blob/f7bde7cbdb1288611466a0d715b1bbc956519eb1/generator/fake.go#L94-L100
9,435
maxbrunsfeld/counterfeiter
generator/fake.go
Generate
func (f *Fake) Generate(runImports bool) ([]byte, error) { var tmpl *template.Template if f.IsInterface() { log.Printf("Writing fake %s for interface %s to package %s\n", f.Name, f.TargetName, f.DestinationPackage) tmpl = template.Must(template.New("fake").Funcs(interfaceFuncs).Parse(interfaceTemplate)) } if f.IsFunction() { log.Printf("Writing fake %s for function %s to package %s\n", f.Name, f.TargetName, f.DestinationPackage) tmpl = template.Must(template.New("fake").Funcs(functionFuncs).Parse(functionTemplate)) } if f.Mode == Package { log.Printf("Writing fake %s for package %s to package %s\n", f.Name, f.TargetPackage, f.DestinationPackage) tmpl = template.Must(template.New("fake").Funcs(packageFuncs).Parse(packageTemplate)) } if tmpl == nil { return nil, errors.New("counterfeiter can only generate fakes for interfaces or specific functions") } b := &bytes.Buffer{} tmpl.Execute(b, f) if runImports { return imports.Process("counterfeiter_temp_process_file", b.Bytes(), nil) } return b.Bytes(), nil }
go
func (f *Fake) Generate(runImports bool) ([]byte, error) { var tmpl *template.Template if f.IsInterface() { log.Printf("Writing fake %s for interface %s to package %s\n", f.Name, f.TargetName, f.DestinationPackage) tmpl = template.Must(template.New("fake").Funcs(interfaceFuncs).Parse(interfaceTemplate)) } if f.IsFunction() { log.Printf("Writing fake %s for function %s to package %s\n", f.Name, f.TargetName, f.DestinationPackage) tmpl = template.Must(template.New("fake").Funcs(functionFuncs).Parse(functionTemplate)) } if f.Mode == Package { log.Printf("Writing fake %s for package %s to package %s\n", f.Name, f.TargetPackage, f.DestinationPackage) tmpl = template.Must(template.New("fake").Funcs(packageFuncs).Parse(packageTemplate)) } if tmpl == nil { return nil, errors.New("counterfeiter can only generate fakes for interfaces or specific functions") } b := &bytes.Buffer{} tmpl.Execute(b, f) if runImports { return imports.Process("counterfeiter_temp_process_file", b.Bytes(), nil) } return b.Bytes(), nil }
[ "func", "(", "f", "*", "Fake", ")", "Generate", "(", "runImports", "bool", ")", "(", "[", "]", "byte", ",", "error", ")", "{", "var", "tmpl", "*", "template", ".", "Template", "\n", "if", "f", ".", "IsInterface", "(", ")", "{", "log", ".", "Printf", "(", "\"", "\\n", "\"", ",", "f", ".", "Name", ",", "f", ".", "TargetName", ",", "f", ".", "DestinationPackage", ")", "\n", "tmpl", "=", "template", ".", "Must", "(", "template", ".", "New", "(", "\"", "\"", ")", ".", "Funcs", "(", "interfaceFuncs", ")", ".", "Parse", "(", "interfaceTemplate", ")", ")", "\n", "}", "\n", "if", "f", ".", "IsFunction", "(", ")", "{", "log", ".", "Printf", "(", "\"", "\\n", "\"", ",", "f", ".", "Name", ",", "f", ".", "TargetName", ",", "f", ".", "DestinationPackage", ")", "\n", "tmpl", "=", "template", ".", "Must", "(", "template", ".", "New", "(", "\"", "\"", ")", ".", "Funcs", "(", "functionFuncs", ")", ".", "Parse", "(", "functionTemplate", ")", ")", "\n", "}", "\n", "if", "f", ".", "Mode", "==", "Package", "{", "log", ".", "Printf", "(", "\"", "\\n", "\"", ",", "f", ".", "Name", ",", "f", ".", "TargetPackage", ",", "f", ".", "DestinationPackage", ")", "\n", "tmpl", "=", "template", ".", "Must", "(", "template", ".", "New", "(", "\"", "\"", ")", ".", "Funcs", "(", "packageFuncs", ")", ".", "Parse", "(", "packageTemplate", ")", ")", "\n", "}", "\n", "if", "tmpl", "==", "nil", "{", "return", "nil", ",", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n\n", "b", ":=", "&", "bytes", ".", "Buffer", "{", "}", "\n", "tmpl", ".", "Execute", "(", "b", ",", "f", ")", "\n", "if", "runImports", "{", "return", "imports", ".", "Process", "(", "\"", "\"", ",", "b", ".", "Bytes", "(", ")", ",", "nil", ")", "\n", "}", "\n", "return", "b", ".", "Bytes", "(", ")", ",", "nil", "\n", "}" ]
// Generate uses the Fake to generate an implementation, optionally running // goimports on the output.
[ "Generate", "uses", "the", "Fake", "to", "generate", "an", "implementation", "optionally", "running", "goimports", "on", "the", "output", "." ]
f7bde7cbdb1288611466a0d715b1bbc956519eb1
https://github.com/maxbrunsfeld/counterfeiter/blob/f7bde7cbdb1288611466a0d715b1bbc956519eb1/generator/fake.go#L118-L142
9,436
maxbrunsfeld/counterfeiter
generator/interface_loader.go
interfaceMethodSet
func interfaceMethodSet(t types.Type) []*rawMethod { if t == nil { return nil } var result []*rawMethod methods := typeutil.IntuitiveMethodSet(t, nil) for i := range methods { if methods[i].Obj() == nil || methods[i].Type() == nil { continue } fun, ok := methods[i].Obj().(*types.Func) if !ok { continue } sig, ok := methods[i].Type().(*types.Signature) if !ok { continue } result = append(result, &rawMethod{ Func: fun, Signature: sig, }) } return result }
go
func interfaceMethodSet(t types.Type) []*rawMethod { if t == nil { return nil } var result []*rawMethod methods := typeutil.IntuitiveMethodSet(t, nil) for i := range methods { if methods[i].Obj() == nil || methods[i].Type() == nil { continue } fun, ok := methods[i].Obj().(*types.Func) if !ok { continue } sig, ok := methods[i].Type().(*types.Signature) if !ok { continue } result = append(result, &rawMethod{ Func: fun, Signature: sig, }) } return result }
[ "func", "interfaceMethodSet", "(", "t", "types", ".", "Type", ")", "[", "]", "*", "rawMethod", "{", "if", "t", "==", "nil", "{", "return", "nil", "\n", "}", "\n", "var", "result", "[", "]", "*", "rawMethod", "\n", "methods", ":=", "typeutil", ".", "IntuitiveMethodSet", "(", "t", ",", "nil", ")", "\n", "for", "i", ":=", "range", "methods", "{", "if", "methods", "[", "i", "]", ".", "Obj", "(", ")", "==", "nil", "||", "methods", "[", "i", "]", ".", "Type", "(", ")", "==", "nil", "{", "continue", "\n", "}", "\n", "fun", ",", "ok", ":=", "methods", "[", "i", "]", ".", "Obj", "(", ")", ".", "(", "*", "types", ".", "Func", ")", "\n", "if", "!", "ok", "{", "continue", "\n", "}", "\n", "sig", ",", "ok", ":=", "methods", "[", "i", "]", ".", "Type", "(", ")", ".", "(", "*", "types", ".", "Signature", ")", "\n", "if", "!", "ok", "{", "continue", "\n", "}", "\n", "result", "=", "append", "(", "result", ",", "&", "rawMethod", "{", "Func", ":", "fun", ",", "Signature", ":", "sig", ",", "}", ")", "\n", "}", "\n\n", "return", "result", "\n", "}" ]
// interfaceMethodSet identifies the methods that are exported for a given // interface.
[ "interfaceMethodSet", "identifies", "the", "methods", "that", "are", "exported", "for", "a", "given", "interface", "." ]
f7bde7cbdb1288611466a0d715b1bbc956519eb1
https://github.com/maxbrunsfeld/counterfeiter/blob/f7bde7cbdb1288611466a0d715b1bbc956519eb1/generator/interface_loader.go#L57-L82
9,437
maxbrunsfeld/counterfeiter
generator/param.go
Slices
func (p Params) Slices() Params { var result Params for i := range p { if p[i].IsSlice { result = append(result, p[i]) } } return result }
go
func (p Params) Slices() Params { var result Params for i := range p { if p[i].IsSlice { result = append(result, p[i]) } } return result }
[ "func", "(", "p", "Params", ")", "Slices", "(", ")", "Params", "{", "var", "result", "Params", "\n", "for", "i", ":=", "range", "p", "{", "if", "p", "[", "i", "]", ".", "IsSlice", "{", "result", "=", "append", "(", "result", ",", "p", "[", "i", "]", ")", "\n", "}", "\n", "}", "\n", "return", "result", "\n", "}" ]
// Slices returns those params that are a slice.
[ "Slices", "returns", "those", "params", "that", "are", "a", "slice", "." ]
f7bde7cbdb1288611466a0d715b1bbc956519eb1
https://github.com/maxbrunsfeld/counterfeiter/blob/f7bde7cbdb1288611466a0d715b1bbc956519eb1/generator/param.go#L17-L25
9,438
maxbrunsfeld/counterfeiter
generator/param.go
WithPrefix
func (p Params) WithPrefix(prefix string) string { if len(p) == 0 { return "" } params := []string{} for i := range p { if prefix == "" { params = append(params, unexport(p[i].Name)) } else { params = append(params, prefix+unexport(p[i].Name)) } } return strings.Join(params, ", ") }
go
func (p Params) WithPrefix(prefix string) string { if len(p) == 0 { return "" } params := []string{} for i := range p { if prefix == "" { params = append(params, unexport(p[i].Name)) } else { params = append(params, prefix+unexport(p[i].Name)) } } return strings.Join(params, ", ") }
[ "func", "(", "p", "Params", ")", "WithPrefix", "(", "prefix", "string", ")", "string", "{", "if", "len", "(", "p", ")", "==", "0", "{", "return", "\"", "\"", "\n", "}", "\n\n", "params", ":=", "[", "]", "string", "{", "}", "\n", "for", "i", ":=", "range", "p", "{", "if", "prefix", "==", "\"", "\"", "{", "params", "=", "append", "(", "params", ",", "unexport", "(", "p", "[", "i", "]", ".", "Name", ")", ")", "\n", "}", "else", "{", "params", "=", "append", "(", "params", ",", "prefix", "+", "unexport", "(", "p", "[", "i", "]", ".", "Name", ")", ")", "\n", "}", "\n", "}", "\n", "return", "strings", ".", "Join", "(", "params", ",", "\"", "\"", ")", "\n", "}" ]
// WithPrefix builds a string representing a functions parameters, and adds a // prefix to each.
[ "WithPrefix", "builds", "a", "string", "representing", "a", "functions", "parameters", "and", "adds", "a", "prefix", "to", "each", "." ]
f7bde7cbdb1288611466a0d715b1bbc956519eb1
https://github.com/maxbrunsfeld/counterfeiter/blob/f7bde7cbdb1288611466a0d715b1bbc956519eb1/generator/param.go#L35-L49
9,439
maxbrunsfeld/counterfeiter
generator/param.go
AsArgs
func (p Params) AsArgs() string { if len(p) == 0 { return "" } params := []string{} for i := range p { params = append(params, p[i].Type) } return strings.Join(params, ", ") }
go
func (p Params) AsArgs() string { if len(p) == 0 { return "" } params := []string{} for i := range p { params = append(params, p[i].Type) } return strings.Join(params, ", ") }
[ "func", "(", "p", "Params", ")", "AsArgs", "(", ")", "string", "{", "if", "len", "(", "p", ")", "==", "0", "{", "return", "\"", "\"", "\n", "}", "\n\n", "params", ":=", "[", "]", "string", "{", "}", "\n", "for", "i", ":=", "range", "p", "{", "params", "=", "append", "(", "params", ",", "p", "[", "i", "]", ".", "Type", ")", "\n", "}", "\n", "return", "strings", ".", "Join", "(", "params", ",", "\"", "\"", ")", "\n", "}" ]
// AsArgs builds a string that represents the parameters to a function as // arguments to a function invocation.
[ "AsArgs", "builds", "a", "string", "that", "represents", "the", "parameters", "to", "a", "function", "as", "arguments", "to", "a", "function", "invocation", "." ]
f7bde7cbdb1288611466a0d715b1bbc956519eb1
https://github.com/maxbrunsfeld/counterfeiter/blob/f7bde7cbdb1288611466a0d715b1bbc956519eb1/generator/param.go#L53-L63
9,440
maxbrunsfeld/counterfeiter
generator/param.go
AsNamedArgsWithTypes
func (p Params) AsNamedArgsWithTypes() string { if len(p) == 0 { return "" } params := []string{} for i := range p { params = append(params, unexport(p[i].Name)+" "+p[i].Type) } return strings.Join(params, ", ") }
go
func (p Params) AsNamedArgsWithTypes() string { if len(p) == 0 { return "" } params := []string{} for i := range p { params = append(params, unexport(p[i].Name)+" "+p[i].Type) } return strings.Join(params, ", ") }
[ "func", "(", "p", "Params", ")", "AsNamedArgsWithTypes", "(", ")", "string", "{", "if", "len", "(", "p", ")", "==", "0", "{", "return", "\"", "\"", "\n", "}", "\n\n", "params", ":=", "[", "]", "string", "{", "}", "\n", "for", "i", ":=", "range", "p", "{", "params", "=", "append", "(", "params", ",", "unexport", "(", "p", "[", "i", "]", ".", "Name", ")", "+", "\"", "\"", "+", "p", "[", "i", "]", ".", "Type", ")", "\n", "}", "\n", "return", "strings", ".", "Join", "(", "params", ",", "\"", "\"", ")", "\n", "}" ]
// AsNamedArgsWithTypes builds a string that represents parameters as named // arugments to a function, with associated types.
[ "AsNamedArgsWithTypes", "builds", "a", "string", "that", "represents", "parameters", "as", "named", "arugments", "to", "a", "function", "with", "associated", "types", "." ]
f7bde7cbdb1288611466a0d715b1bbc956519eb1
https://github.com/maxbrunsfeld/counterfeiter/blob/f7bde7cbdb1288611466a0d715b1bbc956519eb1/generator/param.go#L67-L77
9,441
maxbrunsfeld/counterfeiter
generator/param.go
AsNamedArgs
func (p Params) AsNamedArgs() string { if len(p) == 0 { return "" } params := []string{} for i := range p { if p[i].IsSlice { params = append(params, unexport(p[i].Name)+"Copy") } else { params = append(params, unexport(p[i].Name)) } } return strings.Join(params, ", ") }
go
func (p Params) AsNamedArgs() string { if len(p) == 0 { return "" } params := []string{} for i := range p { if p[i].IsSlice { params = append(params, unexport(p[i].Name)+"Copy") } else { params = append(params, unexport(p[i].Name)) } } return strings.Join(params, ", ") }
[ "func", "(", "p", "Params", ")", "AsNamedArgs", "(", ")", "string", "{", "if", "len", "(", "p", ")", "==", "0", "{", "return", "\"", "\"", "\n", "}", "\n\n", "params", ":=", "[", "]", "string", "{", "}", "\n", "for", "i", ":=", "range", "p", "{", "if", "p", "[", "i", "]", ".", "IsSlice", "{", "params", "=", "append", "(", "params", ",", "unexport", "(", "p", "[", "i", "]", ".", "Name", ")", "+", "\"", "\"", ")", "\n", "}", "else", "{", "params", "=", "append", "(", "params", ",", "unexport", "(", "p", "[", "i", "]", ".", "Name", ")", ")", "\n", "}", "\n", "}", "\n", "return", "strings", ".", "Join", "(", "params", ",", "\"", "\"", ")", "\n", "}" ]
// AsNamedArgs builds a string that represents parameters as named arguments.
[ "AsNamedArgs", "builds", "a", "string", "that", "represents", "parameters", "as", "named", "arguments", "." ]
f7bde7cbdb1288611466a0d715b1bbc956519eb1
https://github.com/maxbrunsfeld/counterfeiter/blob/f7bde7cbdb1288611466a0d715b1bbc956519eb1/generator/param.go#L80-L94
9,442
maxbrunsfeld/counterfeiter
generator/param.go
AsNamedArgsForInvocation
func (p Params) AsNamedArgsForInvocation() string { if len(p) == 0 { return "" } params := []string{} for i := range p { if p[i].IsVariadic { params = append(params, unexport(p[i].Name)+"...") } else { params = append(params, unexport(p[i].Name)) } } return strings.Join(params, ", ") }
go
func (p Params) AsNamedArgsForInvocation() string { if len(p) == 0 { return "" } params := []string{} for i := range p { if p[i].IsVariadic { params = append(params, unexport(p[i].Name)+"...") } else { params = append(params, unexport(p[i].Name)) } } return strings.Join(params, ", ") }
[ "func", "(", "p", "Params", ")", "AsNamedArgsForInvocation", "(", ")", "string", "{", "if", "len", "(", "p", ")", "==", "0", "{", "return", "\"", "\"", "\n", "}", "\n\n", "params", ":=", "[", "]", "string", "{", "}", "\n", "for", "i", ":=", "range", "p", "{", "if", "p", "[", "i", "]", ".", "IsVariadic", "{", "params", "=", "append", "(", "params", ",", "unexport", "(", "p", "[", "i", "]", ".", "Name", ")", "+", "\"", "\"", ")", "\n", "}", "else", "{", "params", "=", "append", "(", "params", ",", "unexport", "(", "p", "[", "i", "]", ".", "Name", ")", ")", "\n", "}", "\n", "}", "\n", "return", "strings", ".", "Join", "(", "params", ",", "\"", "\"", ")", "\n", "}" ]
// AsNamedArgsForInvocation builds a string that represents a function's // arguments as required for invocation of the function.
[ "AsNamedArgsForInvocation", "builds", "a", "string", "that", "represents", "a", "function", "s", "arguments", "as", "required", "for", "invocation", "of", "the", "function", "." ]
f7bde7cbdb1288611466a0d715b1bbc956519eb1
https://github.com/maxbrunsfeld/counterfeiter/blob/f7bde7cbdb1288611466a0d715b1bbc956519eb1/generator/param.go#L98-L112
9,443
maxbrunsfeld/counterfeiter
generator/param.go
AsReturnSignature
func (p Params) AsReturnSignature() string { if len(p) == 0 { return "" } if len(p) == 1 { if p[0].IsVariadic { return strings.Replace(p[0].Type, "...", "[]", -1) } return p[0].Type } result := "(" for i := range p { t := p[i].Type if p[i].IsVariadic { t = strings.Replace(t, "...", "[]", -1) } result = result + t if i < len(p) { result = result + ", " } } result = result + ")" return result }
go
func (p Params) AsReturnSignature() string { if len(p) == 0 { return "" } if len(p) == 1 { if p[0].IsVariadic { return strings.Replace(p[0].Type, "...", "[]", -1) } return p[0].Type } result := "(" for i := range p { t := p[i].Type if p[i].IsVariadic { t = strings.Replace(t, "...", "[]", -1) } result = result + t if i < len(p) { result = result + ", " } } result = result + ")" return result }
[ "func", "(", "p", "Params", ")", "AsReturnSignature", "(", ")", "string", "{", "if", "len", "(", "p", ")", "==", "0", "{", "return", "\"", "\"", "\n", "}", "\n", "if", "len", "(", "p", ")", "==", "1", "{", "if", "p", "[", "0", "]", ".", "IsVariadic", "{", "return", "strings", ".", "Replace", "(", "p", "[", "0", "]", ".", "Type", ",", "\"", "\"", ",", "\"", "\"", ",", "-", "1", ")", "\n", "}", "\n", "return", "p", "[", "0", "]", ".", "Type", "\n", "}", "\n", "result", ":=", "\"", "\"", "\n", "for", "i", ":=", "range", "p", "{", "t", ":=", "p", "[", "i", "]", ".", "Type", "\n", "if", "p", "[", "i", "]", ".", "IsVariadic", "{", "t", "=", "strings", ".", "Replace", "(", "t", ",", "\"", "\"", ",", "\"", "\"", ",", "-", "1", ")", "\n", "}", "\n", "result", "=", "result", "+", "t", "\n", "if", "i", "<", "len", "(", "p", ")", "{", "result", "=", "result", "+", "\"", "\"", "\n", "}", "\n", "}", "\n", "result", "=", "result", "+", "\"", "\"", "\n", "return", "result", "\n", "}" ]
// AsReturnSignature builds a string representing signature for the params of // a function.
[ "AsReturnSignature", "builds", "a", "string", "representing", "signature", "for", "the", "params", "of", "a", "function", "." ]
f7bde7cbdb1288611466a0d715b1bbc956519eb1
https://github.com/maxbrunsfeld/counterfeiter/blob/f7bde7cbdb1288611466a0d715b1bbc956519eb1/generator/param.go#L116-L139
9,444
maxbrunsfeld/counterfeiter
generator/import.go
String
func (i Import) String() string { if path.Base(i.PkgPath) == i.Alias { return `"` + i.PkgPath + `"` } return fmt.Sprintf(`%s "%s"`, i.Alias, i.PkgPath) }
go
func (i Import) String() string { if path.Base(i.PkgPath) == i.Alias { return `"` + i.PkgPath + `"` } return fmt.Sprintf(`%s "%s"`, i.Alias, i.PkgPath) }
[ "func", "(", "i", "Import", ")", "String", "(", ")", "string", "{", "if", "path", ".", "Base", "(", "i", ".", "PkgPath", ")", "==", "i", ".", "Alias", "{", "return", "`\"`", "+", "i", ".", "PkgPath", "+", "`\"`", "\n", "}", "\n", "return", "fmt", ".", "Sprintf", "(", "`%s \"%s\"`", ",", "i", ".", "Alias", ",", "i", ".", "PkgPath", ")", "\n", "}" ]
// String returns a string that may be used as an import line in a go source // file. Imports with aliases that match the package basename are printed without // an alias.
[ "String", "returns", "a", "string", "that", "may", "be", "used", "as", "an", "import", "line", "in", "a", "go", "source", "file", ".", "Imports", "with", "aliases", "that", "match", "the", "package", "basename", "are", "printed", "without", "an", "alias", "." ]
f7bde7cbdb1288611466a0d715b1bbc956519eb1
https://github.com/maxbrunsfeld/counterfeiter/blob/f7bde7cbdb1288611466a0d715b1bbc956519eb1/generator/import.go#L35-L40
9,445
maxbrunsfeld/counterfeiter
generator/import.go
Add
func (i *Imports) Add(alias string, path string) Import { path = imports.VendorlessPath(strings.TrimSpace(path)) alias = strings.TrimSpace(alias) imp, exists := i.ByPkgPath[path] if exists { return imp } _, exists = i.ByAlias[alias] if exists { alias = uniqueAliasForImport(alias, i.ByAlias) } result := Import{Alias: alias, PkgPath: path} i.ByPkgPath[path] = result i.ByAlias[alias] = result return result }
go
func (i *Imports) Add(alias string, path string) Import { path = imports.VendorlessPath(strings.TrimSpace(path)) alias = strings.TrimSpace(alias) imp, exists := i.ByPkgPath[path] if exists { return imp } _, exists = i.ByAlias[alias] if exists { alias = uniqueAliasForImport(alias, i.ByAlias) } result := Import{Alias: alias, PkgPath: path} i.ByPkgPath[path] = result i.ByAlias[alias] = result return result }
[ "func", "(", "i", "*", "Imports", ")", "Add", "(", "alias", "string", ",", "path", "string", ")", "Import", "{", "path", "=", "imports", ".", "VendorlessPath", "(", "strings", ".", "TrimSpace", "(", "path", ")", ")", "\n", "alias", "=", "strings", ".", "TrimSpace", "(", "alias", ")", "\n\n", "imp", ",", "exists", ":=", "i", ".", "ByPkgPath", "[", "path", "]", "\n", "if", "exists", "{", "return", "imp", "\n", "}", "\n\n", "_", ",", "exists", "=", "i", ".", "ByAlias", "[", "alias", "]", "\n", "if", "exists", "{", "alias", "=", "uniqueAliasForImport", "(", "alias", ",", "i", ".", "ByAlias", ")", "\n", "}", "\n\n", "result", ":=", "Import", "{", "Alias", ":", "alias", ",", "PkgPath", ":", "path", "}", "\n", "i", ".", "ByPkgPath", "[", "path", "]", "=", "result", "\n", "i", ".", "ByAlias", "[", "alias", "]", "=", "result", "\n", "return", "result", "\n", "}" ]
// Add creates an import with the given alias and path, and adds it to // Fake.Imports.
[ "Add", "creates", "an", "import", "with", "the", "given", "alias", "and", "path", "and", "adds", "it", "to", "Fake", ".", "Imports", "." ]
f7bde7cbdb1288611466a0d715b1bbc956519eb1
https://github.com/maxbrunsfeld/counterfeiter/blob/f7bde7cbdb1288611466a0d715b1bbc956519eb1/generator/import.go#L44-L62
9,446
maxbrunsfeld/counterfeiter
generator/import.go
AliasForPackage
func (i *Imports) AliasForPackage(p *types.Package) string { return i.ByPkgPath[imports.VendorlessPath(p.Path())].Alias }
go
func (i *Imports) AliasForPackage(p *types.Package) string { return i.ByPkgPath[imports.VendorlessPath(p.Path())].Alias }
[ "func", "(", "i", "*", "Imports", ")", "AliasForPackage", "(", "p", "*", "types", ".", "Package", ")", "string", "{", "return", "i", ".", "ByPkgPath", "[", "imports", ".", "VendorlessPath", "(", "p", ".", "Path", "(", ")", ")", "]", ".", "Alias", "\n", "}" ]
// AliasForPackage returns a package alias for the package.
[ "AliasForPackage", "returns", "a", "package", "alias", "for", "the", "package", "." ]
f7bde7cbdb1288611466a0d715b1bbc956519eb1
https://github.com/maxbrunsfeld/counterfeiter/blob/f7bde7cbdb1288611466a0d715b1bbc956519eb1/generator/import.go#L74-L76
9,447
maxbrunsfeld/counterfeiter
generator/package_loader.go
packageMethodSet
func packageMethodSet(p *packages.Package) []*rawMethod { if p == nil || p.Types == nil || p.Types.Scope() == nil { return nil } var result []*rawMethod scope := p.Types.Scope() for _, name := range scope.Names() { obj := scope.Lookup(name) if !obj.Exported() { continue // skip unexported names } fun, ok := obj.(*types.Func) if !ok { continue } sig, ok := obj.Type().(*types.Signature) if !ok { continue } result = append(result, &rawMethod{ Func: fun, Signature: sig, }) } return result }
go
func packageMethodSet(p *packages.Package) []*rawMethod { if p == nil || p.Types == nil || p.Types.Scope() == nil { return nil } var result []*rawMethod scope := p.Types.Scope() for _, name := range scope.Names() { obj := scope.Lookup(name) if !obj.Exported() { continue // skip unexported names } fun, ok := obj.(*types.Func) if !ok { continue } sig, ok := obj.Type().(*types.Signature) if !ok { continue } result = append(result, &rawMethod{ Func: fun, Signature: sig, }) } return result }
[ "func", "packageMethodSet", "(", "p", "*", "packages", ".", "Package", ")", "[", "]", "*", "rawMethod", "{", "if", "p", "==", "nil", "||", "p", ".", "Types", "==", "nil", "||", "p", ".", "Types", ".", "Scope", "(", ")", "==", "nil", "{", "return", "nil", "\n", "}", "\n", "var", "result", "[", "]", "*", "rawMethod", "\n", "scope", ":=", "p", ".", "Types", ".", "Scope", "(", ")", "\n", "for", "_", ",", "name", ":=", "range", "scope", ".", "Names", "(", ")", "{", "obj", ":=", "scope", ".", "Lookup", "(", "name", ")", "\n", "if", "!", "obj", ".", "Exported", "(", ")", "{", "continue", "// skip unexported names", "\n", "}", "\n", "fun", ",", "ok", ":=", "obj", ".", "(", "*", "types", ".", "Func", ")", "\n", "if", "!", "ok", "{", "continue", "\n", "}", "\n", "sig", ",", "ok", ":=", "obj", ".", "Type", "(", ")", ".", "(", "*", "types", ".", "Signature", ")", "\n", "if", "!", "ok", "{", "continue", "\n", "}", "\n", "result", "=", "append", "(", "result", ",", "&", "rawMethod", "{", "Func", ":", "fun", ",", "Signature", ":", "sig", ",", "}", ")", "\n", "}", "\n\n", "return", "result", "\n", "}" ]
// packageMethodSet identifies the functions that are exported from a given // package.
[ "packageMethodSet", "identifies", "the", "functions", "that", "are", "exported", "from", "a", "given", "package", "." ]
f7bde7cbdb1288611466a0d715b1bbc956519eb1
https://github.com/maxbrunsfeld/counterfeiter/blob/f7bde7cbdb1288611466a0d715b1bbc956519eb1/generator/package_loader.go#L16-L42
9,448
maxbrunsfeld/counterfeiter
generator/loader.go
addImportsFor
func (f *Fake) addImportsFor(typ types.Type) { if typ == nil { return } switch t := typ.(type) { case *types.Basic: return case *types.Pointer: f.addImportsFor(t.Elem()) case *types.Map: f.addImportsFor(t.Key()) f.addImportsFor(t.Elem()) case *types.Chan: f.addImportsFor(t.Elem()) case *types.Named: if t.Obj() != nil && t.Obj().Pkg() != nil { f.Imports.Add(t.Obj().Pkg().Name(), t.Obj().Pkg().Path()) } case *types.Slice: f.addImportsFor(t.Elem()) case *types.Array: f.addImportsFor(t.Elem()) case *types.Interface: return case *types.Signature: f.addTypesForMethod(t) default: log.Printf("!!! WARNING: Missing case for type %s\n", reflect.TypeOf(typ).String()) } }
go
func (f *Fake) addImportsFor(typ types.Type) { if typ == nil { return } switch t := typ.(type) { case *types.Basic: return case *types.Pointer: f.addImportsFor(t.Elem()) case *types.Map: f.addImportsFor(t.Key()) f.addImportsFor(t.Elem()) case *types.Chan: f.addImportsFor(t.Elem()) case *types.Named: if t.Obj() != nil && t.Obj().Pkg() != nil { f.Imports.Add(t.Obj().Pkg().Name(), t.Obj().Pkg().Path()) } case *types.Slice: f.addImportsFor(t.Elem()) case *types.Array: f.addImportsFor(t.Elem()) case *types.Interface: return case *types.Signature: f.addTypesForMethod(t) default: log.Printf("!!! WARNING: Missing case for type %s\n", reflect.TypeOf(typ).String()) } }
[ "func", "(", "f", "*", "Fake", ")", "addImportsFor", "(", "typ", "types", ".", "Type", ")", "{", "if", "typ", "==", "nil", "{", "return", "\n", "}", "\n\n", "switch", "t", ":=", "typ", ".", "(", "type", ")", "{", "case", "*", "types", ".", "Basic", ":", "return", "\n", "case", "*", "types", ".", "Pointer", ":", "f", ".", "addImportsFor", "(", "t", ".", "Elem", "(", ")", ")", "\n", "case", "*", "types", ".", "Map", ":", "f", ".", "addImportsFor", "(", "t", ".", "Key", "(", ")", ")", "\n", "f", ".", "addImportsFor", "(", "t", ".", "Elem", "(", ")", ")", "\n", "case", "*", "types", ".", "Chan", ":", "f", ".", "addImportsFor", "(", "t", ".", "Elem", "(", ")", ")", "\n", "case", "*", "types", ".", "Named", ":", "if", "t", ".", "Obj", "(", ")", "!=", "nil", "&&", "t", ".", "Obj", "(", ")", ".", "Pkg", "(", ")", "!=", "nil", "{", "f", ".", "Imports", ".", "Add", "(", "t", ".", "Obj", "(", ")", ".", "Pkg", "(", ")", ".", "Name", "(", ")", ",", "t", ".", "Obj", "(", ")", ".", "Pkg", "(", ")", ".", "Path", "(", ")", ")", "\n", "}", "\n", "case", "*", "types", ".", "Slice", ":", "f", ".", "addImportsFor", "(", "t", ".", "Elem", "(", ")", ")", "\n", "case", "*", "types", ".", "Array", ":", "f", ".", "addImportsFor", "(", "t", ".", "Elem", "(", ")", ")", "\n", "case", "*", "types", ".", "Interface", ":", "return", "\n", "case", "*", "types", ".", "Signature", ":", "f", ".", "addTypesForMethod", "(", "t", ")", "\n", "default", ":", "log", ".", "Printf", "(", "\"", "\\n", "\"", ",", "reflect", ".", "TypeOf", "(", "typ", ")", ".", "String", "(", ")", ")", "\n", "}", "\n", "}" ]
// addImportsFor inspects the given type and adds imports to the fake if importable // types are found.
[ "addImportsFor", "inspects", "the", "given", "type", "and", "adds", "imports", "to", "the", "fake", "if", "importable", "types", "are", "found", "." ]
f7bde7cbdb1288611466a0d715b1bbc956519eb1
https://github.com/maxbrunsfeld/counterfeiter/blob/f7bde7cbdb1288611466a0d715b1bbc956519eb1/generator/loader.go#L100-L130
9,449
maxbrunsfeld/counterfeiter
generator/return.go
WithPrefix
func (r Returns) WithPrefix(p string) string { if len(r) == 0 { return "" } rets := []string{} for i := range r { if p == "" { rets = append(rets, unexport(r[i].Name)) } else { rets = append(rets, p+unexport(r[i].Name)) } } return strings.Join(rets, ", ") }
go
func (r Returns) WithPrefix(p string) string { if len(r) == 0 { return "" } rets := []string{} for i := range r { if p == "" { rets = append(rets, unexport(r[i].Name)) } else { rets = append(rets, p+unexport(r[i].Name)) } } return strings.Join(rets, ", ") }
[ "func", "(", "r", "Returns", ")", "WithPrefix", "(", "p", "string", ")", "string", "{", "if", "len", "(", "r", ")", "==", "0", "{", "return", "\"", "\"", "\n", "}", "\n\n", "rets", ":=", "[", "]", "string", "{", "}", "\n", "for", "i", ":=", "range", "r", "{", "if", "p", "==", "\"", "\"", "{", "rets", "=", "append", "(", "rets", ",", "unexport", "(", "r", "[", "i", "]", ".", "Name", ")", ")", "\n", "}", "else", "{", "rets", "=", "append", "(", "rets", ",", "p", "+", "unexport", "(", "r", "[", "i", "]", ".", "Name", ")", ")", "\n", "}", "\n", "}", "\n", "return", "strings", ".", "Join", "(", "rets", ",", "\"", "\"", ")", "\n", "}" ]
// WithPrefix builds a string representing the parameters returned from a // function, and adds a prefix to each.
[ "WithPrefix", "builds", "a", "string", "representing", "the", "parameters", "returned", "from", "a", "function", "and", "adds", "a", "prefix", "to", "each", "." ]
f7bde7cbdb1288611466a0d715b1bbc956519eb1
https://github.com/maxbrunsfeld/counterfeiter/blob/f7bde7cbdb1288611466a0d715b1bbc956519eb1/generator/return.go#L23-L37
9,450
maxbrunsfeld/counterfeiter
generator/return.go
AsArgs
func (r Returns) AsArgs() string { if len(r) == 0 { return "" } rets := []string{} for i := range r { rets = append(rets, r[i].Type) } return strings.Join(rets, ", ") }
go
func (r Returns) AsArgs() string { if len(r) == 0 { return "" } rets := []string{} for i := range r { rets = append(rets, r[i].Type) } return strings.Join(rets, ", ") }
[ "func", "(", "r", "Returns", ")", "AsArgs", "(", ")", "string", "{", "if", "len", "(", "r", ")", "==", "0", "{", "return", "\"", "\"", "\n", "}", "\n\n", "rets", ":=", "[", "]", "string", "{", "}", "\n", "for", "i", ":=", "range", "r", "{", "rets", "=", "append", "(", "rets", ",", "r", "[", "i", "]", ".", "Type", ")", "\n", "}", "\n", "return", "strings", ".", "Join", "(", "rets", ",", "\"", "\"", ")", "\n", "}" ]
// AsArgs builds a string representing the arguments passed to a function.
[ "AsArgs", "builds", "a", "string", "representing", "the", "arguments", "passed", "to", "a", "function", "." ]
f7bde7cbdb1288611466a0d715b1bbc956519eb1
https://github.com/maxbrunsfeld/counterfeiter/blob/f7bde7cbdb1288611466a0d715b1bbc956519eb1/generator/return.go#L40-L50
9,451
maxbrunsfeld/counterfeiter
generator/return.go
AsNamedArgsWithTypes
func (r Returns) AsNamedArgsWithTypes() string { if len(r) == 0 { return "" } rets := []string{} for i := range r { rets = append(rets, unexport(r[i].Name)+" "+r[i].Type) } return strings.Join(rets, ", ") }
go
func (r Returns) AsNamedArgsWithTypes() string { if len(r) == 0 { return "" } rets := []string{} for i := range r { rets = append(rets, unexport(r[i].Name)+" "+r[i].Type) } return strings.Join(rets, ", ") }
[ "func", "(", "r", "Returns", ")", "AsNamedArgsWithTypes", "(", ")", "string", "{", "if", "len", "(", "r", ")", "==", "0", "{", "return", "\"", "\"", "\n", "}", "\n\n", "rets", ":=", "[", "]", "string", "{", "}", "\n", "for", "i", ":=", "range", "r", "{", "rets", "=", "append", "(", "rets", ",", "unexport", "(", "r", "[", "i", "]", ".", "Name", ")", "+", "\"", "\"", "+", "r", "[", "i", "]", ".", "Type", ")", "\n", "}", "\n", "return", "strings", ".", "Join", "(", "rets", ",", "\"", "\"", ")", "\n", "}" ]
// AsNamedArgsWithTypes builds a string representing a function's named // arguments, with associated types.
[ "AsNamedArgsWithTypes", "builds", "a", "string", "representing", "a", "function", "s", "named", "arguments", "with", "associated", "types", "." ]
f7bde7cbdb1288611466a0d715b1bbc956519eb1
https://github.com/maxbrunsfeld/counterfeiter/blob/f7bde7cbdb1288611466a0d715b1bbc956519eb1/generator/return.go#L54-L64
9,452
maxbrunsfeld/counterfeiter
generator/return.go
AsNamedArgs
func (r Returns) AsNamedArgs() string { if len(r) == 0 { return "" } rets := []string{} for i := range r { rets = append(rets, unexport(r[i].Name)) } return strings.Join(rets, ", ") }
go
func (r Returns) AsNamedArgs() string { if len(r) == 0 { return "" } rets := []string{} for i := range r { rets = append(rets, unexport(r[i].Name)) } return strings.Join(rets, ", ") }
[ "func", "(", "r", "Returns", ")", "AsNamedArgs", "(", ")", "string", "{", "if", "len", "(", "r", ")", "==", "0", "{", "return", "\"", "\"", "\n", "}", "\n\n", "rets", ":=", "[", "]", "string", "{", "}", "\n", "for", "i", ":=", "range", "r", "{", "rets", "=", "append", "(", "rets", ",", "unexport", "(", "r", "[", "i", "]", ".", "Name", ")", ")", "\n", "}", "\n", "return", "strings", ".", "Join", "(", "rets", ",", "\"", "\"", ")", "\n", "}" ]
// AsNamedArgs builds a string representing a function's named arguments.
[ "AsNamedArgs", "builds", "a", "string", "representing", "a", "function", "s", "named", "arguments", "." ]
f7bde7cbdb1288611466a0d715b1bbc956519eb1
https://github.com/maxbrunsfeld/counterfeiter/blob/f7bde7cbdb1288611466a0d715b1bbc956519eb1/generator/return.go#L67-L77
9,453
maxbrunsfeld/counterfeiter
generator/return.go
AsReturnSignature
func (r Returns) AsReturnSignature() string { if len(r) == 0 { return "" } if len(r) == 1 { return r[0].Type } result := "(" for i := range r { result = result + r[i].Type if i < len(r) { result = result + ", " } } result = result + ")" return result }
go
func (r Returns) AsReturnSignature() string { if len(r) == 0 { return "" } if len(r) == 1 { return r[0].Type } result := "(" for i := range r { result = result + r[i].Type if i < len(r) { result = result + ", " } } result = result + ")" return result }
[ "func", "(", "r", "Returns", ")", "AsReturnSignature", "(", ")", "string", "{", "if", "len", "(", "r", ")", "==", "0", "{", "return", "\"", "\"", "\n", "}", "\n", "if", "len", "(", "r", ")", "==", "1", "{", "return", "r", "[", "0", "]", ".", "Type", "\n", "}", "\n", "result", ":=", "\"", "\"", "\n", "for", "i", ":=", "range", "r", "{", "result", "=", "result", "+", "r", "[", "i", "]", ".", "Type", "\n", "if", "i", "<", "len", "(", "r", ")", "{", "result", "=", "result", "+", "\"", "\"", "\n", "}", "\n", "}", "\n", "result", "=", "result", "+", "\"", "\"", "\n", "return", "result", "\n", "}" ]
// AsReturnSignature builds a string representing signature for the returns of // a function.
[ "AsReturnSignature", "builds", "a", "string", "representing", "signature", "for", "the", "returns", "of", "a", "function", "." ]
f7bde7cbdb1288611466a0d715b1bbc956519eb1
https://github.com/maxbrunsfeld/counterfeiter/blob/f7bde7cbdb1288611466a0d715b1bbc956519eb1/generator/return.go#L81-L97
9,454
libp2p/go-libp2p-peerstore
pstoremem/keybook.go
NewKeyBook
func NewKeyBook() pstore.KeyBook { return &memoryKeyBook{ pks: map[peer.ID]ic.PubKey{}, sks: map[peer.ID]ic.PrivKey{}, } }
go
func NewKeyBook() pstore.KeyBook { return &memoryKeyBook{ pks: map[peer.ID]ic.PubKey{}, sks: map[peer.ID]ic.PrivKey{}, } }
[ "func", "NewKeyBook", "(", ")", "pstore", ".", "KeyBook", "{", "return", "&", "memoryKeyBook", "{", "pks", ":", "map", "[", "peer", ".", "ID", "]", "ic", ".", "PubKey", "{", "}", ",", "sks", ":", "map", "[", "peer", ".", "ID", "]", "ic", ".", "PrivKey", "{", "}", ",", "}", "\n", "}" ]
// noop new, but in the future we may want to do some init work.
[ "noop", "new", "but", "in", "the", "future", "we", "may", "want", "to", "do", "some", "init", "work", "." ]
96639ef5f4c339131552acf2e283d2d041602798
https://github.com/libp2p/go-libp2p-peerstore/blob/96639ef5f4c339131552acf2e283d2d041602798/pstoremem/keybook.go#L22-L27
9,455
libp2p/go-libp2p-peerstore
pstoreds/peerstore.go
NewPeerstore
func NewPeerstore(ctx context.Context, store ds.Batching, opts Options) (pstore.Peerstore, error) { addrBook, err := NewAddrBook(ctx, store, opts) if err != nil { return nil, err } keyBook, err := NewKeyBook(ctx, store, opts) if err != nil { return nil, err } peerMetadata, err := NewPeerMetadata(ctx, store, opts) if err != nil { return nil, err } ps := pstore.NewPeerstore(keyBook, addrBook, peerMetadata) return ps, nil }
go
func NewPeerstore(ctx context.Context, store ds.Batching, opts Options) (pstore.Peerstore, error) { addrBook, err := NewAddrBook(ctx, store, opts) if err != nil { return nil, err } keyBook, err := NewKeyBook(ctx, store, opts) if err != nil { return nil, err } peerMetadata, err := NewPeerMetadata(ctx, store, opts) if err != nil { return nil, err } ps := pstore.NewPeerstore(keyBook, addrBook, peerMetadata) return ps, nil }
[ "func", "NewPeerstore", "(", "ctx", "context", ".", "Context", ",", "store", "ds", ".", "Batching", ",", "opts", "Options", ")", "(", "pstore", ".", "Peerstore", ",", "error", ")", "{", "addrBook", ",", "err", ":=", "NewAddrBook", "(", "ctx", ",", "store", ",", "opts", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "keyBook", ",", "err", ":=", "NewKeyBook", "(", "ctx", ",", "store", ",", "opts", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "peerMetadata", ",", "err", ":=", "NewPeerMetadata", "(", "ctx", ",", "store", ",", "opts", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "ps", ":=", "pstore", ".", "NewPeerstore", "(", "keyBook", ",", "addrBook", ",", "peerMetadata", ")", "\n", "return", "ps", ",", "nil", "\n", "}" ]
// NewPeerstore creates a peerstore backed by the provided persistent datastore.
[ "NewPeerstore", "creates", "a", "peerstore", "backed", "by", "the", "provided", "persistent", "datastore", "." ]
96639ef5f4c339131552acf2e283d2d041602798
https://github.com/libp2p/go-libp2p-peerstore/blob/96639ef5f4c339131552acf2e283d2d041602798/pstoreds/peerstore.go#L50-L68
9,456
libp2p/go-libp2p-peerstore
pstoreds/peerstore.go
uniquePeerIds
func uniquePeerIds(ds ds.Datastore, prefix ds.Key, extractor func(result query.Result) string) (peer.IDSlice, error) { var ( q = query.Query{Prefix: prefix.String(), KeysOnly: true} results query.Results err error ) if results, err = ds.Query(q); err != nil { log.Error(err) return nil, err } defer results.Close() idset := make(map[string]struct{}) for result := range results.Next() { k := extractor(result) idset[k] = struct{}{} } if len(idset) == 0 { return peer.IDSlice{}, nil } ids := make(peer.IDSlice, 0, len(idset)) for id := range idset { pid, _ := base32.RawStdEncoding.DecodeString(id) id, _ := peer.IDFromBytes(pid) ids = append(ids, id) } return ids, nil }
go
func uniquePeerIds(ds ds.Datastore, prefix ds.Key, extractor func(result query.Result) string) (peer.IDSlice, error) { var ( q = query.Query{Prefix: prefix.String(), KeysOnly: true} results query.Results err error ) if results, err = ds.Query(q); err != nil { log.Error(err) return nil, err } defer results.Close() idset := make(map[string]struct{}) for result := range results.Next() { k := extractor(result) idset[k] = struct{}{} } if len(idset) == 0 { return peer.IDSlice{}, nil } ids := make(peer.IDSlice, 0, len(idset)) for id := range idset { pid, _ := base32.RawStdEncoding.DecodeString(id) id, _ := peer.IDFromBytes(pid) ids = append(ids, id) } return ids, nil }
[ "func", "uniquePeerIds", "(", "ds", "ds", ".", "Datastore", ",", "prefix", "ds", ".", "Key", ",", "extractor", "func", "(", "result", "query", ".", "Result", ")", "string", ")", "(", "peer", ".", "IDSlice", ",", "error", ")", "{", "var", "(", "q", "=", "query", ".", "Query", "{", "Prefix", ":", "prefix", ".", "String", "(", ")", ",", "KeysOnly", ":", "true", "}", "\n", "results", "query", ".", "Results", "\n", "err", "error", "\n", ")", "\n\n", "if", "results", ",", "err", "=", "ds", ".", "Query", "(", "q", ")", ";", "err", "!=", "nil", "{", "log", ".", "Error", "(", "err", ")", "\n", "return", "nil", ",", "err", "\n", "}", "\n\n", "defer", "results", ".", "Close", "(", ")", "\n\n", "idset", ":=", "make", "(", "map", "[", "string", "]", "struct", "{", "}", ")", "\n", "for", "result", ":=", "range", "results", ".", "Next", "(", ")", "{", "k", ":=", "extractor", "(", "result", ")", "\n", "idset", "[", "k", "]", "=", "struct", "{", "}", "{", "}", "\n", "}", "\n\n", "if", "len", "(", "idset", ")", "==", "0", "{", "return", "peer", ".", "IDSlice", "{", "}", ",", "nil", "\n", "}", "\n\n", "ids", ":=", "make", "(", "peer", ".", "IDSlice", ",", "0", ",", "len", "(", "idset", ")", ")", "\n", "for", "id", ":=", "range", "idset", "{", "pid", ",", "_", ":=", "base32", ".", "RawStdEncoding", ".", "DecodeString", "(", "id", ")", "\n", "id", ",", "_", ":=", "peer", ".", "IDFromBytes", "(", "pid", ")", "\n", "ids", "=", "append", "(", "ids", ",", "id", ")", "\n", "}", "\n", "return", "ids", ",", "nil", "\n", "}" ]
// uniquePeerIds extracts and returns unique peer IDs from database keys.
[ "uniquePeerIds", "extracts", "and", "returns", "unique", "peer", "IDs", "from", "database", "keys", "." ]
96639ef5f4c339131552acf2e283d2d041602798
https://github.com/libp2p/go-libp2p-peerstore/blob/96639ef5f4c339131552acf2e283d2d041602798/pstoreds/peerstore.go#L71-L102
9,457
libp2p/go-libp2p-peerstore
metrics.go
RecordLatency
func (m *metrics) RecordLatency(p peer.ID, next time.Duration) { nextf := float64(next) s := LatencyEWMASmoothing if s > 1 || s < 0 { s = 0.1 // ignore the knob. it's broken. look, it jiggles. } m.latmu.Lock() ewma, found := m.latmap[p] ewmaf := float64(ewma) if !found { m.latmap[p] = next // when no data, just take it as the mean. } else { nextf = ((1.0 - s) * ewmaf) + (s * nextf) m.latmap[p] = time.Duration(nextf) } m.latmu.Unlock() }
go
func (m *metrics) RecordLatency(p peer.ID, next time.Duration) { nextf := float64(next) s := LatencyEWMASmoothing if s > 1 || s < 0 { s = 0.1 // ignore the knob. it's broken. look, it jiggles. } m.latmu.Lock() ewma, found := m.latmap[p] ewmaf := float64(ewma) if !found { m.latmap[p] = next // when no data, just take it as the mean. } else { nextf = ((1.0 - s) * ewmaf) + (s * nextf) m.latmap[p] = time.Duration(nextf) } m.latmu.Unlock() }
[ "func", "(", "m", "*", "metrics", ")", "RecordLatency", "(", "p", "peer", ".", "ID", ",", "next", "time", ".", "Duration", ")", "{", "nextf", ":=", "float64", "(", "next", ")", "\n", "s", ":=", "LatencyEWMASmoothing", "\n", "if", "s", ">", "1", "||", "s", "<", "0", "{", "s", "=", "0.1", "// ignore the knob. it's broken. look, it jiggles.", "\n", "}", "\n\n", "m", ".", "latmu", ".", "Lock", "(", ")", "\n", "ewma", ",", "found", ":=", "m", ".", "latmap", "[", "p", "]", "\n", "ewmaf", ":=", "float64", "(", "ewma", ")", "\n", "if", "!", "found", "{", "m", ".", "latmap", "[", "p", "]", "=", "next", "// when no data, just take it as the mean.", "\n", "}", "else", "{", "nextf", "=", "(", "(", "1.0", "-", "s", ")", "*", "ewmaf", ")", "+", "(", "s", "*", "nextf", ")", "\n", "m", ".", "latmap", "[", "p", "]", "=", "time", ".", "Duration", "(", "nextf", ")", "\n", "}", "\n", "m", ".", "latmu", ".", "Unlock", "(", ")", "\n", "}" ]
// RecordLatency records a new latency measurement
[ "RecordLatency", "records", "a", "new", "latency", "measurement" ]
96639ef5f4c339131552acf2e283d2d041602798
https://github.com/libp2p/go-libp2p-peerstore/blob/96639ef5f4c339131552acf2e283d2d041602798/metrics.go#L39-L56
9,458
libp2p/go-libp2p-peerstore
metrics.go
LatencyEWMA
func (m *metrics) LatencyEWMA(p peer.ID) time.Duration { m.latmu.RLock() lat := m.latmap[p] m.latmu.RUnlock() return time.Duration(lat) }
go
func (m *metrics) LatencyEWMA(p peer.ID) time.Duration { m.latmu.RLock() lat := m.latmap[p] m.latmu.RUnlock() return time.Duration(lat) }
[ "func", "(", "m", "*", "metrics", ")", "LatencyEWMA", "(", "p", "peer", ".", "ID", ")", "time", ".", "Duration", "{", "m", ".", "latmu", ".", "RLock", "(", ")", "\n", "lat", ":=", "m", ".", "latmap", "[", "p", "]", "\n", "m", ".", "latmu", ".", "RUnlock", "(", ")", "\n", "return", "time", ".", "Duration", "(", "lat", ")", "\n", "}" ]
// LatencyEWMA returns an exponentially-weighted moving avg. // of all measurements of a peer's latency.
[ "LatencyEWMA", "returns", "an", "exponentially", "-", "weighted", "moving", "avg", ".", "of", "all", "measurements", "of", "a", "peer", "s", "latency", "." ]
96639ef5f4c339131552acf2e283d2d041602798
https://github.com/libp2p/go-libp2p-peerstore/blob/96639ef5f4c339131552acf2e283d2d041602798/metrics.go#L60-L65
9,459
libp2p/go-libp2p-peerstore
pb/custom.go
NewPopulatedProtoAddr
func NewPopulatedProtoAddr(r randyPstore) *ProtoAddr { a, _ := ma.NewMultiaddr("/ip4/123.123.123.123/tcp/7001") return &ProtoAddr{Multiaddr: a} }
go
func NewPopulatedProtoAddr(r randyPstore) *ProtoAddr { a, _ := ma.NewMultiaddr("/ip4/123.123.123.123/tcp/7001") return &ProtoAddr{Multiaddr: a} }
[ "func", "NewPopulatedProtoAddr", "(", "r", "randyPstore", ")", "*", "ProtoAddr", "{", "a", ",", "_", ":=", "ma", ".", "NewMultiaddr", "(", "\"", "\"", ")", "\n", "return", "&", "ProtoAddr", "{", "Multiaddr", ":", "a", "}", "\n", "}" ]
// NewPopulatedProtoAddr generates a populated instance of the custom gogo type ProtoAddr. // It is required by gogo-generated tests.
[ "NewPopulatedProtoAddr", "generates", "a", "populated", "instance", "of", "the", "custom", "gogo", "type", "ProtoAddr", ".", "It", "is", "required", "by", "gogo", "-", "generated", "tests", "." ]
96639ef5f4c339131552acf2e283d2d041602798
https://github.com/libp2p/go-libp2p-peerstore/blob/96639ef5f4c339131552acf2e283d2d041602798/pb/custom.go#L100-L103
9,460
libp2p/go-libp2p-peerstore
pb/custom.go
NewPopulatedProtoPeerID
func NewPopulatedProtoPeerID(r randyPstore) *ProtoPeerID { id, _ := pt.RandPeerID() return &ProtoPeerID{ID: id} }
go
func NewPopulatedProtoPeerID(r randyPstore) *ProtoPeerID { id, _ := pt.RandPeerID() return &ProtoPeerID{ID: id} }
[ "func", "NewPopulatedProtoPeerID", "(", "r", "randyPstore", ")", "*", "ProtoPeerID", "{", "id", ",", "_", ":=", "pt", ".", "RandPeerID", "(", ")", "\n", "return", "&", "ProtoPeerID", "{", "ID", ":", "id", "}", "\n", "}" ]
// NewPopulatedProtoPeerID generates a populated instance of the custom gogo type ProtoPeerID. // It is required by gogo-generated tests.
[ "NewPopulatedProtoPeerID", "generates", "a", "populated", "instance", "of", "the", "custom", "gogo", "type", "ProtoPeerID", ".", "It", "is", "required", "by", "gogo", "-", "generated", "tests", "." ]
96639ef5f4c339131552acf2e283d2d041602798
https://github.com/libp2p/go-libp2p-peerstore/blob/96639ef5f4c339131552acf2e283d2d041602798/pb/custom.go#L107-L110
9,461
libp2p/go-libp2p-peerstore
pstoremem/addr_book.go
background
func (mab *memoryAddrBook) background() { ticker := time.NewTicker(1 * time.Hour) defer ticker.Stop() for { select { case <-ticker.C: mab.gc() case <-mab.ctx.Done(): return } } }
go
func (mab *memoryAddrBook) background() { ticker := time.NewTicker(1 * time.Hour) defer ticker.Stop() for { select { case <-ticker.C: mab.gc() case <-mab.ctx.Done(): return } } }
[ "func", "(", "mab", "*", "memoryAddrBook", ")", "background", "(", ")", "{", "ticker", ":=", "time", ".", "NewTicker", "(", "1", "*", "time", ".", "Hour", ")", "\n", "defer", "ticker", ".", "Stop", "(", ")", "\n\n", "for", "{", "select", "{", "case", "<-", "ticker", ".", "C", ":", "mab", ".", "gc", "(", ")", "\n\n", "case", "<-", "mab", ".", "ctx", ".", "Done", "(", ")", ":", "return", "\n", "}", "\n", "}", "\n", "}" ]
// background periodically schedules a gc
[ "background", "periodically", "schedules", "a", "gc" ]
96639ef5f4c339131552acf2e283d2d041602798
https://github.com/libp2p/go-libp2p-peerstore/blob/96639ef5f4c339131552acf2e283d2d041602798/pstoremem/addr_book.go#L60-L73
9,462
libp2p/go-libp2p-peerstore
pstoremem/addr_book.go
gc
func (mab *memoryAddrBook) gc() { mab.addrmu.Lock() defer mab.addrmu.Unlock() now := time.Now() for p, amap := range mab.addrs { for k, addr := range amap { if addr.ExpiredBy(now) { delete(amap, k) } } if len(amap) == 0 { delete(mab.addrs, p) } } }
go
func (mab *memoryAddrBook) gc() { mab.addrmu.Lock() defer mab.addrmu.Unlock() now := time.Now() for p, amap := range mab.addrs { for k, addr := range amap { if addr.ExpiredBy(now) { delete(amap, k) } } if len(amap) == 0 { delete(mab.addrs, p) } } }
[ "func", "(", "mab", "*", "memoryAddrBook", ")", "gc", "(", ")", "{", "mab", ".", "addrmu", ".", "Lock", "(", ")", "\n", "defer", "mab", ".", "addrmu", ".", "Unlock", "(", ")", "\n\n", "now", ":=", "time", ".", "Now", "(", ")", "\n", "for", "p", ",", "amap", ":=", "range", "mab", ".", "addrs", "{", "for", "k", ",", "addr", ":=", "range", "amap", "{", "if", "addr", ".", "ExpiredBy", "(", "now", ")", "{", "delete", "(", "amap", ",", "k", ")", "\n", "}", "\n", "}", "\n", "if", "len", "(", "amap", ")", "==", "0", "{", "delete", "(", "mab", ".", "addrs", ",", "p", ")", "\n", "}", "\n", "}", "\n", "}" ]
// gc garbage collects the in-memory address book.
[ "gc", "garbage", "collects", "the", "in", "-", "memory", "address", "book", "." ]
96639ef5f4c339131552acf2e283d2d041602798
https://github.com/libp2p/go-libp2p-peerstore/blob/96639ef5f4c339131552acf2e283d2d041602798/pstoremem/addr_book.go#L81-L96
9,463
libp2p/go-libp2p-peerstore
pstoremem/addr_book.go
UpdateAddrs
func (mab *memoryAddrBook) UpdateAddrs(p peer.ID, oldTTL time.Duration, newTTL time.Duration) { mab.addrmu.Lock() defer mab.addrmu.Unlock() amap, found := mab.addrs[p] if !found { return } exp := time.Now().Add(newTTL) for k, addr := range amap { if oldTTL == addr.TTL { addr.TTL = newTTL addr.Expires = exp amap[k] = addr } } }
go
func (mab *memoryAddrBook) UpdateAddrs(p peer.ID, oldTTL time.Duration, newTTL time.Duration) { mab.addrmu.Lock() defer mab.addrmu.Unlock() amap, found := mab.addrs[p] if !found { return } exp := time.Now().Add(newTTL) for k, addr := range amap { if oldTTL == addr.TTL { addr.TTL = newTTL addr.Expires = exp amap[k] = addr } } }
[ "func", "(", "mab", "*", "memoryAddrBook", ")", "UpdateAddrs", "(", "p", "peer", ".", "ID", ",", "oldTTL", "time", ".", "Duration", ",", "newTTL", "time", ".", "Duration", ")", "{", "mab", ".", "addrmu", ".", "Lock", "(", ")", "\n", "defer", "mab", ".", "addrmu", ".", "Unlock", "(", ")", "\n\n", "amap", ",", "found", ":=", "mab", ".", "addrs", "[", "p", "]", "\n", "if", "!", "found", "{", "return", "\n", "}", "\n\n", "exp", ":=", "time", ".", "Now", "(", ")", ".", "Add", "(", "newTTL", ")", "\n", "for", "k", ",", "addr", ":=", "range", "amap", "{", "if", "oldTTL", "==", "addr", ".", "TTL", "{", "addr", ".", "TTL", "=", "newTTL", "\n", "addr", ".", "Expires", "=", "exp", "\n", "amap", "[", "k", "]", "=", "addr", "\n", "}", "\n", "}", "\n", "}" ]
// UpdateAddrs updates the addresses associated with the given peer that have // the given oldTTL to have the given newTTL.
[ "UpdateAddrs", "updates", "the", "addresses", "associated", "with", "the", "given", "peer", "that", "have", "the", "given", "oldTTL", "to", "have", "the", "given", "newTTL", "." ]
96639ef5f4c339131552acf2e283d2d041602798
https://github.com/libp2p/go-libp2p-peerstore/blob/96639ef5f4c339131552acf2e283d2d041602798/pstoremem/addr_book.go#L185-L202
9,464
libp2p/go-libp2p-peerstore
pstoremem/addr_book.go
ClearAddrs
func (mab *memoryAddrBook) ClearAddrs(p peer.ID) { mab.addrmu.Lock() defer mab.addrmu.Unlock() delete(mab.addrs, p) }
go
func (mab *memoryAddrBook) ClearAddrs(p peer.ID) { mab.addrmu.Lock() defer mab.addrmu.Unlock() delete(mab.addrs, p) }
[ "func", "(", "mab", "*", "memoryAddrBook", ")", "ClearAddrs", "(", "p", "peer", ".", "ID", ")", "{", "mab", ".", "addrmu", ".", "Lock", "(", ")", "\n", "defer", "mab", ".", "addrmu", ".", "Unlock", "(", ")", "\n\n", "delete", "(", "mab", ".", "addrs", ",", "p", ")", "\n", "}" ]
// ClearAddrs removes all previously stored addresses
[ "ClearAddrs", "removes", "all", "previously", "stored", "addresses" ]
96639ef5f4c339131552acf2e283d2d041602798
https://github.com/libp2p/go-libp2p-peerstore/blob/96639ef5f4c339131552acf2e283d2d041602798/pstoremem/addr_book.go#L226-L231
9,465
libp2p/go-libp2p-peerstore
pstoremem/addr_book.go
removeSub
func (mgr *AddrSubManager) removeSub(p peer.ID, s *addrSub) { mgr.mu.Lock() defer mgr.mu.Unlock() subs := mgr.subs[p] if len(subs) == 1 { if subs[0] != s { return } delete(mgr.subs, p) return } for i, v := range subs { if v == s { subs[i] = subs[len(subs)-1] subs[len(subs)-1] = nil mgr.subs[p] = subs[:len(subs)-1] return } } }
go
func (mgr *AddrSubManager) removeSub(p peer.ID, s *addrSub) { mgr.mu.Lock() defer mgr.mu.Unlock() subs := mgr.subs[p] if len(subs) == 1 { if subs[0] != s { return } delete(mgr.subs, p) return } for i, v := range subs { if v == s { subs[i] = subs[len(subs)-1] subs[len(subs)-1] = nil mgr.subs[p] = subs[:len(subs)-1] return } } }
[ "func", "(", "mgr", "*", "AddrSubManager", ")", "removeSub", "(", "p", "peer", ".", "ID", ",", "s", "*", "addrSub", ")", "{", "mgr", ".", "mu", ".", "Lock", "(", ")", "\n", "defer", "mgr", ".", "mu", ".", "Unlock", "(", ")", "\n\n", "subs", ":=", "mgr", ".", "subs", "[", "p", "]", "\n", "if", "len", "(", "subs", ")", "==", "1", "{", "if", "subs", "[", "0", "]", "!=", "s", "{", "return", "\n", "}", "\n", "delete", "(", "mgr", ".", "subs", ",", "p", ")", "\n", "return", "\n", "}", "\n\n", "for", "i", ",", "v", ":=", "range", "subs", "{", "if", "v", "==", "s", "{", "subs", "[", "i", "]", "=", "subs", "[", "len", "(", "subs", ")", "-", "1", "]", "\n", "subs", "[", "len", "(", "subs", ")", "-", "1", "]", "=", "nil", "\n", "mgr", ".", "subs", "[", "p", "]", "=", "subs", "[", ":", "len", "(", "subs", ")", "-", "1", "]", "\n", "return", "\n", "}", "\n", "}", "\n", "}" ]
// Used internally by the address stream coroutine to remove a subscription // from the manager.
[ "Used", "internally", "by", "the", "address", "stream", "coroutine", "to", "remove", "a", "subscription", "from", "the", "manager", "." ]
96639ef5f4c339131552acf2e283d2d041602798
https://github.com/libp2p/go-libp2p-peerstore/blob/96639ef5f4c339131552acf2e283d2d041602798/pstoremem/addr_book.go#L278-L299
9,466
libp2p/go-libp2p-peerstore
pstoremem/addr_book.go
BroadcastAddr
func (mgr *AddrSubManager) BroadcastAddr(p peer.ID, addr ma.Multiaddr) { mgr.mu.RLock() defer mgr.mu.RUnlock() if subs, ok := mgr.subs[p]; ok { for _, sub := range subs { sub.pubAddr(addr) } } }
go
func (mgr *AddrSubManager) BroadcastAddr(p peer.ID, addr ma.Multiaddr) { mgr.mu.RLock() defer mgr.mu.RUnlock() if subs, ok := mgr.subs[p]; ok { for _, sub := range subs { sub.pubAddr(addr) } } }
[ "func", "(", "mgr", "*", "AddrSubManager", ")", "BroadcastAddr", "(", "p", "peer", ".", "ID", ",", "addr", "ma", ".", "Multiaddr", ")", "{", "mgr", ".", "mu", ".", "RLock", "(", ")", "\n", "defer", "mgr", ".", "mu", ".", "RUnlock", "(", ")", "\n\n", "if", "subs", ",", "ok", ":=", "mgr", ".", "subs", "[", "p", "]", ";", "ok", "{", "for", "_", ",", "sub", ":=", "range", "subs", "{", "sub", ".", "pubAddr", "(", "addr", ")", "\n", "}", "\n", "}", "\n", "}" ]
// BroadcastAddr broadcasts a new address to all subscribed streams.
[ "BroadcastAddr", "broadcasts", "a", "new", "address", "to", "all", "subscribed", "streams", "." ]
96639ef5f4c339131552acf2e283d2d041602798
https://github.com/libp2p/go-libp2p-peerstore/blob/96639ef5f4c339131552acf2e283d2d041602798/pstoremem/addr_book.go#L302-L311
9,467
libp2p/go-libp2p-peerstore
pstoremem/addr_book.go
AddrStream
func (mgr *AddrSubManager) AddrStream(ctx context.Context, p peer.ID, initial []ma.Multiaddr) <-chan ma.Multiaddr { sub := &addrSub{pubch: make(chan ma.Multiaddr), ctx: ctx} out := make(chan ma.Multiaddr) mgr.mu.Lock() if _, ok := mgr.subs[p]; ok { mgr.subs[p] = append(mgr.subs[p], sub) } else { mgr.subs[p] = []*addrSub{sub} } mgr.mu.Unlock() sort.Sort(addr.AddrList(initial)) go func(buffer []ma.Multiaddr) { defer close(out) sent := make(map[string]bool, len(buffer)) var outch chan ma.Multiaddr for _, a := range buffer { sent[string(a.Bytes())] = true } var next ma.Multiaddr if len(buffer) > 0 { next = buffer[0] buffer = buffer[1:] outch = out } for { select { case outch <- next: if len(buffer) > 0 { next = buffer[0] buffer = buffer[1:] } else { outch = nil next = nil } case naddr := <-sub.pubch: if sent[string(naddr.Bytes())] { continue } sent[string(naddr.Bytes())] = true if next == nil { next = naddr outch = out } else { buffer = append(buffer, naddr) } case <-ctx.Done(): mgr.removeSub(p, sub) return } } }(initial) return out }
go
func (mgr *AddrSubManager) AddrStream(ctx context.Context, p peer.ID, initial []ma.Multiaddr) <-chan ma.Multiaddr { sub := &addrSub{pubch: make(chan ma.Multiaddr), ctx: ctx} out := make(chan ma.Multiaddr) mgr.mu.Lock() if _, ok := mgr.subs[p]; ok { mgr.subs[p] = append(mgr.subs[p], sub) } else { mgr.subs[p] = []*addrSub{sub} } mgr.mu.Unlock() sort.Sort(addr.AddrList(initial)) go func(buffer []ma.Multiaddr) { defer close(out) sent := make(map[string]bool, len(buffer)) var outch chan ma.Multiaddr for _, a := range buffer { sent[string(a.Bytes())] = true } var next ma.Multiaddr if len(buffer) > 0 { next = buffer[0] buffer = buffer[1:] outch = out } for { select { case outch <- next: if len(buffer) > 0 { next = buffer[0] buffer = buffer[1:] } else { outch = nil next = nil } case naddr := <-sub.pubch: if sent[string(naddr.Bytes())] { continue } sent[string(naddr.Bytes())] = true if next == nil { next = naddr outch = out } else { buffer = append(buffer, naddr) } case <-ctx.Done(): mgr.removeSub(p, sub) return } } }(initial) return out }
[ "func", "(", "mgr", "*", "AddrSubManager", ")", "AddrStream", "(", "ctx", "context", ".", "Context", ",", "p", "peer", ".", "ID", ",", "initial", "[", "]", "ma", ".", "Multiaddr", ")", "<-", "chan", "ma", ".", "Multiaddr", "{", "sub", ":=", "&", "addrSub", "{", "pubch", ":", "make", "(", "chan", "ma", ".", "Multiaddr", ")", ",", "ctx", ":", "ctx", "}", "\n", "out", ":=", "make", "(", "chan", "ma", ".", "Multiaddr", ")", "\n\n", "mgr", ".", "mu", ".", "Lock", "(", ")", "\n", "if", "_", ",", "ok", ":=", "mgr", ".", "subs", "[", "p", "]", ";", "ok", "{", "mgr", ".", "subs", "[", "p", "]", "=", "append", "(", "mgr", ".", "subs", "[", "p", "]", ",", "sub", ")", "\n", "}", "else", "{", "mgr", ".", "subs", "[", "p", "]", "=", "[", "]", "*", "addrSub", "{", "sub", "}", "\n", "}", "\n", "mgr", ".", "mu", ".", "Unlock", "(", ")", "\n\n", "sort", ".", "Sort", "(", "addr", ".", "AddrList", "(", "initial", ")", ")", "\n\n", "go", "func", "(", "buffer", "[", "]", "ma", ".", "Multiaddr", ")", "{", "defer", "close", "(", "out", ")", "\n\n", "sent", ":=", "make", "(", "map", "[", "string", "]", "bool", ",", "len", "(", "buffer", ")", ")", "\n", "var", "outch", "chan", "ma", ".", "Multiaddr", "\n\n", "for", "_", ",", "a", ":=", "range", "buffer", "{", "sent", "[", "string", "(", "a", ".", "Bytes", "(", ")", ")", "]", "=", "true", "\n", "}", "\n\n", "var", "next", "ma", ".", "Multiaddr", "\n", "if", "len", "(", "buffer", ")", ">", "0", "{", "next", "=", "buffer", "[", "0", "]", "\n", "buffer", "=", "buffer", "[", "1", ":", "]", "\n", "outch", "=", "out", "\n", "}", "\n\n", "for", "{", "select", "{", "case", "outch", "<-", "next", ":", "if", "len", "(", "buffer", ")", ">", "0", "{", "next", "=", "buffer", "[", "0", "]", "\n", "buffer", "=", "buffer", "[", "1", ":", "]", "\n", "}", "else", "{", "outch", "=", "nil", "\n", "next", "=", "nil", "\n", "}", "\n", "case", "naddr", ":=", "<-", "sub", ".", "pubch", ":", "if", "sent", "[", "string", "(", "naddr", ".", "Bytes", "(", ")", ")", "]", "{", "continue", "\n", "}", "\n\n", "sent", "[", "string", "(", "naddr", ".", "Bytes", "(", ")", ")", "]", "=", "true", "\n", "if", "next", "==", "nil", "{", "next", "=", "naddr", "\n", "outch", "=", "out", "\n", "}", "else", "{", "buffer", "=", "append", "(", "buffer", ",", "naddr", ")", "\n", "}", "\n", "case", "<-", "ctx", ".", "Done", "(", ")", ":", "mgr", ".", "removeSub", "(", "p", ",", "sub", ")", "\n", "return", "\n", "}", "\n", "}", "\n\n", "}", "(", "initial", ")", "\n\n", "return", "out", "\n", "}" ]
// AddrStream creates a new subscription for a given peer ID, pre-populating the // channel with any addresses we might already have on file.
[ "AddrStream", "creates", "a", "new", "subscription", "for", "a", "given", "peer", "ID", "pre", "-", "populating", "the", "channel", "with", "any", "addresses", "we", "might", "already", "have", "on", "file", "." ]
96639ef5f4c339131552acf2e283d2d041602798
https://github.com/libp2p/go-libp2p-peerstore/blob/96639ef5f4c339131552acf2e283d2d041602798/pstoremem/addr_book.go#L315-L377
9,468
libp2p/go-libp2p-peerstore
peerstore.go
NewPeerstore
func NewPeerstore(kb KeyBook, ab AddrBook, md PeerMetadata) Peerstore { return &peerstore{ KeyBook: kb, AddrBook: ab, PeerMetadata: md, Metrics: NewMetrics(), internedProtocols: make(map[string]string), } }
go
func NewPeerstore(kb KeyBook, ab AddrBook, md PeerMetadata) Peerstore { return &peerstore{ KeyBook: kb, AddrBook: ab, PeerMetadata: md, Metrics: NewMetrics(), internedProtocols: make(map[string]string), } }
[ "func", "NewPeerstore", "(", "kb", "KeyBook", ",", "ab", "AddrBook", ",", "md", "PeerMetadata", ")", "Peerstore", "{", "return", "&", "peerstore", "{", "KeyBook", ":", "kb", ",", "AddrBook", ":", "ab", ",", "PeerMetadata", ":", "md", ",", "Metrics", ":", "NewMetrics", "(", ")", ",", "internedProtocols", ":", "make", "(", "map", "[", "string", "]", "string", ")", ",", "}", "\n", "}" ]
// NewPeerstore creates a data structure that stores peer data, backed by the // supplied implementations of KeyBook, AddrBook and PeerMetadata.
[ "NewPeerstore", "creates", "a", "data", "structure", "that", "stores", "peer", "data", "backed", "by", "the", "supplied", "implementations", "of", "KeyBook", "AddrBook", "and", "PeerMetadata", "." ]
96639ef5f4c339131552acf2e283d2d041602798
https://github.com/libp2p/go-libp2p-peerstore/blob/96639ef5f4c339131552acf2e283d2d041602798/peerstore.go#L30-L38
9,469
libp2p/go-libp2p-peerstore
pstoreds/addr_book_gc.go
background
func (gc *dsAddrBookGc) background() { defer gc.ab.childrenDone.Done() select { case <-time.After(gc.ab.opts.GCInitialDelay): case <-gc.ab.ctx.Done(): // yield if we have been cancelled/closed before the delay elapses. return } purgeTimer := time.NewTicker(gc.ab.opts.GCPurgeInterval) defer purgeTimer.Stop() var lookaheadCh <-chan time.Time if gc.lookaheadEnabled { lookaheadTimer := time.NewTicker(gc.ab.opts.GCLookaheadInterval) lookaheadCh = lookaheadTimer.C gc.populateLookahead() // do a lookahead now defer lookaheadTimer.Stop() } for { select { case <-purgeTimer.C: gc.purgeFunc() case <-lookaheadCh: // will never trigger if lookahead is disabled (nil Duration). gc.populateLookahead() case <-gc.ctx.Done(): return } } }
go
func (gc *dsAddrBookGc) background() { defer gc.ab.childrenDone.Done() select { case <-time.After(gc.ab.opts.GCInitialDelay): case <-gc.ab.ctx.Done(): // yield if we have been cancelled/closed before the delay elapses. return } purgeTimer := time.NewTicker(gc.ab.opts.GCPurgeInterval) defer purgeTimer.Stop() var lookaheadCh <-chan time.Time if gc.lookaheadEnabled { lookaheadTimer := time.NewTicker(gc.ab.opts.GCLookaheadInterval) lookaheadCh = lookaheadTimer.C gc.populateLookahead() // do a lookahead now defer lookaheadTimer.Stop() } for { select { case <-purgeTimer.C: gc.purgeFunc() case <-lookaheadCh: // will never trigger if lookahead is disabled (nil Duration). gc.populateLookahead() case <-gc.ctx.Done(): return } } }
[ "func", "(", "gc", "*", "dsAddrBookGc", ")", "background", "(", ")", "{", "defer", "gc", ".", "ab", ".", "childrenDone", ".", "Done", "(", ")", "\n\n", "select", "{", "case", "<-", "time", ".", "After", "(", "gc", ".", "ab", ".", "opts", ".", "GCInitialDelay", ")", ":", "case", "<-", "gc", ".", "ab", ".", "ctx", ".", "Done", "(", ")", ":", "// yield if we have been cancelled/closed before the delay elapses.", "return", "\n", "}", "\n\n", "purgeTimer", ":=", "time", ".", "NewTicker", "(", "gc", ".", "ab", ".", "opts", ".", "GCPurgeInterval", ")", "\n", "defer", "purgeTimer", ".", "Stop", "(", ")", "\n\n", "var", "lookaheadCh", "<-", "chan", "time", ".", "Time", "\n", "if", "gc", ".", "lookaheadEnabled", "{", "lookaheadTimer", ":=", "time", ".", "NewTicker", "(", "gc", ".", "ab", ".", "opts", ".", "GCLookaheadInterval", ")", "\n", "lookaheadCh", "=", "lookaheadTimer", ".", "C", "\n", "gc", ".", "populateLookahead", "(", ")", "// do a lookahead now", "\n", "defer", "lookaheadTimer", ".", "Stop", "(", ")", "\n", "}", "\n\n", "for", "{", "select", "{", "case", "<-", "purgeTimer", ".", "C", ":", "gc", ".", "purgeFunc", "(", ")", "\n\n", "case", "<-", "lookaheadCh", ":", "// will never trigger if lookahead is disabled (nil Duration).", "gc", ".", "populateLookahead", "(", ")", "\n\n", "case", "<-", "gc", ".", "ctx", ".", "Done", "(", ")", ":", "return", "\n", "}", "\n", "}", "\n", "}" ]
// gc prunes expired addresses from the datastore at regular intervals. It should be spawned as a goroutine.
[ "gc", "prunes", "expired", "addresses", "from", "the", "datastore", "at", "regular", "intervals", ".", "It", "should", "be", "spawned", "as", "a", "goroutine", "." ]
96639ef5f4c339131552acf2e283d2d041602798
https://github.com/libp2p/go-libp2p-peerstore/blob/96639ef5f4c339131552acf2e283d2d041602798/pstoreds/addr_book_gc.go#L94-L128
9,470
libp2p/go-libp2p-peerstore
pstoreds/addr_book.go
flush
func (r *addrsRecord) flush(write ds.Write) (err error) { key := addrBookBase.ChildString(b32.RawStdEncoding.EncodeToString([]byte(r.Id.ID))) if len(r.Addrs) == 0 { if err = write.Delete(key); err == nil { r.dirty = false } return err } data, err := r.Marshal() if err != nil { return err } if err = write.Put(key, data); err != nil { return err } // write succeeded; record is no longer dirty. r.dirty = false return nil }
go
func (r *addrsRecord) flush(write ds.Write) (err error) { key := addrBookBase.ChildString(b32.RawStdEncoding.EncodeToString([]byte(r.Id.ID))) if len(r.Addrs) == 0 { if err = write.Delete(key); err == nil { r.dirty = false } return err } data, err := r.Marshal() if err != nil { return err } if err = write.Put(key, data); err != nil { return err } // write succeeded; record is no longer dirty. r.dirty = false return nil }
[ "func", "(", "r", "*", "addrsRecord", ")", "flush", "(", "write", "ds", ".", "Write", ")", "(", "err", "error", ")", "{", "key", ":=", "addrBookBase", ".", "ChildString", "(", "b32", ".", "RawStdEncoding", ".", "EncodeToString", "(", "[", "]", "byte", "(", "r", ".", "Id", ".", "ID", ")", ")", ")", "\n", "if", "len", "(", "r", ".", "Addrs", ")", "==", "0", "{", "if", "err", "=", "write", ".", "Delete", "(", "key", ")", ";", "err", "==", "nil", "{", "r", ".", "dirty", "=", "false", "\n", "}", "\n", "return", "err", "\n", "}", "\n\n", "data", ",", "err", ":=", "r", ".", "Marshal", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "if", "err", "=", "write", ".", "Put", "(", "key", ",", "data", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "// write succeeded; record is no longer dirty.", "r", ".", "dirty", "=", "false", "\n", "return", "nil", "\n", "}" ]
// flush writes the record to the datastore by calling ds.Put, unless the record is // marked for deletion, in which case we call ds.Delete. To be called within a lock.
[ "flush", "writes", "the", "record", "to", "the", "datastore", "by", "calling", "ds", ".", "Put", "unless", "the", "record", "is", "marked", "for", "deletion", "in", "which", "case", "we", "call", "ds", ".", "Delete", ".", "To", "be", "called", "within", "a", "lock", "." ]
96639ef5f4c339131552acf2e283d2d041602798
https://github.com/libp2p/go-libp2p-peerstore/blob/96639ef5f4c339131552acf2e283d2d041602798/pstoreds/addr_book.go#L48-L67
9,471
libp2p/go-libp2p-peerstore
pstoreds/addr_book.go
AddAddr
func (ab *dsAddrBook) AddAddr(p peer.ID, addr ma.Multiaddr, ttl time.Duration) { ab.AddAddrs(p, []ma.Multiaddr{addr}, ttl) }
go
func (ab *dsAddrBook) AddAddr(p peer.ID, addr ma.Multiaddr, ttl time.Duration) { ab.AddAddrs(p, []ma.Multiaddr{addr}, ttl) }
[ "func", "(", "ab", "*", "dsAddrBook", ")", "AddAddr", "(", "p", "peer", ".", "ID", ",", "addr", "ma", ".", "Multiaddr", ",", "ttl", "time", ".", "Duration", ")", "{", "ab", ".", "AddAddrs", "(", "p", ",", "[", "]", "ma", ".", "Multiaddr", "{", "addr", "}", ",", "ttl", ")", "\n", "}" ]
// AddAddr will add a new address if it's not already in the AddrBook.
[ "AddAddr", "will", "add", "a", "new", "address", "if", "it", "s", "not", "already", "in", "the", "AddrBook", "." ]
96639ef5f4c339131552acf2e283d2d041602798
https://github.com/libp2p/go-libp2p-peerstore/blob/96639ef5f4c339131552acf2e283d2d041602798/pstoreds/addr_book.go#L233-L235
9,472
libp2p/go-libp2p-peerstore
pstoreds/addr_book.go
AddAddrs
func (ab *dsAddrBook) AddAddrs(p peer.ID, addrs []ma.Multiaddr, ttl time.Duration) { if ttl <= 0 { return } addrs = cleanAddrs(addrs) ab.setAddrs(p, addrs, ttl, ttlExtend) }
go
func (ab *dsAddrBook) AddAddrs(p peer.ID, addrs []ma.Multiaddr, ttl time.Duration) { if ttl <= 0 { return } addrs = cleanAddrs(addrs) ab.setAddrs(p, addrs, ttl, ttlExtend) }
[ "func", "(", "ab", "*", "dsAddrBook", ")", "AddAddrs", "(", "p", "peer", ".", "ID", ",", "addrs", "[", "]", "ma", ".", "Multiaddr", ",", "ttl", "time", ".", "Duration", ")", "{", "if", "ttl", "<=", "0", "{", "return", "\n", "}", "\n", "addrs", "=", "cleanAddrs", "(", "addrs", ")", "\n", "ab", ".", "setAddrs", "(", "p", ",", "addrs", ",", "ttl", ",", "ttlExtend", ")", "\n", "}" ]
// AddAddrs will add many new addresses if they're not already in the AddrBook.
[ "AddAddrs", "will", "add", "many", "new", "addresses", "if", "they", "re", "not", "already", "in", "the", "AddrBook", "." ]
96639ef5f4c339131552acf2e283d2d041602798
https://github.com/libp2p/go-libp2p-peerstore/blob/96639ef5f4c339131552acf2e283d2d041602798/pstoreds/addr_book.go#L238-L244
9,473
libp2p/go-libp2p-peerstore
pstoreds/addr_book.go
SetAddr
func (ab *dsAddrBook) SetAddr(p peer.ID, addr ma.Multiaddr, ttl time.Duration) { ab.SetAddrs(p, []ma.Multiaddr{addr}, ttl) }
go
func (ab *dsAddrBook) SetAddr(p peer.ID, addr ma.Multiaddr, ttl time.Duration) { ab.SetAddrs(p, []ma.Multiaddr{addr}, ttl) }
[ "func", "(", "ab", "*", "dsAddrBook", ")", "SetAddr", "(", "p", "peer", ".", "ID", ",", "addr", "ma", ".", "Multiaddr", ",", "ttl", "time", ".", "Duration", ")", "{", "ab", ".", "SetAddrs", "(", "p", ",", "[", "]", "ma", ".", "Multiaddr", "{", "addr", "}", ",", "ttl", ")", "\n", "}" ]
// SetAddr will add or update the TTL of an address in the AddrBook.
[ "SetAddr", "will", "add", "or", "update", "the", "TTL", "of", "an", "address", "in", "the", "AddrBook", "." ]
96639ef5f4c339131552acf2e283d2d041602798
https://github.com/libp2p/go-libp2p-peerstore/blob/96639ef5f4c339131552acf2e283d2d041602798/pstoreds/addr_book.go#L247-L249
9,474
libp2p/go-libp2p-peerstore
pstoreds/addr_book.go
SetAddrs
func (ab *dsAddrBook) SetAddrs(p peer.ID, addrs []ma.Multiaddr, ttl time.Duration) { addrs = cleanAddrs(addrs) if ttl <= 0 { ab.deleteAddrs(p, addrs) return } ab.setAddrs(p, addrs, ttl, ttlOverride) }
go
func (ab *dsAddrBook) SetAddrs(p peer.ID, addrs []ma.Multiaddr, ttl time.Duration) { addrs = cleanAddrs(addrs) if ttl <= 0 { ab.deleteAddrs(p, addrs) return } ab.setAddrs(p, addrs, ttl, ttlOverride) }
[ "func", "(", "ab", "*", "dsAddrBook", ")", "SetAddrs", "(", "p", "peer", ".", "ID", ",", "addrs", "[", "]", "ma", ".", "Multiaddr", ",", "ttl", "time", ".", "Duration", ")", "{", "addrs", "=", "cleanAddrs", "(", "addrs", ")", "\n", "if", "ttl", "<=", "0", "{", "ab", ".", "deleteAddrs", "(", "p", ",", "addrs", ")", "\n", "return", "\n", "}", "\n", "ab", ".", "setAddrs", "(", "p", ",", "addrs", ",", "ttl", ",", "ttlOverride", ")", "\n", "}" ]
// SetAddrs will add or update the TTLs of addresses in the AddrBook.
[ "SetAddrs", "will", "add", "or", "update", "the", "TTLs", "of", "addresses", "in", "the", "AddrBook", "." ]
96639ef5f4c339131552acf2e283d2d041602798
https://github.com/libp2p/go-libp2p-peerstore/blob/96639ef5f4c339131552acf2e283d2d041602798/pstoreds/addr_book.go#L252-L259
9,475
libp2p/go-libp2p-peerstore
pstoreds/addr_book.go
UpdateAddrs
func (ab *dsAddrBook) UpdateAddrs(p peer.ID, oldTTL time.Duration, newTTL time.Duration) { pr, err := ab.loadRecord(p, true, false) if err != nil { log.Errorf("failed to update ttls for peer %s: %s\n", p.Pretty(), err) return } pr.Lock() defer pr.Unlock() newExp := time.Now().Add(newTTL).Unix() for _, entry := range pr.Addrs { if entry.Ttl != int64(oldTTL) { continue } entry.Ttl, entry.Expiry = int64(newTTL), newExp pr.dirty = true } if pr.clean() { pr.flush(ab.ds) } }
go
func (ab *dsAddrBook) UpdateAddrs(p peer.ID, oldTTL time.Duration, newTTL time.Duration) { pr, err := ab.loadRecord(p, true, false) if err != nil { log.Errorf("failed to update ttls for peer %s: %s\n", p.Pretty(), err) return } pr.Lock() defer pr.Unlock() newExp := time.Now().Add(newTTL).Unix() for _, entry := range pr.Addrs { if entry.Ttl != int64(oldTTL) { continue } entry.Ttl, entry.Expiry = int64(newTTL), newExp pr.dirty = true } if pr.clean() { pr.flush(ab.ds) } }
[ "func", "(", "ab", "*", "dsAddrBook", ")", "UpdateAddrs", "(", "p", "peer", ".", "ID", ",", "oldTTL", "time", ".", "Duration", ",", "newTTL", "time", ".", "Duration", ")", "{", "pr", ",", "err", ":=", "ab", ".", "loadRecord", "(", "p", ",", "true", ",", "false", ")", "\n", "if", "err", "!=", "nil", "{", "log", ".", "Errorf", "(", "\"", "\\n", "\"", ",", "p", ".", "Pretty", "(", ")", ",", "err", ")", "\n", "return", "\n", "}", "\n\n", "pr", ".", "Lock", "(", ")", "\n", "defer", "pr", ".", "Unlock", "(", ")", "\n\n", "newExp", ":=", "time", ".", "Now", "(", ")", ".", "Add", "(", "newTTL", ")", ".", "Unix", "(", ")", "\n", "for", "_", ",", "entry", ":=", "range", "pr", ".", "Addrs", "{", "if", "entry", ".", "Ttl", "!=", "int64", "(", "oldTTL", ")", "{", "continue", "\n", "}", "\n", "entry", ".", "Ttl", ",", "entry", ".", "Expiry", "=", "int64", "(", "newTTL", ")", ",", "newExp", "\n", "pr", ".", "dirty", "=", "true", "\n", "}", "\n\n", "if", "pr", ".", "clean", "(", ")", "{", "pr", ".", "flush", "(", "ab", ".", "ds", ")", "\n", "}", "\n", "}" ]
// UpdateAddrs will update any addresses for a given peer and TTL combination to // have a new TTL.
[ "UpdateAddrs", "will", "update", "any", "addresses", "for", "a", "given", "peer", "and", "TTL", "combination", "to", "have", "a", "new", "TTL", "." ]
96639ef5f4c339131552acf2e283d2d041602798
https://github.com/libp2p/go-libp2p-peerstore/blob/96639ef5f4c339131552acf2e283d2d041602798/pstoreds/addr_book.go#L263-L285
9,476
libp2p/go-libp2p-peerstore
pstoreds/addr_book.go
Addrs
func (ab *dsAddrBook) Addrs(p peer.ID) []ma.Multiaddr { pr, err := ab.loadRecord(p, true, true) if err != nil { log.Warning("failed to load peerstore entry for peer %v while querying addrs, err: %v", p, err) return nil } pr.RLock() defer pr.RUnlock() addrs := make([]ma.Multiaddr, 0, len(pr.Addrs)) for _, a := range pr.Addrs { addrs = append(addrs, a.Addr) } return addrs }
go
func (ab *dsAddrBook) Addrs(p peer.ID) []ma.Multiaddr { pr, err := ab.loadRecord(p, true, true) if err != nil { log.Warning("failed to load peerstore entry for peer %v while querying addrs, err: %v", p, err) return nil } pr.RLock() defer pr.RUnlock() addrs := make([]ma.Multiaddr, 0, len(pr.Addrs)) for _, a := range pr.Addrs { addrs = append(addrs, a.Addr) } return addrs }
[ "func", "(", "ab", "*", "dsAddrBook", ")", "Addrs", "(", "p", "peer", ".", "ID", ")", "[", "]", "ma", ".", "Multiaddr", "{", "pr", ",", "err", ":=", "ab", ".", "loadRecord", "(", "p", ",", "true", ",", "true", ")", "\n", "if", "err", "!=", "nil", "{", "log", ".", "Warning", "(", "\"", "\"", ",", "p", ",", "err", ")", "\n", "return", "nil", "\n", "}", "\n\n", "pr", ".", "RLock", "(", ")", "\n", "defer", "pr", ".", "RUnlock", "(", ")", "\n\n", "addrs", ":=", "make", "(", "[", "]", "ma", ".", "Multiaddr", ",", "0", ",", "len", "(", "pr", ".", "Addrs", ")", ")", "\n", "for", "_", ",", "a", ":=", "range", "pr", ".", "Addrs", "{", "addrs", "=", "append", "(", "addrs", ",", "a", ".", "Addr", ")", "\n", "}", "\n", "return", "addrs", "\n", "}" ]
// Addrs returns all of the non-expired addresses for a given peer.
[ "Addrs", "returns", "all", "of", "the", "non", "-", "expired", "addresses", "for", "a", "given", "peer", "." ]
96639ef5f4c339131552acf2e283d2d041602798
https://github.com/libp2p/go-libp2p-peerstore/blob/96639ef5f4c339131552acf2e283d2d041602798/pstoreds/addr_book.go#L288-L303
9,477
libp2p/go-libp2p-peerstore
pstoreds/addr_book.go
PeersWithAddrs
func (ab *dsAddrBook) PeersWithAddrs() peer.IDSlice { ids, err := uniquePeerIds(ab.ds, addrBookBase, func(result query.Result) string { return ds.RawKey(result.Key).Name() }) if err != nil { log.Errorf("error while retrieving peers with addresses: %v", err) } return ids }
go
func (ab *dsAddrBook) PeersWithAddrs() peer.IDSlice { ids, err := uniquePeerIds(ab.ds, addrBookBase, func(result query.Result) string { return ds.RawKey(result.Key).Name() }) if err != nil { log.Errorf("error while retrieving peers with addresses: %v", err) } return ids }
[ "func", "(", "ab", "*", "dsAddrBook", ")", "PeersWithAddrs", "(", ")", "peer", ".", "IDSlice", "{", "ids", ",", "err", ":=", "uniquePeerIds", "(", "ab", ".", "ds", ",", "addrBookBase", ",", "func", "(", "result", "query", ".", "Result", ")", "string", "{", "return", "ds", ".", "RawKey", "(", "result", ".", "Key", ")", ".", "Name", "(", ")", "\n", "}", ")", "\n", "if", "err", "!=", "nil", "{", "log", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n", "return", "ids", "\n", "}" ]
// Peers returns all of the peer IDs for which the AddrBook has addresses.
[ "Peers", "returns", "all", "of", "the", "peer", "IDs", "for", "which", "the", "AddrBook", "has", "addresses", "." ]
96639ef5f4c339131552acf2e283d2d041602798
https://github.com/libp2p/go-libp2p-peerstore/blob/96639ef5f4c339131552acf2e283d2d041602798/pstoreds/addr_book.go#L306-L314
9,478
libp2p/go-libp2p-peerstore
pstoreds/addr_book.go
ClearAddrs
func (ab *dsAddrBook) ClearAddrs(p peer.ID) { ab.cache.Remove(p) key := addrBookBase.ChildString(b32.RawStdEncoding.EncodeToString([]byte(p))) if err := ab.ds.Delete(key); err != nil { log.Errorf("failed to clear addresses for peer %s: %v", p.Pretty(), err) } }
go
func (ab *dsAddrBook) ClearAddrs(p peer.ID) { ab.cache.Remove(p) key := addrBookBase.ChildString(b32.RawStdEncoding.EncodeToString([]byte(p))) if err := ab.ds.Delete(key); err != nil { log.Errorf("failed to clear addresses for peer %s: %v", p.Pretty(), err) } }
[ "func", "(", "ab", "*", "dsAddrBook", ")", "ClearAddrs", "(", "p", "peer", ".", "ID", ")", "{", "ab", ".", "cache", ".", "Remove", "(", "p", ")", "\n\n", "key", ":=", "addrBookBase", ".", "ChildString", "(", "b32", ".", "RawStdEncoding", ".", "EncodeToString", "(", "[", "]", "byte", "(", "p", ")", ")", ")", "\n", "if", "err", ":=", "ab", ".", "ds", ".", "Delete", "(", "key", ")", ";", "err", "!=", "nil", "{", "log", ".", "Errorf", "(", "\"", "\"", ",", "p", ".", "Pretty", "(", ")", ",", "err", ")", "\n", "}", "\n", "}" ]
// ClearAddrs will delete all known addresses for a peer ID.
[ "ClearAddrs", "will", "delete", "all", "known", "addresses", "for", "a", "peer", "ID", "." ]
96639ef5f4c339131552acf2e283d2d041602798
https://github.com/libp2p/go-libp2p-peerstore/blob/96639ef5f4c339131552acf2e283d2d041602798/pstoreds/addr_book.go#L324-L331
9,479
libp2p/go-libp2p-peerstore
queue/sync.go
NewChanQueue
func NewChanQueue(ctx context.Context, pq PeerQueue) *ChanQueue { cq := &ChanQueue{Queue: pq} cq.process(ctx) return cq }
go
func NewChanQueue(ctx context.Context, pq PeerQueue) *ChanQueue { cq := &ChanQueue{Queue: pq} cq.process(ctx) return cq }
[ "func", "NewChanQueue", "(", "ctx", "context", ".", "Context", ",", "pq", "PeerQueue", ")", "*", "ChanQueue", "{", "cq", ":=", "&", "ChanQueue", "{", "Queue", ":", "pq", "}", "\n", "cq", ".", "process", "(", "ctx", ")", "\n", "return", "cq", "\n", "}" ]
// NewChanQueue creates a ChanQueue by wrapping pq.
[ "NewChanQueue", "creates", "a", "ChanQueue", "by", "wrapping", "pq", "." ]
96639ef5f4c339131552acf2e283d2d041602798
https://github.com/libp2p/go-libp2p-peerstore/blob/96639ef5f4c339131552acf2e283d2d041602798/queue/sync.go#L20-L24
9,480
sendgrid/rest
rest.go
AddQueryParameters
func AddQueryParameters(baseURL string, queryParams map[string]string) string { baseURL += "?" params := url.Values{} for key, value := range queryParams { params.Add(key, value) } return baseURL + params.Encode() }
go
func AddQueryParameters(baseURL string, queryParams map[string]string) string { baseURL += "?" params := url.Values{} for key, value := range queryParams { params.Add(key, value) } return baseURL + params.Encode() }
[ "func", "AddQueryParameters", "(", "baseURL", "string", ",", "queryParams", "map", "[", "string", "]", "string", ")", "string", "{", "baseURL", "+=", "\"", "\"", "\n", "params", ":=", "url", ".", "Values", "{", "}", "\n", "for", "key", ",", "value", ":=", "range", "queryParams", "{", "params", ".", "Add", "(", "key", ",", "value", ")", "\n", "}", "\n", "return", "baseURL", "+", "params", ".", "Encode", "(", ")", "\n", "}" ]
// AddQueryParameters adds query parameters to the URL.
[ "AddQueryParameters", "adds", "query", "parameters", "to", "the", "URL", "." ]
8f995deebcbbba440a60746115fdb5524e7cf3fc
https://github.com/sendgrid/rest/blob/8f995deebcbbba440a60746115fdb5524e7cf3fc/rest.go#L60-L67
9,481
sendgrid/rest
rest.go
BuildRequestObject
func BuildRequestObject(request Request) (*http.Request, error) { // Add any query parameters to the URL. if len(request.QueryParams) != 0 { request.BaseURL = AddQueryParameters(request.BaseURL, request.QueryParams) } req, err := http.NewRequest(string(request.Method), request.BaseURL, bytes.NewBuffer(request.Body)) if err != nil { return req, err } for key, value := range request.Headers { req.Header.Set(key, value) } _, exists := req.Header["Content-Type"] if len(request.Body) > 0 && !exists { req.Header.Set("Content-Type", "application/json") } return req, err }
go
func BuildRequestObject(request Request) (*http.Request, error) { // Add any query parameters to the URL. if len(request.QueryParams) != 0 { request.BaseURL = AddQueryParameters(request.BaseURL, request.QueryParams) } req, err := http.NewRequest(string(request.Method), request.BaseURL, bytes.NewBuffer(request.Body)) if err != nil { return req, err } for key, value := range request.Headers { req.Header.Set(key, value) } _, exists := req.Header["Content-Type"] if len(request.Body) > 0 && !exists { req.Header.Set("Content-Type", "application/json") } return req, err }
[ "func", "BuildRequestObject", "(", "request", "Request", ")", "(", "*", "http", ".", "Request", ",", "error", ")", "{", "// Add any query parameters to the URL.", "if", "len", "(", "request", ".", "QueryParams", ")", "!=", "0", "{", "request", ".", "BaseURL", "=", "AddQueryParameters", "(", "request", ".", "BaseURL", ",", "request", ".", "QueryParams", ")", "\n", "}", "\n", "req", ",", "err", ":=", "http", ".", "NewRequest", "(", "string", "(", "request", ".", "Method", ")", ",", "request", ".", "BaseURL", ",", "bytes", ".", "NewBuffer", "(", "request", ".", "Body", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "req", ",", "err", "\n", "}", "\n", "for", "key", ",", "value", ":=", "range", "request", ".", "Headers", "{", "req", ".", "Header", ".", "Set", "(", "key", ",", "value", ")", "\n", "}", "\n", "_", ",", "exists", ":=", "req", ".", "Header", "[", "\"", "\"", "]", "\n", "if", "len", "(", "request", ".", "Body", ")", ">", "0", "&&", "!", "exists", "{", "req", ".", "Header", ".", "Set", "(", "\"", "\"", ",", "\"", "\"", ")", "\n", "}", "\n", "return", "req", ",", "err", "\n", "}" ]
// BuildRequestObject creates the HTTP request object.
[ "BuildRequestObject", "creates", "the", "HTTP", "request", "object", "." ]
8f995deebcbbba440a60746115fdb5524e7cf3fc
https://github.com/sendgrid/rest/blob/8f995deebcbbba440a60746115fdb5524e7cf3fc/rest.go#L70-L87
9,482
sendgrid/rest
rest.go
MakeRequest
func MakeRequest(req *http.Request) (*http.Response, error) { return DefaultClient.HTTPClient.Do(req) }
go
func MakeRequest(req *http.Request) (*http.Response, error) { return DefaultClient.HTTPClient.Do(req) }
[ "func", "MakeRequest", "(", "req", "*", "http", ".", "Request", ")", "(", "*", "http", ".", "Response", ",", "error", ")", "{", "return", "DefaultClient", ".", "HTTPClient", ".", "Do", "(", "req", ")", "\n", "}" ]
// MakeRequest makes the API call.
[ "MakeRequest", "makes", "the", "API", "call", "." ]
8f995deebcbbba440a60746115fdb5524e7cf3fc
https://github.com/sendgrid/rest/blob/8f995deebcbbba440a60746115fdb5524e7cf3fc/rest.go#L90-L92
9,483
sendgrid/rest
rest.go
BuildResponse
func BuildResponse(res *http.Response) (*Response, error) { body, err := ioutil.ReadAll(res.Body) response := Response{ StatusCode: res.StatusCode, Body: string(body), Headers: res.Header, } res.Body.Close() // nolint return &response, err }
go
func BuildResponse(res *http.Response) (*Response, error) { body, err := ioutil.ReadAll(res.Body) response := Response{ StatusCode: res.StatusCode, Body: string(body), Headers: res.Header, } res.Body.Close() // nolint return &response, err }
[ "func", "BuildResponse", "(", "res", "*", "http", ".", "Response", ")", "(", "*", "Response", ",", "error", ")", "{", "body", ",", "err", ":=", "ioutil", ".", "ReadAll", "(", "res", ".", "Body", ")", "\n", "response", ":=", "Response", "{", "StatusCode", ":", "res", ".", "StatusCode", ",", "Body", ":", "string", "(", "body", ")", ",", "Headers", ":", "res", ".", "Header", ",", "}", "\n", "res", ".", "Body", ".", "Close", "(", ")", "// nolint", "\n", "return", "&", "response", ",", "err", "\n", "}" ]
// BuildResponse builds the response struct.
[ "BuildResponse", "builds", "the", "response", "struct", "." ]
8f995deebcbbba440a60746115fdb5524e7cf3fc
https://github.com/sendgrid/rest/blob/8f995deebcbbba440a60746115fdb5524e7cf3fc/rest.go#L95-L104
9,484
sendgrid/rest
rest.go
MakeRequest
func (c *Client) MakeRequest(req *http.Request) (*http.Response, error) { return c.HTTPClient.Do(req) }
go
func (c *Client) MakeRequest(req *http.Request) (*http.Response, error) { return c.HTTPClient.Do(req) }
[ "func", "(", "c", "*", "Client", ")", "MakeRequest", "(", "req", "*", "http", ".", "Request", ")", "(", "*", "http", ".", "Response", ",", "error", ")", "{", "return", "c", ".", "HTTPClient", ".", "Do", "(", "req", ")", "\n", "}" ]
// The following functions enable the ability to define a // custom HTTP Client // MakeRequest makes the API call.
[ "The", "following", "functions", "enable", "the", "ability", "to", "define", "a", "custom", "HTTP", "Client", "MakeRequest", "makes", "the", "API", "call", "." ]
8f995deebcbbba440a60746115fdb5524e7cf3fc
https://github.com/sendgrid/rest/blob/8f995deebcbbba440a60746115fdb5524e7cf3fc/rest.go#L120-L122
9,485
sendgrid/rest
rest.go
Send
func (c *Client) Send(request Request) (*Response, error) { // Build the HTTP request object. req, err := BuildRequestObject(request) if err != nil { return nil, err } // Build the HTTP client and make the request. res, err := c.MakeRequest(req) if err != nil { return nil, err } // Build Response object. return BuildResponse(res) }
go
func (c *Client) Send(request Request) (*Response, error) { // Build the HTTP request object. req, err := BuildRequestObject(request) if err != nil { return nil, err } // Build the HTTP client and make the request. res, err := c.MakeRequest(req) if err != nil { return nil, err } // Build Response object. return BuildResponse(res) }
[ "func", "(", "c", "*", "Client", ")", "Send", "(", "request", "Request", ")", "(", "*", "Response", ",", "error", ")", "{", "// Build the HTTP request object.", "req", ",", "err", ":=", "BuildRequestObject", "(", "request", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "// Build the HTTP client and make the request.", "res", ",", "err", ":=", "c", ".", "MakeRequest", "(", "req", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "// Build Response object.", "return", "BuildResponse", "(", "res", ")", "\n", "}" ]
// Send will build your request, make the request, and build your response.
[ "Send", "will", "build", "your", "request", "make", "the", "request", "and", "build", "your", "response", "." ]
8f995deebcbbba440a60746115fdb5524e7cf3fc
https://github.com/sendgrid/rest/blob/8f995deebcbbba440a60746115fdb5524e7cf3fc/rest.go#L130-L145
9,486
olebedev/when
when.go
Parse
func (p *Parser) Parse(text string, base time.Time) (*Result, error) { res := Result{ Source: text, Time: base, Index: -1, } if p.options == nil { p.options = defaultOptions } var err error // apply middlewares for _, b := range p.middleware { text, err = b(text) if err != nil { return nil, err } } // find all matches matches := make([]*rules.Match, 0) c := float64(0) for _, rule := range p.rules { r := rule.Find(text) if r != nil { r.Order = c c++ matches = append(matches, r) } } // not found if len(matches) == 0 { return nil, nil } // find a cluster sort.Sort(rules.MatchByIndex(matches)) // get borders of the matches end := matches[0].Right res.Index = matches[0].Left for i, m := range matches { if m.Left <= end+p.options.Distance { end = m.Right } else { matches = matches[:i] break } } res.Text = text[res.Index:end] // apply rules if p.options.MatchByOrder { sort.Sort(rules.MatchByOrder(matches)) } ctx := &rules.Context{Text: res.Text} applied := false for _, applier := range matches { ok, err := applier.Apply(ctx, p.options, res.Time) if err != nil { return nil, err } applied = ok || applied } if !applied { return nil, nil } res.Time, err = ctx.Time(res.Time) if err != nil { return nil, errors.Wrap(err, "bind context") } return &res, nil }
go
func (p *Parser) Parse(text string, base time.Time) (*Result, error) { res := Result{ Source: text, Time: base, Index: -1, } if p.options == nil { p.options = defaultOptions } var err error // apply middlewares for _, b := range p.middleware { text, err = b(text) if err != nil { return nil, err } } // find all matches matches := make([]*rules.Match, 0) c := float64(0) for _, rule := range p.rules { r := rule.Find(text) if r != nil { r.Order = c c++ matches = append(matches, r) } } // not found if len(matches) == 0 { return nil, nil } // find a cluster sort.Sort(rules.MatchByIndex(matches)) // get borders of the matches end := matches[0].Right res.Index = matches[0].Left for i, m := range matches { if m.Left <= end+p.options.Distance { end = m.Right } else { matches = matches[:i] break } } res.Text = text[res.Index:end] // apply rules if p.options.MatchByOrder { sort.Sort(rules.MatchByOrder(matches)) } ctx := &rules.Context{Text: res.Text} applied := false for _, applier := range matches { ok, err := applier.Apply(ctx, p.options, res.Time) if err != nil { return nil, err } applied = ok || applied } if !applied { return nil, nil } res.Time, err = ctx.Time(res.Time) if err != nil { return nil, errors.Wrap(err, "bind context") } return &res, nil }
[ "func", "(", "p", "*", "Parser", ")", "Parse", "(", "text", "string", ",", "base", "time", ".", "Time", ")", "(", "*", "Result", ",", "error", ")", "{", "res", ":=", "Result", "{", "Source", ":", "text", ",", "Time", ":", "base", ",", "Index", ":", "-", "1", ",", "}", "\n\n", "if", "p", ".", "options", "==", "nil", "{", "p", ".", "options", "=", "defaultOptions", "\n", "}", "\n\n", "var", "err", "error", "\n", "// apply middlewares", "for", "_", ",", "b", ":=", "range", "p", ".", "middleware", "{", "text", ",", "err", "=", "b", "(", "text", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "}", "\n\n", "// find all matches", "matches", ":=", "make", "(", "[", "]", "*", "rules", ".", "Match", ",", "0", ")", "\n", "c", ":=", "float64", "(", "0", ")", "\n", "for", "_", ",", "rule", ":=", "range", "p", ".", "rules", "{", "r", ":=", "rule", ".", "Find", "(", "text", ")", "\n", "if", "r", "!=", "nil", "{", "r", ".", "Order", "=", "c", "\n", "c", "++", "\n", "matches", "=", "append", "(", "matches", ",", "r", ")", "\n", "}", "\n", "}", "\n\n", "// not found", "if", "len", "(", "matches", ")", "==", "0", "{", "return", "nil", ",", "nil", "\n", "}", "\n\n", "// find a cluster", "sort", ".", "Sort", "(", "rules", ".", "MatchByIndex", "(", "matches", ")", ")", "\n\n", "// get borders of the matches", "end", ":=", "matches", "[", "0", "]", ".", "Right", "\n", "res", ".", "Index", "=", "matches", "[", "0", "]", ".", "Left", "\n\n", "for", "i", ",", "m", ":=", "range", "matches", "{", "if", "m", ".", "Left", "<=", "end", "+", "p", ".", "options", ".", "Distance", "{", "end", "=", "m", ".", "Right", "\n", "}", "else", "{", "matches", "=", "matches", "[", ":", "i", "]", "\n", "break", "\n", "}", "\n", "}", "\n\n", "res", ".", "Text", "=", "text", "[", "res", ".", "Index", ":", "end", "]", "\n\n", "// apply rules", "if", "p", ".", "options", ".", "MatchByOrder", "{", "sort", ".", "Sort", "(", "rules", ".", "MatchByOrder", "(", "matches", ")", ")", "\n", "}", "\n\n", "ctx", ":=", "&", "rules", ".", "Context", "{", "Text", ":", "res", ".", "Text", "}", "\n", "applied", ":=", "false", "\n", "for", "_", ",", "applier", ":=", "range", "matches", "{", "ok", ",", "err", ":=", "applier", ".", "Apply", "(", "ctx", ",", "p", ".", "options", ",", "res", ".", "Time", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "applied", "=", "ok", "||", "applied", "\n", "}", "\n\n", "if", "!", "applied", "{", "return", "nil", ",", "nil", "\n", "}", "\n\n", "res", ".", "Time", ",", "err", "=", "ctx", ".", "Time", "(", "res", ".", "Time", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Wrap", "(", "err", ",", "\"", "\"", ")", "\n", "}", "\n\n", "return", "&", "res", ",", "nil", "\n", "}" ]
// Parse returns Result and error if any. If have not matches it returns nil, nil.
[ "Parse", "returns", "Result", "and", "error", "if", "any", ".", "If", "have", "not", "matches", "it", "returns", "nil", "nil", "." ]
c3b538a972545a9584eadaea351b97264f29e8a8
https://github.com/olebedev/when/blob/c3b538a972545a9584eadaea351b97264f29e8a8/when.go#L36-L116
9,487
olebedev/when
when.go
Add
func (p *Parser) Add(r ...rules.Rule) { p.rules = append(p.rules, r...) }
go
func (p *Parser) Add(r ...rules.Rule) { p.rules = append(p.rules, r...) }
[ "func", "(", "p", "*", "Parser", ")", "Add", "(", "r", "...", "rules", ".", "Rule", ")", "{", "p", ".", "rules", "=", "append", "(", "p", ".", "rules", ",", "r", "...", ")", "\n", "}" ]
// Add adds given rules to the main chain.
[ "Add", "adds", "given", "rules", "to", "the", "main", "chain", "." ]
c3b538a972545a9584eadaea351b97264f29e8a8
https://github.com/olebedev/when/blob/c3b538a972545a9584eadaea351b97264f29e8a8/when.go#L119-L121
9,488
olebedev/when
when.go
Use
func (p *Parser) Use(f ...func(string) (string, error)) { p.middleware = append(p.middleware, f...) }
go
func (p *Parser) Use(f ...func(string) (string, error)) { p.middleware = append(p.middleware, f...) }
[ "func", "(", "p", "*", "Parser", ")", "Use", "(", "f", "...", "func", "(", "string", ")", "(", "string", ",", "error", ")", ")", "{", "p", ".", "middleware", "=", "append", "(", "p", ".", "middleware", ",", "f", "...", ")", "\n", "}" ]
// Use adds give functions to middlewares.
[ "Use", "adds", "give", "functions", "to", "middlewares", "." ]
c3b538a972545a9584eadaea351b97264f29e8a8
https://github.com/olebedev/when/blob/c3b538a972545a9584eadaea351b97264f29e8a8/when.go#L124-L126
9,489
olebedev/when
when.go
New
func New(o *rules.Options) *Parser { if o == nil { return &Parser{options: defaultOptions} } return &Parser{options: o} }
go
func New(o *rules.Options) *Parser { if o == nil { return &Parser{options: defaultOptions} } return &Parser{options: o} }
[ "func", "New", "(", "o", "*", "rules", ".", "Options", ")", "*", "Parser", "{", "if", "o", "==", "nil", "{", "return", "&", "Parser", "{", "options", ":", "defaultOptions", "}", "\n", "}", "\n", "return", "&", "Parser", "{", "options", ":", "o", "}", "\n", "}" ]
// New returns Parser initialised with given options.
[ "New", "returns", "Parser", "initialised", "with", "given", "options", "." ]
c3b538a972545a9584eadaea351b97264f29e8a8
https://github.com/olebedev/when/blob/c3b538a972545a9584eadaea351b97264f29e8a8/when.go#L134-L139
9,490
rubyist/circuitbreaker
circuitbreaker.go
NewBreakerWithOptions
func NewBreakerWithOptions(options *Options) *Breaker { if options == nil { options = &Options{} } if options.Clock == nil { options.Clock = clock.New() } if options.BackOff == nil { b := backoff.NewExponentialBackOff() b.InitialInterval = defaultInitialBackOffInterval b.MaxElapsedTime = defaultBackoffMaxElapsedTime b.Clock = options.Clock b.Reset() options.BackOff = b } if options.WindowTime == 0 { options.WindowTime = DefaultWindowTime } if options.WindowBuckets == 0 { options.WindowBuckets = DefaultWindowBuckets } return &Breaker{ BackOff: options.BackOff, Clock: options.Clock, ShouldTrip: options.ShouldTrip, nextBackOff: options.BackOff.NextBackOff(), counts: newWindow(options.WindowTime, options.WindowBuckets), } }
go
func NewBreakerWithOptions(options *Options) *Breaker { if options == nil { options = &Options{} } if options.Clock == nil { options.Clock = clock.New() } if options.BackOff == nil { b := backoff.NewExponentialBackOff() b.InitialInterval = defaultInitialBackOffInterval b.MaxElapsedTime = defaultBackoffMaxElapsedTime b.Clock = options.Clock b.Reset() options.BackOff = b } if options.WindowTime == 0 { options.WindowTime = DefaultWindowTime } if options.WindowBuckets == 0 { options.WindowBuckets = DefaultWindowBuckets } return &Breaker{ BackOff: options.BackOff, Clock: options.Clock, ShouldTrip: options.ShouldTrip, nextBackOff: options.BackOff.NextBackOff(), counts: newWindow(options.WindowTime, options.WindowBuckets), } }
[ "func", "NewBreakerWithOptions", "(", "options", "*", "Options", ")", "*", "Breaker", "{", "if", "options", "==", "nil", "{", "options", "=", "&", "Options", "{", "}", "\n", "}", "\n\n", "if", "options", ".", "Clock", "==", "nil", "{", "options", ".", "Clock", "=", "clock", ".", "New", "(", ")", "\n", "}", "\n\n", "if", "options", ".", "BackOff", "==", "nil", "{", "b", ":=", "backoff", ".", "NewExponentialBackOff", "(", ")", "\n", "b", ".", "InitialInterval", "=", "defaultInitialBackOffInterval", "\n", "b", ".", "MaxElapsedTime", "=", "defaultBackoffMaxElapsedTime", "\n", "b", ".", "Clock", "=", "options", ".", "Clock", "\n", "b", ".", "Reset", "(", ")", "\n", "options", ".", "BackOff", "=", "b", "\n", "}", "\n\n", "if", "options", ".", "WindowTime", "==", "0", "{", "options", ".", "WindowTime", "=", "DefaultWindowTime", "\n", "}", "\n\n", "if", "options", ".", "WindowBuckets", "==", "0", "{", "options", ".", "WindowBuckets", "=", "DefaultWindowBuckets", "\n", "}", "\n\n", "return", "&", "Breaker", "{", "BackOff", ":", "options", ".", "BackOff", ",", "Clock", ":", "options", ".", "Clock", ",", "ShouldTrip", ":", "options", ".", "ShouldTrip", ",", "nextBackOff", ":", "options", ".", "BackOff", ".", "NextBackOff", "(", ")", ",", "counts", ":", "newWindow", "(", "options", ".", "WindowTime", ",", "options", ".", "WindowBuckets", ")", ",", "}", "\n", "}" ]
// NewBreakerWithOptions creates a base breaker with a specified backoff, clock and TripFunc
[ "NewBreakerWithOptions", "creates", "a", "base", "breaker", "with", "a", "specified", "backoff", "clock", "and", "TripFunc" ]
2074adba5ddc7d5f7559448a9c3066573521c5bf
https://github.com/rubyist/circuitbreaker/blob/2074adba5ddc7d5f7559448a9c3066573521c5bf/circuitbreaker.go#L130-L163
9,491
rubyist/circuitbreaker
circuitbreaker.go
NewRateBreaker
func NewRateBreaker(rate float64, minSamples int64) *Breaker { return NewBreakerWithOptions(&Options{ ShouldTrip: RateTripFunc(rate, minSamples), }) }
go
func NewRateBreaker(rate float64, minSamples int64) *Breaker { return NewBreakerWithOptions(&Options{ ShouldTrip: RateTripFunc(rate, minSamples), }) }
[ "func", "NewRateBreaker", "(", "rate", "float64", ",", "minSamples", "int64", ")", "*", "Breaker", "{", "return", "NewBreakerWithOptions", "(", "&", "Options", "{", "ShouldTrip", ":", "RateTripFunc", "(", "rate", ",", "minSamples", ")", ",", "}", ")", "\n", "}" ]
// NewRateBreaker creates a Breaker with a RateTripFunc.
[ "NewRateBreaker", "creates", "a", "Breaker", "with", "a", "RateTripFunc", "." ]
2074adba5ddc7d5f7559448a9c3066573521c5bf
https://github.com/rubyist/circuitbreaker/blob/2074adba5ddc7d5f7559448a9c3066573521c5bf/circuitbreaker.go#L185-L189
9,492
rubyist/circuitbreaker
circuitbreaker.go
Subscribe
func (cb *Breaker) Subscribe() <-chan BreakerEvent { eventReader := make(chan BreakerEvent) output := make(chan BreakerEvent, 100) go func() { for v := range eventReader { select { case output <- v: default: <-output output <- v } } }() cb.eventReceivers = append(cb.eventReceivers, eventReader) return output }
go
func (cb *Breaker) Subscribe() <-chan BreakerEvent { eventReader := make(chan BreakerEvent) output := make(chan BreakerEvent, 100) go func() { for v := range eventReader { select { case output <- v: default: <-output output <- v } } }() cb.eventReceivers = append(cb.eventReceivers, eventReader) return output }
[ "func", "(", "cb", "*", "Breaker", ")", "Subscribe", "(", ")", "<-", "chan", "BreakerEvent", "{", "eventReader", ":=", "make", "(", "chan", "BreakerEvent", ")", "\n", "output", ":=", "make", "(", "chan", "BreakerEvent", ",", "100", ")", "\n\n", "go", "func", "(", ")", "{", "for", "v", ":=", "range", "eventReader", "{", "select", "{", "case", "output", "<-", "v", ":", "default", ":", "<-", "output", "\n", "output", "<-", "v", "\n", "}", "\n", "}", "\n", "}", "(", ")", "\n", "cb", ".", "eventReceivers", "=", "append", "(", "cb", ".", "eventReceivers", ",", "eventReader", ")", "\n", "return", "output", "\n", "}" ]
// Subscribe returns a channel of BreakerEvents. Whenever the breaker changes state, // the state will be sent over the channel. See BreakerEvent for the types of events.
[ "Subscribe", "returns", "a", "channel", "of", "BreakerEvents", ".", "Whenever", "the", "breaker", "changes", "state", "the", "state", "will", "be", "sent", "over", "the", "channel", ".", "See", "BreakerEvent", "for", "the", "types", "of", "events", "." ]
2074adba5ddc7d5f7559448a9c3066573521c5bf
https://github.com/rubyist/circuitbreaker/blob/2074adba5ddc7d5f7559448a9c3066573521c5bf/circuitbreaker.go#L193-L209
9,493
rubyist/circuitbreaker
circuitbreaker.go
AddListener
func (cb *Breaker) AddListener(listener chan ListenerEvent) { cb.listeners = append(cb.listeners, listener) }
go
func (cb *Breaker) AddListener(listener chan ListenerEvent) { cb.listeners = append(cb.listeners, listener) }
[ "func", "(", "cb", "*", "Breaker", ")", "AddListener", "(", "listener", "chan", "ListenerEvent", ")", "{", "cb", ".", "listeners", "=", "append", "(", "cb", ".", "listeners", ",", "listener", ")", "\n", "}" ]
// AddListener adds a channel of ListenerEvents on behalf of a listener. // The listener channel must be buffered.
[ "AddListener", "adds", "a", "channel", "of", "ListenerEvents", "on", "behalf", "of", "a", "listener", ".", "The", "listener", "channel", "must", "be", "buffered", "." ]
2074adba5ddc7d5f7559448a9c3066573521c5bf
https://github.com/rubyist/circuitbreaker/blob/2074adba5ddc7d5f7559448a9c3066573521c5bf/circuitbreaker.go#L213-L215
9,494
rubyist/circuitbreaker
circuitbreaker.go
RemoveListener
func (cb *Breaker) RemoveListener(listener chan ListenerEvent) bool { for i, receiver := range cb.listeners { if listener == receiver { cb.listeners = append(cb.listeners[:i], cb.listeners[i+1:]...) return true } } return false }
go
func (cb *Breaker) RemoveListener(listener chan ListenerEvent) bool { for i, receiver := range cb.listeners { if listener == receiver { cb.listeners = append(cb.listeners[:i], cb.listeners[i+1:]...) return true } } return false }
[ "func", "(", "cb", "*", "Breaker", ")", "RemoveListener", "(", "listener", "chan", "ListenerEvent", ")", "bool", "{", "for", "i", ",", "receiver", ":=", "range", "cb", ".", "listeners", "{", "if", "listener", "==", "receiver", "{", "cb", ".", "listeners", "=", "append", "(", "cb", ".", "listeners", "[", ":", "i", "]", ",", "cb", ".", "listeners", "[", "i", "+", "1", ":", "]", "...", ")", "\n", "return", "true", "\n", "}", "\n", "}", "\n", "return", "false", "\n", "}" ]
// RemoveListener removes a channel previously added via AddListener. // Once removed, the channel will no longer receive ListenerEvents. // Returns true if the listener was found and removed.
[ "RemoveListener", "removes", "a", "channel", "previously", "added", "via", "AddListener", ".", "Once", "removed", "the", "channel", "will", "no", "longer", "receive", "ListenerEvents", ".", "Returns", "true", "if", "the", "listener", "was", "found", "and", "removed", "." ]
2074adba5ddc7d5f7559448a9c3066573521c5bf
https://github.com/rubyist/circuitbreaker/blob/2074adba5ddc7d5f7559448a9c3066573521c5bf/circuitbreaker.go#L220-L228
9,495
rubyist/circuitbreaker
circuitbreaker.go
ResetCounters
func (cb *Breaker) ResetCounters() { atomic.StoreInt64(&cb.consecFailures, 0) cb.counts.Reset() }
go
func (cb *Breaker) ResetCounters() { atomic.StoreInt64(&cb.consecFailures, 0) cb.counts.Reset() }
[ "func", "(", "cb", "*", "Breaker", ")", "ResetCounters", "(", ")", "{", "atomic", ".", "StoreInt64", "(", "&", "cb", ".", "consecFailures", ",", "0", ")", "\n", "cb", ".", "counts", ".", "Reset", "(", ")", "\n", "}" ]
// ResetCounters will reset only the failures, consecFailures, and success counters
[ "ResetCounters", "will", "reset", "only", "the", "failures", "consecFailures", "and", "success", "counters" ]
2074adba5ddc7d5f7559448a9c3066573521c5bf
https://github.com/rubyist/circuitbreaker/blob/2074adba5ddc7d5f7559448a9c3066573521c5bf/circuitbreaker.go#L250-L253
9,496
rubyist/circuitbreaker
circuitbreaker.go
Fail
func (cb *Breaker) Fail() { cb.counts.Fail() atomic.AddInt64(&cb.consecFailures, 1) now := cb.Clock.Now() atomic.StoreInt64(&cb.lastFailure, now.UnixNano()) cb.sendEvent(BreakerFail) if cb.ShouldTrip != nil && cb.ShouldTrip(cb) { cb.Trip() } }
go
func (cb *Breaker) Fail() { cb.counts.Fail() atomic.AddInt64(&cb.consecFailures, 1) now := cb.Clock.Now() atomic.StoreInt64(&cb.lastFailure, now.UnixNano()) cb.sendEvent(BreakerFail) if cb.ShouldTrip != nil && cb.ShouldTrip(cb) { cb.Trip() } }
[ "func", "(", "cb", "*", "Breaker", ")", "Fail", "(", ")", "{", "cb", ".", "counts", ".", "Fail", "(", ")", "\n", "atomic", ".", "AddInt64", "(", "&", "cb", ".", "consecFailures", ",", "1", ")", "\n", "now", ":=", "cb", ".", "Clock", ".", "Now", "(", ")", "\n", "atomic", ".", "StoreInt64", "(", "&", "cb", ".", "lastFailure", ",", "now", ".", "UnixNano", "(", ")", ")", "\n", "cb", ".", "sendEvent", "(", "BreakerFail", ")", "\n", "if", "cb", ".", "ShouldTrip", "!=", "nil", "&&", "cb", ".", "ShouldTrip", "(", "cb", ")", "{", "cb", ".", "Trip", "(", ")", "\n", "}", "\n", "}" ]
// Fail is used to indicate a failure condition the Breaker should record. It will // increment the failure counters and store the time of the last failure. If the // breaker has a TripFunc it will be called, tripping the breaker if necessary.
[ "Fail", "is", "used", "to", "indicate", "a", "failure", "condition", "the", "Breaker", "should", "record", ".", "It", "will", "increment", "the", "failure", "counters", "and", "store", "the", "time", "of", "the", "last", "failure", ".", "If", "the", "breaker", "has", "a", "TripFunc", "it", "will", "be", "called", "tripping", "the", "breaker", "if", "necessary", "." ]
2074adba5ddc7d5f7559448a9c3066573521c5bf
https://github.com/rubyist/circuitbreaker/blob/2074adba5ddc7d5f7559448a9c3066573521c5bf/circuitbreaker.go#L285-L294
9,497
rubyist/circuitbreaker
circuitbreaker.go
Ready
func (cb *Breaker) Ready() bool { state := cb.state() if state == halfopen { atomic.StoreInt64(&cb.halfOpens, 0) cb.sendEvent(BreakerReady) } return state == closed || state == halfopen }
go
func (cb *Breaker) Ready() bool { state := cb.state() if state == halfopen { atomic.StoreInt64(&cb.halfOpens, 0) cb.sendEvent(BreakerReady) } return state == closed || state == halfopen }
[ "func", "(", "cb", "*", "Breaker", ")", "Ready", "(", ")", "bool", "{", "state", ":=", "cb", ".", "state", "(", ")", "\n", "if", "state", "==", "halfopen", "{", "atomic", ".", "StoreInt64", "(", "&", "cb", ".", "halfOpens", ",", "0", ")", "\n", "cb", ".", "sendEvent", "(", "BreakerReady", ")", "\n", "}", "\n", "return", "state", "==", "closed", "||", "state", "==", "halfopen", "\n", "}" ]
// Ready will return true if the circuit breaker is ready to call the function. // It will be ready if the breaker is in a reset state, or if it is time to retry // the call for auto resetting.
[ "Ready", "will", "return", "true", "if", "the", "circuit", "breaker", "is", "ready", "to", "call", "the", "function", ".", "It", "will", "be", "ready", "if", "the", "breaker", "is", "in", "a", "reset", "state", "or", "if", "it", "is", "time", "to", "retry", "the", "call", "for", "auto", "resetting", "." ]
2074adba5ddc7d5f7559448a9c3066573521c5bf
https://github.com/rubyist/circuitbreaker/blob/2074adba5ddc7d5f7559448a9c3066573521c5bf/circuitbreaker.go#L321-L328
9,498
rubyist/circuitbreaker
circuitbreaker.go
Call
func (cb *Breaker) Call(circuit func() error, timeout time.Duration) error { return cb.CallContext(context.Background(), circuit, timeout) }
go
func (cb *Breaker) Call(circuit func() error, timeout time.Duration) error { return cb.CallContext(context.Background(), circuit, timeout) }
[ "func", "(", "cb", "*", "Breaker", ")", "Call", "(", "circuit", "func", "(", ")", "error", ",", "timeout", "time", ".", "Duration", ")", "error", "{", "return", "cb", ".", "CallContext", "(", "context", ".", "Background", "(", ")", ",", "circuit", ",", "timeout", ")", "\n", "}" ]
// Call wraps a function the Breaker will protect. A failure is recorded // whenever the function returns an error. If the called function takes longer // than timeout to run, a failure will be recorded.
[ "Call", "wraps", "a", "function", "the", "Breaker", "will", "protect", ".", "A", "failure", "is", "recorded", "whenever", "the", "function", "returns", "an", "error", ".", "If", "the", "called", "function", "takes", "longer", "than", "timeout", "to", "run", "a", "failure", "will", "be", "recorded", "." ]
2074adba5ddc7d5f7559448a9c3066573521c5bf
https://github.com/rubyist/circuitbreaker/blob/2074adba5ddc7d5f7559448a9c3066573521c5bf/circuitbreaker.go#L333-L335
9,499
rubyist/circuitbreaker
circuitbreaker.go
CallContext
func (cb *Breaker) CallContext(ctx context.Context, circuit func() error, timeout time.Duration) error { var err error if !cb.Ready() { return ErrBreakerOpen } if timeout == 0 { err = circuit() } else { c := make(chan error, 1) go func() { c <- circuit() close(c) }() select { case e := <-c: err = e case <-cb.Clock.After(timeout): err = ErrBreakerTimeout } } if err != nil { if ctx.Err() != context.Canceled { cb.Fail() } return err } cb.Success() return nil }
go
func (cb *Breaker) CallContext(ctx context.Context, circuit func() error, timeout time.Duration) error { var err error if !cb.Ready() { return ErrBreakerOpen } if timeout == 0 { err = circuit() } else { c := make(chan error, 1) go func() { c <- circuit() close(c) }() select { case e := <-c: err = e case <-cb.Clock.After(timeout): err = ErrBreakerTimeout } } if err != nil { if ctx.Err() != context.Canceled { cb.Fail() } return err } cb.Success() return nil }
[ "func", "(", "cb", "*", "Breaker", ")", "CallContext", "(", "ctx", "context", ".", "Context", ",", "circuit", "func", "(", ")", "error", ",", "timeout", "time", ".", "Duration", ")", "error", "{", "var", "err", "error", "\n\n", "if", "!", "cb", ".", "Ready", "(", ")", "{", "return", "ErrBreakerOpen", "\n", "}", "\n\n", "if", "timeout", "==", "0", "{", "err", "=", "circuit", "(", ")", "\n", "}", "else", "{", "c", ":=", "make", "(", "chan", "error", ",", "1", ")", "\n", "go", "func", "(", ")", "{", "c", "<-", "circuit", "(", ")", "\n", "close", "(", "c", ")", "\n", "}", "(", ")", "\n\n", "select", "{", "case", "e", ":=", "<-", "c", ":", "err", "=", "e", "\n", "case", "<-", "cb", ".", "Clock", ".", "After", "(", "timeout", ")", ":", "err", "=", "ErrBreakerTimeout", "\n", "}", "\n", "}", "\n\n", "if", "err", "!=", "nil", "{", "if", "ctx", ".", "Err", "(", ")", "!=", "context", ".", "Canceled", "{", "cb", ".", "Fail", "(", ")", "\n", "}", "\n", "return", "err", "\n", "}", "\n\n", "cb", ".", "Success", "(", ")", "\n", "return", "nil", "\n", "}" ]
// CallContext is same as Call but if the ctx is canceled after the circuit returned an error, // the error will not be marked as a failure because the call was canceled intentionally.
[ "CallContext", "is", "same", "as", "Call", "but", "if", "the", "ctx", "is", "canceled", "after", "the", "circuit", "returned", "an", "error", "the", "error", "will", "not", "be", "marked", "as", "a", "failure", "because", "the", "call", "was", "canceled", "intentionally", "." ]
2074adba5ddc7d5f7559448a9c3066573521c5bf
https://github.com/rubyist/circuitbreaker/blob/2074adba5ddc7d5f7559448a9c3066573521c5bf/circuitbreaker.go#L339-L372