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
list
docstring
stringlengths
6
2.61k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
85
252
partition
stringclasses
1 value
nsqio/go-nsq
config.go
unsafeValueOf
func unsafeValueOf(val reflect.Value) reflect.Value { uptr := unsafe.Pointer(val.UnsafeAddr()) return reflect.NewAt(val.Type(), uptr).Elem() }
go
func unsafeValueOf(val reflect.Value) reflect.Value { uptr := unsafe.Pointer(val.UnsafeAddr()) return reflect.NewAt(val.Type(), uptr).Elem() }
[ "func", "unsafeValueOf", "(", "val", "reflect", ".", "Value", ")", "reflect", ".", "Value", "{", "uptr", ":=", "unsafe", ".", "Pointer", "(", "val", ".", "UnsafeAddr", "(", ")", ")", "\n", "return", "reflect", ".", "NewAt", "(", "val", ".", "Type", "(", ")", ",", "uptr", ")", ".", "Elem", "(", ")", "\n", "}" ]
// because Config contains private structs we can't use reflect.Value // directly, instead we need to "unsafely" address the variable
[ "because", "Config", "contains", "private", "structs", "we", "can", "t", "use", "reflect", ".", "Value", "directly", "instead", "we", "need", "to", "unsafely", "address", "the", "variable" ]
61f49c096d0d767be61e4de06f724e1cb5fd85d7
https://github.com/nsqio/go-nsq/blob/61f49c096d0d767be61e4de06f724e1cb5fd85d7/config.go#L479-L482
train
nsqio/go-nsq
protocol.go
ReadUnpackedResponse
func ReadUnpackedResponse(r io.Reader) (int32, []byte, error) { resp, err := ReadResponse(r) if err != nil { return -1, nil, err } return UnpackResponse(resp) }
go
func ReadUnpackedResponse(r io.Reader) (int32, []byte, error) { resp, err := ReadResponse(r) if err != nil { return -1, nil, err } return UnpackResponse(resp) }
[ "func", "ReadUnpackedResponse", "(", "r", "io", ".", "Reader", ")", "(", "int32", ",", "[", "]", "byte", ",", "error", ")", "{", "resp", ",", "err", ":=", "ReadResponse", "(", "r", ")", "\n", "if", "err", "!=", "nil", "{", "return", "-", "1", ",", "nil", ",", "err", "\n", "}", "\n", "return", "UnpackResponse", "(", "resp", ")", "\n", "}" ]
// ReadUnpackedResponse reads and parses data from the underlying // TCP connection according to the NSQ TCP protocol spec and // returns the frameType, data or error
[ "ReadUnpackedResponse", "reads", "and", "parses", "data", "from", "the", "underlying", "TCP", "connection", "according", "to", "the", "NSQ", "TCP", "protocol", "spec", "and", "returns", "the", "frameType", "data", "or", "error" ]
61f49c096d0d767be61e4de06f724e1cb5fd85d7
https://github.com/nsqio/go-nsq/blob/61f49c096d0d767be61e4de06f724e1cb5fd85d7/protocol.go#L90-L96
train
nsqio/go-nsq
conn.go
NewConn
func NewConn(addr string, config *Config, delegate ConnDelegate) *Conn { if !config.initialized { panic("Config must be created with NewConfig()") } return &Conn{ addr: addr, config: config, delegate: delegate, maxRdyCount: 2500, lastMsgTimestamp: time.Now().UnixNano(), cmdChan: make(chan *Command), msgResponseChan: make(chan *msgResponse), exitChan: make(chan int), drainReady: make(chan int), } }
go
func NewConn(addr string, config *Config, delegate ConnDelegate) *Conn { if !config.initialized { panic("Config must be created with NewConfig()") } return &Conn{ addr: addr, config: config, delegate: delegate, maxRdyCount: 2500, lastMsgTimestamp: time.Now().UnixNano(), cmdChan: make(chan *Command), msgResponseChan: make(chan *msgResponse), exitChan: make(chan int), drainReady: make(chan int), } }
[ "func", "NewConn", "(", "addr", "string", ",", "config", "*", "Config", ",", "delegate", "ConnDelegate", ")", "*", "Conn", "{", "if", "!", "config", ".", "initialized", "{", "panic", "(", "\"", "\"", ")", "\n", "}", "\n", "return", "&", "Conn", "{", "addr", ":", "addr", ",", "config", ":", "config", ",", "delegate", ":", "delegate", ",", "maxRdyCount", ":", "2500", ",", "lastMsgTimestamp", ":", "time", ".", "Now", "(", ")", ".", "UnixNano", "(", ")", ",", "cmdChan", ":", "make", "(", "chan", "*", "Command", ")", ",", "msgResponseChan", ":", "make", "(", "chan", "*", "msgResponse", ")", ",", "exitChan", ":", "make", "(", "chan", "int", ")", ",", "drainReady", ":", "make", "(", "chan", "int", ")", ",", "}", "\n", "}" ]
// NewConn returns a new Conn instance
[ "NewConn", "returns", "a", "new", "Conn", "instance" ]
61f49c096d0d767be61e4de06f724e1cb5fd85d7
https://github.com/nsqio/go-nsq/blob/61f49c096d0d767be61e4de06f724e1cb5fd85d7/conn.go#L89-L107
train
nsqio/go-nsq
conn.go
Close
func (c *Conn) Close() error { atomic.StoreInt32(&c.closeFlag, 1) if c.conn != nil && atomic.LoadInt64(&c.messagesInFlight) == 0 { return c.conn.CloseRead() } return nil }
go
func (c *Conn) Close() error { atomic.StoreInt32(&c.closeFlag, 1) if c.conn != nil && atomic.LoadInt64(&c.messagesInFlight) == 0 { return c.conn.CloseRead() } return nil }
[ "func", "(", "c", "*", "Conn", ")", "Close", "(", ")", "error", "{", "atomic", ".", "StoreInt32", "(", "&", "c", ".", "closeFlag", ",", "1", ")", "\n", "if", "c", ".", "conn", "!=", "nil", "&&", "atomic", ".", "LoadInt64", "(", "&", "c", ".", "messagesInFlight", ")", "==", "0", "{", "return", "c", ".", "conn", ".", "CloseRead", "(", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// Close idempotently initiates connection close
[ "Close", "idempotently", "initiates", "connection", "close" ]
61f49c096d0d767be61e4de06f724e1cb5fd85d7
https://github.com/nsqio/go-nsq/blob/61f49c096d0d767be61e4de06f724e1cb5fd85d7/conn.go#L187-L193
train
nsqio/go-nsq
conn.go
SetRDY
func (c *Conn) SetRDY(rdy int64) { atomic.StoreInt64(&c.rdyCount, rdy) if rdy > 0 { atomic.StoreInt64(&c.lastRdyTimestamp, time.Now().UnixNano()) } }
go
func (c *Conn) SetRDY(rdy int64) { atomic.StoreInt64(&c.rdyCount, rdy) if rdy > 0 { atomic.StoreInt64(&c.lastRdyTimestamp, time.Now().UnixNano()) } }
[ "func", "(", "c", "*", "Conn", ")", "SetRDY", "(", "rdy", "int64", ")", "{", "atomic", ".", "StoreInt64", "(", "&", "c", ".", "rdyCount", ",", "rdy", ")", "\n", "if", "rdy", ">", "0", "{", "atomic", ".", "StoreInt64", "(", "&", "c", ".", "lastRdyTimestamp", ",", "time", ".", "Now", "(", ")", ".", "UnixNano", "(", ")", ")", "\n", "}", "\n", "}" ]
// SetRDY stores the specified RDY count
[ "SetRDY", "stores", "the", "specified", "RDY", "count" ]
61f49c096d0d767be61e4de06f724e1cb5fd85d7
https://github.com/nsqio/go-nsq/blob/61f49c096d0d767be61e4de06f724e1cb5fd85d7/conn.go#L213-L218
train
nsqio/go-nsq
conn.go
LastRdyTime
func (c *Conn) LastRdyTime() time.Time { return time.Unix(0, atomic.LoadInt64(&c.lastRdyTimestamp)) }
go
func (c *Conn) LastRdyTime() time.Time { return time.Unix(0, atomic.LoadInt64(&c.lastRdyTimestamp)) }
[ "func", "(", "c", "*", "Conn", ")", "LastRdyTime", "(", ")", "time", ".", "Time", "{", "return", "time", ".", "Unix", "(", "0", ",", "atomic", ".", "LoadInt64", "(", "&", "c", ".", "lastRdyTimestamp", ")", ")", "\n", "}" ]
// LastRdyTime returns the time of the last non-zero RDY // update for this connection
[ "LastRdyTime", "returns", "the", "time", "of", "the", "last", "non", "-", "zero", "RDY", "update", "for", "this", "connection" ]
61f49c096d0d767be61e4de06f724e1cb5fd85d7
https://github.com/nsqio/go-nsq/blob/61f49c096d0d767be61e4de06f724e1cb5fd85d7/conn.go#L228-L230
train
nsqio/go-nsq
conn.go
LastMessageTime
func (c *Conn) LastMessageTime() time.Time { return time.Unix(0, atomic.LoadInt64(&c.lastMsgTimestamp)) }
go
func (c *Conn) LastMessageTime() time.Time { return time.Unix(0, atomic.LoadInt64(&c.lastMsgTimestamp)) }
[ "func", "(", "c", "*", "Conn", ")", "LastMessageTime", "(", ")", "time", ".", "Time", "{", "return", "time", ".", "Unix", "(", "0", ",", "atomic", ".", "LoadInt64", "(", "&", "c", ".", "lastMsgTimestamp", ")", ")", "\n", "}" ]
// LastMessageTime returns a time.Time representing // the time at which the last message was received
[ "LastMessageTime", "returns", "a", "time", ".", "Time", "representing", "the", "time", "at", "which", "the", "last", "message", "was", "received" ]
61f49c096d0d767be61e4de06f724e1cb5fd85d7
https://github.com/nsqio/go-nsq/blob/61f49c096d0d767be61e4de06f724e1cb5fd85d7/conn.go#L234-L236
train
nsqio/go-nsq
conn.go
Read
func (c *Conn) Read(p []byte) (int, error) { c.conn.SetReadDeadline(time.Now().Add(c.config.ReadTimeout)) return c.r.Read(p) }
go
func (c *Conn) Read(p []byte) (int, error) { c.conn.SetReadDeadline(time.Now().Add(c.config.ReadTimeout)) return c.r.Read(p) }
[ "func", "(", "c", "*", "Conn", ")", "Read", "(", "p", "[", "]", "byte", ")", "(", "int", ",", "error", ")", "{", "c", ".", "conn", ".", "SetReadDeadline", "(", "time", ".", "Now", "(", ")", ".", "Add", "(", "c", ".", "config", ".", "ReadTimeout", ")", ")", "\n", "return", "c", ".", "r", ".", "Read", "(", "p", ")", "\n", "}" ]
// Read performs a deadlined read on the underlying TCP connection
[ "Read", "performs", "a", "deadlined", "read", "on", "the", "underlying", "TCP", "connection" ]
61f49c096d0d767be61e4de06f724e1cb5fd85d7
https://github.com/nsqio/go-nsq/blob/61f49c096d0d767be61e4de06f724e1cb5fd85d7/conn.go#L249-L252
train
nsqio/go-nsq
conn.go
Write
func (c *Conn) Write(p []byte) (int, error) { c.conn.SetWriteDeadline(time.Now().Add(c.config.WriteTimeout)) return c.w.Write(p) }
go
func (c *Conn) Write(p []byte) (int, error) { c.conn.SetWriteDeadline(time.Now().Add(c.config.WriteTimeout)) return c.w.Write(p) }
[ "func", "(", "c", "*", "Conn", ")", "Write", "(", "p", "[", "]", "byte", ")", "(", "int", ",", "error", ")", "{", "c", ".", "conn", ".", "SetWriteDeadline", "(", "time", ".", "Now", "(", ")", ".", "Add", "(", "c", ".", "config", ".", "WriteTimeout", ")", ")", "\n", "return", "c", ".", "w", ".", "Write", "(", "p", ")", "\n", "}" ]
// Write performs a deadlined write on the underlying TCP connection
[ "Write", "performs", "a", "deadlined", "write", "on", "the", "underlying", "TCP", "connection" ]
61f49c096d0d767be61e4de06f724e1cb5fd85d7
https://github.com/nsqio/go-nsq/blob/61f49c096d0d767be61e4de06f724e1cb5fd85d7/conn.go#L255-L258
train
nsqio/go-nsq
conn.go
WriteCommand
func (c *Conn) WriteCommand(cmd *Command) error { c.mtx.Lock() _, err := cmd.WriteTo(c) if err != nil { goto exit } err = c.Flush() exit: c.mtx.Unlock() if err != nil { c.log(LogLevelError, "IO error - %s", err) c.delegate.OnIOError(c, err) } return err }
go
func (c *Conn) WriteCommand(cmd *Command) error { c.mtx.Lock() _, err := cmd.WriteTo(c) if err != nil { goto exit } err = c.Flush() exit: c.mtx.Unlock() if err != nil { c.log(LogLevelError, "IO error - %s", err) c.delegate.OnIOError(c, err) } return err }
[ "func", "(", "c", "*", "Conn", ")", "WriteCommand", "(", "cmd", "*", "Command", ")", "error", "{", "c", ".", "mtx", ".", "Lock", "(", ")", "\n\n", "_", ",", "err", ":=", "cmd", ".", "WriteTo", "(", "c", ")", "\n", "if", "err", "!=", "nil", "{", "goto", "exit", "\n", "}", "\n", "err", "=", "c", ".", "Flush", "(", ")", "\n\n", "exit", ":", "c", ".", "mtx", ".", "Unlock", "(", ")", "\n", "if", "err", "!=", "nil", "{", "c", ".", "log", "(", "LogLevelError", ",", "\"", "\"", ",", "err", ")", "\n", "c", ".", "delegate", ".", "OnIOError", "(", "c", ",", "err", ")", "\n", "}", "\n", "return", "err", "\n", "}" ]
// WriteCommand is a goroutine safe method to write a Command // to this connection, and flush.
[ "WriteCommand", "is", "a", "goroutine", "safe", "method", "to", "write", "a", "Command", "to", "this", "connection", "and", "flush", "." ]
61f49c096d0d767be61e4de06f724e1cb5fd85d7
https://github.com/nsqio/go-nsq/blob/61f49c096d0d767be61e4de06f724e1cb5fd85d7/conn.go#L262-L278
train
nsqio/go-nsq
conn.go
Flush
func (c *Conn) Flush() error { if f, ok := c.w.(flusher); ok { return f.Flush() } return nil }
go
func (c *Conn) Flush() error { if f, ok := c.w.(flusher); ok { return f.Flush() } return nil }
[ "func", "(", "c", "*", "Conn", ")", "Flush", "(", ")", "error", "{", "if", "f", ",", "ok", ":=", "c", ".", "w", ".", "(", "flusher", ")", ";", "ok", "{", "return", "f", ".", "Flush", "(", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// Flush writes all buffered data to the underlying TCP connection
[ "Flush", "writes", "all", "buffered", "data", "to", "the", "underlying", "TCP", "connection" ]
61f49c096d0d767be61e4de06f724e1cb5fd85d7
https://github.com/nsqio/go-nsq/blob/61f49c096d0d767be61e4de06f724e1cb5fd85d7/conn.go#L285-L290
train
nsqio/go-nsq
command.go
String
func (c *Command) String() string { if len(c.Params) > 0 { return fmt.Sprintf("%s %s", c.Name, string(bytes.Join(c.Params, byteSpace))) } return string(c.Name) }
go
func (c *Command) String() string { if len(c.Params) > 0 { return fmt.Sprintf("%s %s", c.Name, string(bytes.Join(c.Params, byteSpace))) } return string(c.Name) }
[ "func", "(", "c", "*", "Command", ")", "String", "(", ")", "string", "{", "if", "len", "(", "c", ".", "Params", ")", ">", "0", "{", "return", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "c", ".", "Name", ",", "string", "(", "bytes", ".", "Join", "(", "c", ".", "Params", ",", "byteSpace", ")", ")", ")", "\n", "}", "\n", "return", "string", "(", "c", ".", "Name", ")", "\n", "}" ]
// String returns the name and parameters of the Command
[ "String", "returns", "the", "name", "and", "parameters", "of", "the", "Command" ]
61f49c096d0d767be61e4de06f724e1cb5fd85d7
https://github.com/nsqio/go-nsq/blob/61f49c096d0d767be61e4de06f724e1cb5fd85d7/command.go#L24-L29
train
nsqio/go-nsq
command.go
WriteTo
func (c *Command) WriteTo(w io.Writer) (int64, error) { var total int64 var buf [4]byte n, err := w.Write(c.Name) total += int64(n) if err != nil { return total, err } for _, param := range c.Params { n, err := w.Write(byteSpace) total += int64(n) if err != nil { return total, err } n, err = w.Write(param) total += int64(n) if err != nil { return total, err } } n, err = w.Write(byteNewLine) total += int64(n) if err != nil { return total, err } if c.Body != nil { bufs := buf[:] binary.BigEndian.PutUint32(bufs, uint32(len(c.Body))) n, err := w.Write(bufs) total += int64(n) if err != nil { return total, err } n, err = w.Write(c.Body) total += int64(n) if err != nil { return total, err } } return total, nil }
go
func (c *Command) WriteTo(w io.Writer) (int64, error) { var total int64 var buf [4]byte n, err := w.Write(c.Name) total += int64(n) if err != nil { return total, err } for _, param := range c.Params { n, err := w.Write(byteSpace) total += int64(n) if err != nil { return total, err } n, err = w.Write(param) total += int64(n) if err != nil { return total, err } } n, err = w.Write(byteNewLine) total += int64(n) if err != nil { return total, err } if c.Body != nil { bufs := buf[:] binary.BigEndian.PutUint32(bufs, uint32(len(c.Body))) n, err := w.Write(bufs) total += int64(n) if err != nil { return total, err } n, err = w.Write(c.Body) total += int64(n) if err != nil { return total, err } } return total, nil }
[ "func", "(", "c", "*", "Command", ")", "WriteTo", "(", "w", "io", ".", "Writer", ")", "(", "int64", ",", "error", ")", "{", "var", "total", "int64", "\n", "var", "buf", "[", "4", "]", "byte", "\n\n", "n", ",", "err", ":=", "w", ".", "Write", "(", "c", ".", "Name", ")", "\n", "total", "+=", "int64", "(", "n", ")", "\n", "if", "err", "!=", "nil", "{", "return", "total", ",", "err", "\n", "}", "\n\n", "for", "_", ",", "param", ":=", "range", "c", ".", "Params", "{", "n", ",", "err", ":=", "w", ".", "Write", "(", "byteSpace", ")", "\n", "total", "+=", "int64", "(", "n", ")", "\n", "if", "err", "!=", "nil", "{", "return", "total", ",", "err", "\n", "}", "\n", "n", ",", "err", "=", "w", ".", "Write", "(", "param", ")", "\n", "total", "+=", "int64", "(", "n", ")", "\n", "if", "err", "!=", "nil", "{", "return", "total", ",", "err", "\n", "}", "\n", "}", "\n\n", "n", ",", "err", "=", "w", ".", "Write", "(", "byteNewLine", ")", "\n", "total", "+=", "int64", "(", "n", ")", "\n", "if", "err", "!=", "nil", "{", "return", "total", ",", "err", "\n", "}", "\n\n", "if", "c", ".", "Body", "!=", "nil", "{", "bufs", ":=", "buf", "[", ":", "]", "\n", "binary", ".", "BigEndian", ".", "PutUint32", "(", "bufs", ",", "uint32", "(", "len", "(", "c", ".", "Body", ")", ")", ")", "\n", "n", ",", "err", ":=", "w", ".", "Write", "(", "bufs", ")", "\n", "total", "+=", "int64", "(", "n", ")", "\n", "if", "err", "!=", "nil", "{", "return", "total", ",", "err", "\n", "}", "\n", "n", ",", "err", "=", "w", ".", "Write", "(", "c", ".", "Body", ")", "\n", "total", "+=", "int64", "(", "n", ")", "\n", "if", "err", "!=", "nil", "{", "return", "total", ",", "err", "\n", "}", "\n", "}", "\n\n", "return", "total", ",", "nil", "\n", "}" ]
// WriteTo implements the WriterTo interface and // serializes the Command to the supplied Writer. // // It is suggested that the target Writer is buffered // to avoid performing many system calls.
[ "WriteTo", "implements", "the", "WriterTo", "interface", "and", "serializes", "the", "Command", "to", "the", "supplied", "Writer", ".", "It", "is", "suggested", "that", "the", "target", "Writer", "is", "buffered", "to", "avoid", "performing", "many", "system", "calls", "." ]
61f49c096d0d767be61e4de06f724e1cb5fd85d7
https://github.com/nsqio/go-nsq/blob/61f49c096d0d767be61e4de06f724e1cb5fd85d7/command.go#L36-L81
train
nsqio/go-nsq
command.go
Auth
func Auth(secret string) (*Command, error) { return &Command{[]byte("AUTH"), nil, []byte(secret)}, nil }
go
func Auth(secret string) (*Command, error) { return &Command{[]byte("AUTH"), nil, []byte(secret)}, nil }
[ "func", "Auth", "(", "secret", "string", ")", "(", "*", "Command", ",", "error", ")", "{", "return", "&", "Command", "{", "[", "]", "byte", "(", "\"", "\"", ")", ",", "nil", ",", "[", "]", "byte", "(", "secret", ")", "}", ",", "nil", "\n", "}" ]
// Auth sends credentials for authentication // // After `Identify`, this is usually the first message sent, if auth is used.
[ "Auth", "sends", "credentials", "for", "authentication", "After", "Identify", "this", "is", "usually", "the", "first", "message", "sent", "if", "auth", "is", "used", "." ]
61f49c096d0d767be61e4de06f724e1cb5fd85d7
https://github.com/nsqio/go-nsq/blob/61f49c096d0d767be61e4de06f724e1cb5fd85d7/command.go#L102-L104
train
nsqio/go-nsq
command.go
Publish
func Publish(topic string, body []byte) *Command { var params = [][]byte{[]byte(topic)} return &Command{[]byte("PUB"), params, body} }
go
func Publish(topic string, body []byte) *Command { var params = [][]byte{[]byte(topic)} return &Command{[]byte("PUB"), params, body} }
[ "func", "Publish", "(", "topic", "string", ",", "body", "[", "]", "byte", ")", "*", "Command", "{", "var", "params", "=", "[", "]", "[", "]", "byte", "{", "[", "]", "byte", "(", "topic", ")", "}", "\n", "return", "&", "Command", "{", "[", "]", "byte", "(", "\"", "\"", ")", ",", "params", ",", "body", "}", "\n", "}" ]
// Publish creates a new Command to write a message to a given topic
[ "Publish", "creates", "a", "new", "Command", "to", "write", "a", "message", "to", "a", "given", "topic" ]
61f49c096d0d767be61e4de06f724e1cb5fd85d7
https://github.com/nsqio/go-nsq/blob/61f49c096d0d767be61e4de06f724e1cb5fd85d7/command.go#L131-L134
train
nsqio/go-nsq
command.go
DeferredPublish
func DeferredPublish(topic string, delay time.Duration, body []byte) *Command { var params = [][]byte{[]byte(topic), []byte(strconv.Itoa(int(delay / time.Millisecond)))} return &Command{[]byte("DPUB"), params, body} }
go
func DeferredPublish(topic string, delay time.Duration, body []byte) *Command { var params = [][]byte{[]byte(topic), []byte(strconv.Itoa(int(delay / time.Millisecond)))} return &Command{[]byte("DPUB"), params, body} }
[ "func", "DeferredPublish", "(", "topic", "string", ",", "delay", "time", ".", "Duration", ",", "body", "[", "]", "byte", ")", "*", "Command", "{", "var", "params", "=", "[", "]", "[", "]", "byte", "{", "[", "]", "byte", "(", "topic", ")", ",", "[", "]", "byte", "(", "strconv", ".", "Itoa", "(", "int", "(", "delay", "/", "time", ".", "Millisecond", ")", ")", ")", "}", "\n", "return", "&", "Command", "{", "[", "]", "byte", "(", "\"", "\"", ")", ",", "params", ",", "body", "}", "\n", "}" ]
// DeferredPublish creates a new Command to write a message to a given topic // where the message will queue at the channel level until the timeout expires
[ "DeferredPublish", "creates", "a", "new", "Command", "to", "write", "a", "message", "to", "a", "given", "topic", "where", "the", "message", "will", "queue", "at", "the", "channel", "level", "until", "the", "timeout", "expires" ]
61f49c096d0d767be61e4de06f724e1cb5fd85d7
https://github.com/nsqio/go-nsq/blob/61f49c096d0d767be61e4de06f724e1cb5fd85d7/command.go#L138-L141
train
nsqio/go-nsq
command.go
Ready
func Ready(count int) *Command { var params = [][]byte{[]byte(strconv.Itoa(count))} return &Command{[]byte("RDY"), params, nil} }
go
func Ready(count int) *Command { var params = [][]byte{[]byte(strconv.Itoa(count))} return &Command{[]byte("RDY"), params, nil} }
[ "func", "Ready", "(", "count", "int", ")", "*", "Command", "{", "var", "params", "=", "[", "]", "[", "]", "byte", "{", "[", "]", "byte", "(", "strconv", ".", "Itoa", "(", "count", ")", ")", "}", "\n", "return", "&", "Command", "{", "[", "]", "byte", "(", "\"", "\"", ")", ",", "params", ",", "nil", "}", "\n", "}" ]
// Ready creates a new Command to specify // the number of messages a client is willing to receive
[ "Ready", "creates", "a", "new", "Command", "to", "specify", "the", "number", "of", "messages", "a", "client", "is", "willing", "to", "receive" ]
61f49c096d0d767be61e4de06f724e1cb5fd85d7
https://github.com/nsqio/go-nsq/blob/61f49c096d0d767be61e4de06f724e1cb5fd85d7/command.go#L182-L185
train
nsqio/go-nsq
consumer.go
Stats
func (r *Consumer) Stats() *ConsumerStats { return &ConsumerStats{ MessagesReceived: atomic.LoadUint64(&r.messagesReceived), MessagesFinished: atomic.LoadUint64(&r.messagesFinished), MessagesRequeued: atomic.LoadUint64(&r.messagesRequeued), Connections: len(r.conns()), } }
go
func (r *Consumer) Stats() *ConsumerStats { return &ConsumerStats{ MessagesReceived: atomic.LoadUint64(&r.messagesReceived), MessagesFinished: atomic.LoadUint64(&r.messagesFinished), MessagesRequeued: atomic.LoadUint64(&r.messagesRequeued), Connections: len(r.conns()), } }
[ "func", "(", "r", "*", "Consumer", ")", "Stats", "(", ")", "*", "ConsumerStats", "{", "return", "&", "ConsumerStats", "{", "MessagesReceived", ":", "atomic", ".", "LoadUint64", "(", "&", "r", ".", "messagesReceived", ")", ",", "MessagesFinished", ":", "atomic", ".", "LoadUint64", "(", "&", "r", ".", "messagesFinished", ")", ",", "MessagesRequeued", ":", "atomic", ".", "LoadUint64", "(", "&", "r", ".", "messagesRequeued", ")", ",", "Connections", ":", "len", "(", "r", ".", "conns", "(", ")", ")", ",", "}", "\n", "}" ]
// Stats retrieves the current connection and message statistics for a Consumer
[ "Stats", "retrieves", "the", "current", "connection", "and", "message", "statistics", "for", "a", "Consumer" ]
61f49c096d0d767be61e4de06f724e1cb5fd85d7
https://github.com/nsqio/go-nsq/blob/61f49c096d0d767be61e4de06f724e1cb5fd85d7/consumer.go#L192-L199
train
nsqio/go-nsq
consumer.go
perConnMaxInFlight
func (r *Consumer) perConnMaxInFlight() int64 { b := float64(r.getMaxInFlight()) s := b / float64(len(r.conns())) return int64(math.Min(math.Max(1, s), b)) }
go
func (r *Consumer) perConnMaxInFlight() int64 { b := float64(r.getMaxInFlight()) s := b / float64(len(r.conns())) return int64(math.Min(math.Max(1, s), b)) }
[ "func", "(", "r", "*", "Consumer", ")", "perConnMaxInFlight", "(", ")", "int64", "{", "b", ":=", "float64", "(", "r", ".", "getMaxInFlight", "(", ")", ")", "\n", "s", ":=", "b", "/", "float64", "(", "len", "(", "r", ".", "conns", "(", ")", ")", ")", "\n", "return", "int64", "(", "math", ".", "Min", "(", "math", ".", "Max", "(", "1", ",", "s", ")", ",", "b", ")", ")", "\n", "}" ]
// perConnMaxInFlight calculates the per-connection max-in-flight count. // // This may change dynamically based on the number of connections to nsqd the Consumer // is responsible for.
[ "perConnMaxInFlight", "calculates", "the", "per", "-", "connection", "max", "-", "in", "-", "flight", "count", ".", "This", "may", "change", "dynamically", "based", "on", "the", "number", "of", "connections", "to", "nsqd", "the", "Consumer", "is", "responsible", "for", "." ]
61f49c096d0d767be61e4de06f724e1cb5fd85d7
https://github.com/nsqio/go-nsq/blob/61f49c096d0d767be61e4de06f724e1cb5fd85d7/consumer.go#L257-L261
train
nsqio/go-nsq
consumer.go
ConnectToNSQLookupd
func (r *Consumer) ConnectToNSQLookupd(addr string) error { if atomic.LoadInt32(&r.stopFlag) == 1 { return errors.New("consumer stopped") } if atomic.LoadInt32(&r.runningHandlers) == 0 { return errors.New("no handlers") } if err := validatedLookupAddr(addr); err != nil { return err } atomic.StoreInt32(&r.connectedFlag, 1) r.mtx.Lock() for _, x := range r.lookupdHTTPAddrs { if x == addr { r.mtx.Unlock() return nil } } r.lookupdHTTPAddrs = append(r.lookupdHTTPAddrs, addr) numLookupd := len(r.lookupdHTTPAddrs) r.mtx.Unlock() // if this is the first one, kick off the go loop if numLookupd == 1 { r.queryLookupd() r.wg.Add(1) go r.lookupdLoop() } return nil }
go
func (r *Consumer) ConnectToNSQLookupd(addr string) error { if atomic.LoadInt32(&r.stopFlag) == 1 { return errors.New("consumer stopped") } if atomic.LoadInt32(&r.runningHandlers) == 0 { return errors.New("no handlers") } if err := validatedLookupAddr(addr); err != nil { return err } atomic.StoreInt32(&r.connectedFlag, 1) r.mtx.Lock() for _, x := range r.lookupdHTTPAddrs { if x == addr { r.mtx.Unlock() return nil } } r.lookupdHTTPAddrs = append(r.lookupdHTTPAddrs, addr) numLookupd := len(r.lookupdHTTPAddrs) r.mtx.Unlock() // if this is the first one, kick off the go loop if numLookupd == 1 { r.queryLookupd() r.wg.Add(1) go r.lookupdLoop() } return nil }
[ "func", "(", "r", "*", "Consumer", ")", "ConnectToNSQLookupd", "(", "addr", "string", ")", "error", "{", "if", "atomic", ".", "LoadInt32", "(", "&", "r", ".", "stopFlag", ")", "==", "1", "{", "return", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n", "if", "atomic", ".", "LoadInt32", "(", "&", "r", ".", "runningHandlers", ")", "==", "0", "{", "return", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n\n", "if", "err", ":=", "validatedLookupAddr", "(", "addr", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "atomic", ".", "StoreInt32", "(", "&", "r", ".", "connectedFlag", ",", "1", ")", "\n\n", "r", ".", "mtx", ".", "Lock", "(", ")", "\n", "for", "_", ",", "x", ":=", "range", "r", ".", "lookupdHTTPAddrs", "{", "if", "x", "==", "addr", "{", "r", ".", "mtx", ".", "Unlock", "(", ")", "\n", "return", "nil", "\n", "}", "\n", "}", "\n", "r", ".", "lookupdHTTPAddrs", "=", "append", "(", "r", ".", "lookupdHTTPAddrs", ",", "addr", ")", "\n", "numLookupd", ":=", "len", "(", "r", ".", "lookupdHTTPAddrs", ")", "\n", "r", ".", "mtx", ".", "Unlock", "(", ")", "\n\n", "// if this is the first one, kick off the go loop", "if", "numLookupd", "==", "1", "{", "r", ".", "queryLookupd", "(", ")", "\n", "r", ".", "wg", ".", "Add", "(", "1", ")", "\n", "go", "r", ".", "lookupdLoop", "(", ")", "\n", "}", "\n\n", "return", "nil", "\n", "}" ]
// ConnectToNSQLookupd adds an nsqlookupd address to the list for this Consumer instance. // // If it is the first to be added, it initiates an HTTP request to discover nsqd // producers for the configured topic. // // A goroutine is spawned to handle continual polling.
[ "ConnectToNSQLookupd", "adds", "an", "nsqlookupd", "address", "to", "the", "list", "for", "this", "Consumer", "instance", ".", "If", "it", "is", "the", "first", "to", "be", "added", "it", "initiates", "an", "HTTP", "request", "to", "discover", "nsqd", "producers", "for", "the", "configured", "topic", ".", "A", "goroutine", "is", "spawned", "to", "handle", "continual", "polling", "." ]
61f49c096d0d767be61e4de06f724e1cb5fd85d7
https://github.com/nsqio/go-nsq/blob/61f49c096d0d767be61e4de06f724e1cb5fd85d7/consumer.go#L304-L337
train
nsqio/go-nsq
consumer.go
ConnectToNSQLookupds
func (r *Consumer) ConnectToNSQLookupds(addresses []string) error { for _, addr := range addresses { err := r.ConnectToNSQLookupd(addr) if err != nil { return err } } return nil }
go
func (r *Consumer) ConnectToNSQLookupds(addresses []string) error { for _, addr := range addresses { err := r.ConnectToNSQLookupd(addr) if err != nil { return err } } return nil }
[ "func", "(", "r", "*", "Consumer", ")", "ConnectToNSQLookupds", "(", "addresses", "[", "]", "string", ")", "error", "{", "for", "_", ",", "addr", ":=", "range", "addresses", "{", "err", ":=", "r", ".", "ConnectToNSQLookupd", "(", "addr", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// ConnectToNSQLookupds adds multiple nsqlookupd address to the list for this Consumer instance. // // If adding the first address it initiates an HTTP request to discover nsqd // producers for the configured topic. // // A goroutine is spawned to handle continual polling.
[ "ConnectToNSQLookupds", "adds", "multiple", "nsqlookupd", "address", "to", "the", "list", "for", "this", "Consumer", "instance", ".", "If", "adding", "the", "first", "address", "it", "initiates", "an", "HTTP", "request", "to", "discover", "nsqd", "producers", "for", "the", "configured", "topic", ".", "A", "goroutine", "is", "spawned", "to", "handle", "continual", "polling", "." ]
61f49c096d0d767be61e4de06f724e1cb5fd85d7
https://github.com/nsqio/go-nsq/blob/61f49c096d0d767be61e4de06f724e1cb5fd85d7/consumer.go#L345-L353
train
nsqio/go-nsq
consumer.go
lookupdLoop
func (r *Consumer) lookupdLoop() { // add some jitter so that multiple consumers discovering the same topic, // when restarted at the same time, dont all connect at once. r.rngMtx.Lock() jitter := time.Duration(int64(r.rng.Float64() * r.config.LookupdPollJitter * float64(r.config.LookupdPollInterval))) r.rngMtx.Unlock() var ticker *time.Ticker select { case <-time.After(jitter): case <-r.exitChan: goto exit } ticker = time.NewTicker(r.config.LookupdPollInterval) for { select { case <-ticker.C: r.queryLookupd() case <-r.lookupdRecheckChan: r.queryLookupd() case <-r.exitChan: goto exit } } exit: if ticker != nil { ticker.Stop() } r.log(LogLevelInfo, "exiting lookupdLoop") r.wg.Done() }
go
func (r *Consumer) lookupdLoop() { // add some jitter so that multiple consumers discovering the same topic, // when restarted at the same time, dont all connect at once. r.rngMtx.Lock() jitter := time.Duration(int64(r.rng.Float64() * r.config.LookupdPollJitter * float64(r.config.LookupdPollInterval))) r.rngMtx.Unlock() var ticker *time.Ticker select { case <-time.After(jitter): case <-r.exitChan: goto exit } ticker = time.NewTicker(r.config.LookupdPollInterval) for { select { case <-ticker.C: r.queryLookupd() case <-r.lookupdRecheckChan: r.queryLookupd() case <-r.exitChan: goto exit } } exit: if ticker != nil { ticker.Stop() } r.log(LogLevelInfo, "exiting lookupdLoop") r.wg.Done() }
[ "func", "(", "r", "*", "Consumer", ")", "lookupdLoop", "(", ")", "{", "// add some jitter so that multiple consumers discovering the same topic,", "// when restarted at the same time, dont all connect at once.", "r", ".", "rngMtx", ".", "Lock", "(", ")", "\n", "jitter", ":=", "time", ".", "Duration", "(", "int64", "(", "r", ".", "rng", ".", "Float64", "(", ")", "*", "r", ".", "config", ".", "LookupdPollJitter", "*", "float64", "(", "r", ".", "config", ".", "LookupdPollInterval", ")", ")", ")", "\n", "r", ".", "rngMtx", ".", "Unlock", "(", ")", "\n", "var", "ticker", "*", "time", ".", "Ticker", "\n\n", "select", "{", "case", "<-", "time", ".", "After", "(", "jitter", ")", ":", "case", "<-", "r", ".", "exitChan", ":", "goto", "exit", "\n", "}", "\n\n", "ticker", "=", "time", ".", "NewTicker", "(", "r", ".", "config", ".", "LookupdPollInterval", ")", "\n\n", "for", "{", "select", "{", "case", "<-", "ticker", ".", "C", ":", "r", ".", "queryLookupd", "(", ")", "\n", "case", "<-", "r", ".", "lookupdRecheckChan", ":", "r", ".", "queryLookupd", "(", ")", "\n", "case", "<-", "r", ".", "exitChan", ":", "goto", "exit", "\n", "}", "\n", "}", "\n\n", "exit", ":", "if", "ticker", "!=", "nil", "{", "ticker", ".", "Stop", "(", ")", "\n", "}", "\n", "r", ".", "log", "(", "LogLevelInfo", ",", "\"", "\"", ")", "\n", "r", ".", "wg", ".", "Done", "(", ")", "\n", "}" ]
// poll all known lookup servers every LookupdPollInterval
[ "poll", "all", "known", "lookup", "servers", "every", "LookupdPollInterval" ]
61f49c096d0d767be61e4de06f724e1cb5fd85d7
https://github.com/nsqio/go-nsq/blob/61f49c096d0d767be61e4de06f724e1cb5fd85d7/consumer.go#L370-L404
train
nsqio/go-nsq
consumer.go
nextLookupdEndpoint
func (r *Consumer) nextLookupdEndpoint() string { r.mtx.RLock() if r.lookupdQueryIndex >= len(r.lookupdHTTPAddrs) { r.lookupdQueryIndex = 0 } addr := r.lookupdHTTPAddrs[r.lookupdQueryIndex] num := len(r.lookupdHTTPAddrs) r.mtx.RUnlock() r.lookupdQueryIndex = (r.lookupdQueryIndex + 1) % num urlString := addr if !strings.Contains(urlString, "://") { urlString = "http://" + addr } u, err := url.Parse(urlString) if err != nil { panic(err) } if u.Path == "/" || u.Path == "" { u.Path = "/lookup" } v, err := url.ParseQuery(u.RawQuery) v.Add("topic", r.topic) u.RawQuery = v.Encode() return u.String() }
go
func (r *Consumer) nextLookupdEndpoint() string { r.mtx.RLock() if r.lookupdQueryIndex >= len(r.lookupdHTTPAddrs) { r.lookupdQueryIndex = 0 } addr := r.lookupdHTTPAddrs[r.lookupdQueryIndex] num := len(r.lookupdHTTPAddrs) r.mtx.RUnlock() r.lookupdQueryIndex = (r.lookupdQueryIndex + 1) % num urlString := addr if !strings.Contains(urlString, "://") { urlString = "http://" + addr } u, err := url.Parse(urlString) if err != nil { panic(err) } if u.Path == "/" || u.Path == "" { u.Path = "/lookup" } v, err := url.ParseQuery(u.RawQuery) v.Add("topic", r.topic) u.RawQuery = v.Encode() return u.String() }
[ "func", "(", "r", "*", "Consumer", ")", "nextLookupdEndpoint", "(", ")", "string", "{", "r", ".", "mtx", ".", "RLock", "(", ")", "\n", "if", "r", ".", "lookupdQueryIndex", ">=", "len", "(", "r", ".", "lookupdHTTPAddrs", ")", "{", "r", ".", "lookupdQueryIndex", "=", "0", "\n", "}", "\n", "addr", ":=", "r", ".", "lookupdHTTPAddrs", "[", "r", ".", "lookupdQueryIndex", "]", "\n", "num", ":=", "len", "(", "r", ".", "lookupdHTTPAddrs", ")", "\n", "r", ".", "mtx", ".", "RUnlock", "(", ")", "\n", "r", ".", "lookupdQueryIndex", "=", "(", "r", ".", "lookupdQueryIndex", "+", "1", ")", "%", "num", "\n\n", "urlString", ":=", "addr", "\n", "if", "!", "strings", ".", "Contains", "(", "urlString", ",", "\"", "\"", ")", "{", "urlString", "=", "\"", "\"", "+", "addr", "\n", "}", "\n\n", "u", ",", "err", ":=", "url", ".", "Parse", "(", "urlString", ")", "\n", "if", "err", "!=", "nil", "{", "panic", "(", "err", ")", "\n", "}", "\n", "if", "u", ".", "Path", "==", "\"", "\"", "||", "u", ".", "Path", "==", "\"", "\"", "{", "u", ".", "Path", "=", "\"", "\"", "\n", "}", "\n\n", "v", ",", "err", ":=", "url", ".", "ParseQuery", "(", "u", ".", "RawQuery", ")", "\n", "v", ".", "Add", "(", "\"", "\"", ",", "r", ".", "topic", ")", "\n", "u", ".", "RawQuery", "=", "v", ".", "Encode", "(", ")", "\n", "return", "u", ".", "String", "(", ")", "\n", "}" ]
// return the next lookupd endpoint to query // keeping track of which one was last used
[ "return", "the", "next", "lookupd", "endpoint", "to", "query", "keeping", "track", "of", "which", "one", "was", "last", "used" ]
61f49c096d0d767be61e4de06f724e1cb5fd85d7
https://github.com/nsqio/go-nsq/blob/61f49c096d0d767be61e4de06f724e1cb5fd85d7/consumer.go#L408-L435
train
nsqio/go-nsq
consumer.go
queryLookupd
func (r *Consumer) queryLookupd() { retries := 0 retry: endpoint := r.nextLookupdEndpoint() r.log(LogLevelInfo, "querying nsqlookupd %s", endpoint) var data lookupResp err := apiRequestNegotiateV1("GET", endpoint, nil, &data) if err != nil { r.log(LogLevelError, "error querying nsqlookupd (%s) - %s", endpoint, err) retries++ if retries < 3 { r.log(LogLevelInfo, "retrying with next nsqlookupd") goto retry } return } var nsqdAddrs []string for _, producer := range data.Producers { broadcastAddress := producer.BroadcastAddress port := producer.TCPPort joined := net.JoinHostPort(broadcastAddress, strconv.Itoa(port)) nsqdAddrs = append(nsqdAddrs, joined) } // apply filter if discoveryFilter, ok := r.behaviorDelegate.(DiscoveryFilter); ok { nsqdAddrs = discoveryFilter.Filter(nsqdAddrs) } for _, addr := range nsqdAddrs { err = r.ConnectToNSQD(addr) if err != nil && err != ErrAlreadyConnected { r.log(LogLevelError, "(%s) error connecting to nsqd - %s", addr, err) continue } } }
go
func (r *Consumer) queryLookupd() { retries := 0 retry: endpoint := r.nextLookupdEndpoint() r.log(LogLevelInfo, "querying nsqlookupd %s", endpoint) var data lookupResp err := apiRequestNegotiateV1("GET", endpoint, nil, &data) if err != nil { r.log(LogLevelError, "error querying nsqlookupd (%s) - %s", endpoint, err) retries++ if retries < 3 { r.log(LogLevelInfo, "retrying with next nsqlookupd") goto retry } return } var nsqdAddrs []string for _, producer := range data.Producers { broadcastAddress := producer.BroadcastAddress port := producer.TCPPort joined := net.JoinHostPort(broadcastAddress, strconv.Itoa(port)) nsqdAddrs = append(nsqdAddrs, joined) } // apply filter if discoveryFilter, ok := r.behaviorDelegate.(DiscoveryFilter); ok { nsqdAddrs = discoveryFilter.Filter(nsqdAddrs) } for _, addr := range nsqdAddrs { err = r.ConnectToNSQD(addr) if err != nil && err != ErrAlreadyConnected { r.log(LogLevelError, "(%s) error connecting to nsqd - %s", addr, err) continue } } }
[ "func", "(", "r", "*", "Consumer", ")", "queryLookupd", "(", ")", "{", "retries", ":=", "0", "\n\n", "retry", ":", "endpoint", ":=", "r", ".", "nextLookupdEndpoint", "(", ")", "\n\n", "r", ".", "log", "(", "LogLevelInfo", ",", "\"", "\"", ",", "endpoint", ")", "\n\n", "var", "data", "lookupResp", "\n", "err", ":=", "apiRequestNegotiateV1", "(", "\"", "\"", ",", "endpoint", ",", "nil", ",", "&", "data", ")", "\n", "if", "err", "!=", "nil", "{", "r", ".", "log", "(", "LogLevelError", ",", "\"", "\"", ",", "endpoint", ",", "err", ")", "\n", "retries", "++", "\n", "if", "retries", "<", "3", "{", "r", ".", "log", "(", "LogLevelInfo", ",", "\"", "\"", ")", "\n", "goto", "retry", "\n", "}", "\n", "return", "\n", "}", "\n\n", "var", "nsqdAddrs", "[", "]", "string", "\n", "for", "_", ",", "producer", ":=", "range", "data", ".", "Producers", "{", "broadcastAddress", ":=", "producer", ".", "BroadcastAddress", "\n", "port", ":=", "producer", ".", "TCPPort", "\n", "joined", ":=", "net", ".", "JoinHostPort", "(", "broadcastAddress", ",", "strconv", ".", "Itoa", "(", "port", ")", ")", "\n", "nsqdAddrs", "=", "append", "(", "nsqdAddrs", ",", "joined", ")", "\n", "}", "\n", "// apply filter", "if", "discoveryFilter", ",", "ok", ":=", "r", ".", "behaviorDelegate", ".", "(", "DiscoveryFilter", ")", ";", "ok", "{", "nsqdAddrs", "=", "discoveryFilter", ".", "Filter", "(", "nsqdAddrs", ")", "\n", "}", "\n", "for", "_", ",", "addr", ":=", "range", "nsqdAddrs", "{", "err", "=", "r", ".", "ConnectToNSQD", "(", "addr", ")", "\n", "if", "err", "!=", "nil", "&&", "err", "!=", "ErrAlreadyConnected", "{", "r", ".", "log", "(", "LogLevelError", ",", "\"", "\"", ",", "addr", ",", "err", ")", "\n", "continue", "\n", "}", "\n", "}", "\n", "}" ]
// make an HTTP req to one of the configured nsqlookupd instances to discover // which nsqd's provide the topic we are consuming. // // initiate a connection to any new producers that are identified.
[ "make", "an", "HTTP", "req", "to", "one", "of", "the", "configured", "nsqlookupd", "instances", "to", "discover", "which", "nsqd", "s", "provide", "the", "topic", "we", "are", "consuming", ".", "initiate", "a", "connection", "to", "any", "new", "producers", "that", "are", "identified", "." ]
61f49c096d0d767be61e4de06f724e1cb5fd85d7
https://github.com/nsqio/go-nsq/blob/61f49c096d0d767be61e4de06f724e1cb5fd85d7/consumer.go#L456-L494
train
nsqio/go-nsq
consumer.go
ConnectToNSQDs
func (r *Consumer) ConnectToNSQDs(addresses []string) error { for _, addr := range addresses { err := r.ConnectToNSQD(addr) if err != nil { return err } } return nil }
go
func (r *Consumer) ConnectToNSQDs(addresses []string) error { for _, addr := range addresses { err := r.ConnectToNSQD(addr) if err != nil { return err } } return nil }
[ "func", "(", "r", "*", "Consumer", ")", "ConnectToNSQDs", "(", "addresses", "[", "]", "string", ")", "error", "{", "for", "_", ",", "addr", ":=", "range", "addresses", "{", "err", ":=", "r", ".", "ConnectToNSQD", "(", "addr", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// ConnectToNSQDs takes multiple nsqd addresses to connect directly to. // // It is recommended to use ConnectToNSQLookupd so that topics are discovered // automatically. This method is useful when you want to connect to local instance.
[ "ConnectToNSQDs", "takes", "multiple", "nsqd", "addresses", "to", "connect", "directly", "to", ".", "It", "is", "recommended", "to", "use", "ConnectToNSQLookupd", "so", "that", "topics", "are", "discovered", "automatically", ".", "This", "method", "is", "useful", "when", "you", "want", "to", "connect", "to", "local", "instance", "." ]
61f49c096d0d767be61e4de06f724e1cb5fd85d7
https://github.com/nsqio/go-nsq/blob/61f49c096d0d767be61e4de06f724e1cb5fd85d7/consumer.go#L500-L508
train
nsqio/go-nsq
consumer.go
ConnectToNSQD
func (r *Consumer) ConnectToNSQD(addr string) error { if atomic.LoadInt32(&r.stopFlag) == 1 { return errors.New("consumer stopped") } if atomic.LoadInt32(&r.runningHandlers) == 0 { return errors.New("no handlers") } atomic.StoreInt32(&r.connectedFlag, 1) logger, logLvl := r.getLogger() conn := NewConn(addr, &r.config, &consumerConnDelegate{r}) conn.SetLogger(logger, logLvl, fmt.Sprintf("%3d [%s/%s] (%%s)", r.id, r.topic, r.channel)) r.mtx.Lock() _, pendingOk := r.pendingConnections[addr] _, ok := r.connections[addr] if ok || pendingOk { r.mtx.Unlock() return ErrAlreadyConnected } r.pendingConnections[addr] = conn if idx := indexOf(addr, r.nsqdTCPAddrs); idx == -1 { r.nsqdTCPAddrs = append(r.nsqdTCPAddrs, addr) } r.mtx.Unlock() r.log(LogLevelInfo, "(%s) connecting to nsqd", addr) cleanupConnection := func() { r.mtx.Lock() delete(r.pendingConnections, addr) r.mtx.Unlock() conn.Close() } resp, err := conn.Connect() if err != nil { cleanupConnection() return err } if resp != nil { if resp.MaxRdyCount < int64(r.getMaxInFlight()) { r.log(LogLevelWarning, "(%s) max RDY count %d < consumer max in flight %d, truncation possible", conn.String(), resp.MaxRdyCount, r.getMaxInFlight()) } } cmd := Subscribe(r.topic, r.channel) err = conn.WriteCommand(cmd) if err != nil { cleanupConnection() return fmt.Errorf("[%s] failed to subscribe to %s:%s - %s", conn, r.topic, r.channel, err.Error()) } r.mtx.Lock() delete(r.pendingConnections, addr) r.connections[addr] = conn r.mtx.Unlock() // pre-emptive signal to existing connections to lower their RDY count for _, c := range r.conns() { r.maybeUpdateRDY(c) } return nil }
go
func (r *Consumer) ConnectToNSQD(addr string) error { if atomic.LoadInt32(&r.stopFlag) == 1 { return errors.New("consumer stopped") } if atomic.LoadInt32(&r.runningHandlers) == 0 { return errors.New("no handlers") } atomic.StoreInt32(&r.connectedFlag, 1) logger, logLvl := r.getLogger() conn := NewConn(addr, &r.config, &consumerConnDelegate{r}) conn.SetLogger(logger, logLvl, fmt.Sprintf("%3d [%s/%s] (%%s)", r.id, r.topic, r.channel)) r.mtx.Lock() _, pendingOk := r.pendingConnections[addr] _, ok := r.connections[addr] if ok || pendingOk { r.mtx.Unlock() return ErrAlreadyConnected } r.pendingConnections[addr] = conn if idx := indexOf(addr, r.nsqdTCPAddrs); idx == -1 { r.nsqdTCPAddrs = append(r.nsqdTCPAddrs, addr) } r.mtx.Unlock() r.log(LogLevelInfo, "(%s) connecting to nsqd", addr) cleanupConnection := func() { r.mtx.Lock() delete(r.pendingConnections, addr) r.mtx.Unlock() conn.Close() } resp, err := conn.Connect() if err != nil { cleanupConnection() return err } if resp != nil { if resp.MaxRdyCount < int64(r.getMaxInFlight()) { r.log(LogLevelWarning, "(%s) max RDY count %d < consumer max in flight %d, truncation possible", conn.String(), resp.MaxRdyCount, r.getMaxInFlight()) } } cmd := Subscribe(r.topic, r.channel) err = conn.WriteCommand(cmd) if err != nil { cleanupConnection() return fmt.Errorf("[%s] failed to subscribe to %s:%s - %s", conn, r.topic, r.channel, err.Error()) } r.mtx.Lock() delete(r.pendingConnections, addr) r.connections[addr] = conn r.mtx.Unlock() // pre-emptive signal to existing connections to lower their RDY count for _, c := range r.conns() { r.maybeUpdateRDY(c) } return nil }
[ "func", "(", "r", "*", "Consumer", ")", "ConnectToNSQD", "(", "addr", "string", ")", "error", "{", "if", "atomic", ".", "LoadInt32", "(", "&", "r", ".", "stopFlag", ")", "==", "1", "{", "return", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n\n", "if", "atomic", ".", "LoadInt32", "(", "&", "r", ".", "runningHandlers", ")", "==", "0", "{", "return", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n\n", "atomic", ".", "StoreInt32", "(", "&", "r", ".", "connectedFlag", ",", "1", ")", "\n\n", "logger", ",", "logLvl", ":=", "r", ".", "getLogger", "(", ")", "\n\n", "conn", ":=", "NewConn", "(", "addr", ",", "&", "r", ".", "config", ",", "&", "consumerConnDelegate", "{", "r", "}", ")", "\n", "conn", ".", "SetLogger", "(", "logger", ",", "logLvl", ",", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "r", ".", "id", ",", "r", ".", "topic", ",", "r", ".", "channel", ")", ")", "\n\n", "r", ".", "mtx", ".", "Lock", "(", ")", "\n", "_", ",", "pendingOk", ":=", "r", ".", "pendingConnections", "[", "addr", "]", "\n", "_", ",", "ok", ":=", "r", ".", "connections", "[", "addr", "]", "\n", "if", "ok", "||", "pendingOk", "{", "r", ".", "mtx", ".", "Unlock", "(", ")", "\n", "return", "ErrAlreadyConnected", "\n", "}", "\n", "r", ".", "pendingConnections", "[", "addr", "]", "=", "conn", "\n", "if", "idx", ":=", "indexOf", "(", "addr", ",", "r", ".", "nsqdTCPAddrs", ")", ";", "idx", "==", "-", "1", "{", "r", ".", "nsqdTCPAddrs", "=", "append", "(", "r", ".", "nsqdTCPAddrs", ",", "addr", ")", "\n", "}", "\n", "r", ".", "mtx", ".", "Unlock", "(", ")", "\n\n", "r", ".", "log", "(", "LogLevelInfo", ",", "\"", "\"", ",", "addr", ")", "\n\n", "cleanupConnection", ":=", "func", "(", ")", "{", "r", ".", "mtx", ".", "Lock", "(", ")", "\n", "delete", "(", "r", ".", "pendingConnections", ",", "addr", ")", "\n", "r", ".", "mtx", ".", "Unlock", "(", ")", "\n", "conn", ".", "Close", "(", ")", "\n", "}", "\n\n", "resp", ",", "err", ":=", "conn", ".", "Connect", "(", ")", "\n", "if", "err", "!=", "nil", "{", "cleanupConnection", "(", ")", "\n", "return", "err", "\n", "}", "\n\n", "if", "resp", "!=", "nil", "{", "if", "resp", ".", "MaxRdyCount", "<", "int64", "(", "r", ".", "getMaxInFlight", "(", ")", ")", "{", "r", ".", "log", "(", "LogLevelWarning", ",", "\"", "\"", ",", "conn", ".", "String", "(", ")", ",", "resp", ".", "MaxRdyCount", ",", "r", ".", "getMaxInFlight", "(", ")", ")", "\n", "}", "\n", "}", "\n\n", "cmd", ":=", "Subscribe", "(", "r", ".", "topic", ",", "r", ".", "channel", ")", "\n", "err", "=", "conn", ".", "WriteCommand", "(", "cmd", ")", "\n", "if", "err", "!=", "nil", "{", "cleanupConnection", "(", ")", "\n", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "conn", ",", "r", ".", "topic", ",", "r", ".", "channel", ",", "err", ".", "Error", "(", ")", ")", "\n", "}", "\n\n", "r", ".", "mtx", ".", "Lock", "(", ")", "\n", "delete", "(", "r", ".", "pendingConnections", ",", "addr", ")", "\n", "r", ".", "connections", "[", "addr", "]", "=", "conn", "\n", "r", ".", "mtx", ".", "Unlock", "(", ")", "\n\n", "// pre-emptive signal to existing connections to lower their RDY count", "for", "_", ",", "c", ":=", "range", "r", ".", "conns", "(", ")", "{", "r", ".", "maybeUpdateRDY", "(", "c", ")", "\n", "}", "\n\n", "return", "nil", "\n", "}" ]
// ConnectToNSQD takes a nsqd address to connect directly to. // // It is recommended to use ConnectToNSQLookupd so that topics are discovered // automatically. This method is useful when you want to connect to a single, local, // instance.
[ "ConnectToNSQD", "takes", "a", "nsqd", "address", "to", "connect", "directly", "to", ".", "It", "is", "recommended", "to", "use", "ConnectToNSQLookupd", "so", "that", "topics", "are", "discovered", "automatically", ".", "This", "method", "is", "useful", "when", "you", "want", "to", "connect", "to", "a", "single", "local", "instance", "." ]
61f49c096d0d767be61e4de06f724e1cb5fd85d7
https://github.com/nsqio/go-nsq/blob/61f49c096d0d767be61e4de06f724e1cb5fd85d7/consumer.go#L515-L587
train
nsqio/go-nsq
consumer.go
DisconnectFromNSQD
func (r *Consumer) DisconnectFromNSQD(addr string) error { r.mtx.Lock() defer r.mtx.Unlock() idx := indexOf(addr, r.nsqdTCPAddrs) if idx == -1 { return ErrNotConnected } // slice delete r.nsqdTCPAddrs = append(r.nsqdTCPAddrs[:idx], r.nsqdTCPAddrs[idx+1:]...) pendingConn, pendingOk := r.pendingConnections[addr] conn, ok := r.connections[addr] if ok { conn.Close() } else if pendingOk { pendingConn.Close() } return nil }
go
func (r *Consumer) DisconnectFromNSQD(addr string) error { r.mtx.Lock() defer r.mtx.Unlock() idx := indexOf(addr, r.nsqdTCPAddrs) if idx == -1 { return ErrNotConnected } // slice delete r.nsqdTCPAddrs = append(r.nsqdTCPAddrs[:idx], r.nsqdTCPAddrs[idx+1:]...) pendingConn, pendingOk := r.pendingConnections[addr] conn, ok := r.connections[addr] if ok { conn.Close() } else if pendingOk { pendingConn.Close() } return nil }
[ "func", "(", "r", "*", "Consumer", ")", "DisconnectFromNSQD", "(", "addr", "string", ")", "error", "{", "r", ".", "mtx", ".", "Lock", "(", ")", "\n", "defer", "r", ".", "mtx", ".", "Unlock", "(", ")", "\n\n", "idx", ":=", "indexOf", "(", "addr", ",", "r", ".", "nsqdTCPAddrs", ")", "\n", "if", "idx", "==", "-", "1", "{", "return", "ErrNotConnected", "\n", "}", "\n\n", "// slice delete", "r", ".", "nsqdTCPAddrs", "=", "append", "(", "r", ".", "nsqdTCPAddrs", "[", ":", "idx", "]", ",", "r", ".", "nsqdTCPAddrs", "[", "idx", "+", "1", ":", "]", "...", ")", "\n\n", "pendingConn", ",", "pendingOk", ":=", "r", ".", "pendingConnections", "[", "addr", "]", "\n", "conn", ",", "ok", ":=", "r", ".", "connections", "[", "addr", "]", "\n\n", "if", "ok", "{", "conn", ".", "Close", "(", ")", "\n", "}", "else", "if", "pendingOk", "{", "pendingConn", ".", "Close", "(", ")", "\n", "}", "\n\n", "return", "nil", "\n", "}" ]
// DisconnectFromNSQD closes the connection to and removes the specified // `nsqd` address from the list
[ "DisconnectFromNSQD", "closes", "the", "connection", "to", "and", "removes", "the", "specified", "nsqd", "address", "from", "the", "list" ]
61f49c096d0d767be61e4de06f724e1cb5fd85d7
https://github.com/nsqio/go-nsq/blob/61f49c096d0d767be61e4de06f724e1cb5fd85d7/consumer.go#L600-L622
train
nsqio/go-nsq
consumer.go
DisconnectFromNSQLookupd
func (r *Consumer) DisconnectFromNSQLookupd(addr string) error { r.mtx.Lock() defer r.mtx.Unlock() idx := indexOf(addr, r.lookupdHTTPAddrs) if idx == -1 { return ErrNotConnected } if len(r.lookupdHTTPAddrs) == 1 { return fmt.Errorf("cannot disconnect from only remaining nsqlookupd HTTP address %s", addr) } r.lookupdHTTPAddrs = append(r.lookupdHTTPAddrs[:idx], r.lookupdHTTPAddrs[idx+1:]...) return nil }
go
func (r *Consumer) DisconnectFromNSQLookupd(addr string) error { r.mtx.Lock() defer r.mtx.Unlock() idx := indexOf(addr, r.lookupdHTTPAddrs) if idx == -1 { return ErrNotConnected } if len(r.lookupdHTTPAddrs) == 1 { return fmt.Errorf("cannot disconnect from only remaining nsqlookupd HTTP address %s", addr) } r.lookupdHTTPAddrs = append(r.lookupdHTTPAddrs[:idx], r.lookupdHTTPAddrs[idx+1:]...) return nil }
[ "func", "(", "r", "*", "Consumer", ")", "DisconnectFromNSQLookupd", "(", "addr", "string", ")", "error", "{", "r", ".", "mtx", ".", "Lock", "(", ")", "\n", "defer", "r", ".", "mtx", ".", "Unlock", "(", ")", "\n\n", "idx", ":=", "indexOf", "(", "addr", ",", "r", ".", "lookupdHTTPAddrs", ")", "\n", "if", "idx", "==", "-", "1", "{", "return", "ErrNotConnected", "\n", "}", "\n\n", "if", "len", "(", "r", ".", "lookupdHTTPAddrs", ")", "==", "1", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "addr", ")", "\n", "}", "\n\n", "r", ".", "lookupdHTTPAddrs", "=", "append", "(", "r", ".", "lookupdHTTPAddrs", "[", ":", "idx", "]", ",", "r", ".", "lookupdHTTPAddrs", "[", "idx", "+", "1", ":", "]", "...", ")", "\n\n", "return", "nil", "\n", "}" ]
// DisconnectFromNSQLookupd removes the specified `nsqlookupd` address // from the list used for periodic discovery.
[ "DisconnectFromNSQLookupd", "removes", "the", "specified", "nsqlookupd", "address", "from", "the", "list", "used", "for", "periodic", "discovery", "." ]
61f49c096d0d767be61e4de06f724e1cb5fd85d7
https://github.com/nsqio/go-nsq/blob/61f49c096d0d767be61e4de06f724e1cb5fd85d7/consumer.go#L626-L642
train
nsqio/go-nsq
message.go
Finish
func (m *Message) Finish() { if !atomic.CompareAndSwapInt32(&m.responded, 0, 1) { return } m.Delegate.OnFinish(m) }
go
func (m *Message) Finish() { if !atomic.CompareAndSwapInt32(&m.responded, 0, 1) { return } m.Delegate.OnFinish(m) }
[ "func", "(", "m", "*", "Message", ")", "Finish", "(", ")", "{", "if", "!", "atomic", ".", "CompareAndSwapInt32", "(", "&", "m", ".", "responded", ",", "0", ",", "1", ")", "{", "return", "\n", "}", "\n", "m", ".", "Delegate", ".", "OnFinish", "(", "m", ")", "\n", "}" ]
// Finish sends a FIN command to the nsqd which // sent this message
[ "Finish", "sends", "a", "FIN", "command", "to", "the", "nsqd", "which", "sent", "this", "message" ]
61f49c096d0d767be61e4de06f724e1cb5fd85d7
https://github.com/nsqio/go-nsq/blob/61f49c096d0d767be61e4de06f724e1cb5fd85d7/message.go#L66-L71
train
nsqio/go-nsq
message.go
Requeue
func (m *Message) Requeue(delay time.Duration) { m.doRequeue(delay, true) }
go
func (m *Message) Requeue(delay time.Duration) { m.doRequeue(delay, true) }
[ "func", "(", "m", "*", "Message", ")", "Requeue", "(", "delay", "time", ".", "Duration", ")", "{", "m", ".", "doRequeue", "(", "delay", ",", "true", ")", "\n", "}" ]
// Requeue sends a REQ command to the nsqd which // sent this message, using the supplied delay. // // A delay of -1 will automatically calculate // based on the number of attempts and the // configured default_requeue_delay
[ "Requeue", "sends", "a", "REQ", "command", "to", "the", "nsqd", "which", "sent", "this", "message", "using", "the", "supplied", "delay", ".", "A", "delay", "of", "-", "1", "will", "automatically", "calculate", "based", "on", "the", "number", "of", "attempts", "and", "the", "configured", "default_requeue_delay" ]
61f49c096d0d767be61e4de06f724e1cb5fd85d7
https://github.com/nsqio/go-nsq/blob/61f49c096d0d767be61e4de06f724e1cb5fd85d7/message.go#L88-L90
train
nsqio/go-nsq
message.go
RequeueWithoutBackoff
func (m *Message) RequeueWithoutBackoff(delay time.Duration) { m.doRequeue(delay, false) }
go
func (m *Message) RequeueWithoutBackoff(delay time.Duration) { m.doRequeue(delay, false) }
[ "func", "(", "m", "*", "Message", ")", "RequeueWithoutBackoff", "(", "delay", "time", ".", "Duration", ")", "{", "m", ".", "doRequeue", "(", "delay", ",", "false", ")", "\n", "}" ]
// RequeueWithoutBackoff sends a REQ command to the nsqd which // sent this message, using the supplied delay. // // Notably, using this method to respond does not trigger a backoff // event on the configured Delegate.
[ "RequeueWithoutBackoff", "sends", "a", "REQ", "command", "to", "the", "nsqd", "which", "sent", "this", "message", "using", "the", "supplied", "delay", ".", "Notably", "using", "this", "method", "to", "respond", "does", "not", "trigger", "a", "backoff", "event", "on", "the", "configured", "Delegate", "." ]
61f49c096d0d767be61e4de06f724e1cb5fd85d7
https://github.com/nsqio/go-nsq/blob/61f49c096d0d767be61e4de06f724e1cb5fd85d7/message.go#L97-L99
train
nsqio/go-nsq
producer.go
Publish
func (w *Producer) Publish(topic string, body []byte) error { return w.sendCommand(Publish(topic, body)) }
go
func (w *Producer) Publish(topic string, body []byte) error { return w.sendCommand(Publish(topic, body)) }
[ "func", "(", "w", "*", "Producer", ")", "Publish", "(", "topic", "string", ",", "body", "[", "]", "byte", ")", "error", "{", "return", "w", ".", "sendCommand", "(", "Publish", "(", "topic", ",", "body", ")", ")", "\n", "}" ]
// Publish synchronously publishes a message body to the specified topic, returning // an error if publish failed
[ "Publish", "synchronously", "publishes", "a", "message", "body", "to", "the", "specified", "topic", "returning", "an", "error", "if", "publish", "failed" ]
61f49c096d0d767be61e4de06f724e1cb5fd85d7
https://github.com/nsqio/go-nsq/blob/61f49c096d0d767be61e4de06f724e1cb5fd85d7/producer.go#L184-L186
train
nsqio/go-nsq
producer.go
MultiPublish
func (w *Producer) MultiPublish(topic string, body [][]byte) error { cmd, err := MultiPublish(topic, body) if err != nil { return err } return w.sendCommand(cmd) }
go
func (w *Producer) MultiPublish(topic string, body [][]byte) error { cmd, err := MultiPublish(topic, body) if err != nil { return err } return w.sendCommand(cmd) }
[ "func", "(", "w", "*", "Producer", ")", "MultiPublish", "(", "topic", "string", ",", "body", "[", "]", "[", "]", "byte", ")", "error", "{", "cmd", ",", "err", ":=", "MultiPublish", "(", "topic", ",", "body", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "return", "w", ".", "sendCommand", "(", "cmd", ")", "\n", "}" ]
// MultiPublish synchronously publishes a slice of message bodies to the specified topic, returning // an error if publish failed
[ "MultiPublish", "synchronously", "publishes", "a", "slice", "of", "message", "bodies", "to", "the", "specified", "topic", "returning", "an", "error", "if", "publish", "failed" ]
61f49c096d0d767be61e4de06f724e1cb5fd85d7
https://github.com/nsqio/go-nsq/blob/61f49c096d0d767be61e4de06f724e1cb5fd85d7/producer.go#L190-L196
train
nsqio/go-nsq
producer.go
DeferredPublish
func (w *Producer) DeferredPublish(topic string, delay time.Duration, body []byte) error { return w.sendCommand(DeferredPublish(topic, delay, body)) }
go
func (w *Producer) DeferredPublish(topic string, delay time.Duration, body []byte) error { return w.sendCommand(DeferredPublish(topic, delay, body)) }
[ "func", "(", "w", "*", "Producer", ")", "DeferredPublish", "(", "topic", "string", ",", "delay", "time", ".", "Duration", ",", "body", "[", "]", "byte", ")", "error", "{", "return", "w", ".", "sendCommand", "(", "DeferredPublish", "(", "topic", ",", "delay", ",", "body", ")", ")", "\n", "}" ]
// DeferredPublish synchronously publishes a message body to the specified topic // where the message will queue at the channel level until the timeout expires, returning // an error if publish failed
[ "DeferredPublish", "synchronously", "publishes", "a", "message", "body", "to", "the", "specified", "topic", "where", "the", "message", "will", "queue", "at", "the", "channel", "level", "until", "the", "timeout", "expires", "returning", "an", "error", "if", "publish", "failed" ]
61f49c096d0d767be61e4de06f724e1cb5fd85d7
https://github.com/nsqio/go-nsq/blob/61f49c096d0d767be61e4de06f724e1cb5fd85d7/producer.go#L201-L203
train
goftp/server
listformatter.go
Short
func (formatter listFormatter) Short() []byte { var buf bytes.Buffer for _, file := range formatter { fmt.Fprintf(&buf, "%s\r\n", file.Name()) } return buf.Bytes() }
go
func (formatter listFormatter) Short() []byte { var buf bytes.Buffer for _, file := range formatter { fmt.Fprintf(&buf, "%s\r\n", file.Name()) } return buf.Bytes() }
[ "func", "(", "formatter", "listFormatter", ")", "Short", "(", ")", "[", "]", "byte", "{", "var", "buf", "bytes", ".", "Buffer", "\n", "for", "_", ",", "file", ":=", "range", "formatter", "{", "fmt", ".", "Fprintf", "(", "&", "buf", ",", "\"", "\\r", "\\n", "\"", ",", "file", ".", "Name", "(", ")", ")", "\n", "}", "\n", "return", "buf", ".", "Bytes", "(", ")", "\n", "}" ]
// Short returns a string that lists the collection of files by name only, // one per line
[ "Short", "returns", "a", "string", "that", "lists", "the", "collection", "of", "files", "by", "name", "only", "one", "per", "line" ]
eabccc535b5a216dfa00bb8194563f73224a546d
https://github.com/goftp/server/blob/eabccc535b5a216dfa00bb8194563f73224a546d/listformatter.go#L18-L24
train
goftp/server
listformatter.go
Detailed
func (formatter listFormatter) Detailed() []byte { var buf bytes.Buffer for _, file := range formatter { fmt.Fprintf(&buf, file.Mode().String()) fmt.Fprintf(&buf, " 1 %s %s ", file.Owner(), file.Group()) fmt.Fprintf(&buf, lpad(strconv.FormatInt(file.Size(), 10), 12)) fmt.Fprintf(&buf, file.ModTime().Format(" Jan _2 15:04 ")) fmt.Fprintf(&buf, "%s\r\n", file.Name()) } return buf.Bytes() }
go
func (formatter listFormatter) Detailed() []byte { var buf bytes.Buffer for _, file := range formatter { fmt.Fprintf(&buf, file.Mode().String()) fmt.Fprintf(&buf, " 1 %s %s ", file.Owner(), file.Group()) fmt.Fprintf(&buf, lpad(strconv.FormatInt(file.Size(), 10), 12)) fmt.Fprintf(&buf, file.ModTime().Format(" Jan _2 15:04 ")) fmt.Fprintf(&buf, "%s\r\n", file.Name()) } return buf.Bytes() }
[ "func", "(", "formatter", "listFormatter", ")", "Detailed", "(", ")", "[", "]", "byte", "{", "var", "buf", "bytes", ".", "Buffer", "\n", "for", "_", ",", "file", ":=", "range", "formatter", "{", "fmt", ".", "Fprintf", "(", "&", "buf", ",", "file", ".", "Mode", "(", ")", ".", "String", "(", ")", ")", "\n", "fmt", ".", "Fprintf", "(", "&", "buf", ",", "\"", "\"", ",", "file", ".", "Owner", "(", ")", ",", "file", ".", "Group", "(", ")", ")", "\n", "fmt", ".", "Fprintf", "(", "&", "buf", ",", "lpad", "(", "strconv", ".", "FormatInt", "(", "file", ".", "Size", "(", ")", ",", "10", ")", ",", "12", ")", ")", "\n", "fmt", ".", "Fprintf", "(", "&", "buf", ",", "file", ".", "ModTime", "(", ")", ".", "Format", "(", "\"", "\"", ")", ")", "\n", "fmt", ".", "Fprintf", "(", "&", "buf", ",", "\"", "\\r", "\\n", "\"", ",", "file", ".", "Name", "(", ")", ")", "\n", "}", "\n", "return", "buf", ".", "Bytes", "(", ")", "\n", "}" ]
// Detailed returns a string that lists the collection of files with extra // detail, one per line
[ "Detailed", "returns", "a", "string", "that", "lists", "the", "collection", "of", "files", "with", "extra", "detail", "one", "per", "line" ]
eabccc535b5a216dfa00bb8194563f73224a546d
https://github.com/goftp/server/blob/eabccc535b5a216dfa00bb8194563f73224a546d/listformatter.go#L28-L38
train
goftp/server
auth.go
CheckPasswd
func (a *SimpleAuth) CheckPasswd(name, pass string) (bool, error) { if name != a.Name || pass != a.Password { return false, nil } return true, nil }
go
func (a *SimpleAuth) CheckPasswd(name, pass string) (bool, error) { if name != a.Name || pass != a.Password { return false, nil } return true, nil }
[ "func", "(", "a", "*", "SimpleAuth", ")", "CheckPasswd", "(", "name", ",", "pass", "string", ")", "(", "bool", ",", "error", ")", "{", "if", "name", "!=", "a", ".", "Name", "||", "pass", "!=", "a", ".", "Password", "{", "return", "false", ",", "nil", "\n", "}", "\n", "return", "true", ",", "nil", "\n", "}" ]
// CheckPasswd will check user's password
[ "CheckPasswd", "will", "check", "user", "s", "password" ]
eabccc535b5a216dfa00bb8194563f73224a546d
https://github.com/goftp/server/blob/eabccc535b5a216dfa00bb8194563f73224a546d/auth.go#L23-L28
train
goftp/server
server.go
serverOptsWithDefaults
func serverOptsWithDefaults(opts *ServerOpts) *ServerOpts { var newOpts ServerOpts if opts == nil { opts = &ServerOpts{} } if opts.Hostname == "" { newOpts.Hostname = "::" } else { newOpts.Hostname = opts.Hostname } if opts.Port == 0 { newOpts.Port = 3000 } else { newOpts.Port = opts.Port } newOpts.Factory = opts.Factory if opts.Name == "" { newOpts.Name = "Go FTP Server" } else { newOpts.Name = opts.Name } if opts.WelcomeMessage == "" { newOpts.WelcomeMessage = defaultWelcomeMessage } else { newOpts.WelcomeMessage = opts.WelcomeMessage } if opts.Auth != nil { newOpts.Auth = opts.Auth } newOpts.Logger = &StdLogger{} if opts.Logger != nil { newOpts.Logger = opts.Logger } newOpts.TLS = opts.TLS newOpts.KeyFile = opts.KeyFile newOpts.CertFile = opts.CertFile newOpts.ExplicitFTPS = opts.ExplicitFTPS newOpts.PublicIp = opts.PublicIp newOpts.PassivePorts = opts.PassivePorts return &newOpts }
go
func serverOptsWithDefaults(opts *ServerOpts) *ServerOpts { var newOpts ServerOpts if opts == nil { opts = &ServerOpts{} } if opts.Hostname == "" { newOpts.Hostname = "::" } else { newOpts.Hostname = opts.Hostname } if opts.Port == 0 { newOpts.Port = 3000 } else { newOpts.Port = opts.Port } newOpts.Factory = opts.Factory if opts.Name == "" { newOpts.Name = "Go FTP Server" } else { newOpts.Name = opts.Name } if opts.WelcomeMessage == "" { newOpts.WelcomeMessage = defaultWelcomeMessage } else { newOpts.WelcomeMessage = opts.WelcomeMessage } if opts.Auth != nil { newOpts.Auth = opts.Auth } newOpts.Logger = &StdLogger{} if opts.Logger != nil { newOpts.Logger = opts.Logger } newOpts.TLS = opts.TLS newOpts.KeyFile = opts.KeyFile newOpts.CertFile = opts.CertFile newOpts.ExplicitFTPS = opts.ExplicitFTPS newOpts.PublicIp = opts.PublicIp newOpts.PassivePorts = opts.PassivePorts return &newOpts }
[ "func", "serverOptsWithDefaults", "(", "opts", "*", "ServerOpts", ")", "*", "ServerOpts", "{", "var", "newOpts", "ServerOpts", "\n", "if", "opts", "==", "nil", "{", "opts", "=", "&", "ServerOpts", "{", "}", "\n", "}", "\n", "if", "opts", ".", "Hostname", "==", "\"", "\"", "{", "newOpts", ".", "Hostname", "=", "\"", "\"", "\n", "}", "else", "{", "newOpts", ".", "Hostname", "=", "opts", ".", "Hostname", "\n", "}", "\n", "if", "opts", ".", "Port", "==", "0", "{", "newOpts", ".", "Port", "=", "3000", "\n", "}", "else", "{", "newOpts", ".", "Port", "=", "opts", ".", "Port", "\n", "}", "\n", "newOpts", ".", "Factory", "=", "opts", ".", "Factory", "\n", "if", "opts", ".", "Name", "==", "\"", "\"", "{", "newOpts", ".", "Name", "=", "\"", "\"", "\n", "}", "else", "{", "newOpts", ".", "Name", "=", "opts", ".", "Name", "\n", "}", "\n\n", "if", "opts", ".", "WelcomeMessage", "==", "\"", "\"", "{", "newOpts", ".", "WelcomeMessage", "=", "defaultWelcomeMessage", "\n", "}", "else", "{", "newOpts", ".", "WelcomeMessage", "=", "opts", ".", "WelcomeMessage", "\n", "}", "\n\n", "if", "opts", ".", "Auth", "!=", "nil", "{", "newOpts", ".", "Auth", "=", "opts", ".", "Auth", "\n", "}", "\n\n", "newOpts", ".", "Logger", "=", "&", "StdLogger", "{", "}", "\n", "if", "opts", ".", "Logger", "!=", "nil", "{", "newOpts", ".", "Logger", "=", "opts", ".", "Logger", "\n", "}", "\n\n", "newOpts", ".", "TLS", "=", "opts", ".", "TLS", "\n", "newOpts", ".", "KeyFile", "=", "opts", ".", "KeyFile", "\n", "newOpts", ".", "CertFile", "=", "opts", ".", "CertFile", "\n", "newOpts", ".", "ExplicitFTPS", "=", "opts", ".", "ExplicitFTPS", "\n\n", "newOpts", ".", "PublicIp", "=", "opts", ".", "PublicIp", "\n", "newOpts", ".", "PassivePorts", "=", "opts", ".", "PassivePorts", "\n\n", "return", "&", "newOpts", "\n", "}" ]
// serverOptsWithDefaults copies an ServerOpts struct into a new struct, // then adds any default values that are missing and returns the new data.
[ "serverOptsWithDefaults", "copies", "an", "ServerOpts", "struct", "into", "a", "new", "struct", "then", "adds", "any", "default", "values", "that", "are", "missing", "and", "returns", "the", "new", "data", "." ]
eabccc535b5a216dfa00bb8194563f73224a546d
https://github.com/goftp/server/blob/eabccc535b5a216dfa00bb8194563f73224a546d/server.go#L86-L132
train
goftp/server
server.go
newConn
func (server *Server) newConn(tcpConn net.Conn, driver Driver) *Conn { c := new(Conn) c.namePrefix = "/" c.conn = tcpConn c.controlReader = bufio.NewReader(tcpConn) c.controlWriter = bufio.NewWriter(tcpConn) c.driver = driver c.auth = server.Auth c.server = server c.sessionID = newSessionID() c.logger = server.logger c.tlsConfig = server.tlsConfig driver.Init(c) return c }
go
func (server *Server) newConn(tcpConn net.Conn, driver Driver) *Conn { c := new(Conn) c.namePrefix = "/" c.conn = tcpConn c.controlReader = bufio.NewReader(tcpConn) c.controlWriter = bufio.NewWriter(tcpConn) c.driver = driver c.auth = server.Auth c.server = server c.sessionID = newSessionID() c.logger = server.logger c.tlsConfig = server.tlsConfig driver.Init(c) return c }
[ "func", "(", "server", "*", "Server", ")", "newConn", "(", "tcpConn", "net", ".", "Conn", ",", "driver", "Driver", ")", "*", "Conn", "{", "c", ":=", "new", "(", "Conn", ")", "\n", "c", ".", "namePrefix", "=", "\"", "\"", "\n", "c", ".", "conn", "=", "tcpConn", "\n", "c", ".", "controlReader", "=", "bufio", ".", "NewReader", "(", "tcpConn", ")", "\n", "c", ".", "controlWriter", "=", "bufio", ".", "NewWriter", "(", "tcpConn", ")", "\n", "c", ".", "driver", "=", "driver", "\n", "c", ".", "auth", "=", "server", ".", "Auth", "\n", "c", ".", "server", "=", "server", "\n", "c", ".", "sessionID", "=", "newSessionID", "(", ")", "\n", "c", ".", "logger", "=", "server", ".", "logger", "\n", "c", ".", "tlsConfig", "=", "server", ".", "tlsConfig", "\n\n", "driver", ".", "Init", "(", "c", ")", "\n", "return", "c", "\n", "}" ]
// NewConn constructs a new object that will handle the FTP protocol over // an active net.TCPConn. The TCP connection should already be open before // it is handed to this functions. driver is an instance of FTPDriver that // will handle all auth and persistence details.
[ "NewConn", "constructs", "a", "new", "object", "that", "will", "handle", "the", "FTP", "protocol", "over", "an", "active", "net", ".", "TCPConn", ".", "The", "TCP", "connection", "should", "already", "be", "open", "before", "it", "is", "handed", "to", "this", "functions", ".", "driver", "is", "an", "instance", "of", "FTPDriver", "that", "will", "handle", "all", "auth", "and", "persistence", "details", "." ]
eabccc535b5a216dfa00bb8194563f73224a546d
https://github.com/goftp/server/blob/eabccc535b5a216dfa00bb8194563f73224a546d/server.go#L164-L179
train
goftp/server
server.go
ListenAndServe
func (server *Server) ListenAndServe() error { var listener net.Listener var err error var curFeats = featCmds if server.ServerOpts.TLS { server.tlsConfig, err = simpleTLSConfig(server.CertFile, server.KeyFile) if err != nil { return err } curFeats += " AUTH TLS\n PBSZ\n PROT\n" if server.ServerOpts.ExplicitFTPS { listener, err = net.Listen("tcp", server.listenTo) } else { listener, err = tls.Listen("tcp", server.listenTo, server.tlsConfig) } } else { listener, err = net.Listen("tcp", server.listenTo) } if err != nil { return err } server.feats = fmt.Sprintf(feats, curFeats) sessionID := "" server.logger.Printf(sessionID, "%s listening on %d", server.Name, server.Port) return server.Serve(listener) }
go
func (server *Server) ListenAndServe() error { var listener net.Listener var err error var curFeats = featCmds if server.ServerOpts.TLS { server.tlsConfig, err = simpleTLSConfig(server.CertFile, server.KeyFile) if err != nil { return err } curFeats += " AUTH TLS\n PBSZ\n PROT\n" if server.ServerOpts.ExplicitFTPS { listener, err = net.Listen("tcp", server.listenTo) } else { listener, err = tls.Listen("tcp", server.listenTo, server.tlsConfig) } } else { listener, err = net.Listen("tcp", server.listenTo) } if err != nil { return err } server.feats = fmt.Sprintf(feats, curFeats) sessionID := "" server.logger.Printf(sessionID, "%s listening on %d", server.Name, server.Port) return server.Serve(listener) }
[ "func", "(", "server", "*", "Server", ")", "ListenAndServe", "(", ")", "error", "{", "var", "listener", "net", ".", "Listener", "\n", "var", "err", "error", "\n", "var", "curFeats", "=", "featCmds", "\n\n", "if", "server", ".", "ServerOpts", ".", "TLS", "{", "server", ".", "tlsConfig", ",", "err", "=", "simpleTLSConfig", "(", "server", ".", "CertFile", ",", "server", ".", "KeyFile", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "curFeats", "+=", "\"", "\\n", "\\n", "\\n", "\"", "\n\n", "if", "server", ".", "ServerOpts", ".", "ExplicitFTPS", "{", "listener", ",", "err", "=", "net", ".", "Listen", "(", "\"", "\"", ",", "server", ".", "listenTo", ")", "\n", "}", "else", "{", "listener", ",", "err", "=", "tls", ".", "Listen", "(", "\"", "\"", ",", "server", ".", "listenTo", ",", "server", ".", "tlsConfig", ")", "\n", "}", "\n", "}", "else", "{", "listener", ",", "err", "=", "net", ".", "Listen", "(", "\"", "\"", ",", "server", ".", "listenTo", ")", "\n", "}", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "server", ".", "feats", "=", "fmt", ".", "Sprintf", "(", "feats", ",", "curFeats", ")", "\n\n", "sessionID", ":=", "\"", "\"", "\n", "server", ".", "logger", ".", "Printf", "(", "sessionID", ",", "\"", "\"", ",", "server", ".", "Name", ",", "server", ".", "Port", ")", "\n\n", "return", "server", ".", "Serve", "(", "listener", ")", "\n", "}" ]
// ListenAndServe asks a new Server to begin accepting client connections. It // accepts no arguments - all configuration is provided via the NewServer // function. // // If the server fails to start for any reason, an error will be returned. Common // errors are trying to bind to a privileged port or something else is already // listening on the same port. //
[ "ListenAndServe", "asks", "a", "new", "Server", "to", "begin", "accepting", "client", "connections", ".", "It", "accepts", "no", "arguments", "-", "all", "configuration", "is", "provided", "via", "the", "NewServer", "function", ".", "If", "the", "server", "fails", "to", "start", "for", "any", "reason", "an", "error", "will", "be", "returned", ".", "Common", "errors", "are", "trying", "to", "bind", "to", "a", "privileged", "port", "or", "something", "else", "is", "already", "listening", "on", "the", "same", "port", "." ]
eabccc535b5a216dfa00bb8194563f73224a546d
https://github.com/goftp/server/blob/eabccc535b5a216dfa00bb8194563f73224a546d/server.go#L204-L234
train
goftp/server
server.go
Serve
func (server *Server) Serve(l net.Listener) error { server.listener = l server.ctx, server.cancel = context.WithCancel(context.Background()) sessionID := "" for { tcpConn, err := server.listener.Accept() if err != nil { select { case <-server.ctx.Done(): return ErrServerClosed default: } server.logger.Printf(sessionID, "listening error: %v", err) if ne, ok := err.(net.Error); ok && ne.Temporary() { continue } return err } driver, err := server.Factory.NewDriver() if err != nil { server.logger.Printf(sessionID, "Error creating driver, aborting client connection: %v", err) tcpConn.Close() } else { ftpConn := server.newConn(tcpConn, driver) go ftpConn.Serve() } } }
go
func (server *Server) Serve(l net.Listener) error { server.listener = l server.ctx, server.cancel = context.WithCancel(context.Background()) sessionID := "" for { tcpConn, err := server.listener.Accept() if err != nil { select { case <-server.ctx.Done(): return ErrServerClosed default: } server.logger.Printf(sessionID, "listening error: %v", err) if ne, ok := err.(net.Error); ok && ne.Temporary() { continue } return err } driver, err := server.Factory.NewDriver() if err != nil { server.logger.Printf(sessionID, "Error creating driver, aborting client connection: %v", err) tcpConn.Close() } else { ftpConn := server.newConn(tcpConn, driver) go ftpConn.Serve() } } }
[ "func", "(", "server", "*", "Server", ")", "Serve", "(", "l", "net", ".", "Listener", ")", "error", "{", "server", ".", "listener", "=", "l", "\n", "server", ".", "ctx", ",", "server", ".", "cancel", "=", "context", ".", "WithCancel", "(", "context", ".", "Background", "(", ")", ")", "\n", "sessionID", ":=", "\"", "\"", "\n", "for", "{", "tcpConn", ",", "err", ":=", "server", ".", "listener", ".", "Accept", "(", ")", "\n", "if", "err", "!=", "nil", "{", "select", "{", "case", "<-", "server", ".", "ctx", ".", "Done", "(", ")", ":", "return", "ErrServerClosed", "\n", "default", ":", "}", "\n", "server", ".", "logger", ".", "Printf", "(", "sessionID", ",", "\"", "\"", ",", "err", ")", "\n", "if", "ne", ",", "ok", ":=", "err", ".", "(", "net", ".", "Error", ")", ";", "ok", "&&", "ne", ".", "Temporary", "(", ")", "{", "continue", "\n", "}", "\n", "return", "err", "\n", "}", "\n", "driver", ",", "err", ":=", "server", ".", "Factory", ".", "NewDriver", "(", ")", "\n", "if", "err", "!=", "nil", "{", "server", ".", "logger", ".", "Printf", "(", "sessionID", ",", "\"", "\"", ",", "err", ")", "\n", "tcpConn", ".", "Close", "(", ")", "\n", "}", "else", "{", "ftpConn", ":=", "server", ".", "newConn", "(", "tcpConn", ",", "driver", ")", "\n", "go", "ftpConn", ".", "Serve", "(", ")", "\n", "}", "\n", "}", "\n", "}" ]
// Serve accepts connections on a given net.Listener and handles each // request in a new goroutine. //
[ "Serve", "accepts", "connections", "on", "a", "given", "net", ".", "Listener", "and", "handles", "each", "request", "in", "a", "new", "goroutine", "." ]
eabccc535b5a216dfa00bb8194563f73224a546d
https://github.com/goftp/server/blob/eabccc535b5a216dfa00bb8194563f73224a546d/server.go#L239-L266
train
goftp/server
server.go
Shutdown
func (server *Server) Shutdown() error { if server.cancel != nil { server.cancel() } if server.listener != nil { return server.listener.Close() } // server wasnt even started return nil }
go
func (server *Server) Shutdown() error { if server.cancel != nil { server.cancel() } if server.listener != nil { return server.listener.Close() } // server wasnt even started return nil }
[ "func", "(", "server", "*", "Server", ")", "Shutdown", "(", ")", "error", "{", "if", "server", ".", "cancel", "!=", "nil", "{", "server", ".", "cancel", "(", ")", "\n", "}", "\n", "if", "server", ".", "listener", "!=", "nil", "{", "return", "server", ".", "listener", ".", "Close", "(", ")", "\n", "}", "\n", "// server wasnt even started", "return", "nil", "\n", "}" ]
// Shutdown will gracefully stop a server. Already connected clients will retain their connections
[ "Shutdown", "will", "gracefully", "stop", "a", "server", ".", "Already", "connected", "clients", "will", "retain", "their", "connections" ]
eabccc535b5a216dfa00bb8194563f73224a546d
https://github.com/goftp/server/blob/eabccc535b5a216dfa00bb8194563f73224a546d/server.go#L269-L278
train
goftp/server
conn.go
newSessionID
func newSessionID() string { hash := sha256.New() _, err := io.CopyN(hash, rand.Reader, 50) if err != nil { return "????????????????????" } md := hash.Sum(nil) mdStr := hex.EncodeToString(md) return mdStr[0:20] }
go
func newSessionID() string { hash := sha256.New() _, err := io.CopyN(hash, rand.Reader, 50) if err != nil { return "????????????????????" } md := hash.Sum(nil) mdStr := hex.EncodeToString(md) return mdStr[0:20] }
[ "func", "newSessionID", "(", ")", "string", "{", "hash", ":=", "sha256", ".", "New", "(", ")", "\n", "_", ",", "err", ":=", "io", ".", "CopyN", "(", "hash", ",", "rand", ".", "Reader", ",", "50", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\"", "\"", "\n", "}", "\n", "md", ":=", "hash", ".", "Sum", "(", "nil", ")", "\n", "mdStr", ":=", "hex", ".", "EncodeToString", "(", "md", ")", "\n", "return", "mdStr", "[", "0", ":", "20", "]", "\n", "}" ]
// returns a random 20 char string that can be used as a unique session ID
[ "returns", "a", "random", "20", "char", "string", "that", "can", "be", "used", "as", "a", "unique", "session", "ID" ]
eabccc535b5a216dfa00bb8194563f73224a546d
https://github.com/goftp/server/blob/eabccc535b5a216dfa00bb8194563f73224a546d/conn.go#L86-L95
train
goftp/server
conn.go
Serve
func (conn *Conn) Serve() { conn.logger.Print(conn.sessionID, "Connection Established") // send welcome conn.writeMessage(220, conn.server.WelcomeMessage) // read commands for { line, err := conn.controlReader.ReadString('\n') if err != nil { if err != io.EOF { conn.logger.Print(conn.sessionID, fmt.Sprint("read error:", err)) } break } conn.receiveLine(line) // QUIT command closes connection, break to avoid error on reading from // closed socket if conn.closed == true { break } } conn.Close() conn.logger.Print(conn.sessionID, "Connection Terminated") }
go
func (conn *Conn) Serve() { conn.logger.Print(conn.sessionID, "Connection Established") // send welcome conn.writeMessage(220, conn.server.WelcomeMessage) // read commands for { line, err := conn.controlReader.ReadString('\n') if err != nil { if err != io.EOF { conn.logger.Print(conn.sessionID, fmt.Sprint("read error:", err)) } break } conn.receiveLine(line) // QUIT command closes connection, break to avoid error on reading from // closed socket if conn.closed == true { break } } conn.Close() conn.logger.Print(conn.sessionID, "Connection Terminated") }
[ "func", "(", "conn", "*", "Conn", ")", "Serve", "(", ")", "{", "conn", ".", "logger", ".", "Print", "(", "conn", ".", "sessionID", ",", "\"", "\"", ")", "\n", "// send welcome", "conn", ".", "writeMessage", "(", "220", ",", "conn", ".", "server", ".", "WelcomeMessage", ")", "\n", "// read commands", "for", "{", "line", ",", "err", ":=", "conn", ".", "controlReader", ".", "ReadString", "(", "'\\n'", ")", "\n", "if", "err", "!=", "nil", "{", "if", "err", "!=", "io", ".", "EOF", "{", "conn", ".", "logger", ".", "Print", "(", "conn", ".", "sessionID", ",", "fmt", ".", "Sprint", "(", "\"", "\"", ",", "err", ")", ")", "\n", "}", "\n\n", "break", "\n", "}", "\n", "conn", ".", "receiveLine", "(", "line", ")", "\n", "// QUIT command closes connection, break to avoid error on reading from", "// closed socket", "if", "conn", ".", "closed", "==", "true", "{", "break", "\n", "}", "\n", "}", "\n", "conn", ".", "Close", "(", ")", "\n", "conn", ".", "logger", ".", "Print", "(", "conn", ".", "sessionID", ",", "\"", "\"", ")", "\n", "}" ]
// Serve starts an endless loop that reads FTP commands from the client and // responds appropriately. terminated is a channel that will receive a true // message when the connection closes. This loop will be running inside a // goroutine, so use this channel to be notified when the connection can be // cleaned up.
[ "Serve", "starts", "an", "endless", "loop", "that", "reads", "FTP", "commands", "from", "the", "client", "and", "responds", "appropriately", ".", "terminated", "is", "a", "channel", "that", "will", "receive", "a", "true", "message", "when", "the", "connection", "closes", ".", "This", "loop", "will", "be", "running", "inside", "a", "goroutine", "so", "use", "this", "channel", "to", "be", "notified", "when", "the", "connection", "can", "be", "cleaned", "up", "." ]
eabccc535b5a216dfa00bb8194563f73224a546d
https://github.com/goftp/server/blob/eabccc535b5a216dfa00bb8194563f73224a546d/conn.go#L102-L125
train
goftp/server
conn.go
Close
func (conn *Conn) Close() { conn.conn.Close() conn.closed = true if conn.dataConn != nil { conn.dataConn.Close() conn.dataConn = nil } }
go
func (conn *Conn) Close() { conn.conn.Close() conn.closed = true if conn.dataConn != nil { conn.dataConn.Close() conn.dataConn = nil } }
[ "func", "(", "conn", "*", "Conn", ")", "Close", "(", ")", "{", "conn", ".", "conn", ".", "Close", "(", ")", "\n", "conn", ".", "closed", "=", "true", "\n", "if", "conn", ".", "dataConn", "!=", "nil", "{", "conn", ".", "dataConn", ".", "Close", "(", ")", "\n", "conn", ".", "dataConn", "=", "nil", "\n", "}", "\n", "}" ]
// Close will manually close this connection, even if the client isn't ready.
[ "Close", "will", "manually", "close", "this", "connection", "even", "if", "the", "client", "isn", "t", "ready", "." ]
eabccc535b5a216dfa00bb8194563f73224a546d
https://github.com/goftp/server/blob/eabccc535b5a216dfa00bb8194563f73224a546d/conn.go#L128-L135
train
goftp/server
conn.go
receiveLine
func (conn *Conn) receiveLine(line string) { command, param := conn.parseLine(line) conn.logger.PrintCommand(conn.sessionID, command, param) cmdObj := commands[strings.ToUpper(command)] if cmdObj == nil { conn.writeMessage(500, "Command not found") return } if cmdObj.RequireParam() && param == "" { conn.writeMessage(553, "action aborted, required param missing") } else if cmdObj.RequireAuth() && conn.user == "" { conn.writeMessage(530, "not logged in") } else { cmdObj.Execute(conn, param) } }
go
func (conn *Conn) receiveLine(line string) { command, param := conn.parseLine(line) conn.logger.PrintCommand(conn.sessionID, command, param) cmdObj := commands[strings.ToUpper(command)] if cmdObj == nil { conn.writeMessage(500, "Command not found") return } if cmdObj.RequireParam() && param == "" { conn.writeMessage(553, "action aborted, required param missing") } else if cmdObj.RequireAuth() && conn.user == "" { conn.writeMessage(530, "not logged in") } else { cmdObj.Execute(conn, param) } }
[ "func", "(", "conn", "*", "Conn", ")", "receiveLine", "(", "line", "string", ")", "{", "command", ",", "param", ":=", "conn", ".", "parseLine", "(", "line", ")", "\n", "conn", ".", "logger", ".", "PrintCommand", "(", "conn", ".", "sessionID", ",", "command", ",", "param", ")", "\n", "cmdObj", ":=", "commands", "[", "strings", ".", "ToUpper", "(", "command", ")", "]", "\n", "if", "cmdObj", "==", "nil", "{", "conn", ".", "writeMessage", "(", "500", ",", "\"", "\"", ")", "\n", "return", "\n", "}", "\n", "if", "cmdObj", ".", "RequireParam", "(", ")", "&&", "param", "==", "\"", "\"", "{", "conn", ".", "writeMessage", "(", "553", ",", "\"", "\"", ")", "\n", "}", "else", "if", "cmdObj", ".", "RequireAuth", "(", ")", "&&", "conn", ".", "user", "==", "\"", "\"", "{", "conn", ".", "writeMessage", "(", "530", ",", "\"", "\"", ")", "\n", "}", "else", "{", "cmdObj", ".", "Execute", "(", "conn", ",", "param", ")", "\n", "}", "\n", "}" ]
// receiveLine accepts a single line FTP command and co-ordinates an // appropriate response.
[ "receiveLine", "accepts", "a", "single", "line", "FTP", "command", "and", "co", "-", "ordinates", "an", "appropriate", "response", "." ]
eabccc535b5a216dfa00bb8194563f73224a546d
https://github.com/goftp/server/blob/eabccc535b5a216dfa00bb8194563f73224a546d/conn.go#L152-L167
train
goftp/server
conn.go
writeMessage
func (conn *Conn) writeMessage(code int, message string) (wrote int, err error) { conn.logger.PrintResponse(conn.sessionID, code, message) line := fmt.Sprintf("%d %s\r\n", code, message) wrote, err = conn.controlWriter.WriteString(line) conn.controlWriter.Flush() return }
go
func (conn *Conn) writeMessage(code int, message string) (wrote int, err error) { conn.logger.PrintResponse(conn.sessionID, code, message) line := fmt.Sprintf("%d %s\r\n", code, message) wrote, err = conn.controlWriter.WriteString(line) conn.controlWriter.Flush() return }
[ "func", "(", "conn", "*", "Conn", ")", "writeMessage", "(", "code", "int", ",", "message", "string", ")", "(", "wrote", "int", ",", "err", "error", ")", "{", "conn", ".", "logger", ".", "PrintResponse", "(", "conn", ".", "sessionID", ",", "code", ",", "message", ")", "\n", "line", ":=", "fmt", ".", "Sprintf", "(", "\"", "\\r", "\\n", "\"", ",", "code", ",", "message", ")", "\n", "wrote", ",", "err", "=", "conn", ".", "controlWriter", ".", "WriteString", "(", "line", ")", "\n", "conn", ".", "controlWriter", ".", "Flush", "(", ")", "\n", "return", "\n", "}" ]
// writeMessage will send a standard FTP response back to the client.
[ "writeMessage", "will", "send", "a", "standard", "FTP", "response", "back", "to", "the", "client", "." ]
eabccc535b5a216dfa00bb8194563f73224a546d
https://github.com/goftp/server/blob/eabccc535b5a216dfa00bb8194563f73224a546d/conn.go#L178-L184
train
goftp/server
conn.go
sendOutofbandData
func (conn *Conn) sendOutofbandData(data []byte) { bytes := len(data) if conn.dataConn != nil { conn.dataConn.Write(data) conn.dataConn.Close() conn.dataConn = nil } message := "Closing data connection, sent " + strconv.Itoa(bytes) + " bytes" conn.writeMessage(226, message) }
go
func (conn *Conn) sendOutofbandData(data []byte) { bytes := len(data) if conn.dataConn != nil { conn.dataConn.Write(data) conn.dataConn.Close() conn.dataConn = nil } message := "Closing data connection, sent " + strconv.Itoa(bytes) + " bytes" conn.writeMessage(226, message) }
[ "func", "(", "conn", "*", "Conn", ")", "sendOutofbandData", "(", "data", "[", "]", "byte", ")", "{", "bytes", ":=", "len", "(", "data", ")", "\n", "if", "conn", ".", "dataConn", "!=", "nil", "{", "conn", ".", "dataConn", ".", "Write", "(", "data", ")", "\n", "conn", ".", "dataConn", ".", "Close", "(", ")", "\n", "conn", ".", "dataConn", "=", "nil", "\n", "}", "\n", "message", ":=", "\"", "\"", "+", "strconv", ".", "Itoa", "(", "bytes", ")", "+", "\"", "\"", "\n", "conn", ".", "writeMessage", "(", "226", ",", "message", ")", "\n", "}" ]
// sendOutofbandData will send a string to the client via the currently open // data socket. Assumes the socket is open and ready to be used.
[ "sendOutofbandData", "will", "send", "a", "string", "to", "the", "client", "via", "the", "currently", "open", "data", "socket", ".", "Assumes", "the", "socket", "is", "open", "and", "ready", "to", "be", "used", "." ]
eabccc535b5a216dfa00bb8194563f73224a546d
https://github.com/goftp/server/blob/eabccc535b5a216dfa00bb8194563f73224a546d/conn.go#L227-L236
train
c-bata/go-prompt
completer/file.go
Complete
func (c *FilePathCompleter) Complete(d prompt.Document) []prompt.Suggest { if c.fileListCache == nil { c.fileListCache = make(map[string][]prompt.Suggest, 4) } path := d.GetWordBeforeCursor() dir, base, err := cleanFilePath(path) if err != nil { debug.Log("completer: cannot get current user:" + err.Error()) return nil } if cached, ok := c.fileListCache[dir]; ok { return prompt.FilterHasPrefix(cached, base, c.IgnoreCase) } files, err := ioutil.ReadDir(dir) if err != nil && os.IsNotExist(err) { return nil } else if err != nil { debug.Log("completer: cannot read directory items:" + err.Error()) return nil } suggests := make([]prompt.Suggest, 0, len(files)) for _, f := range files { if c.Filter != nil && !c.Filter(f) { continue } suggests = append(suggests, prompt.Suggest{Text: f.Name()}) } c.fileListCache[dir] = suggests return prompt.FilterHasPrefix(suggests, base, c.IgnoreCase) }
go
func (c *FilePathCompleter) Complete(d prompt.Document) []prompt.Suggest { if c.fileListCache == nil { c.fileListCache = make(map[string][]prompt.Suggest, 4) } path := d.GetWordBeforeCursor() dir, base, err := cleanFilePath(path) if err != nil { debug.Log("completer: cannot get current user:" + err.Error()) return nil } if cached, ok := c.fileListCache[dir]; ok { return prompt.FilterHasPrefix(cached, base, c.IgnoreCase) } files, err := ioutil.ReadDir(dir) if err != nil && os.IsNotExist(err) { return nil } else if err != nil { debug.Log("completer: cannot read directory items:" + err.Error()) return nil } suggests := make([]prompt.Suggest, 0, len(files)) for _, f := range files { if c.Filter != nil && !c.Filter(f) { continue } suggests = append(suggests, prompt.Suggest{Text: f.Name()}) } c.fileListCache[dir] = suggests return prompt.FilterHasPrefix(suggests, base, c.IgnoreCase) }
[ "func", "(", "c", "*", "FilePathCompleter", ")", "Complete", "(", "d", "prompt", ".", "Document", ")", "[", "]", "prompt", ".", "Suggest", "{", "if", "c", ".", "fileListCache", "==", "nil", "{", "c", ".", "fileListCache", "=", "make", "(", "map", "[", "string", "]", "[", "]", "prompt", ".", "Suggest", ",", "4", ")", "\n", "}", "\n\n", "path", ":=", "d", ".", "GetWordBeforeCursor", "(", ")", "\n", "dir", ",", "base", ",", "err", ":=", "cleanFilePath", "(", "path", ")", "\n", "if", "err", "!=", "nil", "{", "debug", ".", "Log", "(", "\"", "\"", "+", "err", ".", "Error", "(", ")", ")", "\n", "return", "nil", "\n", "}", "\n\n", "if", "cached", ",", "ok", ":=", "c", ".", "fileListCache", "[", "dir", "]", ";", "ok", "{", "return", "prompt", ".", "FilterHasPrefix", "(", "cached", ",", "base", ",", "c", ".", "IgnoreCase", ")", "\n", "}", "\n\n", "files", ",", "err", ":=", "ioutil", ".", "ReadDir", "(", "dir", ")", "\n", "if", "err", "!=", "nil", "&&", "os", ".", "IsNotExist", "(", "err", ")", "{", "return", "nil", "\n", "}", "else", "if", "err", "!=", "nil", "{", "debug", ".", "Log", "(", "\"", "\"", "+", "err", ".", "Error", "(", ")", ")", "\n", "return", "nil", "\n", "}", "\n\n", "suggests", ":=", "make", "(", "[", "]", "prompt", ".", "Suggest", ",", "0", ",", "len", "(", "files", ")", ")", "\n", "for", "_", ",", "f", ":=", "range", "files", "{", "if", "c", ".", "Filter", "!=", "nil", "&&", "!", "c", ".", "Filter", "(", "f", ")", "{", "continue", "\n", "}", "\n", "suggests", "=", "append", "(", "suggests", ",", "prompt", ".", "Suggest", "{", "Text", ":", "f", ".", "Name", "(", ")", "}", ")", "\n", "}", "\n", "c", ".", "fileListCache", "[", "dir", "]", "=", "suggests", "\n", "return", "prompt", ".", "FilterHasPrefix", "(", "suggests", ",", "base", ",", "c", ".", "IgnoreCase", ")", "\n", "}" ]
// Complete returns suggestions from your local file system.
[ "Complete", "returns", "suggestions", "from", "your", "local", "file", "system", "." ]
c8c75cc295ca66affff899dba2c452667e65b9e5
https://github.com/c-bata/go-prompt/blob/c8c75cc295ca66affff899dba2c452667e65b9e5/completer/file.go#L57-L90
train
c-bata/go-prompt
internal/bisect/bisect.go
Right
func Right(a []int, v int) int { return bisectRightRange(a, v, 0, len(a)) }
go
func Right(a []int, v int) int { return bisectRightRange(a, v, 0, len(a)) }
[ "func", "Right", "(", "a", "[", "]", "int", ",", "v", "int", ")", "int", "{", "return", "bisectRightRange", "(", "a", ",", "v", ",", "0", ",", "len", "(", "a", ")", ")", "\n", "}" ]
// Right to locate the insertion point for v in a to maintain sorted order.
[ "Right", "to", "locate", "the", "insertion", "point", "for", "v", "in", "a", "to", "maintain", "sorted", "order", "." ]
c8c75cc295ca66affff899dba2c452667e65b9e5
https://github.com/c-bata/go-prompt/blob/c8c75cc295ca66affff899dba2c452667e65b9e5/internal/bisect/bisect.go#L6-L8
train
c-bata/go-prompt
internal/term/term.go
Restore
func Restore() error { o, err := getOriginalTermios(saveTermiosFD) if err != nil { return err } return termios.Tcsetattr(uintptr(saveTermiosFD), termios.TCSANOW, &o) }
go
func Restore() error { o, err := getOriginalTermios(saveTermiosFD) if err != nil { return err } return termios.Tcsetattr(uintptr(saveTermiosFD), termios.TCSANOW, &o) }
[ "func", "Restore", "(", ")", "error", "{", "o", ",", "err", ":=", "getOriginalTermios", "(", "saveTermiosFD", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "return", "termios", ".", "Tcsetattr", "(", "uintptr", "(", "saveTermiosFD", ")", ",", "termios", ".", "TCSANOW", ",", "&", "o", ")", "\n", "}" ]
// Restore terminal's mode.
[ "Restore", "terminal", "s", "mode", "." ]
c8c75cc295ca66affff899dba2c452667e65b9e5
https://github.com/c-bata/go-prompt/blob/c8c75cc295ca66affff899dba2c452667e65b9e5/internal/term/term.go#L28-L34
train
c-bata/go-prompt
output_vt100.go
WriteRaw
func (w *VT100Writer) WriteRaw(data []byte) { w.buffer = append(w.buffer, data...) return }
go
func (w *VT100Writer) WriteRaw(data []byte) { w.buffer = append(w.buffer, data...) return }
[ "func", "(", "w", "*", "VT100Writer", ")", "WriteRaw", "(", "data", "[", "]", "byte", ")", "{", "w", ".", "buffer", "=", "append", "(", "w", ".", "buffer", ",", "data", "...", ")", "\n", "return", "\n", "}" ]
// WriteRaw to write raw byte array
[ "WriteRaw", "to", "write", "raw", "byte", "array" ]
c8c75cc295ca66affff899dba2c452667e65b9e5
https://github.com/c-bata/go-prompt/blob/c8c75cc295ca66affff899dba2c452667e65b9e5/output_vt100.go#L14-L17
train
c-bata/go-prompt
output_vt100.go
Write
func (w *VT100Writer) Write(data []byte) { w.WriteRaw(bytes.Replace(data, []byte{0x1b}, []byte{'?'}, -1)) return }
go
func (w *VT100Writer) Write(data []byte) { w.WriteRaw(bytes.Replace(data, []byte{0x1b}, []byte{'?'}, -1)) return }
[ "func", "(", "w", "*", "VT100Writer", ")", "Write", "(", "data", "[", "]", "byte", ")", "{", "w", ".", "WriteRaw", "(", "bytes", ".", "Replace", "(", "data", ",", "[", "]", "byte", "{", "0x1b", "}", ",", "[", "]", "byte", "{", "'?'", "}", ",", "-", "1", ")", ")", "\n", "return", "\n", "}" ]
// Write to write safety byte array by removing control sequences.
[ "Write", "to", "write", "safety", "byte", "array", "by", "removing", "control", "sequences", "." ]
c8c75cc295ca66affff899dba2c452667e65b9e5
https://github.com/c-bata/go-prompt/blob/c8c75cc295ca66affff899dba2c452667e65b9e5/output_vt100.go#L20-L23
train
c-bata/go-prompt
output_vt100.go
CursorGoTo
func (w *VT100Writer) CursorGoTo(row, col int) { if row == 0 && col == 0 { // If no row/column parameters are provided (ie. <ESC>[H), the cursor will move to the home position. w.WriteRaw([]byte{0x1b, '[', 'H'}) return } r := strconv.Itoa(row) c := strconv.Itoa(col) w.WriteRaw([]byte{0x1b, '['}) w.WriteRaw([]byte(r)) w.WriteRaw([]byte{';'}) w.WriteRaw([]byte(c)) w.WriteRaw([]byte{'H'}) return }
go
func (w *VT100Writer) CursorGoTo(row, col int) { if row == 0 && col == 0 { // If no row/column parameters are provided (ie. <ESC>[H), the cursor will move to the home position. w.WriteRaw([]byte{0x1b, '[', 'H'}) return } r := strconv.Itoa(row) c := strconv.Itoa(col) w.WriteRaw([]byte{0x1b, '['}) w.WriteRaw([]byte(r)) w.WriteRaw([]byte{';'}) w.WriteRaw([]byte(c)) w.WriteRaw([]byte{'H'}) return }
[ "func", "(", "w", "*", "VT100Writer", ")", "CursorGoTo", "(", "row", ",", "col", "int", ")", "{", "if", "row", "==", "0", "&&", "col", "==", "0", "{", "// If no row/column parameters are provided (ie. <ESC>[H), the cursor will move to the home position.", "w", ".", "WriteRaw", "(", "[", "]", "byte", "{", "0x1b", ",", "'['", ",", "'H'", "}", ")", "\n", "return", "\n", "}", "\n", "r", ":=", "strconv", ".", "Itoa", "(", "row", ")", "\n", "c", ":=", "strconv", ".", "Itoa", "(", "col", ")", "\n", "w", ".", "WriteRaw", "(", "[", "]", "byte", "{", "0x1b", ",", "'['", "}", ")", "\n", "w", ".", "WriteRaw", "(", "[", "]", "byte", "(", "r", ")", ")", "\n", "w", ".", "WriteRaw", "(", "[", "]", "byte", "{", "';'", "}", ")", "\n", "w", ".", "WriteRaw", "(", "[", "]", "byte", "(", "c", ")", ")", "\n", "w", ".", "WriteRaw", "(", "[", "]", "byte", "{", "'H'", "}", ")", "\n", "return", "\n", "}" ]
// CursorGoTo sets the cursor position where subsequent text will begin.
[ "CursorGoTo", "sets", "the", "cursor", "position", "where", "subsequent", "text", "will", "begin", "." ]
c8c75cc295ca66affff899dba2c452667e65b9e5
https://github.com/c-bata/go-prompt/blob/c8c75cc295ca66affff899dba2c452667e65b9e5/output_vt100.go#L89-L103
train
c-bata/go-prompt
output_vt100.go
CursorUp
func (w *VT100Writer) CursorUp(n int) { if n == 0 { return } else if n < 0 { w.CursorDown(-n) return } s := strconv.Itoa(n) w.WriteRaw([]byte{0x1b, '['}) w.WriteRaw([]byte(s)) w.WriteRaw([]byte{'A'}) return }
go
func (w *VT100Writer) CursorUp(n int) { if n == 0 { return } else if n < 0 { w.CursorDown(-n) return } s := strconv.Itoa(n) w.WriteRaw([]byte{0x1b, '['}) w.WriteRaw([]byte(s)) w.WriteRaw([]byte{'A'}) return }
[ "func", "(", "w", "*", "VT100Writer", ")", "CursorUp", "(", "n", "int", ")", "{", "if", "n", "==", "0", "{", "return", "\n", "}", "else", "if", "n", "<", "0", "{", "w", ".", "CursorDown", "(", "-", "n", ")", "\n", "return", "\n", "}", "\n", "s", ":=", "strconv", ".", "Itoa", "(", "n", ")", "\n", "w", ".", "WriteRaw", "(", "[", "]", "byte", "{", "0x1b", ",", "'['", "}", ")", "\n", "w", ".", "WriteRaw", "(", "[", "]", "byte", "(", "s", ")", ")", "\n", "w", ".", "WriteRaw", "(", "[", "]", "byte", "{", "'A'", "}", ")", "\n", "return", "\n", "}" ]
// CursorUp moves the cursor up by 'n' rows; the default count is 1.
[ "CursorUp", "moves", "the", "cursor", "up", "by", "n", "rows", ";", "the", "default", "count", "is", "1", "." ]
c8c75cc295ca66affff899dba2c452667e65b9e5
https://github.com/c-bata/go-prompt/blob/c8c75cc295ca66affff899dba2c452667e65b9e5/output_vt100.go#L106-L118
train
c-bata/go-prompt
output_vt100.go
CursorForward
func (w *VT100Writer) CursorForward(n int) { if n == 0 { return } else if n < 0 { w.CursorBackward(-n) return } s := strconv.Itoa(n) w.WriteRaw([]byte{0x1b, '['}) w.WriteRaw([]byte(s)) w.WriteRaw([]byte{'C'}) return }
go
func (w *VT100Writer) CursorForward(n int) { if n == 0 { return } else if n < 0 { w.CursorBackward(-n) return } s := strconv.Itoa(n) w.WriteRaw([]byte{0x1b, '['}) w.WriteRaw([]byte(s)) w.WriteRaw([]byte{'C'}) return }
[ "func", "(", "w", "*", "VT100Writer", ")", "CursorForward", "(", "n", "int", ")", "{", "if", "n", "==", "0", "{", "return", "\n", "}", "else", "if", "n", "<", "0", "{", "w", ".", "CursorBackward", "(", "-", "n", ")", "\n", "return", "\n", "}", "\n", "s", ":=", "strconv", ".", "Itoa", "(", "n", ")", "\n", "w", ".", "WriteRaw", "(", "[", "]", "byte", "{", "0x1b", ",", "'['", "}", ")", "\n", "w", ".", "WriteRaw", "(", "[", "]", "byte", "(", "s", ")", ")", "\n", "w", ".", "WriteRaw", "(", "[", "]", "byte", "{", "'C'", "}", ")", "\n", "return", "\n", "}" ]
// CursorForward moves the cursor forward by 'n' columns; the default count is 1.
[ "CursorForward", "moves", "the", "cursor", "forward", "by", "n", "columns", ";", "the", "default", "count", "is", "1", "." ]
c8c75cc295ca66affff899dba2c452667e65b9e5
https://github.com/c-bata/go-prompt/blob/c8c75cc295ca66affff899dba2c452667e65b9e5/output_vt100.go#L136-L148
train
c-bata/go-prompt
output_vt100.go
SetDisplayAttributes
func (w *VT100Writer) SetDisplayAttributes(fg, bg Color, attrs ...DisplayAttribute) { w.WriteRaw([]byte{0x1b, '['}) // control sequence introducer defer w.WriteRaw([]byte{'m'}) // final character var separator byte = ';' for i := range attrs { p, ok := displayAttributeParameters[attrs[i]] if !ok { continue } w.WriteRaw(p) w.WriteRaw([]byte{separator}) } f, ok := foregroundANSIColors[fg] if !ok { f = foregroundANSIColors[DefaultColor] } w.WriteRaw(f) w.WriteRaw([]byte{separator}) b, ok := backgroundANSIColors[bg] if !ok { b = backgroundANSIColors[DefaultColor] } w.WriteRaw(b) return }
go
func (w *VT100Writer) SetDisplayAttributes(fg, bg Color, attrs ...DisplayAttribute) { w.WriteRaw([]byte{0x1b, '['}) // control sequence introducer defer w.WriteRaw([]byte{'m'}) // final character var separator byte = ';' for i := range attrs { p, ok := displayAttributeParameters[attrs[i]] if !ok { continue } w.WriteRaw(p) w.WriteRaw([]byte{separator}) } f, ok := foregroundANSIColors[fg] if !ok { f = foregroundANSIColors[DefaultColor] } w.WriteRaw(f) w.WriteRaw([]byte{separator}) b, ok := backgroundANSIColors[bg] if !ok { b = backgroundANSIColors[DefaultColor] } w.WriteRaw(b) return }
[ "func", "(", "w", "*", "VT100Writer", ")", "SetDisplayAttributes", "(", "fg", ",", "bg", "Color", ",", "attrs", "...", "DisplayAttribute", ")", "{", "w", ".", "WriteRaw", "(", "[", "]", "byte", "{", "0x1b", ",", "'['", "}", ")", "// control sequence introducer", "\n", "defer", "w", ".", "WriteRaw", "(", "[", "]", "byte", "{", "'m'", "}", ")", "// final character", "\n\n", "var", "separator", "byte", "=", "';'", "\n", "for", "i", ":=", "range", "attrs", "{", "p", ",", "ok", ":=", "displayAttributeParameters", "[", "attrs", "[", "i", "]", "]", "\n", "if", "!", "ok", "{", "continue", "\n", "}", "\n", "w", ".", "WriteRaw", "(", "p", ")", "\n", "w", ".", "WriteRaw", "(", "[", "]", "byte", "{", "separator", "}", ")", "\n", "}", "\n\n", "f", ",", "ok", ":=", "foregroundANSIColors", "[", "fg", "]", "\n", "if", "!", "ok", "{", "f", "=", "foregroundANSIColors", "[", "DefaultColor", "]", "\n", "}", "\n", "w", ".", "WriteRaw", "(", "f", ")", "\n", "w", ".", "WriteRaw", "(", "[", "]", "byte", "{", "separator", "}", ")", "\n", "b", ",", "ok", ":=", "backgroundANSIColors", "[", "bg", "]", "\n", "if", "!", "ok", "{", "b", "=", "backgroundANSIColors", "[", "DefaultColor", "]", "\n", "}", "\n", "w", ".", "WriteRaw", "(", "b", ")", "\n", "return", "\n", "}" ]
// SetDisplayAttributes to set VT100 display attributes.
[ "SetDisplayAttributes", "to", "set", "VT100", "display", "attributes", "." ]
c8c75cc295ca66affff899dba2c452667e65b9e5
https://github.com/c-bata/go-prompt/blob/c8c75cc295ca66affff899dba2c452667e65b9e5/output_vt100.go#L247-L273
train
c-bata/go-prompt
option.go
OptionParser
func OptionParser(x ConsoleParser) Option { return func(p *Prompt) error { p.in = x return nil } }
go
func OptionParser(x ConsoleParser) Option { return func(p *Prompt) error { p.in = x return nil } }
[ "func", "OptionParser", "(", "x", "ConsoleParser", ")", "Option", "{", "return", "func", "(", "p", "*", "Prompt", ")", "error", "{", "p", ".", "in", "=", "x", "\n", "return", "nil", "\n", "}", "\n", "}" ]
// OptionParser to set a custom ConsoleParser object. An argument should implement ConsoleParser interface.
[ "OptionParser", "to", "set", "a", "custom", "ConsoleParser", "object", ".", "An", "argument", "should", "implement", "ConsoleParser", "interface", "." ]
c8c75cc295ca66affff899dba2c452667e65b9e5
https://github.com/c-bata/go-prompt/blob/c8c75cc295ca66affff899dba2c452667e65b9e5/option.go#L8-L13
train
c-bata/go-prompt
option.go
OptionWriter
func OptionWriter(x ConsoleWriter) Option { return func(p *Prompt) error { registerConsoleWriter(x) p.renderer.out = x return nil } }
go
func OptionWriter(x ConsoleWriter) Option { return func(p *Prompt) error { registerConsoleWriter(x) p.renderer.out = x return nil } }
[ "func", "OptionWriter", "(", "x", "ConsoleWriter", ")", "Option", "{", "return", "func", "(", "p", "*", "Prompt", ")", "error", "{", "registerConsoleWriter", "(", "x", ")", "\n", "p", ".", "renderer", ".", "out", "=", "x", "\n", "return", "nil", "\n", "}", "\n", "}" ]
// OptionWriter to set a custom ConsoleWriter object. An argument should implement ConsoleWriter interface.
[ "OptionWriter", "to", "set", "a", "custom", "ConsoleWriter", "object", ".", "An", "argument", "should", "implement", "ConsoleWriter", "interface", "." ]
c8c75cc295ca66affff899dba2c452667e65b9e5
https://github.com/c-bata/go-prompt/blob/c8c75cc295ca66affff899dba2c452667e65b9e5/option.go#L16-L22
train
c-bata/go-prompt
option.go
OptionTitle
func OptionTitle(x string) Option { return func(p *Prompt) error { p.renderer.title = x return nil } }
go
func OptionTitle(x string) Option { return func(p *Prompt) error { p.renderer.title = x return nil } }
[ "func", "OptionTitle", "(", "x", "string", ")", "Option", "{", "return", "func", "(", "p", "*", "Prompt", ")", "error", "{", "p", ".", "renderer", ".", "title", "=", "x", "\n", "return", "nil", "\n", "}", "\n", "}" ]
// OptionTitle to set title displayed at the header bar of terminal.
[ "OptionTitle", "to", "set", "title", "displayed", "at", "the", "header", "bar", "of", "terminal", "." ]
c8c75cc295ca66affff899dba2c452667e65b9e5
https://github.com/c-bata/go-prompt/blob/c8c75cc295ca66affff899dba2c452667e65b9e5/option.go#L25-L30
train
c-bata/go-prompt
option.go
OptionPrefix
func OptionPrefix(x string) Option { return func(p *Prompt) error { p.renderer.prefix = x return nil } }
go
func OptionPrefix(x string) Option { return func(p *Prompt) error { p.renderer.prefix = x return nil } }
[ "func", "OptionPrefix", "(", "x", "string", ")", "Option", "{", "return", "func", "(", "p", "*", "Prompt", ")", "error", "{", "p", ".", "renderer", ".", "prefix", "=", "x", "\n", "return", "nil", "\n", "}", "\n", "}" ]
// OptionPrefix to set prefix string.
[ "OptionPrefix", "to", "set", "prefix", "string", "." ]
c8c75cc295ca66affff899dba2c452667e65b9e5
https://github.com/c-bata/go-prompt/blob/c8c75cc295ca66affff899dba2c452667e65b9e5/option.go#L33-L38
train
c-bata/go-prompt
option.go
OptionCompletionWordSeparator
func OptionCompletionWordSeparator(x string) Option { return func(p *Prompt) error { p.completion.wordSeparator = x return nil } }
go
func OptionCompletionWordSeparator(x string) Option { return func(p *Prompt) error { p.completion.wordSeparator = x return nil } }
[ "func", "OptionCompletionWordSeparator", "(", "x", "string", ")", "Option", "{", "return", "func", "(", "p", "*", "Prompt", ")", "error", "{", "p", ".", "completion", ".", "wordSeparator", "=", "x", "\n", "return", "nil", "\n", "}", "\n", "}" ]
// OptionCompletionWordSeparator to set word separators. Enable only ' ' if empty.
[ "OptionCompletionWordSeparator", "to", "set", "word", "separators", ".", "Enable", "only", "if", "empty", "." ]
c8c75cc295ca66affff899dba2c452667e65b9e5
https://github.com/c-bata/go-prompt/blob/c8c75cc295ca66affff899dba2c452667e65b9e5/option.go#L41-L46
train
c-bata/go-prompt
option.go
OptionLivePrefix
func OptionLivePrefix(f func() (prefix string, useLivePrefix bool)) Option { return func(p *Prompt) error { p.renderer.livePrefixCallback = f return nil } }
go
func OptionLivePrefix(f func() (prefix string, useLivePrefix bool)) Option { return func(p *Prompt) error { p.renderer.livePrefixCallback = f return nil } }
[ "func", "OptionLivePrefix", "(", "f", "func", "(", ")", "(", "prefix", "string", ",", "useLivePrefix", "bool", ")", ")", "Option", "{", "return", "func", "(", "p", "*", "Prompt", ")", "error", "{", "p", ".", "renderer", ".", "livePrefixCallback", "=", "f", "\n", "return", "nil", "\n", "}", "\n", "}" ]
// OptionLivePrefix to change the prefix dynamically by callback function
[ "OptionLivePrefix", "to", "change", "the", "prefix", "dynamically", "by", "callback", "function" ]
c8c75cc295ca66affff899dba2c452667e65b9e5
https://github.com/c-bata/go-prompt/blob/c8c75cc295ca66affff899dba2c452667e65b9e5/option.go#L49-L54
train
c-bata/go-prompt
option.go
OptionPrefixTextColor
func OptionPrefixTextColor(x Color) Option { return func(p *Prompt) error { p.renderer.prefixTextColor = x return nil } }
go
func OptionPrefixTextColor(x Color) Option { return func(p *Prompt) error { p.renderer.prefixTextColor = x return nil } }
[ "func", "OptionPrefixTextColor", "(", "x", "Color", ")", "Option", "{", "return", "func", "(", "p", "*", "Prompt", ")", "error", "{", "p", ".", "renderer", ".", "prefixTextColor", "=", "x", "\n", "return", "nil", "\n", "}", "\n", "}" ]
// OptionPrefixTextColor change a text color of prefix string
[ "OptionPrefixTextColor", "change", "a", "text", "color", "of", "prefix", "string" ]
c8c75cc295ca66affff899dba2c452667e65b9e5
https://github.com/c-bata/go-prompt/blob/c8c75cc295ca66affff899dba2c452667e65b9e5/option.go#L57-L62
train
c-bata/go-prompt
option.go
OptionPrefixBackgroundColor
func OptionPrefixBackgroundColor(x Color) Option { return func(p *Prompt) error { p.renderer.prefixBGColor = x return nil } }
go
func OptionPrefixBackgroundColor(x Color) Option { return func(p *Prompt) error { p.renderer.prefixBGColor = x return nil } }
[ "func", "OptionPrefixBackgroundColor", "(", "x", "Color", ")", "Option", "{", "return", "func", "(", "p", "*", "Prompt", ")", "error", "{", "p", ".", "renderer", ".", "prefixBGColor", "=", "x", "\n", "return", "nil", "\n", "}", "\n", "}" ]
// OptionPrefixBackgroundColor to change a background color of prefix string
[ "OptionPrefixBackgroundColor", "to", "change", "a", "background", "color", "of", "prefix", "string" ]
c8c75cc295ca66affff899dba2c452667e65b9e5
https://github.com/c-bata/go-prompt/blob/c8c75cc295ca66affff899dba2c452667e65b9e5/option.go#L65-L70
train
c-bata/go-prompt
option.go
OptionInputTextColor
func OptionInputTextColor(x Color) Option { return func(p *Prompt) error { p.renderer.inputTextColor = x return nil } }
go
func OptionInputTextColor(x Color) Option { return func(p *Prompt) error { p.renderer.inputTextColor = x return nil } }
[ "func", "OptionInputTextColor", "(", "x", "Color", ")", "Option", "{", "return", "func", "(", "p", "*", "Prompt", ")", "error", "{", "p", ".", "renderer", ".", "inputTextColor", "=", "x", "\n", "return", "nil", "\n", "}", "\n", "}" ]
// OptionInputTextColor to change a color of text which is input by user
[ "OptionInputTextColor", "to", "change", "a", "color", "of", "text", "which", "is", "input", "by", "user" ]
c8c75cc295ca66affff899dba2c452667e65b9e5
https://github.com/c-bata/go-prompt/blob/c8c75cc295ca66affff899dba2c452667e65b9e5/option.go#L73-L78
train
c-bata/go-prompt
option.go
OptionInputBGColor
func OptionInputBGColor(x Color) Option { return func(p *Prompt) error { p.renderer.inputBGColor = x return nil } }
go
func OptionInputBGColor(x Color) Option { return func(p *Prompt) error { p.renderer.inputBGColor = x return nil } }
[ "func", "OptionInputBGColor", "(", "x", "Color", ")", "Option", "{", "return", "func", "(", "p", "*", "Prompt", ")", "error", "{", "p", ".", "renderer", ".", "inputBGColor", "=", "x", "\n", "return", "nil", "\n", "}", "\n", "}" ]
// OptionInputBGColor to change a color of background which is input by user
[ "OptionInputBGColor", "to", "change", "a", "color", "of", "background", "which", "is", "input", "by", "user" ]
c8c75cc295ca66affff899dba2c452667e65b9e5
https://github.com/c-bata/go-prompt/blob/c8c75cc295ca66affff899dba2c452667e65b9e5/option.go#L81-L86
train
c-bata/go-prompt
option.go
OptionPreviewSuggestionTextColor
func OptionPreviewSuggestionTextColor(x Color) Option { return func(p *Prompt) error { p.renderer.previewSuggestionTextColor = x return nil } }
go
func OptionPreviewSuggestionTextColor(x Color) Option { return func(p *Prompt) error { p.renderer.previewSuggestionTextColor = x return nil } }
[ "func", "OptionPreviewSuggestionTextColor", "(", "x", "Color", ")", "Option", "{", "return", "func", "(", "p", "*", "Prompt", ")", "error", "{", "p", ".", "renderer", ".", "previewSuggestionTextColor", "=", "x", "\n", "return", "nil", "\n", "}", "\n", "}" ]
// OptionPreviewSuggestionTextColor to change a text color which is completed
[ "OptionPreviewSuggestionTextColor", "to", "change", "a", "text", "color", "which", "is", "completed" ]
c8c75cc295ca66affff899dba2c452667e65b9e5
https://github.com/c-bata/go-prompt/blob/c8c75cc295ca66affff899dba2c452667e65b9e5/option.go#L89-L94
train
c-bata/go-prompt
option.go
OptionPreviewSuggestionBGColor
func OptionPreviewSuggestionBGColor(x Color) Option { return func(p *Prompt) error { p.renderer.previewSuggestionBGColor = x return nil } }
go
func OptionPreviewSuggestionBGColor(x Color) Option { return func(p *Prompt) error { p.renderer.previewSuggestionBGColor = x return nil } }
[ "func", "OptionPreviewSuggestionBGColor", "(", "x", "Color", ")", "Option", "{", "return", "func", "(", "p", "*", "Prompt", ")", "error", "{", "p", ".", "renderer", ".", "previewSuggestionBGColor", "=", "x", "\n", "return", "nil", "\n", "}", "\n", "}" ]
// OptionPreviewSuggestionBGColor to change a background color which is completed
[ "OptionPreviewSuggestionBGColor", "to", "change", "a", "background", "color", "which", "is", "completed" ]
c8c75cc295ca66affff899dba2c452667e65b9e5
https://github.com/c-bata/go-prompt/blob/c8c75cc295ca66affff899dba2c452667e65b9e5/option.go#L97-L102
train
c-bata/go-prompt
option.go
OptionSuggestionTextColor
func OptionSuggestionTextColor(x Color) Option { return func(p *Prompt) error { p.renderer.suggestionTextColor = x return nil } }
go
func OptionSuggestionTextColor(x Color) Option { return func(p *Prompt) error { p.renderer.suggestionTextColor = x return nil } }
[ "func", "OptionSuggestionTextColor", "(", "x", "Color", ")", "Option", "{", "return", "func", "(", "p", "*", "Prompt", ")", "error", "{", "p", ".", "renderer", ".", "suggestionTextColor", "=", "x", "\n", "return", "nil", "\n", "}", "\n", "}" ]
// OptionSuggestionTextColor to change a text color in drop down suggestions.
[ "OptionSuggestionTextColor", "to", "change", "a", "text", "color", "in", "drop", "down", "suggestions", "." ]
c8c75cc295ca66affff899dba2c452667e65b9e5
https://github.com/c-bata/go-prompt/blob/c8c75cc295ca66affff899dba2c452667e65b9e5/option.go#L105-L110
train
c-bata/go-prompt
option.go
OptionSuggestionBGColor
func OptionSuggestionBGColor(x Color) Option { return func(p *Prompt) error { p.renderer.suggestionBGColor = x return nil } }
go
func OptionSuggestionBGColor(x Color) Option { return func(p *Prompt) error { p.renderer.suggestionBGColor = x return nil } }
[ "func", "OptionSuggestionBGColor", "(", "x", "Color", ")", "Option", "{", "return", "func", "(", "p", "*", "Prompt", ")", "error", "{", "p", ".", "renderer", ".", "suggestionBGColor", "=", "x", "\n", "return", "nil", "\n", "}", "\n", "}" ]
// OptionSuggestionBGColor change a background color in drop down suggestions.
[ "OptionSuggestionBGColor", "change", "a", "background", "color", "in", "drop", "down", "suggestions", "." ]
c8c75cc295ca66affff899dba2c452667e65b9e5
https://github.com/c-bata/go-prompt/blob/c8c75cc295ca66affff899dba2c452667e65b9e5/option.go#L113-L118
train
c-bata/go-prompt
option.go
OptionSelectedSuggestionTextColor
func OptionSelectedSuggestionTextColor(x Color) Option { return func(p *Prompt) error { p.renderer.selectedSuggestionTextColor = x return nil } }
go
func OptionSelectedSuggestionTextColor(x Color) Option { return func(p *Prompt) error { p.renderer.selectedSuggestionTextColor = x return nil } }
[ "func", "OptionSelectedSuggestionTextColor", "(", "x", "Color", ")", "Option", "{", "return", "func", "(", "p", "*", "Prompt", ")", "error", "{", "p", ".", "renderer", ".", "selectedSuggestionTextColor", "=", "x", "\n", "return", "nil", "\n", "}", "\n", "}" ]
// OptionSelectedSuggestionTextColor to change a text color for completed text which is selected inside suggestions drop down box.
[ "OptionSelectedSuggestionTextColor", "to", "change", "a", "text", "color", "for", "completed", "text", "which", "is", "selected", "inside", "suggestions", "drop", "down", "box", "." ]
c8c75cc295ca66affff899dba2c452667e65b9e5
https://github.com/c-bata/go-prompt/blob/c8c75cc295ca66affff899dba2c452667e65b9e5/option.go#L121-L126
train
c-bata/go-prompt
option.go
OptionSelectedSuggestionBGColor
func OptionSelectedSuggestionBGColor(x Color) Option { return func(p *Prompt) error { p.renderer.selectedSuggestionBGColor = x return nil } }
go
func OptionSelectedSuggestionBGColor(x Color) Option { return func(p *Prompt) error { p.renderer.selectedSuggestionBGColor = x return nil } }
[ "func", "OptionSelectedSuggestionBGColor", "(", "x", "Color", ")", "Option", "{", "return", "func", "(", "p", "*", "Prompt", ")", "error", "{", "p", ".", "renderer", ".", "selectedSuggestionBGColor", "=", "x", "\n", "return", "nil", "\n", "}", "\n", "}" ]
// OptionSelectedSuggestionBGColor to change a background color for completed text which is selected inside suggestions drop down box.
[ "OptionSelectedSuggestionBGColor", "to", "change", "a", "background", "color", "for", "completed", "text", "which", "is", "selected", "inside", "suggestions", "drop", "down", "box", "." ]
c8c75cc295ca66affff899dba2c452667e65b9e5
https://github.com/c-bata/go-prompt/blob/c8c75cc295ca66affff899dba2c452667e65b9e5/option.go#L129-L134
train
c-bata/go-prompt
option.go
OptionDescriptionTextColor
func OptionDescriptionTextColor(x Color) Option { return func(p *Prompt) error { p.renderer.descriptionTextColor = x return nil } }
go
func OptionDescriptionTextColor(x Color) Option { return func(p *Prompt) error { p.renderer.descriptionTextColor = x return nil } }
[ "func", "OptionDescriptionTextColor", "(", "x", "Color", ")", "Option", "{", "return", "func", "(", "p", "*", "Prompt", ")", "error", "{", "p", ".", "renderer", ".", "descriptionTextColor", "=", "x", "\n", "return", "nil", "\n", "}", "\n", "}" ]
// OptionDescriptionTextColor to change a background color of description text in drop down suggestions.
[ "OptionDescriptionTextColor", "to", "change", "a", "background", "color", "of", "description", "text", "in", "drop", "down", "suggestions", "." ]
c8c75cc295ca66affff899dba2c452667e65b9e5
https://github.com/c-bata/go-prompt/blob/c8c75cc295ca66affff899dba2c452667e65b9e5/option.go#L137-L142
train
c-bata/go-prompt
option.go
OptionDescriptionBGColor
func OptionDescriptionBGColor(x Color) Option { return func(p *Prompt) error { p.renderer.descriptionBGColor = x return nil } }
go
func OptionDescriptionBGColor(x Color) Option { return func(p *Prompt) error { p.renderer.descriptionBGColor = x return nil } }
[ "func", "OptionDescriptionBGColor", "(", "x", "Color", ")", "Option", "{", "return", "func", "(", "p", "*", "Prompt", ")", "error", "{", "p", ".", "renderer", ".", "descriptionBGColor", "=", "x", "\n", "return", "nil", "\n", "}", "\n", "}" ]
// OptionDescriptionBGColor to change a background color of description text in drop down suggestions.
[ "OptionDescriptionBGColor", "to", "change", "a", "background", "color", "of", "description", "text", "in", "drop", "down", "suggestions", "." ]
c8c75cc295ca66affff899dba2c452667e65b9e5
https://github.com/c-bata/go-prompt/blob/c8c75cc295ca66affff899dba2c452667e65b9e5/option.go#L145-L150
train
c-bata/go-prompt
option.go
OptionSelectedDescriptionTextColor
func OptionSelectedDescriptionTextColor(x Color) Option { return func(p *Prompt) error { p.renderer.selectedDescriptionTextColor = x return nil } }
go
func OptionSelectedDescriptionTextColor(x Color) Option { return func(p *Prompt) error { p.renderer.selectedDescriptionTextColor = x return nil } }
[ "func", "OptionSelectedDescriptionTextColor", "(", "x", "Color", ")", "Option", "{", "return", "func", "(", "p", "*", "Prompt", ")", "error", "{", "p", ".", "renderer", ".", "selectedDescriptionTextColor", "=", "x", "\n", "return", "nil", "\n", "}", "\n", "}" ]
// OptionSelectedDescriptionTextColor to change a text color of description which is selected inside suggestions drop down box.
[ "OptionSelectedDescriptionTextColor", "to", "change", "a", "text", "color", "of", "description", "which", "is", "selected", "inside", "suggestions", "drop", "down", "box", "." ]
c8c75cc295ca66affff899dba2c452667e65b9e5
https://github.com/c-bata/go-prompt/blob/c8c75cc295ca66affff899dba2c452667e65b9e5/option.go#L153-L158
train
c-bata/go-prompt
option.go
OptionSelectedDescriptionBGColor
func OptionSelectedDescriptionBGColor(x Color) Option { return func(p *Prompt) error { p.renderer.selectedDescriptionBGColor = x return nil } }
go
func OptionSelectedDescriptionBGColor(x Color) Option { return func(p *Prompt) error { p.renderer.selectedDescriptionBGColor = x return nil } }
[ "func", "OptionSelectedDescriptionBGColor", "(", "x", "Color", ")", "Option", "{", "return", "func", "(", "p", "*", "Prompt", ")", "error", "{", "p", ".", "renderer", ".", "selectedDescriptionBGColor", "=", "x", "\n", "return", "nil", "\n", "}", "\n", "}" ]
// OptionSelectedDescriptionBGColor to change a background color of description which is selected inside suggestions drop down box.
[ "OptionSelectedDescriptionBGColor", "to", "change", "a", "background", "color", "of", "description", "which", "is", "selected", "inside", "suggestions", "drop", "down", "box", "." ]
c8c75cc295ca66affff899dba2c452667e65b9e5
https://github.com/c-bata/go-prompt/blob/c8c75cc295ca66affff899dba2c452667e65b9e5/option.go#L161-L166
train
c-bata/go-prompt
option.go
OptionScrollbarThumbColor
func OptionScrollbarThumbColor(x Color) Option { return func(p *Prompt) error { p.renderer.scrollbarThumbColor = x return nil } }
go
func OptionScrollbarThumbColor(x Color) Option { return func(p *Prompt) error { p.renderer.scrollbarThumbColor = x return nil } }
[ "func", "OptionScrollbarThumbColor", "(", "x", "Color", ")", "Option", "{", "return", "func", "(", "p", "*", "Prompt", ")", "error", "{", "p", ".", "renderer", ".", "scrollbarThumbColor", "=", "x", "\n", "return", "nil", "\n", "}", "\n", "}" ]
// OptionScrollbarThumbColor to change a thumb color on scrollbar.
[ "OptionScrollbarThumbColor", "to", "change", "a", "thumb", "color", "on", "scrollbar", "." ]
c8c75cc295ca66affff899dba2c452667e65b9e5
https://github.com/c-bata/go-prompt/blob/c8c75cc295ca66affff899dba2c452667e65b9e5/option.go#L169-L174
train
c-bata/go-prompt
option.go
OptionScrollbarBGColor
func OptionScrollbarBGColor(x Color) Option { return func(p *Prompt) error { p.renderer.scrollbarBGColor = x return nil } }
go
func OptionScrollbarBGColor(x Color) Option { return func(p *Prompt) error { p.renderer.scrollbarBGColor = x return nil } }
[ "func", "OptionScrollbarBGColor", "(", "x", "Color", ")", "Option", "{", "return", "func", "(", "p", "*", "Prompt", ")", "error", "{", "p", ".", "renderer", ".", "scrollbarBGColor", "=", "x", "\n", "return", "nil", "\n", "}", "\n", "}" ]
// OptionScrollbarBGColor to change a background color of scrollbar.
[ "OptionScrollbarBGColor", "to", "change", "a", "background", "color", "of", "scrollbar", "." ]
c8c75cc295ca66affff899dba2c452667e65b9e5
https://github.com/c-bata/go-prompt/blob/c8c75cc295ca66affff899dba2c452667e65b9e5/option.go#L177-L182
train
c-bata/go-prompt
option.go
OptionMaxSuggestion
func OptionMaxSuggestion(x uint16) Option { return func(p *Prompt) error { p.completion.max = x return nil } }
go
func OptionMaxSuggestion(x uint16) Option { return func(p *Prompt) error { p.completion.max = x return nil } }
[ "func", "OptionMaxSuggestion", "(", "x", "uint16", ")", "Option", "{", "return", "func", "(", "p", "*", "Prompt", ")", "error", "{", "p", ".", "completion", ".", "max", "=", "x", "\n", "return", "nil", "\n", "}", "\n", "}" ]
// OptionMaxSuggestion specify the max number of displayed suggestions.
[ "OptionMaxSuggestion", "specify", "the", "max", "number", "of", "displayed", "suggestions", "." ]
c8c75cc295ca66affff899dba2c452667e65b9e5
https://github.com/c-bata/go-prompt/blob/c8c75cc295ca66affff899dba2c452667e65b9e5/option.go#L185-L190
train
c-bata/go-prompt
option.go
OptionHistory
func OptionHistory(x []string) Option { return func(p *Prompt) error { p.history.histories = x p.history.Clear() return nil } }
go
func OptionHistory(x []string) Option { return func(p *Prompt) error { p.history.histories = x p.history.Clear() return nil } }
[ "func", "OptionHistory", "(", "x", "[", "]", "string", ")", "Option", "{", "return", "func", "(", "p", "*", "Prompt", ")", "error", "{", "p", ".", "history", ".", "histories", "=", "x", "\n", "p", ".", "history", ".", "Clear", "(", ")", "\n", "return", "nil", "\n", "}", "\n", "}" ]
// OptionHistory to set history expressed by string array.
[ "OptionHistory", "to", "set", "history", "expressed", "by", "string", "array", "." ]
c8c75cc295ca66affff899dba2c452667e65b9e5
https://github.com/c-bata/go-prompt/blob/c8c75cc295ca66affff899dba2c452667e65b9e5/option.go#L193-L199
train
c-bata/go-prompt
option.go
OptionSwitchKeyBindMode
func OptionSwitchKeyBindMode(m KeyBindMode) Option { return func(p *Prompt) error { p.keyBindMode = m return nil } }
go
func OptionSwitchKeyBindMode(m KeyBindMode) Option { return func(p *Prompt) error { p.keyBindMode = m return nil } }
[ "func", "OptionSwitchKeyBindMode", "(", "m", "KeyBindMode", ")", "Option", "{", "return", "func", "(", "p", "*", "Prompt", ")", "error", "{", "p", ".", "keyBindMode", "=", "m", "\n", "return", "nil", "\n", "}", "\n", "}" ]
// OptionSwitchKeyBindMode set a key bind mode.
[ "OptionSwitchKeyBindMode", "set", "a", "key", "bind", "mode", "." ]
c8c75cc295ca66affff899dba2c452667e65b9e5
https://github.com/c-bata/go-prompt/blob/c8c75cc295ca66affff899dba2c452667e65b9e5/option.go#L202-L207
train
c-bata/go-prompt
option.go
OptionAddKeyBind
func OptionAddKeyBind(b ...KeyBind) Option { return func(p *Prompt) error { p.keyBindings = append(p.keyBindings, b...) return nil } }
go
func OptionAddKeyBind(b ...KeyBind) Option { return func(p *Prompt) error { p.keyBindings = append(p.keyBindings, b...) return nil } }
[ "func", "OptionAddKeyBind", "(", "b", "...", "KeyBind", ")", "Option", "{", "return", "func", "(", "p", "*", "Prompt", ")", "error", "{", "p", ".", "keyBindings", "=", "append", "(", "p", ".", "keyBindings", ",", "b", "...", ")", "\n", "return", "nil", "\n", "}", "\n", "}" ]
// OptionAddKeyBind to set a custom key bind.
[ "OptionAddKeyBind", "to", "set", "a", "custom", "key", "bind", "." ]
c8c75cc295ca66affff899dba2c452667e65b9e5
https://github.com/c-bata/go-prompt/blob/c8c75cc295ca66affff899dba2c452667e65b9e5/option.go#L214-L219
train
c-bata/go-prompt
option.go
OptionAddASCIICodeBind
func OptionAddASCIICodeBind(b ...ASCIICodeBind) Option { return func(p *Prompt) error { p.ASCIICodeBindings = append(p.ASCIICodeBindings, b...) return nil } }
go
func OptionAddASCIICodeBind(b ...ASCIICodeBind) Option { return func(p *Prompt) error { p.ASCIICodeBindings = append(p.ASCIICodeBindings, b...) return nil } }
[ "func", "OptionAddASCIICodeBind", "(", "b", "...", "ASCIICodeBind", ")", "Option", "{", "return", "func", "(", "p", "*", "Prompt", ")", "error", "{", "p", ".", "ASCIICodeBindings", "=", "append", "(", "p", ".", "ASCIICodeBindings", ",", "b", "...", ")", "\n", "return", "nil", "\n", "}", "\n", "}" ]
// OptionAddASCIICodeBind to set a custom key bind.
[ "OptionAddASCIICodeBind", "to", "set", "a", "custom", "key", "bind", "." ]
c8c75cc295ca66affff899dba2c452667e65b9e5
https://github.com/c-bata/go-prompt/blob/c8c75cc295ca66affff899dba2c452667e65b9e5/option.go#L222-L227
train
c-bata/go-prompt
option.go
OptionShowCompletionAtStart
func OptionShowCompletionAtStart() Option { return func(p *Prompt) error { p.completion.showAtStart = true return nil } }
go
func OptionShowCompletionAtStart() Option { return func(p *Prompt) error { p.completion.showAtStart = true return nil } }
[ "func", "OptionShowCompletionAtStart", "(", ")", "Option", "{", "return", "func", "(", "p", "*", "Prompt", ")", "error", "{", "p", ".", "completion", ".", "showAtStart", "=", "true", "\n", "return", "nil", "\n", "}", "\n", "}" ]
// OptionShowCompletionAtStart to set completion window is open at start.
[ "OptionShowCompletionAtStart", "to", "set", "completion", "window", "is", "open", "at", "start", "." ]
c8c75cc295ca66affff899dba2c452667e65b9e5
https://github.com/c-bata/go-prompt/blob/c8c75cc295ca66affff899dba2c452667e65b9e5/option.go#L230-L235
train
c-bata/go-prompt
option.go
New
func New(executor Executor, completer Completer, opts ...Option) *Prompt { defaultWriter := NewStdoutWriter() registerConsoleWriter(defaultWriter) pt := &Prompt{ in: NewStandardInputParser(), renderer: &Render{ prefix: "> ", out: defaultWriter, livePrefixCallback: func() (string, bool) { return "", false }, prefixTextColor: Blue, prefixBGColor: DefaultColor, inputTextColor: DefaultColor, inputBGColor: DefaultColor, previewSuggestionTextColor: Green, previewSuggestionBGColor: DefaultColor, suggestionTextColor: White, suggestionBGColor: Cyan, selectedSuggestionTextColor: Black, selectedSuggestionBGColor: Turquoise, descriptionTextColor: Black, descriptionBGColor: Turquoise, selectedDescriptionTextColor: White, selectedDescriptionBGColor: Cyan, scrollbarThumbColor: DarkGray, scrollbarBGColor: Cyan, }, buf: NewBuffer(), executor: executor, history: NewHistory(), completion: NewCompletionManager(completer, 6), keyBindMode: EmacsKeyBind, // All the above assume that bash is running in the default Emacs setting } for _, opt := range opts { if err := opt(pt); err != nil { panic(err) } } return pt }
go
func New(executor Executor, completer Completer, opts ...Option) *Prompt { defaultWriter := NewStdoutWriter() registerConsoleWriter(defaultWriter) pt := &Prompt{ in: NewStandardInputParser(), renderer: &Render{ prefix: "> ", out: defaultWriter, livePrefixCallback: func() (string, bool) { return "", false }, prefixTextColor: Blue, prefixBGColor: DefaultColor, inputTextColor: DefaultColor, inputBGColor: DefaultColor, previewSuggestionTextColor: Green, previewSuggestionBGColor: DefaultColor, suggestionTextColor: White, suggestionBGColor: Cyan, selectedSuggestionTextColor: Black, selectedSuggestionBGColor: Turquoise, descriptionTextColor: Black, descriptionBGColor: Turquoise, selectedDescriptionTextColor: White, selectedDescriptionBGColor: Cyan, scrollbarThumbColor: DarkGray, scrollbarBGColor: Cyan, }, buf: NewBuffer(), executor: executor, history: NewHistory(), completion: NewCompletionManager(completer, 6), keyBindMode: EmacsKeyBind, // All the above assume that bash is running in the default Emacs setting } for _, opt := range opts { if err := opt(pt); err != nil { panic(err) } } return pt }
[ "func", "New", "(", "executor", "Executor", ",", "completer", "Completer", ",", "opts", "...", "Option", ")", "*", "Prompt", "{", "defaultWriter", ":=", "NewStdoutWriter", "(", ")", "\n", "registerConsoleWriter", "(", "defaultWriter", ")", "\n\n", "pt", ":=", "&", "Prompt", "{", "in", ":", "NewStandardInputParser", "(", ")", ",", "renderer", ":", "&", "Render", "{", "prefix", ":", "\"", "\"", ",", "out", ":", "defaultWriter", ",", "livePrefixCallback", ":", "func", "(", ")", "(", "string", ",", "bool", ")", "{", "return", "\"", "\"", ",", "false", "}", ",", "prefixTextColor", ":", "Blue", ",", "prefixBGColor", ":", "DefaultColor", ",", "inputTextColor", ":", "DefaultColor", ",", "inputBGColor", ":", "DefaultColor", ",", "previewSuggestionTextColor", ":", "Green", ",", "previewSuggestionBGColor", ":", "DefaultColor", ",", "suggestionTextColor", ":", "White", ",", "suggestionBGColor", ":", "Cyan", ",", "selectedSuggestionTextColor", ":", "Black", ",", "selectedSuggestionBGColor", ":", "Turquoise", ",", "descriptionTextColor", ":", "Black", ",", "descriptionBGColor", ":", "Turquoise", ",", "selectedDescriptionTextColor", ":", "White", ",", "selectedDescriptionBGColor", ":", "Cyan", ",", "scrollbarThumbColor", ":", "DarkGray", ",", "scrollbarBGColor", ":", "Cyan", ",", "}", ",", "buf", ":", "NewBuffer", "(", ")", ",", "executor", ":", "executor", ",", "history", ":", "NewHistory", "(", ")", ",", "completion", ":", "NewCompletionManager", "(", "completer", ",", "6", ")", ",", "keyBindMode", ":", "EmacsKeyBind", ",", "// All the above assume that bash is running in the default Emacs setting", "}", "\n\n", "for", "_", ",", "opt", ":=", "range", "opts", "{", "if", "err", ":=", "opt", "(", "pt", ")", ";", "err", "!=", "nil", "{", "panic", "(", "err", ")", "\n", "}", "\n", "}", "\n", "return", "pt", "\n", "}" ]
// New returns a Prompt with powerful auto-completion.
[ "New", "returns", "a", "Prompt", "with", "powerful", "auto", "-", "completion", "." ]
c8c75cc295ca66affff899dba2c452667e65b9e5
https://github.com/c-bata/go-prompt/blob/c8c75cc295ca66affff899dba2c452667e65b9e5/option.go#L238-L278
train
c-bata/go-prompt
document.go
GetCharRelativeToCursor
func (d *Document) GetCharRelativeToCursor(offset int) (r rune) { s := d.Text cnt := 0 for len(s) > 0 { cnt++ r, size := utf8.DecodeRuneInString(s) if cnt == d.cursorPosition+offset { return r } s = s[size:] } return 0 }
go
func (d *Document) GetCharRelativeToCursor(offset int) (r rune) { s := d.Text cnt := 0 for len(s) > 0 { cnt++ r, size := utf8.DecodeRuneInString(s) if cnt == d.cursorPosition+offset { return r } s = s[size:] } return 0 }
[ "func", "(", "d", "*", "Document", ")", "GetCharRelativeToCursor", "(", "offset", "int", ")", "(", "r", "rune", ")", "{", "s", ":=", "d", ".", "Text", "\n", "cnt", ":=", "0", "\n\n", "for", "len", "(", "s", ")", ">", "0", "{", "cnt", "++", "\n", "r", ",", "size", ":=", "utf8", ".", "DecodeRuneInString", "(", "s", ")", "\n", "if", "cnt", "==", "d", ".", "cursorPosition", "+", "offset", "{", "return", "r", "\n", "}", "\n", "s", "=", "s", "[", "size", ":", "]", "\n", "}", "\n", "return", "0", "\n", "}" ]
// GetCharRelativeToCursor return character relative to cursor position, or empty string
[ "GetCharRelativeToCursor", "return", "character", "relative", "to", "cursor", "position", "or", "empty", "string" ]
c8c75cc295ca66affff899dba2c452667e65b9e5
https://github.com/c-bata/go-prompt/blob/c8c75cc295ca66affff899dba2c452667e65b9e5/document.go#L41-L54
train
c-bata/go-prompt
document.go
TextBeforeCursor
func (d *Document) TextBeforeCursor() string { r := []rune(d.Text) return string(r[:d.cursorPosition]) }
go
func (d *Document) TextBeforeCursor() string { r := []rune(d.Text) return string(r[:d.cursorPosition]) }
[ "func", "(", "d", "*", "Document", ")", "TextBeforeCursor", "(", ")", "string", "{", "r", ":=", "[", "]", "rune", "(", "d", ".", "Text", ")", "\n", "return", "string", "(", "r", "[", ":", "d", ".", "cursorPosition", "]", ")", "\n", "}" ]
// TextBeforeCursor returns the text before the cursor.
[ "TextBeforeCursor", "returns", "the", "text", "before", "the", "cursor", "." ]
c8c75cc295ca66affff899dba2c452667e65b9e5
https://github.com/c-bata/go-prompt/blob/c8c75cc295ca66affff899dba2c452667e65b9e5/document.go#L57-L60
train
c-bata/go-prompt
document.go
TextAfterCursor
func (d *Document) TextAfterCursor() string { r := []rune(d.Text) return string(r[d.cursorPosition:]) }
go
func (d *Document) TextAfterCursor() string { r := []rune(d.Text) return string(r[d.cursorPosition:]) }
[ "func", "(", "d", "*", "Document", ")", "TextAfterCursor", "(", ")", "string", "{", "r", ":=", "[", "]", "rune", "(", "d", ".", "Text", ")", "\n", "return", "string", "(", "r", "[", "d", ".", "cursorPosition", ":", "]", ")", "\n", "}" ]
// TextAfterCursor returns the text after the cursor.
[ "TextAfterCursor", "returns", "the", "text", "after", "the", "cursor", "." ]
c8c75cc295ca66affff899dba2c452667e65b9e5
https://github.com/c-bata/go-prompt/blob/c8c75cc295ca66affff899dba2c452667e65b9e5/document.go#L63-L66
train
c-bata/go-prompt
document.go
GetWordBeforeCursor
func (d *Document) GetWordBeforeCursor() string { x := d.TextBeforeCursor() return x[d.FindStartOfPreviousWord():] }
go
func (d *Document) GetWordBeforeCursor() string { x := d.TextBeforeCursor() return x[d.FindStartOfPreviousWord():] }
[ "func", "(", "d", "*", "Document", ")", "GetWordBeforeCursor", "(", ")", "string", "{", "x", ":=", "d", ".", "TextBeforeCursor", "(", ")", "\n", "return", "x", "[", "d", ".", "FindStartOfPreviousWord", "(", ")", ":", "]", "\n", "}" ]
// GetWordBeforeCursor returns the word before the cursor. // If we have whitespace before the cursor this returns an empty string.
[ "GetWordBeforeCursor", "returns", "the", "word", "before", "the", "cursor", ".", "If", "we", "have", "whitespace", "before", "the", "cursor", "this", "returns", "an", "empty", "string", "." ]
c8c75cc295ca66affff899dba2c452667e65b9e5
https://github.com/c-bata/go-prompt/blob/c8c75cc295ca66affff899dba2c452667e65b9e5/document.go#L70-L73
train
c-bata/go-prompt
document.go
GetWordAfterCursor
func (d *Document) GetWordAfterCursor() string { x := d.TextAfterCursor() return x[:d.FindEndOfCurrentWord()] }
go
func (d *Document) GetWordAfterCursor() string { x := d.TextAfterCursor() return x[:d.FindEndOfCurrentWord()] }
[ "func", "(", "d", "*", "Document", ")", "GetWordAfterCursor", "(", ")", "string", "{", "x", ":=", "d", ".", "TextAfterCursor", "(", ")", "\n", "return", "x", "[", ":", "d", ".", "FindEndOfCurrentWord", "(", ")", "]", "\n", "}" ]
// GetWordAfterCursor returns the word after the cursor. // If we have whitespace after the cursor this returns an empty string.
[ "GetWordAfterCursor", "returns", "the", "word", "after", "the", "cursor", ".", "If", "we", "have", "whitespace", "after", "the", "cursor", "this", "returns", "an", "empty", "string", "." ]
c8c75cc295ca66affff899dba2c452667e65b9e5
https://github.com/c-bata/go-prompt/blob/c8c75cc295ca66affff899dba2c452667e65b9e5/document.go#L77-L80
train
c-bata/go-prompt
document.go
GetWordBeforeCursorWithSpace
func (d *Document) GetWordBeforeCursorWithSpace() string { x := d.TextBeforeCursor() return x[d.FindStartOfPreviousWordWithSpace():] }
go
func (d *Document) GetWordBeforeCursorWithSpace() string { x := d.TextBeforeCursor() return x[d.FindStartOfPreviousWordWithSpace():] }
[ "func", "(", "d", "*", "Document", ")", "GetWordBeforeCursorWithSpace", "(", ")", "string", "{", "x", ":=", "d", ".", "TextBeforeCursor", "(", ")", "\n", "return", "x", "[", "d", ".", "FindStartOfPreviousWordWithSpace", "(", ")", ":", "]", "\n", "}" ]
// GetWordBeforeCursorWithSpace returns the word before the cursor. // Unlike GetWordBeforeCursor, it returns string containing space
[ "GetWordBeforeCursorWithSpace", "returns", "the", "word", "before", "the", "cursor", ".", "Unlike", "GetWordBeforeCursor", "it", "returns", "string", "containing", "space" ]
c8c75cc295ca66affff899dba2c452667e65b9e5
https://github.com/c-bata/go-prompt/blob/c8c75cc295ca66affff899dba2c452667e65b9e5/document.go#L84-L87
train
c-bata/go-prompt
document.go
GetWordAfterCursorWithSpace
func (d *Document) GetWordAfterCursorWithSpace() string { x := d.TextAfterCursor() return x[:d.FindEndOfCurrentWordWithSpace()] }
go
func (d *Document) GetWordAfterCursorWithSpace() string { x := d.TextAfterCursor() return x[:d.FindEndOfCurrentWordWithSpace()] }
[ "func", "(", "d", "*", "Document", ")", "GetWordAfterCursorWithSpace", "(", ")", "string", "{", "x", ":=", "d", ".", "TextAfterCursor", "(", ")", "\n", "return", "x", "[", ":", "d", ".", "FindEndOfCurrentWordWithSpace", "(", ")", "]", "\n", "}" ]
// GetWordAfterCursorWithSpace returns the word after the cursor. // Unlike GetWordAfterCursor, it returns string containing space
[ "GetWordAfterCursorWithSpace", "returns", "the", "word", "after", "the", "cursor", ".", "Unlike", "GetWordAfterCursor", "it", "returns", "string", "containing", "space" ]
c8c75cc295ca66affff899dba2c452667e65b9e5
https://github.com/c-bata/go-prompt/blob/c8c75cc295ca66affff899dba2c452667e65b9e5/document.go#L91-L94
train
c-bata/go-prompt
document.go
GetWordBeforeCursorUntilSeparator
func (d *Document) GetWordBeforeCursorUntilSeparator(sep string) string { x := d.TextBeforeCursor() return x[d.FindStartOfPreviousWordUntilSeparator(sep):] }
go
func (d *Document) GetWordBeforeCursorUntilSeparator(sep string) string { x := d.TextBeforeCursor() return x[d.FindStartOfPreviousWordUntilSeparator(sep):] }
[ "func", "(", "d", "*", "Document", ")", "GetWordBeforeCursorUntilSeparator", "(", "sep", "string", ")", "string", "{", "x", ":=", "d", ".", "TextBeforeCursor", "(", ")", "\n", "return", "x", "[", "d", ".", "FindStartOfPreviousWordUntilSeparator", "(", "sep", ")", ":", "]", "\n", "}" ]
// GetWordBeforeCursorUntilSeparator returns the text before the cursor until next separator.
[ "GetWordBeforeCursorUntilSeparator", "returns", "the", "text", "before", "the", "cursor", "until", "next", "separator", "." ]
c8c75cc295ca66affff899dba2c452667e65b9e5
https://github.com/c-bata/go-prompt/blob/c8c75cc295ca66affff899dba2c452667e65b9e5/document.go#L97-L100
train
c-bata/go-prompt
document.go
GetWordAfterCursorUntilSeparator
func (d *Document) GetWordAfterCursorUntilSeparator(sep string) string { x := d.TextAfterCursor() return x[:d.FindEndOfCurrentWordUntilSeparator(sep)] }
go
func (d *Document) GetWordAfterCursorUntilSeparator(sep string) string { x := d.TextAfterCursor() return x[:d.FindEndOfCurrentWordUntilSeparator(sep)] }
[ "func", "(", "d", "*", "Document", ")", "GetWordAfterCursorUntilSeparator", "(", "sep", "string", ")", "string", "{", "x", ":=", "d", ".", "TextAfterCursor", "(", ")", "\n", "return", "x", "[", ":", "d", ".", "FindEndOfCurrentWordUntilSeparator", "(", "sep", ")", "]", "\n", "}" ]
// GetWordAfterCursorUntilSeparator returns the text after the cursor until next separator.
[ "GetWordAfterCursorUntilSeparator", "returns", "the", "text", "after", "the", "cursor", "until", "next", "separator", "." ]
c8c75cc295ca66affff899dba2c452667e65b9e5
https://github.com/c-bata/go-prompt/blob/c8c75cc295ca66affff899dba2c452667e65b9e5/document.go#L103-L106
train
c-bata/go-prompt
document.go
GetWordBeforeCursorUntilSeparatorIgnoreNextToCursor
func (d *Document) GetWordBeforeCursorUntilSeparatorIgnoreNextToCursor(sep string) string { x := d.TextBeforeCursor() return x[d.FindStartOfPreviousWordUntilSeparatorIgnoreNextToCursor(sep):] }
go
func (d *Document) GetWordBeforeCursorUntilSeparatorIgnoreNextToCursor(sep string) string { x := d.TextBeforeCursor() return x[d.FindStartOfPreviousWordUntilSeparatorIgnoreNextToCursor(sep):] }
[ "func", "(", "d", "*", "Document", ")", "GetWordBeforeCursorUntilSeparatorIgnoreNextToCursor", "(", "sep", "string", ")", "string", "{", "x", ":=", "d", ".", "TextBeforeCursor", "(", ")", "\n", "return", "x", "[", "d", ".", "FindStartOfPreviousWordUntilSeparatorIgnoreNextToCursor", "(", "sep", ")", ":", "]", "\n", "}" ]
// GetWordBeforeCursorUntilSeparatorIgnoreNextToCursor returns the word before the cursor. // Unlike GetWordBeforeCursor, it returns string containing space
[ "GetWordBeforeCursorUntilSeparatorIgnoreNextToCursor", "returns", "the", "word", "before", "the", "cursor", ".", "Unlike", "GetWordBeforeCursor", "it", "returns", "string", "containing", "space" ]
c8c75cc295ca66affff899dba2c452667e65b9e5
https://github.com/c-bata/go-prompt/blob/c8c75cc295ca66affff899dba2c452667e65b9e5/document.go#L110-L113
train
c-bata/go-prompt
document.go
GetWordAfterCursorUntilSeparatorIgnoreNextToCursor
func (d *Document) GetWordAfterCursorUntilSeparatorIgnoreNextToCursor(sep string) string { x := d.TextAfterCursor() return x[:d.FindEndOfCurrentWordUntilSeparatorIgnoreNextToCursor(sep)] }
go
func (d *Document) GetWordAfterCursorUntilSeparatorIgnoreNextToCursor(sep string) string { x := d.TextAfterCursor() return x[:d.FindEndOfCurrentWordUntilSeparatorIgnoreNextToCursor(sep)] }
[ "func", "(", "d", "*", "Document", ")", "GetWordAfterCursorUntilSeparatorIgnoreNextToCursor", "(", "sep", "string", ")", "string", "{", "x", ":=", "d", ".", "TextAfterCursor", "(", ")", "\n", "return", "x", "[", ":", "d", ".", "FindEndOfCurrentWordUntilSeparatorIgnoreNextToCursor", "(", "sep", ")", "]", "\n", "}" ]
// GetWordAfterCursorUntilSeparatorIgnoreNextToCursor returns the word after the cursor. // Unlike GetWordAfterCursor, it returns string containing space
[ "GetWordAfterCursorUntilSeparatorIgnoreNextToCursor", "returns", "the", "word", "after", "the", "cursor", ".", "Unlike", "GetWordAfterCursor", "it", "returns", "string", "containing", "space" ]
c8c75cc295ca66affff899dba2c452667e65b9e5
https://github.com/c-bata/go-prompt/blob/c8c75cc295ca66affff899dba2c452667e65b9e5/document.go#L117-L120
train
c-bata/go-prompt
document.go
FindStartOfPreviousWord
func (d *Document) FindStartOfPreviousWord() int { x := d.TextBeforeCursor() i := strings.LastIndexByte(x, ' ') if i != -1 { return i + 1 } return 0 }
go
func (d *Document) FindStartOfPreviousWord() int { x := d.TextBeforeCursor() i := strings.LastIndexByte(x, ' ') if i != -1 { return i + 1 } return 0 }
[ "func", "(", "d", "*", "Document", ")", "FindStartOfPreviousWord", "(", ")", "int", "{", "x", ":=", "d", ".", "TextBeforeCursor", "(", ")", "\n", "i", ":=", "strings", ".", "LastIndexByte", "(", "x", ",", "' '", ")", "\n", "if", "i", "!=", "-", "1", "{", "return", "i", "+", "1", "\n", "}", "\n", "return", "0", "\n", "}" ]
// FindStartOfPreviousWord returns an index relative to the cursor position // pointing to the start of the previous word. Return 0 if nothing was found.
[ "FindStartOfPreviousWord", "returns", "an", "index", "relative", "to", "the", "cursor", "position", "pointing", "to", "the", "start", "of", "the", "previous", "word", ".", "Return", "0", "if", "nothing", "was", "found", "." ]
c8c75cc295ca66affff899dba2c452667e65b9e5
https://github.com/c-bata/go-prompt/blob/c8c75cc295ca66affff899dba2c452667e65b9e5/document.go#L124-L131
train
c-bata/go-prompt
document.go
FindStartOfPreviousWordWithSpace
func (d *Document) FindStartOfPreviousWordWithSpace() int { x := d.TextBeforeCursor() end := istrings.LastIndexNotByte(x, ' ') if end == -1 { return 0 } start := strings.LastIndexByte(x[:end], ' ') if start == -1 { return 0 } return start + 1 }
go
func (d *Document) FindStartOfPreviousWordWithSpace() int { x := d.TextBeforeCursor() end := istrings.LastIndexNotByte(x, ' ') if end == -1 { return 0 } start := strings.LastIndexByte(x[:end], ' ') if start == -1 { return 0 } return start + 1 }
[ "func", "(", "d", "*", "Document", ")", "FindStartOfPreviousWordWithSpace", "(", ")", "int", "{", "x", ":=", "d", ".", "TextBeforeCursor", "(", ")", "\n", "end", ":=", "istrings", ".", "LastIndexNotByte", "(", "x", ",", "' '", ")", "\n", "if", "end", "==", "-", "1", "{", "return", "0", "\n", "}", "\n\n", "start", ":=", "strings", ".", "LastIndexByte", "(", "x", "[", ":", "end", "]", ",", "' '", ")", "\n", "if", "start", "==", "-", "1", "{", "return", "0", "\n", "}", "\n", "return", "start", "+", "1", "\n", "}" ]
// FindStartOfPreviousWordWithSpace is almost the same as FindStartOfPreviousWord. // The only difference is to ignore contiguous spaces.
[ "FindStartOfPreviousWordWithSpace", "is", "almost", "the", "same", "as", "FindStartOfPreviousWord", ".", "The", "only", "difference", "is", "to", "ignore", "contiguous", "spaces", "." ]
c8c75cc295ca66affff899dba2c452667e65b9e5
https://github.com/c-bata/go-prompt/blob/c8c75cc295ca66affff899dba2c452667e65b9e5/document.go#L135-L147
train
c-bata/go-prompt
document.go
FindStartOfPreviousWordUntilSeparator
func (d *Document) FindStartOfPreviousWordUntilSeparator(sep string) int { if sep == "" { return d.FindStartOfPreviousWord() } x := d.TextBeforeCursor() i := strings.LastIndexAny(x, sep) if i != -1 { return i + 1 } return 0 }
go
func (d *Document) FindStartOfPreviousWordUntilSeparator(sep string) int { if sep == "" { return d.FindStartOfPreviousWord() } x := d.TextBeforeCursor() i := strings.LastIndexAny(x, sep) if i != -1 { return i + 1 } return 0 }
[ "func", "(", "d", "*", "Document", ")", "FindStartOfPreviousWordUntilSeparator", "(", "sep", "string", ")", "int", "{", "if", "sep", "==", "\"", "\"", "{", "return", "d", ".", "FindStartOfPreviousWord", "(", ")", "\n", "}", "\n\n", "x", ":=", "d", ".", "TextBeforeCursor", "(", ")", "\n", "i", ":=", "strings", ".", "LastIndexAny", "(", "x", ",", "sep", ")", "\n", "if", "i", "!=", "-", "1", "{", "return", "i", "+", "1", "\n", "}", "\n", "return", "0", "\n", "}" ]
// FindStartOfPreviousWordUntilSeparator is almost the same as FindStartOfPreviousWord. // But this can specify Separator. Return 0 if nothing was found.
[ "FindStartOfPreviousWordUntilSeparator", "is", "almost", "the", "same", "as", "FindStartOfPreviousWord", ".", "But", "this", "can", "specify", "Separator", ".", "Return", "0", "if", "nothing", "was", "found", "." ]
c8c75cc295ca66affff899dba2c452667e65b9e5
https://github.com/c-bata/go-prompt/blob/c8c75cc295ca66affff899dba2c452667e65b9e5/document.go#L151-L162
train