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
alicebob/miniredis
miniredis.go
RequireAuth
func (m *Miniredis) RequireAuth(pw string) { m.Lock() defer m.Unlock() m.password = pw }
go
func (m *Miniredis) RequireAuth(pw string) { m.Lock() defer m.Unlock() m.password = pw }
[ "func", "(", "m", "*", "Miniredis", ")", "RequireAuth", "(", "pw", "string", ")", "{", "m", ".", "Lock", "(", ")", "\n", "defer", "m", ".", "Unlock", "(", ")", "\n", "m", ".", "password", "=", "pw", "\n", "}" ]
// RequireAuth makes every connection need to AUTH first. Disable again by // setting an empty string.
[ "RequireAuth", "makes", "every", "connection", "need", "to", "AUTH", "first", ".", "Disable", "again", "by", "setting", "an", "empty", "string", "." ]
3d7aa1333af56ab862d446678d93aaa6803e0938
https://github.com/alicebob/miniredis/blob/3d7aa1333af56ab862d446678d93aaa6803e0938/miniredis.go#L177-L181
train
alicebob/miniredis
miniredis.go
DB
func (m *Miniredis) DB(i int) *RedisDB { m.Lock() defer m.Unlock() return m.db(i) }
go
func (m *Miniredis) DB(i int) *RedisDB { m.Lock() defer m.Unlock() return m.db(i) }
[ "func", "(", "m", "*", "Miniredis", ")", "DB", "(", "i", "int", ")", "*", "RedisDB", "{", "m", ".", "Lock", "(", ")", "\n", "defer", "m", ".", "Unlock", "(", ")", "\n", "return", "m", ".", "db", "(", "i", ")", "\n", "}" ]
// DB returns a DB by ID.
[ "DB", "returns", "a", "DB", "by", "ID", "." ]
3d7aa1333af56ab862d446678d93aaa6803e0938
https://github.com/alicebob/miniredis/blob/3d7aa1333af56ab862d446678d93aaa6803e0938/miniredis.go#L184-L188
train
alicebob/miniredis
miniredis.go
db
func (m *Miniredis) db(i int) *RedisDB { if db, ok := m.dbs[i]; ok { return db } db := newRedisDB(i, &m.Mutex) // the DB has our lock. m.dbs[i] = &db return &db }
go
func (m *Miniredis) db(i int) *RedisDB { if db, ok := m.dbs[i]; ok { return db } db := newRedisDB(i, &m.Mutex) // the DB has our lock. m.dbs[i] = &db return &db }
[ "func", "(", "m", "*", "Miniredis", ")", "db", "(", "i", "int", ")", "*", "RedisDB", "{", "if", "db", ",", "ok", ":=", "m", ".", "dbs", "[", "i", "]", ";", "ok", "{", "return", "db", "\n", "}", "\n", "db", ":=", "newRedisDB", "(", "i", ",", "&", "m", ".", "Mutex", ")", "// the DB has our lock.", "\n", "m", ".", "dbs", "[", "i", "]", "=", "&", "db", "\n", "return", "&", "db", "\n", "}" ]
// get DB. No locks!
[ "get", "DB", ".", "No", "locks!" ]
3d7aa1333af56ab862d446678d93aaa6803e0938
https://github.com/alicebob/miniredis/blob/3d7aa1333af56ab862d446678d93aaa6803e0938/miniredis.go#L191-L198
train
alicebob/miniredis
miniredis.go
SwapDB
func (m *Miniredis) SwapDB(i, j int) bool { m.Lock() defer m.Unlock() return m.swapDB(i, j) }
go
func (m *Miniredis) SwapDB(i, j int) bool { m.Lock() defer m.Unlock() return m.swapDB(i, j) }
[ "func", "(", "m", "*", "Miniredis", ")", "SwapDB", "(", "i", ",", "j", "int", ")", "bool", "{", "m", ".", "Lock", "(", ")", "\n", "defer", "m", ".", "Unlock", "(", ")", "\n", "return", "m", ".", "swapDB", "(", "i", ",", "j", ")", "\n", "}" ]
// SwapDB swaps DBs by IDs.
[ "SwapDB", "swaps", "DBs", "by", "IDs", "." ]
3d7aa1333af56ab862d446678d93aaa6803e0938
https://github.com/alicebob/miniredis/blob/3d7aa1333af56ab862d446678d93aaa6803e0938/miniredis.go#L201-L205
train
alicebob/miniredis
miniredis.go
swapDB
func (m *Miniredis) swapDB(i, j int) bool { db1 := m.db(i) db2 := m.db(j) db1.id = j db2.id = i m.dbs[i] = db2 m.dbs[j] = db1 return true }
go
func (m *Miniredis) swapDB(i, j int) bool { db1 := m.db(i) db2 := m.db(j) db1.id = j db2.id = i m.dbs[i] = db2 m.dbs[j] = db1 return true }
[ "func", "(", "m", "*", "Miniredis", ")", "swapDB", "(", "i", ",", "j", "int", ")", "bool", "{", "db1", ":=", "m", ".", "db", "(", "i", ")", "\n", "db2", ":=", "m", ".", "db", "(", "j", ")", "\n\n", "db1", ".", "id", "=", "j", "\n", "db2", ".", "id", "=", "i", "\n\n", "m", ".", "dbs", "[", "i", "]", "=", "db2", "\n", "m", ".", "dbs", "[", "j", "]", "=", "db1", "\n\n", "return", "true", "\n", "}" ]
// swap DB. No locks!
[ "swap", "DB", ".", "No", "locks!" ]
3d7aa1333af56ab862d446678d93aaa6803e0938
https://github.com/alicebob/miniredis/blob/3d7aa1333af56ab862d446678d93aaa6803e0938/miniredis.go#L208-L219
train
alicebob/miniredis
miniredis.go
CommandCount
func (m *Miniredis) CommandCount() int { m.Lock() defer m.Unlock() return int(m.srv.TotalCommands()) }
go
func (m *Miniredis) CommandCount() int { m.Lock() defer m.Unlock() return int(m.srv.TotalCommands()) }
[ "func", "(", "m", "*", "Miniredis", ")", "CommandCount", "(", ")", "int", "{", "m", ".", "Lock", "(", ")", "\n", "defer", "m", ".", "Unlock", "(", ")", "\n", "return", "int", "(", "m", ".", "srv", ".", "TotalCommands", "(", ")", ")", "\n", "}" ]
// CommandCount returns the number of processed commands.
[ "CommandCount", "returns", "the", "number", "of", "processed", "commands", "." ]
3d7aa1333af56ab862d446678d93aaa6803e0938
https://github.com/alicebob/miniredis/blob/3d7aa1333af56ab862d446678d93aaa6803e0938/miniredis.go#L244-L248
train
alicebob/miniredis
miniredis.go
CurrentConnectionCount
func (m *Miniredis) CurrentConnectionCount() int { m.Lock() defer m.Unlock() return m.srv.ClientsLen() }
go
func (m *Miniredis) CurrentConnectionCount() int { m.Lock() defer m.Unlock() return m.srv.ClientsLen() }
[ "func", "(", "m", "*", "Miniredis", ")", "CurrentConnectionCount", "(", ")", "int", "{", "m", ".", "Lock", "(", ")", "\n", "defer", "m", ".", "Unlock", "(", ")", "\n", "return", "m", ".", "srv", ".", "ClientsLen", "(", ")", "\n", "}" ]
// CurrentConnectionCount returns the number of currently connected clients.
[ "CurrentConnectionCount", "returns", "the", "number", "of", "currently", "connected", "clients", "." ]
3d7aa1333af56ab862d446678d93aaa6803e0938
https://github.com/alicebob/miniredis/blob/3d7aa1333af56ab862d446678d93aaa6803e0938/miniredis.go#L251-L255
train
alicebob/miniredis
miniredis.go
TotalConnectionCount
func (m *Miniredis) TotalConnectionCount() int { m.Lock() defer m.Unlock() return int(m.srv.TotalConnections()) }
go
func (m *Miniredis) TotalConnectionCount() int { m.Lock() defer m.Unlock() return int(m.srv.TotalConnections()) }
[ "func", "(", "m", "*", "Miniredis", ")", "TotalConnectionCount", "(", ")", "int", "{", "m", ".", "Lock", "(", ")", "\n", "defer", "m", ".", "Unlock", "(", ")", "\n", "return", "int", "(", "m", ".", "srv", ".", "TotalConnections", "(", ")", ")", "\n", "}" ]
// TotalConnectionCount returns the number of client connections since server start.
[ "TotalConnectionCount", "returns", "the", "number", "of", "client", "connections", "since", "server", "start", "." ]
3d7aa1333af56ab862d446678d93aaa6803e0938
https://github.com/alicebob/miniredis/blob/3d7aa1333af56ab862d446678d93aaa6803e0938/miniredis.go#L258-L262
train
alicebob/miniredis
miniredis.go
FastForward
func (m *Miniredis) FastForward(duration time.Duration) { m.Lock() defer m.Unlock() for _, db := range m.dbs { db.fastForward(duration) } }
go
func (m *Miniredis) FastForward(duration time.Duration) { m.Lock() defer m.Unlock() for _, db := range m.dbs { db.fastForward(duration) } }
[ "func", "(", "m", "*", "Miniredis", ")", "FastForward", "(", "duration", "time", ".", "Duration", ")", "{", "m", ".", "Lock", "(", ")", "\n", "defer", "m", ".", "Unlock", "(", ")", "\n", "for", "_", ",", "db", ":=", "range", "m", ".", "dbs", "{", "db", ".", "fastForward", "(", "duration", ")", "\n", "}", "\n", "}" ]
// FastForward decreases all TTLs by the given duration. All TTLs <= 0 will be // expired.
[ "FastForward", "decreases", "all", "TTLs", "by", "the", "given", "duration", ".", "All", "TTLs", "<", "=", "0", "will", "be", "expired", "." ]
3d7aa1333af56ab862d446678d93aaa6803e0938
https://github.com/alicebob/miniredis/blob/3d7aa1333af56ab862d446678d93aaa6803e0938/miniredis.go#L266-L272
train
alicebob/miniredis
miniredis.go
redigo
func (m *Miniredis) redigo() redigo.Conn { c1, c2 := net.Pipe() m.srv.ServeConn(c1) c := redigo.NewConn(c2, 0, 0) if m.password != "" { if _, err := c.Do("AUTH", m.password); err != nil { // ? } } return c }
go
func (m *Miniredis) redigo() redigo.Conn { c1, c2 := net.Pipe() m.srv.ServeConn(c1) c := redigo.NewConn(c2, 0, 0) if m.password != "" { if _, err := c.Do("AUTH", m.password); err != nil { // ? } } return c }
[ "func", "(", "m", "*", "Miniredis", ")", "redigo", "(", ")", "redigo", ".", "Conn", "{", "c1", ",", "c2", ":=", "net", ".", "Pipe", "(", ")", "\n", "m", ".", "srv", ".", "ServeConn", "(", "c1", ")", "\n", "c", ":=", "redigo", ".", "NewConn", "(", "c2", ",", "0", ",", "0", ")", "\n", "if", "m", ".", "password", "!=", "\"", "\"", "{", "if", "_", ",", "err", ":=", "c", ".", "Do", "(", "\"", "\"", ",", "m", ".", "password", ")", ";", "err", "!=", "nil", "{", "// ?", "}", "\n", "}", "\n", "return", "c", "\n", "}" ]
// redigo returns a redigo.Conn, connected using net.Pipe
[ "redigo", "returns", "a", "redigo", ".", "Conn", "connected", "using", "net", ".", "Pipe" ]
3d7aa1333af56ab862d446678d93aaa6803e0938
https://github.com/alicebob/miniredis/blob/3d7aa1333af56ab862d446678d93aaa6803e0938/miniredis.go#L275-L285
train
alicebob/miniredis
miniredis.go
Dump
func (m *Miniredis) Dump() string { m.Lock() defer m.Unlock() var ( maxLen = 60 indent = " " db = m.db(m.selectedDB) r = "" v = func(s string) string { suffix := "" if len(s) > maxLen { suffix = fmt.Sprintf("...(%d)", len(s)) s = s[:maxLen-len(suffix)] } return fmt.Sprintf("%q%s", s, suffix) } ) for _, k := range db.allKeys() { r += fmt.Sprintf("- %s\n", k) t := db.t(k) switch t { case "string": r += fmt.Sprintf("%s%s\n", indent, v(db.stringKeys[k])) case "hash": for _, hk := range db.hashFields(k) { r += fmt.Sprintf("%s%s: %s\n", indent, hk, v(db.hashGet(k, hk))) } case "list": for _, lk := range db.listKeys[k] { r += fmt.Sprintf("%s%s\n", indent, v(lk)) } case "set": for _, mk := range db.setMembers(k) { r += fmt.Sprintf("%s%s\n", indent, v(mk)) } case "zset": for _, el := range db.ssetElements(k) { r += fmt.Sprintf("%s%f: %s\n", indent, el.score, v(el.member)) } default: r += fmt.Sprintf("%s(a %s, fixme!)\n", indent, t) } } return r }
go
func (m *Miniredis) Dump() string { m.Lock() defer m.Unlock() var ( maxLen = 60 indent = " " db = m.db(m.selectedDB) r = "" v = func(s string) string { suffix := "" if len(s) > maxLen { suffix = fmt.Sprintf("...(%d)", len(s)) s = s[:maxLen-len(suffix)] } return fmt.Sprintf("%q%s", s, suffix) } ) for _, k := range db.allKeys() { r += fmt.Sprintf("- %s\n", k) t := db.t(k) switch t { case "string": r += fmt.Sprintf("%s%s\n", indent, v(db.stringKeys[k])) case "hash": for _, hk := range db.hashFields(k) { r += fmt.Sprintf("%s%s: %s\n", indent, hk, v(db.hashGet(k, hk))) } case "list": for _, lk := range db.listKeys[k] { r += fmt.Sprintf("%s%s\n", indent, v(lk)) } case "set": for _, mk := range db.setMembers(k) { r += fmt.Sprintf("%s%s\n", indent, v(mk)) } case "zset": for _, el := range db.ssetElements(k) { r += fmt.Sprintf("%s%f: %s\n", indent, el.score, v(el.member)) } default: r += fmt.Sprintf("%s(a %s, fixme!)\n", indent, t) } } return r }
[ "func", "(", "m", "*", "Miniredis", ")", "Dump", "(", ")", "string", "{", "m", ".", "Lock", "(", ")", "\n", "defer", "m", ".", "Unlock", "(", ")", "\n\n", "var", "(", "maxLen", "=", "60", "\n", "indent", "=", "\"", "\"", "\n", "db", "=", "m", ".", "db", "(", "m", ".", "selectedDB", ")", "\n", "r", "=", "\"", "\"", "\n", "v", "=", "func", "(", "s", "string", ")", "string", "{", "suffix", ":=", "\"", "\"", "\n", "if", "len", "(", "s", ")", ">", "maxLen", "{", "suffix", "=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "len", "(", "s", ")", ")", "\n", "s", "=", "s", "[", ":", "maxLen", "-", "len", "(", "suffix", ")", "]", "\n", "}", "\n", "return", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "s", ",", "suffix", ")", "\n", "}", "\n", ")", "\n", "for", "_", ",", "k", ":=", "range", "db", ".", "allKeys", "(", ")", "{", "r", "+=", "fmt", ".", "Sprintf", "(", "\"", "\\n", "\"", ",", "k", ")", "\n", "t", ":=", "db", ".", "t", "(", "k", ")", "\n", "switch", "t", "{", "case", "\"", "\"", ":", "r", "+=", "fmt", ".", "Sprintf", "(", "\"", "\\n", "\"", ",", "indent", ",", "v", "(", "db", ".", "stringKeys", "[", "k", "]", ")", ")", "\n", "case", "\"", "\"", ":", "for", "_", ",", "hk", ":=", "range", "db", ".", "hashFields", "(", "k", ")", "{", "r", "+=", "fmt", ".", "Sprintf", "(", "\"", "\\n", "\"", ",", "indent", ",", "hk", ",", "v", "(", "db", ".", "hashGet", "(", "k", ",", "hk", ")", ")", ")", "\n", "}", "\n", "case", "\"", "\"", ":", "for", "_", ",", "lk", ":=", "range", "db", ".", "listKeys", "[", "k", "]", "{", "r", "+=", "fmt", ".", "Sprintf", "(", "\"", "\\n", "\"", ",", "indent", ",", "v", "(", "lk", ")", ")", "\n", "}", "\n", "case", "\"", "\"", ":", "for", "_", ",", "mk", ":=", "range", "db", ".", "setMembers", "(", "k", ")", "{", "r", "+=", "fmt", ".", "Sprintf", "(", "\"", "\\n", "\"", ",", "indent", ",", "v", "(", "mk", ")", ")", "\n", "}", "\n", "case", "\"", "\"", ":", "for", "_", ",", "el", ":=", "range", "db", ".", "ssetElements", "(", "k", ")", "{", "r", "+=", "fmt", ".", "Sprintf", "(", "\"", "\\n", "\"", ",", "indent", ",", "el", ".", "score", ",", "v", "(", "el", ".", "member", ")", ")", "\n", "}", "\n", "default", ":", "r", "+=", "fmt", ".", "Sprintf", "(", "\"", "\\n", "\"", ",", "indent", ",", "t", ")", "\n", "}", "\n", "}", "\n", "return", "r", "\n", "}" ]
// Dump returns a text version of the selected DB, usable for debugging.
[ "Dump", "returns", "a", "text", "version", "of", "the", "selected", "DB", "usable", "for", "debugging", "." ]
3d7aa1333af56ab862d446678d93aaa6803e0938
https://github.com/alicebob/miniredis/blob/3d7aa1333af56ab862d446678d93aaa6803e0938/miniredis.go#L288-L333
train
alicebob/miniredis
miniredis.go
handleAuth
func (m *Miniredis) handleAuth(c *server.Peer) bool { m.Lock() defer m.Unlock() if m.password == "" { return true } if !getCtx(c).authenticated { c.WriteError("NOAUTH Authentication required.") return false } return true }
go
func (m *Miniredis) handleAuth(c *server.Peer) bool { m.Lock() defer m.Unlock() if m.password == "" { return true } if !getCtx(c).authenticated { c.WriteError("NOAUTH Authentication required.") return false } return true }
[ "func", "(", "m", "*", "Miniredis", ")", "handleAuth", "(", "c", "*", "server", ".", "Peer", ")", "bool", "{", "m", ".", "Lock", "(", ")", "\n", "defer", "m", ".", "Unlock", "(", ")", "\n", "if", "m", ".", "password", "==", "\"", "\"", "{", "return", "true", "\n", "}", "\n", "if", "!", "getCtx", "(", "c", ")", ".", "authenticated", "{", "c", ".", "WriteError", "(", "\"", "\"", ")", "\n", "return", "false", "\n", "}", "\n", "return", "true", "\n", "}" ]
// handleAuth returns false if connection has no access. It sends the reply.
[ "handleAuth", "returns", "false", "if", "connection", "has", "no", "access", ".", "It", "sends", "the", "reply", "." ]
3d7aa1333af56ab862d446678d93aaa6803e0938
https://github.com/alicebob/miniredis/blob/3d7aa1333af56ab862d446678d93aaa6803e0938/miniredis.go#L344-L355
train
alicebob/miniredis
miniredis.go
checkPubsub
func (m *Miniredis) checkPubsub(c *server.Peer) bool { m.Lock() defer m.Unlock() ctx := getCtx(c) if ctx.subscriber == nil { return false } c.WriteError("ERR only (P)SUBSCRIBE / (P)UNSUBSCRIBE / PING / QUIT allowed in this context") return true }
go
func (m *Miniredis) checkPubsub(c *server.Peer) bool { m.Lock() defer m.Unlock() ctx := getCtx(c) if ctx.subscriber == nil { return false } c.WriteError("ERR only (P)SUBSCRIBE / (P)UNSUBSCRIBE / PING / QUIT allowed in this context") return true }
[ "func", "(", "m", "*", "Miniredis", ")", "checkPubsub", "(", "c", "*", "server", ".", "Peer", ")", "bool", "{", "m", ".", "Lock", "(", ")", "\n", "defer", "m", ".", "Unlock", "(", ")", "\n\n", "ctx", ":=", "getCtx", "(", "c", ")", "\n", "if", "ctx", ".", "subscriber", "==", "nil", "{", "return", "false", "\n", "}", "\n\n", "c", ".", "WriteError", "(", "\"", "\"", ")", "\n", "return", "true", "\n", "}" ]
// handlePubsub sends an error to the user if the connection is in PUBSUB mode. // It'll return true if it did.
[ "handlePubsub", "sends", "an", "error", "to", "the", "user", "if", "the", "connection", "is", "in", "PUBSUB", "mode", ".", "It", "ll", "return", "true", "if", "it", "did", "." ]
3d7aa1333af56ab862d446678d93aaa6803e0938
https://github.com/alicebob/miniredis/blob/3d7aa1333af56ab862d446678d93aaa6803e0938/miniredis.go#L359-L370
train
alicebob/miniredis
miniredis.go
setDirty
func setDirty(c *server.Peer) { if c.Ctx == nil { // No transaction. Not relevant. return } getCtx(c).dirtyTransaction = true }
go
func setDirty(c *server.Peer) { if c.Ctx == nil { // No transaction. Not relevant. return } getCtx(c).dirtyTransaction = true }
[ "func", "setDirty", "(", "c", "*", "server", ".", "Peer", ")", "{", "if", "c", ".", "Ctx", "==", "nil", "{", "// No transaction. Not relevant.", "return", "\n", "}", "\n", "getCtx", "(", "c", ")", ".", "dirtyTransaction", "=", "true", "\n", "}" ]
// setDirty can be called even when not in an tx. Is an no-op then.
[ "setDirty", "can", "be", "called", "even", "when", "not", "in", "an", "tx", ".", "Is", "an", "no", "-", "op", "then", "." ]
3d7aa1333af56ab862d446678d93aaa6803e0938
https://github.com/alicebob/miniredis/blob/3d7aa1333af56ab862d446678d93aaa6803e0938/miniredis.go#L409-L415
train
alicebob/miniredis
miniredis.go
removeSubscriber
func (m *Miniredis) removeSubscriber(s *Subscriber) { _, ok := m.subscribers[s] delete(m.subscribers, s) if ok { s.Close() } }
go
func (m *Miniredis) removeSubscriber(s *Subscriber) { _, ok := m.subscribers[s] delete(m.subscribers, s) if ok { s.Close() } }
[ "func", "(", "m", "*", "Miniredis", ")", "removeSubscriber", "(", "s", "*", "Subscriber", ")", "{", "_", ",", "ok", ":=", "m", ".", "subscribers", "[", "s", "]", "\n", "delete", "(", "m", ".", "subscribers", ",", "s", ")", "\n", "if", "ok", "{", "s", ".", "Close", "(", ")", "\n", "}", "\n", "}" ]
// closes and remove the subscriber.
[ "closes", "and", "remove", "the", "subscriber", "." ]
3d7aa1333af56ab862d446678d93aaa6803e0938
https://github.com/alicebob/miniredis/blob/3d7aa1333af56ab862d446678d93aaa6803e0938/miniredis.go#L426-L432
train
alicebob/miniredis
miniredis.go
subscribedState
func (m *Miniredis) subscribedState(c *server.Peer) *Subscriber { ctx := getCtx(c) sub := ctx.subscriber if sub != nil { return sub } sub = newSubscriber() m.addSubscriber(sub) c.OnDisconnect(func() { m.Lock() m.removeSubscriber(sub) m.Unlock() }) ctx.subscriber = sub go monitorPublish(c, sub.publish) return sub }
go
func (m *Miniredis) subscribedState(c *server.Peer) *Subscriber { ctx := getCtx(c) sub := ctx.subscriber if sub != nil { return sub } sub = newSubscriber() m.addSubscriber(sub) c.OnDisconnect(func() { m.Lock() m.removeSubscriber(sub) m.Unlock() }) ctx.subscriber = sub go monitorPublish(c, sub.publish) return sub }
[ "func", "(", "m", "*", "Miniredis", ")", "subscribedState", "(", "c", "*", "server", ".", "Peer", ")", "*", "Subscriber", "{", "ctx", ":=", "getCtx", "(", "c", ")", "\n", "sub", ":=", "ctx", ".", "subscriber", "\n", "if", "sub", "!=", "nil", "{", "return", "sub", "\n", "}", "\n\n", "sub", "=", "newSubscriber", "(", ")", "\n", "m", ".", "addSubscriber", "(", "sub", ")", "\n\n", "c", ".", "OnDisconnect", "(", "func", "(", ")", "{", "m", ".", "Lock", "(", ")", "\n", "m", ".", "removeSubscriber", "(", "sub", ")", "\n", "m", ".", "Unlock", "(", ")", "\n", "}", ")", "\n\n", "ctx", ".", "subscriber", "=", "sub", "\n\n", "go", "monitorPublish", "(", "c", ",", "sub", ".", "publish", ")", "\n\n", "return", "sub", "\n", "}" ]
// enter 'subscribed state', or return the existing one.
[ "enter", "subscribed", "state", "or", "return", "the", "existing", "one", "." ]
3d7aa1333af56ab862d446678d93aaa6803e0938
https://github.com/alicebob/miniredis/blob/3d7aa1333af56ab862d446678d93aaa6803e0938/miniredis.go#L443-L464
train
alicebob/miniredis
miniredis.go
endSubscriber
func endSubscriber(m *Miniredis, c *server.Peer) { ctx := getCtx(c) if sub := ctx.subscriber; sub != nil { m.removeSubscriber(sub) // will Close() the sub } ctx.subscriber = nil }
go
func endSubscriber(m *Miniredis, c *server.Peer) { ctx := getCtx(c) if sub := ctx.subscriber; sub != nil { m.removeSubscriber(sub) // will Close() the sub } ctx.subscriber = nil }
[ "func", "endSubscriber", "(", "m", "*", "Miniredis", ",", "c", "*", "server", ".", "Peer", ")", "{", "ctx", ":=", "getCtx", "(", "c", ")", "\n", "if", "sub", ":=", "ctx", ".", "subscriber", ";", "sub", "!=", "nil", "{", "m", ".", "removeSubscriber", "(", "sub", ")", "// will Close() the sub", "\n", "}", "\n", "ctx", ".", "subscriber", "=", "nil", "\n", "}" ]
// whenever the p?sub count drops to 0 subscribed state should be stopped, and // all redis commands are allowed again.
[ "whenever", "the", "p?sub", "count", "drops", "to", "0", "subscribed", "state", "should", "be", "stopped", "and", "all", "redis", "commands", "are", "allowed", "again", "." ]
3d7aa1333af56ab862d446678d93aaa6803e0938
https://github.com/alicebob/miniredis/blob/3d7aa1333af56ab862d446678d93aaa6803e0938/miniredis.go#L468-L474
train
alicebob/miniredis
sorted_set.go
elems
func (ss *sortedSet) elems() ssElems { elems := make(ssElems, 0, len(*ss)) for e, s := range *ss { elems = append(elems, ssElem{s, e}) } return elems }
go
func (ss *sortedSet) elems() ssElems { elems := make(ssElems, 0, len(*ss)) for e, s := range *ss { elems = append(elems, ssElem{s, e}) } return elems }
[ "func", "(", "ss", "*", "sortedSet", ")", "elems", "(", ")", "ssElems", "{", "elems", ":=", "make", "(", "ssElems", ",", "0", ",", "len", "(", "*", "ss", ")", ")", "\n", "for", "e", ",", "s", ":=", "range", "*", "ss", "{", "elems", "=", "append", "(", "elems", ",", "ssElem", "{", "s", ",", "e", "}", ")", "\n", "}", "\n", "return", "elems", "\n", "}" ]
// elems gives the list of ssElem, ready to sort.
[ "elems", "gives", "the", "list", "of", "ssElem", "ready", "to", "sort", "." ]
3d7aa1333af56ab862d446678d93aaa6803e0938
https://github.com/alicebob/miniredis/blob/3d7aa1333af56ab862d446678d93aaa6803e0938/sorted_set.go#L54-L60
train
alicebob/miniredis
cmd_generic.go
commandsGeneric
func commandsGeneric(m *Miniredis) { m.srv.Register("DEL", m.cmdDel) // DUMP m.srv.Register("EXISTS", m.cmdExists) m.srv.Register("EXPIRE", makeCmdExpire(m, false, time.Second)) m.srv.Register("EXPIREAT", makeCmdExpire(m, true, time.Second)) m.srv.Register("KEYS", m.cmdKeys) // MIGRATE m.srv.Register("MOVE", m.cmdMove) // OBJECT m.srv.Register("PERSIST", m.cmdPersist) m.srv.Register("PEXPIRE", makeCmdExpire(m, false, time.Millisecond)) m.srv.Register("PEXPIREAT", makeCmdExpire(m, true, time.Millisecond)) m.srv.Register("PTTL", m.cmdPTTL) m.srv.Register("RANDOMKEY", m.cmdRandomkey) m.srv.Register("RENAME", m.cmdRename) m.srv.Register("RENAMENX", m.cmdRenamenx) // RESTORE // SORT m.srv.Register("TTL", m.cmdTTL) m.srv.Register("TYPE", m.cmdType) m.srv.Register("SCAN", m.cmdScan) }
go
func commandsGeneric(m *Miniredis) { m.srv.Register("DEL", m.cmdDel) // DUMP m.srv.Register("EXISTS", m.cmdExists) m.srv.Register("EXPIRE", makeCmdExpire(m, false, time.Second)) m.srv.Register("EXPIREAT", makeCmdExpire(m, true, time.Second)) m.srv.Register("KEYS", m.cmdKeys) // MIGRATE m.srv.Register("MOVE", m.cmdMove) // OBJECT m.srv.Register("PERSIST", m.cmdPersist) m.srv.Register("PEXPIRE", makeCmdExpire(m, false, time.Millisecond)) m.srv.Register("PEXPIREAT", makeCmdExpire(m, true, time.Millisecond)) m.srv.Register("PTTL", m.cmdPTTL) m.srv.Register("RANDOMKEY", m.cmdRandomkey) m.srv.Register("RENAME", m.cmdRename) m.srv.Register("RENAMENX", m.cmdRenamenx) // RESTORE // SORT m.srv.Register("TTL", m.cmdTTL) m.srv.Register("TYPE", m.cmdType) m.srv.Register("SCAN", m.cmdScan) }
[ "func", "commandsGeneric", "(", "m", "*", "Miniredis", ")", "{", "m", ".", "srv", ".", "Register", "(", "\"", "\"", ",", "m", ".", "cmdDel", ")", "\n", "// DUMP", "m", ".", "srv", ".", "Register", "(", "\"", "\"", ",", "m", ".", "cmdExists", ")", "\n", "m", ".", "srv", ".", "Register", "(", "\"", "\"", ",", "makeCmdExpire", "(", "m", ",", "false", ",", "time", ".", "Second", ")", ")", "\n", "m", ".", "srv", ".", "Register", "(", "\"", "\"", ",", "makeCmdExpire", "(", "m", ",", "true", ",", "time", ".", "Second", ")", ")", "\n", "m", ".", "srv", ".", "Register", "(", "\"", "\"", ",", "m", ".", "cmdKeys", ")", "\n", "// MIGRATE", "m", ".", "srv", ".", "Register", "(", "\"", "\"", ",", "m", ".", "cmdMove", ")", "\n", "// OBJECT", "m", ".", "srv", ".", "Register", "(", "\"", "\"", ",", "m", ".", "cmdPersist", ")", "\n", "m", ".", "srv", ".", "Register", "(", "\"", "\"", ",", "makeCmdExpire", "(", "m", ",", "false", ",", "time", ".", "Millisecond", ")", ")", "\n", "m", ".", "srv", ".", "Register", "(", "\"", "\"", ",", "makeCmdExpire", "(", "m", ",", "true", ",", "time", ".", "Millisecond", ")", ")", "\n", "m", ".", "srv", ".", "Register", "(", "\"", "\"", ",", "m", ".", "cmdPTTL", ")", "\n", "m", ".", "srv", ".", "Register", "(", "\"", "\"", ",", "m", ".", "cmdRandomkey", ")", "\n", "m", ".", "srv", ".", "Register", "(", "\"", "\"", ",", "m", ".", "cmdRename", ")", "\n", "m", ".", "srv", ".", "Register", "(", "\"", "\"", ",", "m", ".", "cmdRenamenx", ")", "\n", "// RESTORE", "// SORT", "m", ".", "srv", ".", "Register", "(", "\"", "\"", ",", "m", ".", "cmdTTL", ")", "\n", "m", ".", "srv", ".", "Register", "(", "\"", "\"", ",", "m", ".", "cmdType", ")", "\n", "m", ".", "srv", ".", "Register", "(", "\"", "\"", ",", "m", ".", "cmdScan", ")", "\n", "}" ]
// commandsGeneric handles EXPIRE, TTL, PERSIST, &c.
[ "commandsGeneric", "handles", "EXPIRE", "TTL", "PERSIST", "&c", "." ]
3d7aa1333af56ab862d446678d93aaa6803e0938
https://github.com/alicebob/miniredis/blob/3d7aa1333af56ab862d446678d93aaa6803e0938/cmd_generic.go#L15-L37
train
alicebob/miniredis
cmd_generic.go
makeCmdExpire
func makeCmdExpire(m *Miniredis, unix bool, d time.Duration) func(*server.Peer, string, []string) { return func(c *server.Peer, cmd string, args []string) { if len(args) != 2 { setDirty(c) c.WriteError(errWrongNumber(cmd)) return } if !m.handleAuth(c) { return } if m.checkPubsub(c) { return } key := args[0] value := args[1] i, err := strconv.Atoi(value) if err != nil { setDirty(c) c.WriteError(msgInvalidInt) return } withTx(m, c, func(c *server.Peer, ctx *connCtx) { db := m.db(ctx.selectedDB) // Key must be present. if _, ok := db.keys[key]; !ok { c.WriteInt(0) return } if unix { var ts time.Time switch d { case time.Millisecond: ts = time.Unix(int64(i/1000), 1000000*int64(i%1000)) case time.Second: ts = time.Unix(int64(i), 0) default: panic("invalid time unit (d). Fixme!") } now := m.now if now.IsZero() { now = time.Now().UTC() } db.ttl[key] = ts.Sub(now) } else { db.ttl[key] = time.Duration(i) * d } db.keyVersion[key]++ db.checkTTL(key) c.WriteInt(1) }) } }
go
func makeCmdExpire(m *Miniredis, unix bool, d time.Duration) func(*server.Peer, string, []string) { return func(c *server.Peer, cmd string, args []string) { if len(args) != 2 { setDirty(c) c.WriteError(errWrongNumber(cmd)) return } if !m.handleAuth(c) { return } if m.checkPubsub(c) { return } key := args[0] value := args[1] i, err := strconv.Atoi(value) if err != nil { setDirty(c) c.WriteError(msgInvalidInt) return } withTx(m, c, func(c *server.Peer, ctx *connCtx) { db := m.db(ctx.selectedDB) // Key must be present. if _, ok := db.keys[key]; !ok { c.WriteInt(0) return } if unix { var ts time.Time switch d { case time.Millisecond: ts = time.Unix(int64(i/1000), 1000000*int64(i%1000)) case time.Second: ts = time.Unix(int64(i), 0) default: panic("invalid time unit (d). Fixme!") } now := m.now if now.IsZero() { now = time.Now().UTC() } db.ttl[key] = ts.Sub(now) } else { db.ttl[key] = time.Duration(i) * d } db.keyVersion[key]++ db.checkTTL(key) c.WriteInt(1) }) } }
[ "func", "makeCmdExpire", "(", "m", "*", "Miniredis", ",", "unix", "bool", ",", "d", "time", ".", "Duration", ")", "func", "(", "*", "server", ".", "Peer", ",", "string", ",", "[", "]", "string", ")", "{", "return", "func", "(", "c", "*", "server", ".", "Peer", ",", "cmd", "string", ",", "args", "[", "]", "string", ")", "{", "if", "len", "(", "args", ")", "!=", "2", "{", "setDirty", "(", "c", ")", "\n", "c", ".", "WriteError", "(", "errWrongNumber", "(", "cmd", ")", ")", "\n", "return", "\n", "}", "\n", "if", "!", "m", ".", "handleAuth", "(", "c", ")", "{", "return", "\n", "}", "\n", "if", "m", ".", "checkPubsub", "(", "c", ")", "{", "return", "\n", "}", "\n\n", "key", ":=", "args", "[", "0", "]", "\n", "value", ":=", "args", "[", "1", "]", "\n", "i", ",", "err", ":=", "strconv", ".", "Atoi", "(", "value", ")", "\n", "if", "err", "!=", "nil", "{", "setDirty", "(", "c", ")", "\n", "c", ".", "WriteError", "(", "msgInvalidInt", ")", "\n", "return", "\n", "}", "\n\n", "withTx", "(", "m", ",", "c", ",", "func", "(", "c", "*", "server", ".", "Peer", ",", "ctx", "*", "connCtx", ")", "{", "db", ":=", "m", ".", "db", "(", "ctx", ".", "selectedDB", ")", "\n\n", "// Key must be present.", "if", "_", ",", "ok", ":=", "db", ".", "keys", "[", "key", "]", ";", "!", "ok", "{", "c", ".", "WriteInt", "(", "0", ")", "\n", "return", "\n", "}", "\n", "if", "unix", "{", "var", "ts", "time", ".", "Time", "\n", "switch", "d", "{", "case", "time", ".", "Millisecond", ":", "ts", "=", "time", ".", "Unix", "(", "int64", "(", "i", "/", "1000", ")", ",", "1000000", "*", "int64", "(", "i", "%", "1000", ")", ")", "\n", "case", "time", ".", "Second", ":", "ts", "=", "time", ".", "Unix", "(", "int64", "(", "i", ")", ",", "0", ")", "\n", "default", ":", "panic", "(", "\"", "\"", ")", "\n", "}", "\n", "now", ":=", "m", ".", "now", "\n", "if", "now", ".", "IsZero", "(", ")", "{", "now", "=", "time", ".", "Now", "(", ")", ".", "UTC", "(", ")", "\n", "}", "\n", "db", ".", "ttl", "[", "key", "]", "=", "ts", ".", "Sub", "(", "now", ")", "\n", "}", "else", "{", "db", ".", "ttl", "[", "key", "]", "=", "time", ".", "Duration", "(", "i", ")", "*", "d", "\n", "}", "\n", "db", ".", "keyVersion", "[", "key", "]", "++", "\n", "db", ".", "checkTTL", "(", "key", ")", "\n", "c", ".", "WriteInt", "(", "1", ")", "\n", "}", ")", "\n", "}", "\n", "}" ]
// generic expire command for EXPIRE, PEXPIRE, EXPIREAT, PEXPIREAT // d is the time unit. If unix is set it'll be seen as a unixtimestamp and // converted to a duration.
[ "generic", "expire", "command", "for", "EXPIRE", "PEXPIRE", "EXPIREAT", "PEXPIREAT", "d", "is", "the", "time", "unit", ".", "If", "unix", "is", "set", "it", "ll", "be", "seen", "as", "a", "unixtimestamp", "and", "converted", "to", "a", "duration", "." ]
3d7aa1333af56ab862d446678d93aaa6803e0938
https://github.com/alicebob/miniredis/blob/3d7aa1333af56ab862d446678d93aaa6803e0938/cmd_generic.go#L42-L96
train
alicebob/miniredis
redis.go
withTx
func withTx( m *Miniredis, c *server.Peer, cb txCmd, ) { ctx := getCtx(c) if inTx(ctx) { addTxCmd(ctx, cb) c.WriteInline("QUEUED") return } m.Lock() cb(c, ctx) // done, wake up anyone who waits on anything. m.signal.Broadcast() m.Unlock() }
go
func withTx( m *Miniredis, c *server.Peer, cb txCmd, ) { ctx := getCtx(c) if inTx(ctx) { addTxCmd(ctx, cb) c.WriteInline("QUEUED") return } m.Lock() cb(c, ctx) // done, wake up anyone who waits on anything. m.signal.Broadcast() m.Unlock() }
[ "func", "withTx", "(", "m", "*", "Miniredis", ",", "c", "*", "server", ".", "Peer", ",", "cb", "txCmd", ",", ")", "{", "ctx", ":=", "getCtx", "(", "c", ")", "\n", "if", "inTx", "(", "ctx", ")", "{", "addTxCmd", "(", "ctx", ",", "cb", ")", "\n", "c", ".", "WriteInline", "(", "\"", "\"", ")", "\n", "return", "\n", "}", "\n", "m", ".", "Lock", "(", ")", "\n", "cb", "(", "c", ",", "ctx", ")", "\n", "// done, wake up anyone who waits on anything.", "m", ".", "signal", ".", "Broadcast", "(", ")", "\n", "m", ".", "Unlock", "(", ")", "\n", "}" ]
// withTx wraps the non-argument-checking part of command handling code in // transaction logic.
[ "withTx", "wraps", "the", "non", "-", "argument", "-", "checking", "part", "of", "command", "handling", "code", "in", "transaction", "logic", "." ]
3d7aa1333af56ab862d446678d93aaa6803e0938
https://github.com/alicebob/miniredis/blob/3d7aa1333af56ab862d446678d93aaa6803e0938/redis.go#L47-L63
train
alicebob/miniredis
redis.go
matchKeys
func matchKeys(keys []string, match string) []string { re := patternRE(match) if re == nil { // Special case, the given pattern won't match anything / is // invalid. return nil } res := []string{} for _, k := range keys { if !re.MatchString(k) { continue } res = append(res, k) } return res }
go
func matchKeys(keys []string, match string) []string { re := patternRE(match) if re == nil { // Special case, the given pattern won't match anything / is // invalid. return nil } res := []string{} for _, k := range keys { if !re.MatchString(k) { continue } res = append(res, k) } return res }
[ "func", "matchKeys", "(", "keys", "[", "]", "string", ",", "match", "string", ")", "[", "]", "string", "{", "re", ":=", "patternRE", "(", "match", ")", "\n", "if", "re", "==", "nil", "{", "// Special case, the given pattern won't match anything / is", "// invalid.", "return", "nil", "\n", "}", "\n", "res", ":=", "[", "]", "string", "{", "}", "\n", "for", "_", ",", "k", ":=", "range", "keys", "{", "if", "!", "re", ".", "MatchString", "(", "k", ")", "{", "continue", "\n", "}", "\n", "res", "=", "append", "(", "res", ",", "k", ")", "\n", "}", "\n", "return", "res", "\n", "}" ]
// matchKeys filters only matching keys. // Will return an empty list on invalid match expression.
[ "matchKeys", "filters", "only", "matching", "keys", ".", "Will", "return", "an", "empty", "list", "on", "invalid", "match", "expression", "." ]
3d7aa1333af56ab862d446678d93aaa6803e0938
https://github.com/alicebob/miniredis/blob/3d7aa1333af56ab862d446678d93aaa6803e0938/redis.go#L194-L209
train
alicebob/miniredis
db.go
allKeys
func (db *RedisDB) allKeys() []string { res := make([]string, 0, len(db.keys)) for k := range db.keys { res = append(res, k) } sort.Strings(res) // To make things deterministic. return res }
go
func (db *RedisDB) allKeys() []string { res := make([]string, 0, len(db.keys)) for k := range db.keys { res = append(res, k) } sort.Strings(res) // To make things deterministic. return res }
[ "func", "(", "db", "*", "RedisDB", ")", "allKeys", "(", ")", "[", "]", "string", "{", "res", ":=", "make", "(", "[", "]", "string", ",", "0", ",", "len", "(", "db", ".", "keys", ")", ")", "\n", "for", "k", ":=", "range", "db", ".", "keys", "{", "res", "=", "append", "(", "res", ",", "k", ")", "\n", "}", "\n", "sort", ".", "Strings", "(", "res", ")", "// To make things deterministic.", "\n", "return", "res", "\n", "}" ]
// allKeys returns all keys. Sorted.
[ "allKeys", "returns", "all", "keys", ".", "Sorted", "." ]
3d7aa1333af56ab862d446678d93aaa6803e0938
https://github.com/alicebob/miniredis/blob/3d7aa1333af56ab862d446678d93aaa6803e0938/db.go#L20-L27
train
alicebob/miniredis
db.go
flush
func (db *RedisDB) flush() { db.keys = map[string]string{} db.stringKeys = map[string]string{} db.hashKeys = map[string]hashKey{} db.listKeys = map[string]listKey{} db.setKeys = map[string]setKey{} db.sortedsetKeys = map[string]sortedSet{} db.ttl = map[string]time.Duration{} }
go
func (db *RedisDB) flush() { db.keys = map[string]string{} db.stringKeys = map[string]string{} db.hashKeys = map[string]hashKey{} db.listKeys = map[string]listKey{} db.setKeys = map[string]setKey{} db.sortedsetKeys = map[string]sortedSet{} db.ttl = map[string]time.Duration{} }
[ "func", "(", "db", "*", "RedisDB", ")", "flush", "(", ")", "{", "db", ".", "keys", "=", "map", "[", "string", "]", "string", "{", "}", "\n", "db", ".", "stringKeys", "=", "map", "[", "string", "]", "string", "{", "}", "\n", "db", ".", "hashKeys", "=", "map", "[", "string", "]", "hashKey", "{", "}", "\n", "db", ".", "listKeys", "=", "map", "[", "string", "]", "listKey", "{", "}", "\n", "db", ".", "setKeys", "=", "map", "[", "string", "]", "setKey", "{", "}", "\n", "db", ".", "sortedsetKeys", "=", "map", "[", "string", "]", "sortedSet", "{", "}", "\n", "db", ".", "ttl", "=", "map", "[", "string", "]", "time", ".", "Duration", "{", "}", "\n", "}" ]
// flush removes all keys and values.
[ "flush", "removes", "all", "keys", "and", "values", "." ]
3d7aa1333af56ab862d446678d93aaa6803e0938
https://github.com/alicebob/miniredis/blob/3d7aa1333af56ab862d446678d93aaa6803e0938/db.go#L30-L38
train
alicebob/miniredis
db.go
move
func (db *RedisDB) move(key string, to *RedisDB) bool { if _, ok := to.keys[key]; ok { return false } t, ok := db.keys[key] if !ok { return false } to.keys[key] = db.keys[key] switch t { case "string": to.stringKeys[key] = db.stringKeys[key] case "hash": to.hashKeys[key] = db.hashKeys[key] case "list": to.listKeys[key] = db.listKeys[key] case "set": to.setKeys[key] = db.setKeys[key] case "zset": to.sortedsetKeys[key] = db.sortedsetKeys[key] default: panic("unhandled key type") } to.keyVersion[key]++ if v, ok := db.ttl[key]; ok { to.ttl[key] = v } db.del(key, true) return true }
go
func (db *RedisDB) move(key string, to *RedisDB) bool { if _, ok := to.keys[key]; ok { return false } t, ok := db.keys[key] if !ok { return false } to.keys[key] = db.keys[key] switch t { case "string": to.stringKeys[key] = db.stringKeys[key] case "hash": to.hashKeys[key] = db.hashKeys[key] case "list": to.listKeys[key] = db.listKeys[key] case "set": to.setKeys[key] = db.setKeys[key] case "zset": to.sortedsetKeys[key] = db.sortedsetKeys[key] default: panic("unhandled key type") } to.keyVersion[key]++ if v, ok := db.ttl[key]; ok { to.ttl[key] = v } db.del(key, true) return true }
[ "func", "(", "db", "*", "RedisDB", ")", "move", "(", "key", "string", ",", "to", "*", "RedisDB", ")", "bool", "{", "if", "_", ",", "ok", ":=", "to", ".", "keys", "[", "key", "]", ";", "ok", "{", "return", "false", "\n", "}", "\n\n", "t", ",", "ok", ":=", "db", ".", "keys", "[", "key", "]", "\n", "if", "!", "ok", "{", "return", "false", "\n", "}", "\n", "to", ".", "keys", "[", "key", "]", "=", "db", ".", "keys", "[", "key", "]", "\n", "switch", "t", "{", "case", "\"", "\"", ":", "to", ".", "stringKeys", "[", "key", "]", "=", "db", ".", "stringKeys", "[", "key", "]", "\n", "case", "\"", "\"", ":", "to", ".", "hashKeys", "[", "key", "]", "=", "db", ".", "hashKeys", "[", "key", "]", "\n", "case", "\"", "\"", ":", "to", ".", "listKeys", "[", "key", "]", "=", "db", ".", "listKeys", "[", "key", "]", "\n", "case", "\"", "\"", ":", "to", ".", "setKeys", "[", "key", "]", "=", "db", ".", "setKeys", "[", "key", "]", "\n", "case", "\"", "\"", ":", "to", ".", "sortedsetKeys", "[", "key", "]", "=", "db", ".", "sortedsetKeys", "[", "key", "]", "\n", "default", ":", "panic", "(", "\"", "\"", ")", "\n", "}", "\n", "to", ".", "keyVersion", "[", "key", "]", "++", "\n", "if", "v", ",", "ok", ":=", "db", ".", "ttl", "[", "key", "]", ";", "ok", "{", "to", ".", "ttl", "[", "key", "]", "=", "v", "\n", "}", "\n", "db", ".", "del", "(", "key", ",", "true", ")", "\n", "return", "true", "\n", "}" ]
// move something to another db. Will return ok. Or not.
[ "move", "something", "to", "another", "db", ".", "Will", "return", "ok", ".", "Or", "not", "." ]
3d7aa1333af56ab862d446678d93aaa6803e0938
https://github.com/alicebob/miniredis/blob/3d7aa1333af56ab862d446678d93aaa6803e0938/db.go#L41-L71
train
alicebob/miniredis
db.go
stringIncr
func (db *RedisDB) stringIncr(k string, delta int) (int, error) { v := 0 if sv, ok := db.stringKeys[k]; ok { var err error v, err = strconv.Atoi(sv) if err != nil { return 0, ErrIntValueError } } v += delta db.stringSet(k, strconv.Itoa(v)) return v, nil }
go
func (db *RedisDB) stringIncr(k string, delta int) (int, error) { v := 0 if sv, ok := db.stringKeys[k]; ok { var err error v, err = strconv.Atoi(sv) if err != nil { return 0, ErrIntValueError } } v += delta db.stringSet(k, strconv.Itoa(v)) return v, nil }
[ "func", "(", "db", "*", "RedisDB", ")", "stringIncr", "(", "k", "string", ",", "delta", "int", ")", "(", "int", ",", "error", ")", "{", "v", ":=", "0", "\n", "if", "sv", ",", "ok", ":=", "db", ".", "stringKeys", "[", "k", "]", ";", "ok", "{", "var", "err", "error", "\n", "v", ",", "err", "=", "strconv", ".", "Atoi", "(", "sv", ")", "\n", "if", "err", "!=", "nil", "{", "return", "0", ",", "ErrIntValueError", "\n", "}", "\n", "}", "\n", "v", "+=", "delta", "\n", "db", ".", "stringSet", "(", "k", ",", "strconv", ".", "Itoa", "(", "v", ")", ")", "\n", "return", "v", ",", "nil", "\n", "}" ]
// change int key value
[ "change", "int", "key", "value" ]
3d7aa1333af56ab862d446678d93aaa6803e0938
https://github.com/alicebob/miniredis/blob/3d7aa1333af56ab862d446678d93aaa6803e0938/db.go#L139-L151
train
alicebob/miniredis
db.go
stringIncrfloat
func (db *RedisDB) stringIncrfloat(k string, delta float64) (float64, error) { v := 0.0 if sv, ok := db.stringKeys[k]; ok { var err error v, err = strconv.ParseFloat(sv, 64) if err != nil { return 0, ErrFloatValueError } } v += delta db.stringSet(k, formatFloat(v)) return v, nil }
go
func (db *RedisDB) stringIncrfloat(k string, delta float64) (float64, error) { v := 0.0 if sv, ok := db.stringKeys[k]; ok { var err error v, err = strconv.ParseFloat(sv, 64) if err != nil { return 0, ErrFloatValueError } } v += delta db.stringSet(k, formatFloat(v)) return v, nil }
[ "func", "(", "db", "*", "RedisDB", ")", "stringIncrfloat", "(", "k", "string", ",", "delta", "float64", ")", "(", "float64", ",", "error", ")", "{", "v", ":=", "0.0", "\n", "if", "sv", ",", "ok", ":=", "db", ".", "stringKeys", "[", "k", "]", ";", "ok", "{", "var", "err", "error", "\n", "v", ",", "err", "=", "strconv", ".", "ParseFloat", "(", "sv", ",", "64", ")", "\n", "if", "err", "!=", "nil", "{", "return", "0", ",", "ErrFloatValueError", "\n", "}", "\n", "}", "\n", "v", "+=", "delta", "\n", "db", ".", "stringSet", "(", "k", ",", "formatFloat", "(", "v", ")", ")", "\n", "return", "v", ",", "nil", "\n", "}" ]
// change float key value
[ "change", "float", "key", "value" ]
3d7aa1333af56ab862d446678d93aaa6803e0938
https://github.com/alicebob/miniredis/blob/3d7aa1333af56ab862d446678d93aaa6803e0938/db.go#L154-L166
train
alicebob/miniredis
db.go
listLpush
func (db *RedisDB) listLpush(k, v string) int { l, ok := db.listKeys[k] if !ok { db.keys[k] = "list" } l = append([]string{v}, l...) db.listKeys[k] = l db.keyVersion[k]++ return len(l) }
go
func (db *RedisDB) listLpush(k, v string) int { l, ok := db.listKeys[k] if !ok { db.keys[k] = "list" } l = append([]string{v}, l...) db.listKeys[k] = l db.keyVersion[k]++ return len(l) }
[ "func", "(", "db", "*", "RedisDB", ")", "listLpush", "(", "k", ",", "v", "string", ")", "int", "{", "l", ",", "ok", ":=", "db", ".", "listKeys", "[", "k", "]", "\n", "if", "!", "ok", "{", "db", ".", "keys", "[", "k", "]", "=", "\"", "\"", "\n", "}", "\n", "l", "=", "append", "(", "[", "]", "string", "{", "v", "}", ",", "l", "...", ")", "\n", "db", ".", "listKeys", "[", "k", "]", "=", "l", "\n", "db", ".", "keyVersion", "[", "k", "]", "++", "\n", "return", "len", "(", "l", ")", "\n", "}" ]
// listLpush is 'left push', aka unshift. Returns the new length.
[ "listLpush", "is", "left", "push", "aka", "unshift", ".", "Returns", "the", "new", "length", "." ]
3d7aa1333af56ab862d446678d93aaa6803e0938
https://github.com/alicebob/miniredis/blob/3d7aa1333af56ab862d446678d93aaa6803e0938/db.go#L169-L178
train
alicebob/miniredis
db.go
listLpop
func (db *RedisDB) listLpop(k string) string { l := db.listKeys[k] el := l[0] l = l[1:] if len(l) == 0 { db.del(k, true) } else { db.listKeys[k] = l } db.keyVersion[k]++ return el }
go
func (db *RedisDB) listLpop(k string) string { l := db.listKeys[k] el := l[0] l = l[1:] if len(l) == 0 { db.del(k, true) } else { db.listKeys[k] = l } db.keyVersion[k]++ return el }
[ "func", "(", "db", "*", "RedisDB", ")", "listLpop", "(", "k", "string", ")", "string", "{", "l", ":=", "db", ".", "listKeys", "[", "k", "]", "\n", "el", ":=", "l", "[", "0", "]", "\n", "l", "=", "l", "[", "1", ":", "]", "\n", "if", "len", "(", "l", ")", "==", "0", "{", "db", ".", "del", "(", "k", ",", "true", ")", "\n", "}", "else", "{", "db", ".", "listKeys", "[", "k", "]", "=", "l", "\n", "}", "\n", "db", ".", "keyVersion", "[", "k", "]", "++", "\n", "return", "el", "\n", "}" ]
// 'left pop', aka shift.
[ "left", "pop", "aka", "shift", "." ]
3d7aa1333af56ab862d446678d93aaa6803e0938
https://github.com/alicebob/miniredis/blob/3d7aa1333af56ab862d446678d93aaa6803e0938/db.go#L181-L192
train
alicebob/miniredis
db.go
setSet
func (db *RedisDB) setSet(k string, set setKey) { db.keys[k] = "set" db.setKeys[k] = set db.keyVersion[k]++ }
go
func (db *RedisDB) setSet(k string, set setKey) { db.keys[k] = "set" db.setKeys[k] = set db.keyVersion[k]++ }
[ "func", "(", "db", "*", "RedisDB", ")", "setSet", "(", "k", "string", ",", "set", "setKey", ")", "{", "db", ".", "keys", "[", "k", "]", "=", "\"", "\"", "\n", "db", ".", "setKeys", "[", "k", "]", "=", "set", "\n", "db", ".", "keyVersion", "[", "k", "]", "++", "\n", "}" ]
// setset replaces a whole set.
[ "setset", "replaces", "a", "whole", "set", "." ]
3d7aa1333af56ab862d446678d93aaa6803e0938
https://github.com/alicebob/miniredis/blob/3d7aa1333af56ab862d446678d93aaa6803e0938/db.go#L219-L223
train
alicebob/miniredis
db.go
setAdd
func (db *RedisDB) setAdd(k string, elems ...string) int { s, ok := db.setKeys[k] if !ok { s = setKey{} db.keys[k] = "set" } added := 0 for _, e := range elems { if _, ok := s[e]; !ok { added++ } s[e] = struct{}{} } db.setKeys[k] = s db.keyVersion[k]++ return added }
go
func (db *RedisDB) setAdd(k string, elems ...string) int { s, ok := db.setKeys[k] if !ok { s = setKey{} db.keys[k] = "set" } added := 0 for _, e := range elems { if _, ok := s[e]; !ok { added++ } s[e] = struct{}{} } db.setKeys[k] = s db.keyVersion[k]++ return added }
[ "func", "(", "db", "*", "RedisDB", ")", "setAdd", "(", "k", "string", ",", "elems", "...", "string", ")", "int", "{", "s", ",", "ok", ":=", "db", ".", "setKeys", "[", "k", "]", "\n", "if", "!", "ok", "{", "s", "=", "setKey", "{", "}", "\n", "db", ".", "keys", "[", "k", "]", "=", "\"", "\"", "\n", "}", "\n", "added", ":=", "0", "\n", "for", "_", ",", "e", ":=", "range", "elems", "{", "if", "_", ",", "ok", ":=", "s", "[", "e", "]", ";", "!", "ok", "{", "added", "++", "\n", "}", "\n", "s", "[", "e", "]", "=", "struct", "{", "}", "{", "}", "\n", "}", "\n", "db", ".", "setKeys", "[", "k", "]", "=", "s", "\n", "db", ".", "keyVersion", "[", "k", "]", "++", "\n", "return", "added", "\n", "}" ]
// setadd adds members to a set. Returns nr of new keys.
[ "setadd", "adds", "members", "to", "a", "set", ".", "Returns", "nr", "of", "new", "keys", "." ]
3d7aa1333af56ab862d446678d93aaa6803e0938
https://github.com/alicebob/miniredis/blob/3d7aa1333af56ab862d446678d93aaa6803e0938/db.go#L226-L242
train
alicebob/miniredis
db.go
setRem
func (db *RedisDB) setRem(k string, fields ...string) int { s, ok := db.setKeys[k] if !ok { return 0 } removed := 0 for _, f := range fields { if _, ok := s[f]; ok { removed++ delete(s, f) } } if len(s) == 0 { db.del(k, true) } else { db.setKeys[k] = s } db.keyVersion[k]++ return removed }
go
func (db *RedisDB) setRem(k string, fields ...string) int { s, ok := db.setKeys[k] if !ok { return 0 } removed := 0 for _, f := range fields { if _, ok := s[f]; ok { removed++ delete(s, f) } } if len(s) == 0 { db.del(k, true) } else { db.setKeys[k] = s } db.keyVersion[k]++ return removed }
[ "func", "(", "db", "*", "RedisDB", ")", "setRem", "(", "k", "string", ",", "fields", "...", "string", ")", "int", "{", "s", ",", "ok", ":=", "db", ".", "setKeys", "[", "k", "]", "\n", "if", "!", "ok", "{", "return", "0", "\n", "}", "\n", "removed", ":=", "0", "\n", "for", "_", ",", "f", ":=", "range", "fields", "{", "if", "_", ",", "ok", ":=", "s", "[", "f", "]", ";", "ok", "{", "removed", "++", "\n", "delete", "(", "s", ",", "f", ")", "\n", "}", "\n", "}", "\n", "if", "len", "(", "s", ")", "==", "0", "{", "db", ".", "del", "(", "k", ",", "true", ")", "\n", "}", "else", "{", "db", ".", "setKeys", "[", "k", "]", "=", "s", "\n", "}", "\n", "db", ".", "keyVersion", "[", "k", "]", "++", "\n", "return", "removed", "\n", "}" ]
// setrem removes members from a set. Returns nr of deleted keys.
[ "setrem", "removes", "members", "from", "a", "set", ".", "Returns", "nr", "of", "deleted", "keys", "." ]
3d7aa1333af56ab862d446678d93aaa6803e0938
https://github.com/alicebob/miniredis/blob/3d7aa1333af56ab862d446678d93aaa6803e0938/db.go#L245-L264
train
alicebob/miniredis
db.go
setMembers
func (db *RedisDB) setMembers(k string) []string { set := db.setKeys[k] members := make([]string, 0, len(set)) for k := range set { members = append(members, k) } sort.Strings(members) return members }
go
func (db *RedisDB) setMembers(k string) []string { set := db.setKeys[k] members := make([]string, 0, len(set)) for k := range set { members = append(members, k) } sort.Strings(members) return members }
[ "func", "(", "db", "*", "RedisDB", ")", "setMembers", "(", "k", "string", ")", "[", "]", "string", "{", "set", ":=", "db", ".", "setKeys", "[", "k", "]", "\n", "members", ":=", "make", "(", "[", "]", "string", ",", "0", ",", "len", "(", "set", ")", ")", "\n", "for", "k", ":=", "range", "set", "{", "members", "=", "append", "(", "members", ",", "k", ")", "\n", "}", "\n", "sort", ".", "Strings", "(", "members", ")", "\n", "return", "members", "\n", "}" ]
// All members of a set.
[ "All", "members", "of", "a", "set", "." ]
3d7aa1333af56ab862d446678d93aaa6803e0938
https://github.com/alicebob/miniredis/blob/3d7aa1333af56ab862d446678d93aaa6803e0938/db.go#L267-L275
train
alicebob/miniredis
db.go
setIsMember
func (db *RedisDB) setIsMember(k, v string) bool { set, ok := db.setKeys[k] if !ok { return false } _, ok = set[v] return ok }
go
func (db *RedisDB) setIsMember(k, v string) bool { set, ok := db.setKeys[k] if !ok { return false } _, ok = set[v] return ok }
[ "func", "(", "db", "*", "RedisDB", ")", "setIsMember", "(", "k", ",", "v", "string", ")", "bool", "{", "set", ",", "ok", ":=", "db", ".", "setKeys", "[", "k", "]", "\n", "if", "!", "ok", "{", "return", "false", "\n", "}", "\n", "_", ",", "ok", "=", "set", "[", "v", "]", "\n", "return", "ok", "\n", "}" ]
// Is a SET value present?
[ "Is", "a", "SET", "value", "present?" ]
3d7aa1333af56ab862d446678d93aaa6803e0938
https://github.com/alicebob/miniredis/blob/3d7aa1333af56ab862d446678d93aaa6803e0938/db.go#L278-L285
train
alicebob/miniredis
db.go
hashGet
func (db *RedisDB) hashGet(key, field string) string { return db.hashKeys[key][field] }
go
func (db *RedisDB) hashGet(key, field string) string { return db.hashKeys[key][field] }
[ "func", "(", "db", "*", "RedisDB", ")", "hashGet", "(", "key", ",", "field", "string", ")", "string", "{", "return", "db", ".", "hashKeys", "[", "key", "]", "[", "field", "]", "\n", "}" ]
// hashGet a value
[ "hashGet", "a", "value" ]
3d7aa1333af56ab862d446678d93aaa6803e0938
https://github.com/alicebob/miniredis/blob/3d7aa1333af56ab862d446678d93aaa6803e0938/db.go#L299-L301
train
alicebob/miniredis
db.go
hashSet
func (db *RedisDB) hashSet(k, f, v string) bool { if t, ok := db.keys[k]; ok && t != "hash" { db.del(k, true) } db.keys[k] = "hash" if _, ok := db.hashKeys[k]; !ok { db.hashKeys[k] = map[string]string{} } _, ok := db.hashKeys[k][f] db.hashKeys[k][f] = v db.keyVersion[k]++ return ok }
go
func (db *RedisDB) hashSet(k, f, v string) bool { if t, ok := db.keys[k]; ok && t != "hash" { db.del(k, true) } db.keys[k] = "hash" if _, ok := db.hashKeys[k]; !ok { db.hashKeys[k] = map[string]string{} } _, ok := db.hashKeys[k][f] db.hashKeys[k][f] = v db.keyVersion[k]++ return ok }
[ "func", "(", "db", "*", "RedisDB", ")", "hashSet", "(", "k", ",", "f", ",", "v", "string", ")", "bool", "{", "if", "t", ",", "ok", ":=", "db", ".", "keys", "[", "k", "]", ";", "ok", "&&", "t", "!=", "\"", "\"", "{", "db", ".", "del", "(", "k", ",", "true", ")", "\n", "}", "\n", "db", ".", "keys", "[", "k", "]", "=", "\"", "\"", "\n", "if", "_", ",", "ok", ":=", "db", ".", "hashKeys", "[", "k", "]", ";", "!", "ok", "{", "db", ".", "hashKeys", "[", "k", "]", "=", "map", "[", "string", "]", "string", "{", "}", "\n", "}", "\n", "_", ",", "ok", ":=", "db", ".", "hashKeys", "[", "k", "]", "[", "f", "]", "\n", "db", ".", "hashKeys", "[", "k", "]", "[", "f", "]", "=", "v", "\n", "db", ".", "keyVersion", "[", "k", "]", "++", "\n", "return", "ok", "\n", "}" ]
// hashSet returns whether the key already existed
[ "hashSet", "returns", "whether", "the", "key", "already", "existed" ]
3d7aa1333af56ab862d446678d93aaa6803e0938
https://github.com/alicebob/miniredis/blob/3d7aa1333af56ab862d446678d93aaa6803e0938/db.go#L304-L316
train
alicebob/miniredis
db.go
hashIncr
func (db *RedisDB) hashIncr(key, field string, delta int) (int, error) { v := 0 if h, ok := db.hashKeys[key]; ok { if f, ok := h[field]; ok { var err error v, err = strconv.Atoi(f) if err != nil { return 0, ErrIntValueError } } } v += delta db.hashSet(key, field, strconv.Itoa(v)) return v, nil }
go
func (db *RedisDB) hashIncr(key, field string, delta int) (int, error) { v := 0 if h, ok := db.hashKeys[key]; ok { if f, ok := h[field]; ok { var err error v, err = strconv.Atoi(f) if err != nil { return 0, ErrIntValueError } } } v += delta db.hashSet(key, field, strconv.Itoa(v)) return v, nil }
[ "func", "(", "db", "*", "RedisDB", ")", "hashIncr", "(", "key", ",", "field", "string", ",", "delta", "int", ")", "(", "int", ",", "error", ")", "{", "v", ":=", "0", "\n", "if", "h", ",", "ok", ":=", "db", ".", "hashKeys", "[", "key", "]", ";", "ok", "{", "if", "f", ",", "ok", ":=", "h", "[", "field", "]", ";", "ok", "{", "var", "err", "error", "\n", "v", ",", "err", "=", "strconv", ".", "Atoi", "(", "f", ")", "\n", "if", "err", "!=", "nil", "{", "return", "0", ",", "ErrIntValueError", "\n", "}", "\n", "}", "\n", "}", "\n", "v", "+=", "delta", "\n", "db", ".", "hashSet", "(", "key", ",", "field", ",", "strconv", ".", "Itoa", "(", "v", ")", ")", "\n", "return", "v", ",", "nil", "\n", "}" ]
// hashIncr changes int key value
[ "hashIncr", "changes", "int", "key", "value" ]
3d7aa1333af56ab862d446678d93aaa6803e0938
https://github.com/alicebob/miniredis/blob/3d7aa1333af56ab862d446678d93aaa6803e0938/db.go#L319-L333
train
alicebob/miniredis
db.go
hashIncrfloat
func (db *RedisDB) hashIncrfloat(key, field string, delta float64) (float64, error) { v := 0.0 if h, ok := db.hashKeys[key]; ok { if f, ok := h[field]; ok { var err error v, err = strconv.ParseFloat(f, 64) if err != nil { return 0, ErrFloatValueError } } } v += delta db.hashSet(key, field, formatFloat(v)) return v, nil }
go
func (db *RedisDB) hashIncrfloat(key, field string, delta float64) (float64, error) { v := 0.0 if h, ok := db.hashKeys[key]; ok { if f, ok := h[field]; ok { var err error v, err = strconv.ParseFloat(f, 64) if err != nil { return 0, ErrFloatValueError } } } v += delta db.hashSet(key, field, formatFloat(v)) return v, nil }
[ "func", "(", "db", "*", "RedisDB", ")", "hashIncrfloat", "(", "key", ",", "field", "string", ",", "delta", "float64", ")", "(", "float64", ",", "error", ")", "{", "v", ":=", "0.0", "\n", "if", "h", ",", "ok", ":=", "db", ".", "hashKeys", "[", "key", "]", ";", "ok", "{", "if", "f", ",", "ok", ":=", "h", "[", "field", "]", ";", "ok", "{", "var", "err", "error", "\n", "v", ",", "err", "=", "strconv", ".", "ParseFloat", "(", "f", ",", "64", ")", "\n", "if", "err", "!=", "nil", "{", "return", "0", ",", "ErrFloatValueError", "\n", "}", "\n", "}", "\n", "}", "\n", "v", "+=", "delta", "\n", "db", ".", "hashSet", "(", "key", ",", "field", ",", "formatFloat", "(", "v", ")", ")", "\n", "return", "v", ",", "nil", "\n", "}" ]
// hashIncrfloat changes float key value
[ "hashIncrfloat", "changes", "float", "key", "value" ]
3d7aa1333af56ab862d446678d93aaa6803e0938
https://github.com/alicebob/miniredis/blob/3d7aa1333af56ab862d446678d93aaa6803e0938/db.go#L336-L350
train
alicebob/miniredis
db.go
sortedSet
func (db *RedisDB) sortedSet(key string) map[string]float64 { ss := db.sortedsetKeys[key] return map[string]float64(ss) }
go
func (db *RedisDB) sortedSet(key string) map[string]float64 { ss := db.sortedsetKeys[key] return map[string]float64(ss) }
[ "func", "(", "db", "*", "RedisDB", ")", "sortedSet", "(", "key", "string", ")", "map", "[", "string", "]", "float64", "{", "ss", ":=", "db", ".", "sortedsetKeys", "[", "key", "]", "\n", "return", "map", "[", "string", "]", "float64", "(", "ss", ")", "\n", "}" ]
// sortedSet set returns a sortedSet as map
[ "sortedSet", "set", "returns", "a", "sortedSet", "as", "map" ]
3d7aa1333af56ab862d446678d93aaa6803e0938
https://github.com/alicebob/miniredis/blob/3d7aa1333af56ab862d446678d93aaa6803e0938/db.go#L353-L356
train
alicebob/miniredis
db.go
ssetSet
func (db *RedisDB) ssetSet(key string, sset sortedSet) { db.keys[key] = "zset" db.keyVersion[key]++ db.sortedsetKeys[key] = sset }
go
func (db *RedisDB) ssetSet(key string, sset sortedSet) { db.keys[key] = "zset" db.keyVersion[key]++ db.sortedsetKeys[key] = sset }
[ "func", "(", "db", "*", "RedisDB", ")", "ssetSet", "(", "key", "string", ",", "sset", "sortedSet", ")", "{", "db", ".", "keys", "[", "key", "]", "=", "\"", "\"", "\n", "db", ".", "keyVersion", "[", "key", "]", "++", "\n", "db", ".", "sortedsetKeys", "[", "key", "]", "=", "sset", "\n", "}" ]
// ssetSet sets a complete sorted set.
[ "ssetSet", "sets", "a", "complete", "sorted", "set", "." ]
3d7aa1333af56ab862d446678d93aaa6803e0938
https://github.com/alicebob/miniredis/blob/3d7aa1333af56ab862d446678d93aaa6803e0938/db.go#L359-L363
train
alicebob/miniredis
db.go
ssetAdd
func (db *RedisDB) ssetAdd(key string, score float64, member string) bool { ss, ok := db.sortedsetKeys[key] if !ok { ss = newSortedSet() db.keys[key] = "zset" } _, ok = ss[member] ss[member] = score db.sortedsetKeys[key] = ss db.keyVersion[key]++ return !ok }
go
func (db *RedisDB) ssetAdd(key string, score float64, member string) bool { ss, ok := db.sortedsetKeys[key] if !ok { ss = newSortedSet() db.keys[key] = "zset" } _, ok = ss[member] ss[member] = score db.sortedsetKeys[key] = ss db.keyVersion[key]++ return !ok }
[ "func", "(", "db", "*", "RedisDB", ")", "ssetAdd", "(", "key", "string", ",", "score", "float64", ",", "member", "string", ")", "bool", "{", "ss", ",", "ok", ":=", "db", ".", "sortedsetKeys", "[", "key", "]", "\n", "if", "!", "ok", "{", "ss", "=", "newSortedSet", "(", ")", "\n", "db", ".", "keys", "[", "key", "]", "=", "\"", "\"", "\n", "}", "\n", "_", ",", "ok", "=", "ss", "[", "member", "]", "\n", "ss", "[", "member", "]", "=", "score", "\n", "db", ".", "sortedsetKeys", "[", "key", "]", "=", "ss", "\n", "db", ".", "keyVersion", "[", "key", "]", "++", "\n", "return", "!", "ok", "\n", "}" ]
// ssetAdd adds member to a sorted set. Returns whether this was a new member.
[ "ssetAdd", "adds", "member", "to", "a", "sorted", "set", ".", "Returns", "whether", "this", "was", "a", "new", "member", "." ]
3d7aa1333af56ab862d446678d93aaa6803e0938
https://github.com/alicebob/miniredis/blob/3d7aa1333af56ab862d446678d93aaa6803e0938/db.go#L366-L377
train
alicebob/miniredis
db.go
ssetMembers
func (db *RedisDB) ssetMembers(key string) []string { ss, ok := db.sortedsetKeys[key] if !ok { return nil } elems := ss.byScore(asc) members := make([]string, 0, len(elems)) for _, e := range elems { members = append(members, e.member) } return members }
go
func (db *RedisDB) ssetMembers(key string) []string { ss, ok := db.sortedsetKeys[key] if !ok { return nil } elems := ss.byScore(asc) members := make([]string, 0, len(elems)) for _, e := range elems { members = append(members, e.member) } return members }
[ "func", "(", "db", "*", "RedisDB", ")", "ssetMembers", "(", "key", "string", ")", "[", "]", "string", "{", "ss", ",", "ok", ":=", "db", ".", "sortedsetKeys", "[", "key", "]", "\n", "if", "!", "ok", "{", "return", "nil", "\n", "}", "\n", "elems", ":=", "ss", ".", "byScore", "(", "asc", ")", "\n", "members", ":=", "make", "(", "[", "]", "string", ",", "0", ",", "len", "(", "elems", ")", ")", "\n", "for", "_", ",", "e", ":=", "range", "elems", "{", "members", "=", "append", "(", "members", ",", "e", ".", "member", ")", "\n", "}", "\n", "return", "members", "\n", "}" ]
// All members from a sorted set, ordered by score.
[ "All", "members", "from", "a", "sorted", "set", "ordered", "by", "score", "." ]
3d7aa1333af56ab862d446678d93aaa6803e0938
https://github.com/alicebob/miniredis/blob/3d7aa1333af56ab862d446678d93aaa6803e0938/db.go#L380-L391
train
alicebob/miniredis
db.go
ssetElements
func (db *RedisDB) ssetElements(key string) ssElems { ss, ok := db.sortedsetKeys[key] if !ok { return nil } return ss.byScore(asc) }
go
func (db *RedisDB) ssetElements(key string) ssElems { ss, ok := db.sortedsetKeys[key] if !ok { return nil } return ss.byScore(asc) }
[ "func", "(", "db", "*", "RedisDB", ")", "ssetElements", "(", "key", "string", ")", "ssElems", "{", "ss", ",", "ok", ":=", "db", ".", "sortedsetKeys", "[", "key", "]", "\n", "if", "!", "ok", "{", "return", "nil", "\n", "}", "\n", "return", "ss", ".", "byScore", "(", "asc", ")", "\n", "}" ]
// All members+scores from a sorted set, ordered by score.
[ "All", "members", "+", "scores", "from", "a", "sorted", "set", "ordered", "by", "score", "." ]
3d7aa1333af56ab862d446678d93aaa6803e0938
https://github.com/alicebob/miniredis/blob/3d7aa1333af56ab862d446678d93aaa6803e0938/db.go#L394-L400
train
alicebob/miniredis
db.go
ssetCard
func (db *RedisDB) ssetCard(key string) int { ss := db.sortedsetKeys[key] return ss.card() }
go
func (db *RedisDB) ssetCard(key string) int { ss := db.sortedsetKeys[key] return ss.card() }
[ "func", "(", "db", "*", "RedisDB", ")", "ssetCard", "(", "key", "string", ")", "int", "{", "ss", ":=", "db", ".", "sortedsetKeys", "[", "key", "]", "\n", "return", "ss", ".", "card", "(", ")", "\n", "}" ]
// ssetCard is the sorted set cardinality.
[ "ssetCard", "is", "the", "sorted", "set", "cardinality", "." ]
3d7aa1333af56ab862d446678d93aaa6803e0938
https://github.com/alicebob/miniredis/blob/3d7aa1333af56ab862d446678d93aaa6803e0938/db.go#L403-L406
train
alicebob/miniredis
db.go
ssetRank
func (db *RedisDB) ssetRank(key, member string, d direction) (int, bool) { ss := db.sortedsetKeys[key] return ss.rankByScore(member, d) }
go
func (db *RedisDB) ssetRank(key, member string, d direction) (int, bool) { ss := db.sortedsetKeys[key] return ss.rankByScore(member, d) }
[ "func", "(", "db", "*", "RedisDB", ")", "ssetRank", "(", "key", ",", "member", "string", ",", "d", "direction", ")", "(", "int", ",", "bool", ")", "{", "ss", ":=", "db", ".", "sortedsetKeys", "[", "key", "]", "\n", "return", "ss", ".", "rankByScore", "(", "member", ",", "d", ")", "\n", "}" ]
// ssetRank is the sorted set rank.
[ "ssetRank", "is", "the", "sorted", "set", "rank", "." ]
3d7aa1333af56ab862d446678d93aaa6803e0938
https://github.com/alicebob/miniredis/blob/3d7aa1333af56ab862d446678d93aaa6803e0938/db.go#L409-L412
train
alicebob/miniredis
db.go
ssetScore
func (db *RedisDB) ssetScore(key, member string) float64 { ss := db.sortedsetKeys[key] return ss[member] }
go
func (db *RedisDB) ssetScore(key, member string) float64 { ss := db.sortedsetKeys[key] return ss[member] }
[ "func", "(", "db", "*", "RedisDB", ")", "ssetScore", "(", "key", ",", "member", "string", ")", "float64", "{", "ss", ":=", "db", ".", "sortedsetKeys", "[", "key", "]", "\n", "return", "ss", "[", "member", "]", "\n", "}" ]
// ssetScore is sorted set score.
[ "ssetScore", "is", "sorted", "set", "score", "." ]
3d7aa1333af56ab862d446678d93aaa6803e0938
https://github.com/alicebob/miniredis/blob/3d7aa1333af56ab862d446678d93aaa6803e0938/db.go#L415-L418
train
alicebob/miniredis
db.go
ssetRem
func (db *RedisDB) ssetRem(key, member string) bool { ss := db.sortedsetKeys[key] _, ok := ss[member] delete(ss, member) if len(ss) == 0 { // Delete key on removal of last member db.del(key, true) } return ok }
go
func (db *RedisDB) ssetRem(key, member string) bool { ss := db.sortedsetKeys[key] _, ok := ss[member] delete(ss, member) if len(ss) == 0 { // Delete key on removal of last member db.del(key, true) } return ok }
[ "func", "(", "db", "*", "RedisDB", ")", "ssetRem", "(", "key", ",", "member", "string", ")", "bool", "{", "ss", ":=", "db", ".", "sortedsetKeys", "[", "key", "]", "\n", "_", ",", "ok", ":=", "ss", "[", "member", "]", "\n", "delete", "(", "ss", ",", "member", ")", "\n", "if", "len", "(", "ss", ")", "==", "0", "{", "// Delete key on removal of last member", "db", ".", "del", "(", "key", ",", "true", ")", "\n", "}", "\n", "return", "ok", "\n", "}" ]
// ssetRem is sorted set key delete.
[ "ssetRem", "is", "sorted", "set", "key", "delete", "." ]
3d7aa1333af56ab862d446678d93aaa6803e0938
https://github.com/alicebob/miniredis/blob/3d7aa1333af56ab862d446678d93aaa6803e0938/db.go#L421-L430
train
alicebob/miniredis
db.go
ssetExists
func (db *RedisDB) ssetExists(key, member string) bool { ss := db.sortedsetKeys[key] _, ok := ss[member] return ok }
go
func (db *RedisDB) ssetExists(key, member string) bool { ss := db.sortedsetKeys[key] _, ok := ss[member] return ok }
[ "func", "(", "db", "*", "RedisDB", ")", "ssetExists", "(", "key", ",", "member", "string", ")", "bool", "{", "ss", ":=", "db", ".", "sortedsetKeys", "[", "key", "]", "\n", "_", ",", "ok", ":=", "ss", "[", "member", "]", "\n", "return", "ok", "\n", "}" ]
// ssetExists tells if a member exists in a sorted set.
[ "ssetExists", "tells", "if", "a", "member", "exists", "in", "a", "sorted", "set", "." ]
3d7aa1333af56ab862d446678d93aaa6803e0938
https://github.com/alicebob/miniredis/blob/3d7aa1333af56ab862d446678d93aaa6803e0938/db.go#L433-L437
train
alicebob/miniredis
db.go
ssetIncrby
func (db *RedisDB) ssetIncrby(k, m string, delta float64) float64 { ss, ok := db.sortedsetKeys[k] if !ok { ss = newSortedSet() db.keys[k] = "zset" db.sortedsetKeys[k] = ss } v, _ := ss.get(m) v += delta ss.set(v, m) db.keyVersion[k]++ return v }
go
func (db *RedisDB) ssetIncrby(k, m string, delta float64) float64 { ss, ok := db.sortedsetKeys[k] if !ok { ss = newSortedSet() db.keys[k] = "zset" db.sortedsetKeys[k] = ss } v, _ := ss.get(m) v += delta ss.set(v, m) db.keyVersion[k]++ return v }
[ "func", "(", "db", "*", "RedisDB", ")", "ssetIncrby", "(", "k", ",", "m", "string", ",", "delta", "float64", ")", "float64", "{", "ss", ",", "ok", ":=", "db", ".", "sortedsetKeys", "[", "k", "]", "\n", "if", "!", "ok", "{", "ss", "=", "newSortedSet", "(", ")", "\n", "db", ".", "keys", "[", "k", "]", "=", "\"", "\"", "\n", "db", ".", "sortedsetKeys", "[", "k", "]", "=", "ss", "\n", "}", "\n\n", "v", ",", "_", ":=", "ss", ".", "get", "(", "m", ")", "\n", "v", "+=", "delta", "\n", "ss", ".", "set", "(", "v", ",", "m", ")", "\n", "db", ".", "keyVersion", "[", "k", "]", "++", "\n", "return", "v", "\n", "}" ]
// ssetIncrby changes float sorted set score.
[ "ssetIncrby", "changes", "float", "sorted", "set", "score", "." ]
3d7aa1333af56ab862d446678d93aaa6803e0938
https://github.com/alicebob/miniredis/blob/3d7aa1333af56ab862d446678d93aaa6803e0938/db.go#L440-L453
train
alicebob/miniredis
db.go
fastForward
func (db *RedisDB) fastForward(duration time.Duration) { for _, key := range db.allKeys() { if value, ok := db.ttl[key]; ok { db.ttl[key] = value - duration db.checkTTL(key) } } }
go
func (db *RedisDB) fastForward(duration time.Duration) { for _, key := range db.allKeys() { if value, ok := db.ttl[key]; ok { db.ttl[key] = value - duration db.checkTTL(key) } } }
[ "func", "(", "db", "*", "RedisDB", ")", "fastForward", "(", "duration", "time", ".", "Duration", ")", "{", "for", "_", ",", "key", ":=", "range", "db", ".", "allKeys", "(", ")", "{", "if", "value", ",", "ok", ":=", "db", ".", "ttl", "[", "key", "]", ";", "ok", "{", "db", ".", "ttl", "[", "key", "]", "=", "value", "-", "duration", "\n", "db", ".", "checkTTL", "(", "key", ")", "\n", "}", "\n", "}", "\n", "}" ]
// fastForward proceeds the current timestamp with duration, works as a time machine
[ "fastForward", "proceeds", "the", "current", "timestamp", "with", "duration", "works", "as", "a", "time", "machine" ]
3d7aa1333af56ab862d446678d93aaa6803e0938
https://github.com/alicebob/miniredis/blob/3d7aa1333af56ab862d446678d93aaa6803e0938/db.go#L538-L545
train
alicebob/miniredis
cmd_sorted_set.go
commandsSortedSet
func commandsSortedSet(m *Miniredis) { m.srv.Register("ZADD", m.cmdZadd) m.srv.Register("ZCARD", m.cmdZcard) m.srv.Register("ZCOUNT", m.cmdZcount) m.srv.Register("ZINCRBY", m.cmdZincrby) m.srv.Register("ZINTERSTORE", m.cmdZinterstore) m.srv.Register("ZLEXCOUNT", m.cmdZlexcount) m.srv.Register("ZRANGE", m.makeCmdZrange(false)) m.srv.Register("ZRANGEBYLEX", m.makeCmdZrangebylex(false)) m.srv.Register("ZRANGEBYSCORE", m.makeCmdZrangebyscore(false)) m.srv.Register("ZRANK", m.makeCmdZrank(false)) m.srv.Register("ZREM", m.cmdZrem) m.srv.Register("ZREMRANGEBYLEX", m.cmdZremrangebylex) m.srv.Register("ZREMRANGEBYRANK", m.cmdZremrangebyrank) m.srv.Register("ZREMRANGEBYSCORE", m.cmdZremrangebyscore) m.srv.Register("ZREVRANGE", m.makeCmdZrange(true)) m.srv.Register("ZREVRANGEBYLEX", m.makeCmdZrangebylex(true)) m.srv.Register("ZREVRANGEBYSCORE", m.makeCmdZrangebyscore(true)) m.srv.Register("ZREVRANK", m.makeCmdZrank(true)) m.srv.Register("ZSCORE", m.cmdZscore) m.srv.Register("ZUNIONSTORE", m.cmdZunionstore) m.srv.Register("ZSCAN", m.cmdZscan) m.srv.Register("ZPOPMAX", m.cmdZpopmax(true)) m.srv.Register("ZPOPMIN", m.cmdZpopmax(false)) }
go
func commandsSortedSet(m *Miniredis) { m.srv.Register("ZADD", m.cmdZadd) m.srv.Register("ZCARD", m.cmdZcard) m.srv.Register("ZCOUNT", m.cmdZcount) m.srv.Register("ZINCRBY", m.cmdZincrby) m.srv.Register("ZINTERSTORE", m.cmdZinterstore) m.srv.Register("ZLEXCOUNT", m.cmdZlexcount) m.srv.Register("ZRANGE", m.makeCmdZrange(false)) m.srv.Register("ZRANGEBYLEX", m.makeCmdZrangebylex(false)) m.srv.Register("ZRANGEBYSCORE", m.makeCmdZrangebyscore(false)) m.srv.Register("ZRANK", m.makeCmdZrank(false)) m.srv.Register("ZREM", m.cmdZrem) m.srv.Register("ZREMRANGEBYLEX", m.cmdZremrangebylex) m.srv.Register("ZREMRANGEBYRANK", m.cmdZremrangebyrank) m.srv.Register("ZREMRANGEBYSCORE", m.cmdZremrangebyscore) m.srv.Register("ZREVRANGE", m.makeCmdZrange(true)) m.srv.Register("ZREVRANGEBYLEX", m.makeCmdZrangebylex(true)) m.srv.Register("ZREVRANGEBYSCORE", m.makeCmdZrangebyscore(true)) m.srv.Register("ZREVRANK", m.makeCmdZrank(true)) m.srv.Register("ZSCORE", m.cmdZscore) m.srv.Register("ZUNIONSTORE", m.cmdZunionstore) m.srv.Register("ZSCAN", m.cmdZscan) m.srv.Register("ZPOPMAX", m.cmdZpopmax(true)) m.srv.Register("ZPOPMIN", m.cmdZpopmax(false)) }
[ "func", "commandsSortedSet", "(", "m", "*", "Miniredis", ")", "{", "m", ".", "srv", ".", "Register", "(", "\"", "\"", ",", "m", ".", "cmdZadd", ")", "\n", "m", ".", "srv", ".", "Register", "(", "\"", "\"", ",", "m", ".", "cmdZcard", ")", "\n", "m", ".", "srv", ".", "Register", "(", "\"", "\"", ",", "m", ".", "cmdZcount", ")", "\n", "m", ".", "srv", ".", "Register", "(", "\"", "\"", ",", "m", ".", "cmdZincrby", ")", "\n", "m", ".", "srv", ".", "Register", "(", "\"", "\"", ",", "m", ".", "cmdZinterstore", ")", "\n", "m", ".", "srv", ".", "Register", "(", "\"", "\"", ",", "m", ".", "cmdZlexcount", ")", "\n", "m", ".", "srv", ".", "Register", "(", "\"", "\"", ",", "m", ".", "makeCmdZrange", "(", "false", ")", ")", "\n", "m", ".", "srv", ".", "Register", "(", "\"", "\"", ",", "m", ".", "makeCmdZrangebylex", "(", "false", ")", ")", "\n", "m", ".", "srv", ".", "Register", "(", "\"", "\"", ",", "m", ".", "makeCmdZrangebyscore", "(", "false", ")", ")", "\n", "m", ".", "srv", ".", "Register", "(", "\"", "\"", ",", "m", ".", "makeCmdZrank", "(", "false", ")", ")", "\n", "m", ".", "srv", ".", "Register", "(", "\"", "\"", ",", "m", ".", "cmdZrem", ")", "\n", "m", ".", "srv", ".", "Register", "(", "\"", "\"", ",", "m", ".", "cmdZremrangebylex", ")", "\n", "m", ".", "srv", ".", "Register", "(", "\"", "\"", ",", "m", ".", "cmdZremrangebyrank", ")", "\n", "m", ".", "srv", ".", "Register", "(", "\"", "\"", ",", "m", ".", "cmdZremrangebyscore", ")", "\n", "m", ".", "srv", ".", "Register", "(", "\"", "\"", ",", "m", ".", "makeCmdZrange", "(", "true", ")", ")", "\n", "m", ".", "srv", ".", "Register", "(", "\"", "\"", ",", "m", ".", "makeCmdZrangebylex", "(", "true", ")", ")", "\n", "m", ".", "srv", ".", "Register", "(", "\"", "\"", ",", "m", ".", "makeCmdZrangebyscore", "(", "true", ")", ")", "\n", "m", ".", "srv", ".", "Register", "(", "\"", "\"", ",", "m", ".", "makeCmdZrank", "(", "true", ")", ")", "\n", "m", ".", "srv", ".", "Register", "(", "\"", "\"", ",", "m", ".", "cmdZscore", ")", "\n", "m", ".", "srv", ".", "Register", "(", "\"", "\"", ",", "m", ".", "cmdZunionstore", ")", "\n", "m", ".", "srv", ".", "Register", "(", "\"", "\"", ",", "m", ".", "cmdZscan", ")", "\n", "m", ".", "srv", ".", "Register", "(", "\"", "\"", ",", "m", ".", "cmdZpopmax", "(", "true", ")", ")", "\n", "m", ".", "srv", ".", "Register", "(", "\"", "\"", ",", "m", ".", "cmdZpopmax", "(", "false", ")", ")", "\n", "}" ]
// commandsSortedSet handles all sorted set operations.
[ "commandsSortedSet", "handles", "all", "sorted", "set", "operations", "." ]
3d7aa1333af56ab862d446678d93aaa6803e0938
https://github.com/alicebob/miniredis/blob/3d7aa1333af56ab862d446678d93aaa6803e0938/cmd_sorted_set.go#L19-L43
train
alicebob/miniredis
cmd_sorted_set.go
makeCmdZrank
func (m *Miniredis) makeCmdZrank(reverse bool) server.Cmd { return func(c *server.Peer, cmd string, args []string) { if len(args) != 2 { setDirty(c) c.WriteError(errWrongNumber(cmd)) return } if !m.handleAuth(c) { return } if m.checkPubsub(c) { return } key, member := args[0], args[1] withTx(m, c, func(c *server.Peer, ctx *connCtx) { db := m.db(ctx.selectedDB) if !db.exists(key) { c.WriteNull() return } if db.t(key) != "zset" { c.WriteError(ErrWrongType.Error()) return } direction := asc if reverse { direction = desc } rank, ok := db.ssetRank(key, member, direction) if !ok { c.WriteNull() return } c.WriteInt(rank) }) } }
go
func (m *Miniredis) makeCmdZrank(reverse bool) server.Cmd { return func(c *server.Peer, cmd string, args []string) { if len(args) != 2 { setDirty(c) c.WriteError(errWrongNumber(cmd)) return } if !m.handleAuth(c) { return } if m.checkPubsub(c) { return } key, member := args[0], args[1] withTx(m, c, func(c *server.Peer, ctx *connCtx) { db := m.db(ctx.selectedDB) if !db.exists(key) { c.WriteNull() return } if db.t(key) != "zset" { c.WriteError(ErrWrongType.Error()) return } direction := asc if reverse { direction = desc } rank, ok := db.ssetRank(key, member, direction) if !ok { c.WriteNull() return } c.WriteInt(rank) }) } }
[ "func", "(", "m", "*", "Miniredis", ")", "makeCmdZrank", "(", "reverse", "bool", ")", "server", ".", "Cmd", "{", "return", "func", "(", "c", "*", "server", ".", "Peer", ",", "cmd", "string", ",", "args", "[", "]", "string", ")", "{", "if", "len", "(", "args", ")", "!=", "2", "{", "setDirty", "(", "c", ")", "\n", "c", ".", "WriteError", "(", "errWrongNumber", "(", "cmd", ")", ")", "\n", "return", "\n", "}", "\n", "if", "!", "m", ".", "handleAuth", "(", "c", ")", "{", "return", "\n", "}", "\n", "if", "m", ".", "checkPubsub", "(", "c", ")", "{", "return", "\n", "}", "\n\n", "key", ",", "member", ":=", "args", "[", "0", "]", ",", "args", "[", "1", "]", "\n\n", "withTx", "(", "m", ",", "c", ",", "func", "(", "c", "*", "server", ".", "Peer", ",", "ctx", "*", "connCtx", ")", "{", "db", ":=", "m", ".", "db", "(", "ctx", ".", "selectedDB", ")", "\n\n", "if", "!", "db", ".", "exists", "(", "key", ")", "{", "c", ".", "WriteNull", "(", ")", "\n", "return", "\n", "}", "\n\n", "if", "db", ".", "t", "(", "key", ")", "!=", "\"", "\"", "{", "c", ".", "WriteError", "(", "ErrWrongType", ".", "Error", "(", ")", ")", "\n", "return", "\n", "}", "\n\n", "direction", ":=", "asc", "\n", "if", "reverse", "{", "direction", "=", "desc", "\n", "}", "\n", "rank", ",", "ok", ":=", "db", ".", "ssetRank", "(", "key", ",", "member", ",", "direction", ")", "\n", "if", "!", "ok", "{", "c", ".", "WriteNull", "(", ")", "\n", "return", "\n", "}", "\n", "c", ".", "WriteInt", "(", "rank", ")", "\n", "}", ")", "\n", "}", "\n", "}" ]
// ZRANK and ZREVRANK
[ "ZRANK", "and", "ZREVRANK" ]
3d7aa1333af56ab862d446678d93aaa6803e0938
https://github.com/alicebob/miniredis/blob/3d7aa1333af56ab862d446678d93aaa6803e0938/cmd_sorted_set.go#L778-L819
train
alicebob/miniredis
cmd_sorted_set.go
parseFloatRange
func parseFloatRange(s string) (float64, bool, error) { if len(s) == 0 { return 0, false, nil } inclusive := true if s[0] == '(' { s = s[1:] inclusive = false } f, err := strconv.ParseFloat(s, 64) return f, inclusive, err }
go
func parseFloatRange(s string) (float64, bool, error) { if len(s) == 0 { return 0, false, nil } inclusive := true if s[0] == '(' { s = s[1:] inclusive = false } f, err := strconv.ParseFloat(s, 64) return f, inclusive, err }
[ "func", "parseFloatRange", "(", "s", "string", ")", "(", "float64", ",", "bool", ",", "error", ")", "{", "if", "len", "(", "s", ")", "==", "0", "{", "return", "0", ",", "false", ",", "nil", "\n", "}", "\n", "inclusive", ":=", "true", "\n", "if", "s", "[", "0", "]", "==", "'('", "{", "s", "=", "s", "[", "1", ":", "]", "\n", "inclusive", "=", "false", "\n", "}", "\n", "f", ",", "err", ":=", "strconv", ".", "ParseFloat", "(", "s", ",", "64", ")", "\n", "return", "f", ",", "inclusive", ",", "err", "\n", "}" ]
// parseFloatRange handles ZRANGEBYSCORE floats. They are inclusive unless the // string starts with '('
[ "parseFloatRange", "handles", "ZRANGEBYSCORE", "floats", ".", "They", "are", "inclusive", "unless", "the", "string", "starts", "with", "(" ]
3d7aa1333af56ab862d446678d93aaa6803e0938
https://github.com/alicebob/miniredis/blob/3d7aa1333af56ab862d446678d93aaa6803e0938/cmd_sorted_set.go#L1054-L1065
train
alicebob/miniredis
cmd_sorted_set.go
parseLexrange
func parseLexrange(s string) (string, bool, error) { if len(s) == 0 { return "", false, errInvalidRangeItem } if s == "+" || s == "-" { return s, false, nil } switch s[0] { case '(': return s[1:], false, nil case '[': return s[1:], true, nil default: return "", false, errInvalidRangeItem } }
go
func parseLexrange(s string) (string, bool, error) { if len(s) == 0 { return "", false, errInvalidRangeItem } if s == "+" || s == "-" { return s, false, nil } switch s[0] { case '(': return s[1:], false, nil case '[': return s[1:], true, nil default: return "", false, errInvalidRangeItem } }
[ "func", "parseLexrange", "(", "s", "string", ")", "(", "string", ",", "bool", ",", "error", ")", "{", "if", "len", "(", "s", ")", "==", "0", "{", "return", "\"", "\"", ",", "false", ",", "errInvalidRangeItem", "\n", "}", "\n", "if", "s", "==", "\"", "\"", "||", "s", "==", "\"", "\"", "{", "return", "s", ",", "false", ",", "nil", "\n", "}", "\n", "switch", "s", "[", "0", "]", "{", "case", "'('", ":", "return", "s", "[", "1", ":", "]", ",", "false", ",", "nil", "\n", "case", "'['", ":", "return", "s", "[", "1", ":", "]", ",", "true", ",", "nil", "\n", "default", ":", "return", "\"", "\"", ",", "false", ",", "errInvalidRangeItem", "\n", "}", "\n", "}" ]
// parseLexrange handles ZRANGEBYLEX ranges. They start with '[', '(', or are // '+' or '-'. // Returns range, inclusive, error. // On '+' or '-' that's just returned.
[ "parseLexrange", "handles", "ZRANGEBYLEX", "ranges", ".", "They", "start", "with", "[", "(", "or", "are", "+", "or", "-", ".", "Returns", "range", "inclusive", "error", ".", "On", "+", "or", "-", "that", "s", "just", "returned", "." ]
3d7aa1333af56ab862d446678d93aaa6803e0938
https://github.com/alicebob/miniredis/blob/3d7aa1333af56ab862d446678d93aaa6803e0938/cmd_sorted_set.go#L1071-L1086
train
alicebob/miniredis
cmd_sorted_set.go
withSSRange
func withSSRange(members ssElems, min float64, minIncl bool, max float64, maxIncl bool) ssElems { gt := func(a, b float64) bool { return a > b } gteq := func(a, b float64) bool { return a >= b } mincmp := gt if minIncl { mincmp = gteq } for i, m := range members { if mincmp(m.score, min) { members = members[i:] goto checkmax } } // all elements were smaller return nil checkmax: maxcmp := gteq if maxIncl { maxcmp = gt } for i, m := range members { if maxcmp(m.score, max) { members = members[:i] break } } return members }
go
func withSSRange(members ssElems, min float64, minIncl bool, max float64, maxIncl bool) ssElems { gt := func(a, b float64) bool { return a > b } gteq := func(a, b float64) bool { return a >= b } mincmp := gt if minIncl { mincmp = gteq } for i, m := range members { if mincmp(m.score, min) { members = members[i:] goto checkmax } } // all elements were smaller return nil checkmax: maxcmp := gteq if maxIncl { maxcmp = gt } for i, m := range members { if maxcmp(m.score, max) { members = members[:i] break } } return members }
[ "func", "withSSRange", "(", "members", "ssElems", ",", "min", "float64", ",", "minIncl", "bool", ",", "max", "float64", ",", "maxIncl", "bool", ")", "ssElems", "{", "gt", ":=", "func", "(", "a", ",", "b", "float64", ")", "bool", "{", "return", "a", ">", "b", "}", "\n", "gteq", ":=", "func", "(", "a", ",", "b", "float64", ")", "bool", "{", "return", "a", ">=", "b", "}", "\n\n", "mincmp", ":=", "gt", "\n", "if", "minIncl", "{", "mincmp", "=", "gteq", "\n", "}", "\n", "for", "i", ",", "m", ":=", "range", "members", "{", "if", "mincmp", "(", "m", ".", "score", ",", "min", ")", "{", "members", "=", "members", "[", "i", ":", "]", "\n", "goto", "checkmax", "\n", "}", "\n", "}", "\n", "// all elements were smaller", "return", "nil", "\n\n", "checkmax", ":", "maxcmp", ":=", "gteq", "\n", "if", "maxIncl", "{", "maxcmp", "=", "gt", "\n", "}", "\n", "for", "i", ",", "m", ":=", "range", "members", "{", "if", "maxcmp", "(", "m", ".", "score", ",", "max", ")", "{", "members", "=", "members", "[", ":", "i", "]", "\n", "break", "\n", "}", "\n", "}", "\n\n", "return", "members", "\n", "}" ]
// withSSRange limits a list of sorted set elements by the ZRANGEBYSCORE range // logic.
[ "withSSRange", "limits", "a", "list", "of", "sorted", "set", "elements", "by", "the", "ZRANGEBYSCORE", "range", "logic", "." ]
3d7aa1333af56ab862d446678d93aaa6803e0938
https://github.com/alicebob/miniredis/blob/3d7aa1333af56ab862d446678d93aaa6803e0938/cmd_sorted_set.go#L1090-L1120
train
alicebob/miniredis
cmd_sorted_set.go
withLexRange
func withLexRange(members []string, min string, minIncl bool, max string, maxIncl bool) []string { if max == "-" || min == "+" { return nil } if min != "-" { if minIncl { for i, m := range members { if m >= min { members = members[i:] break } } } else { // Excluding min for i, m := range members { if m > min { members = members[i:] break } } } } if max != "+" { if maxIncl { for i, m := range members { if m > max { members = members[:i] break } } } else { // Excluding max for i, m := range members { if m >= max { members = members[:i] break } } } } return members }
go
func withLexRange(members []string, min string, minIncl bool, max string, maxIncl bool) []string { if max == "-" || min == "+" { return nil } if min != "-" { if minIncl { for i, m := range members { if m >= min { members = members[i:] break } } } else { // Excluding min for i, m := range members { if m > min { members = members[i:] break } } } } if max != "+" { if maxIncl { for i, m := range members { if m > max { members = members[:i] break } } } else { // Excluding max for i, m := range members { if m >= max { members = members[:i] break } } } } return members }
[ "func", "withLexRange", "(", "members", "[", "]", "string", ",", "min", "string", ",", "minIncl", "bool", ",", "max", "string", ",", "maxIncl", "bool", ")", "[", "]", "string", "{", "if", "max", "==", "\"", "\"", "||", "min", "==", "\"", "\"", "{", "return", "nil", "\n", "}", "\n", "if", "min", "!=", "\"", "\"", "{", "if", "minIncl", "{", "for", "i", ",", "m", ":=", "range", "members", "{", "if", "m", ">=", "min", "{", "members", "=", "members", "[", "i", ":", "]", "\n", "break", "\n", "}", "\n", "}", "\n", "}", "else", "{", "// Excluding min", "for", "i", ",", "m", ":=", "range", "members", "{", "if", "m", ">", "min", "{", "members", "=", "members", "[", "i", ":", "]", "\n", "break", "\n", "}", "\n", "}", "\n", "}", "\n", "}", "\n", "if", "max", "!=", "\"", "\"", "{", "if", "maxIncl", "{", "for", "i", ",", "m", ":=", "range", "members", "{", "if", "m", ">", "max", "{", "members", "=", "members", "[", ":", "i", "]", "\n", "break", "\n", "}", "\n", "}", "\n", "}", "else", "{", "// Excluding max", "for", "i", ",", "m", ":=", "range", "members", "{", "if", "m", ">=", "max", "{", "members", "=", "members", "[", ":", "i", "]", "\n", "break", "\n", "}", "\n", "}", "\n", "}", "\n", "}", "\n", "return", "members", "\n", "}" ]
// withLexRange limits a list of sorted set elements.
[ "withLexRange", "limits", "a", "list", "of", "sorted", "set", "elements", "." ]
3d7aa1333af56ab862d446678d93aaa6803e0938
https://github.com/alicebob/miniredis/blob/3d7aa1333af56ab862d446678d93aaa6803e0938/cmd_sorted_set.go#L1123-L1164
train
alicebob/miniredis
cmd_sorted_set.go
cmdZpopmax
func (m *Miniredis) cmdZpopmax(reverse bool) server.Cmd { return func(c *server.Peer, cmd string, args []string) { if len(args) < 1 { setDirty(c) c.WriteError(errWrongNumber(cmd)) return } if !m.handleAuth(c) { return } key := args[0] count := 1 var err error if len(args) > 1 { count, err = strconv.Atoi(args[1]) if err != nil { setDirty(c) c.WriteError(msgInvalidInt) return } } withScores := true if len(args) > 2 { c.WriteError(msgSyntaxError) return } withTx(m, c, func(c *server.Peer, ctx *connCtx) { db := m.db(ctx.selectedDB) if !db.exists(key) { c.WriteLen(0) return } if db.t(key) != "zset" { c.WriteError(ErrWrongType.Error()) return } members := db.ssetMembers(key) if reverse { reverseSlice(members) } rs, re := redisRange(len(members), 0, count-1, false) if withScores { c.WriteLen((re - rs) * 2) } else { c.WriteLen(re - rs) } for _, el := range members[rs:re] { c.WriteBulk(el) if withScores { c.WriteBulk(formatFloat(db.ssetScore(key, el))) } db.ssetRem(key, el) } }) } }
go
func (m *Miniredis) cmdZpopmax(reverse bool) server.Cmd { return func(c *server.Peer, cmd string, args []string) { if len(args) < 1 { setDirty(c) c.WriteError(errWrongNumber(cmd)) return } if !m.handleAuth(c) { return } key := args[0] count := 1 var err error if len(args) > 1 { count, err = strconv.Atoi(args[1]) if err != nil { setDirty(c) c.WriteError(msgInvalidInt) return } } withScores := true if len(args) > 2 { c.WriteError(msgSyntaxError) return } withTx(m, c, func(c *server.Peer, ctx *connCtx) { db := m.db(ctx.selectedDB) if !db.exists(key) { c.WriteLen(0) return } if db.t(key) != "zset" { c.WriteError(ErrWrongType.Error()) return } members := db.ssetMembers(key) if reverse { reverseSlice(members) } rs, re := redisRange(len(members), 0, count-1, false) if withScores { c.WriteLen((re - rs) * 2) } else { c.WriteLen(re - rs) } for _, el := range members[rs:re] { c.WriteBulk(el) if withScores { c.WriteBulk(formatFloat(db.ssetScore(key, el))) } db.ssetRem(key, el) } }) } }
[ "func", "(", "m", "*", "Miniredis", ")", "cmdZpopmax", "(", "reverse", "bool", ")", "server", ".", "Cmd", "{", "return", "func", "(", "c", "*", "server", ".", "Peer", ",", "cmd", "string", ",", "args", "[", "]", "string", ")", "{", "if", "len", "(", "args", ")", "<", "1", "{", "setDirty", "(", "c", ")", "\n", "c", ".", "WriteError", "(", "errWrongNumber", "(", "cmd", ")", ")", "\n", "return", "\n", "}", "\n", "if", "!", "m", ".", "handleAuth", "(", "c", ")", "{", "return", "\n", "}", "\n\n", "key", ":=", "args", "[", "0", "]", "\n", "count", ":=", "1", "\n", "var", "err", "error", "\n", "if", "len", "(", "args", ")", ">", "1", "{", "count", ",", "err", "=", "strconv", ".", "Atoi", "(", "args", "[", "1", "]", ")", "\n\n", "if", "err", "!=", "nil", "{", "setDirty", "(", "c", ")", "\n", "c", ".", "WriteError", "(", "msgInvalidInt", ")", "\n", "return", "\n", "}", "\n", "}", "\n\n", "withScores", ":=", "true", "\n", "if", "len", "(", "args", ")", ">", "2", "{", "c", ".", "WriteError", "(", "msgSyntaxError", ")", "\n", "return", "\n", "}", "\n\n", "withTx", "(", "m", ",", "c", ",", "func", "(", "c", "*", "server", ".", "Peer", ",", "ctx", "*", "connCtx", ")", "{", "db", ":=", "m", ".", "db", "(", "ctx", ".", "selectedDB", ")", "\n\n", "if", "!", "db", ".", "exists", "(", "key", ")", "{", "c", ".", "WriteLen", "(", "0", ")", "\n", "return", "\n", "}", "\n\n", "if", "db", ".", "t", "(", "key", ")", "!=", "\"", "\"", "{", "c", ".", "WriteError", "(", "ErrWrongType", ".", "Error", "(", ")", ")", "\n", "return", "\n", "}", "\n\n", "members", ":=", "db", ".", "ssetMembers", "(", "key", ")", "\n", "if", "reverse", "{", "reverseSlice", "(", "members", ")", "\n", "}", "\n", "rs", ",", "re", ":=", "redisRange", "(", "len", "(", "members", ")", ",", "0", ",", "count", "-", "1", ",", "false", ")", "\n", "if", "withScores", "{", "c", ".", "WriteLen", "(", "(", "re", "-", "rs", ")", "*", "2", ")", "\n", "}", "else", "{", "c", ".", "WriteLen", "(", "re", "-", "rs", ")", "\n", "}", "\n", "for", "_", ",", "el", ":=", "range", "members", "[", "rs", ":", "re", "]", "{", "c", ".", "WriteBulk", "(", "el", ")", "\n", "if", "withScores", "{", "c", ".", "WriteBulk", "(", "formatFloat", "(", "db", ".", "ssetScore", "(", "key", ",", "el", ")", ")", ")", "\n", "}", "\n", "db", ".", "ssetRem", "(", "key", ",", "el", ")", "\n", "}", "\n", "}", ")", "\n", "}", "\n", "}" ]
// ZPOPMAX and ZPOPMIN
[ "ZPOPMAX", "and", "ZPOPMIN" ]
3d7aa1333af56ab862d446678d93aaa6803e0938
https://github.com/alicebob/miniredis/blob/3d7aa1333af56ab862d446678d93aaa6803e0938/cmd_sorted_set.go#L1388-L1450
train
alicebob/miniredis
cmd_transactions.go
commandsTransaction
func commandsTransaction(m *Miniredis) { m.srv.Register("DISCARD", m.cmdDiscard) m.srv.Register("EXEC", m.cmdExec) m.srv.Register("MULTI", m.cmdMulti) m.srv.Register("UNWATCH", m.cmdUnwatch) m.srv.Register("WATCH", m.cmdWatch) }
go
func commandsTransaction(m *Miniredis) { m.srv.Register("DISCARD", m.cmdDiscard) m.srv.Register("EXEC", m.cmdExec) m.srv.Register("MULTI", m.cmdMulti) m.srv.Register("UNWATCH", m.cmdUnwatch) m.srv.Register("WATCH", m.cmdWatch) }
[ "func", "commandsTransaction", "(", "m", "*", "Miniredis", ")", "{", "m", ".", "srv", ".", "Register", "(", "\"", "\"", ",", "m", ".", "cmdDiscard", ")", "\n", "m", ".", "srv", ".", "Register", "(", "\"", "\"", ",", "m", ".", "cmdExec", ")", "\n", "m", ".", "srv", ".", "Register", "(", "\"", "\"", ",", "m", ".", "cmdMulti", ")", "\n", "m", ".", "srv", ".", "Register", "(", "\"", "\"", ",", "m", ".", "cmdUnwatch", ")", "\n", "m", ".", "srv", ".", "Register", "(", "\"", "\"", ",", "m", ".", "cmdWatch", ")", "\n", "}" ]
// commandsTransaction handles MULTI &c.
[ "commandsTransaction", "handles", "MULTI", "&c", "." ]
3d7aa1333af56ab862d446678d93aaa6803e0938
https://github.com/alicebob/miniredis/blob/3d7aa1333af56ab862d446678d93aaa6803e0938/cmd_transactions.go#L10-L16
train
alicebob/miniredis
cmd_set.go
commandsSet
func commandsSet(m *Miniredis) { m.srv.Register("SADD", m.cmdSadd) m.srv.Register("SCARD", m.cmdScard) m.srv.Register("SDIFF", m.cmdSdiff) m.srv.Register("SDIFFSTORE", m.cmdSdiffstore) m.srv.Register("SINTER", m.cmdSinter) m.srv.Register("SINTERSTORE", m.cmdSinterstore) m.srv.Register("SISMEMBER", m.cmdSismember) m.srv.Register("SMEMBERS", m.cmdSmembers) m.srv.Register("SMOVE", m.cmdSmove) m.srv.Register("SPOP", m.cmdSpop) m.srv.Register("SRANDMEMBER", m.cmdSrandmember) m.srv.Register("SREM", m.cmdSrem) m.srv.Register("SUNION", m.cmdSunion) m.srv.Register("SUNIONSTORE", m.cmdSunionstore) m.srv.Register("SSCAN", m.cmdSscan) }
go
func commandsSet(m *Miniredis) { m.srv.Register("SADD", m.cmdSadd) m.srv.Register("SCARD", m.cmdScard) m.srv.Register("SDIFF", m.cmdSdiff) m.srv.Register("SDIFFSTORE", m.cmdSdiffstore) m.srv.Register("SINTER", m.cmdSinter) m.srv.Register("SINTERSTORE", m.cmdSinterstore) m.srv.Register("SISMEMBER", m.cmdSismember) m.srv.Register("SMEMBERS", m.cmdSmembers) m.srv.Register("SMOVE", m.cmdSmove) m.srv.Register("SPOP", m.cmdSpop) m.srv.Register("SRANDMEMBER", m.cmdSrandmember) m.srv.Register("SREM", m.cmdSrem) m.srv.Register("SUNION", m.cmdSunion) m.srv.Register("SUNIONSTORE", m.cmdSunionstore) m.srv.Register("SSCAN", m.cmdSscan) }
[ "func", "commandsSet", "(", "m", "*", "Miniredis", ")", "{", "m", ".", "srv", ".", "Register", "(", "\"", "\"", ",", "m", ".", "cmdSadd", ")", "\n", "m", ".", "srv", ".", "Register", "(", "\"", "\"", ",", "m", ".", "cmdScard", ")", "\n", "m", ".", "srv", ".", "Register", "(", "\"", "\"", ",", "m", ".", "cmdSdiff", ")", "\n", "m", ".", "srv", ".", "Register", "(", "\"", "\"", ",", "m", ".", "cmdSdiffstore", ")", "\n", "m", ".", "srv", ".", "Register", "(", "\"", "\"", ",", "m", ".", "cmdSinter", ")", "\n", "m", ".", "srv", ".", "Register", "(", "\"", "\"", ",", "m", ".", "cmdSinterstore", ")", "\n", "m", ".", "srv", ".", "Register", "(", "\"", "\"", ",", "m", ".", "cmdSismember", ")", "\n", "m", ".", "srv", ".", "Register", "(", "\"", "\"", ",", "m", ".", "cmdSmembers", ")", "\n", "m", ".", "srv", ".", "Register", "(", "\"", "\"", ",", "m", ".", "cmdSmove", ")", "\n", "m", ".", "srv", ".", "Register", "(", "\"", "\"", ",", "m", ".", "cmdSpop", ")", "\n", "m", ".", "srv", ".", "Register", "(", "\"", "\"", ",", "m", ".", "cmdSrandmember", ")", "\n", "m", ".", "srv", ".", "Register", "(", "\"", "\"", ",", "m", ".", "cmdSrem", ")", "\n", "m", ".", "srv", ".", "Register", "(", "\"", "\"", ",", "m", ".", "cmdSunion", ")", "\n", "m", ".", "srv", ".", "Register", "(", "\"", "\"", ",", "m", ".", "cmdSunionstore", ")", "\n", "m", ".", "srv", ".", "Register", "(", "\"", "\"", ",", "m", ".", "cmdSscan", ")", "\n", "}" ]
// commandsSet handles all set value operations.
[ "commandsSet", "handles", "all", "set", "value", "operations", "." ]
3d7aa1333af56ab862d446678d93aaa6803e0938
https://github.com/alicebob/miniredis/blob/3d7aa1333af56ab862d446678d93aaa6803e0938/cmd_set.go#L14-L30
train
alicebob/miniredis
cmd_set.go
shuffle
func shuffle(m []string) { for _ = range m { i := rand.Intn(len(m)) j := rand.Intn(len(m)) m[i], m[j] = m[j], m[i] } }
go
func shuffle(m []string) { for _ = range m { i := rand.Intn(len(m)) j := rand.Intn(len(m)) m[i], m[j] = m[j], m[i] } }
[ "func", "shuffle", "(", "m", "[", "]", "string", ")", "{", "for", "_", "=", "range", "m", "{", "i", ":=", "rand", ".", "Intn", "(", "len", "(", "m", ")", ")", "\n", "j", ":=", "rand", ".", "Intn", "(", "len", "(", "m", ")", ")", "\n", "m", "[", "i", "]", ",", "m", "[", "j", "]", "=", "m", "[", "j", "]", ",", "m", "[", "i", "]", "\n", "}", "\n", "}" ]
// shuffle shuffles a string. Kinda.
[ "shuffle", "shuffles", "a", "string", ".", "Kinda", "." ]
3d7aa1333af56ab862d446678d93aaa6803e0938
https://github.com/alicebob/miniredis/blob/3d7aa1333af56ab862d446678d93aaa6803e0938/cmd_set.go#L678-L684
train
minio/mc
pkg/ioutils/filepath.go
IsDirEmpty
func IsDirEmpty(dirname string) (status bool, err error) { f, err := os.Open(dirname) if err == nil { defer f.Close() if _, err = f.Readdirnames(1); err == io.EOF { status = true err = nil } } return }
go
func IsDirEmpty(dirname string) (status bool, err error) { f, err := os.Open(dirname) if err == nil { defer f.Close() if _, err = f.Readdirnames(1); err == io.EOF { status = true err = nil } } return }
[ "func", "IsDirEmpty", "(", "dirname", "string", ")", "(", "status", "bool", ",", "err", "error", ")", "{", "f", ",", "err", ":=", "os", ".", "Open", "(", "dirname", ")", "\n", "if", "err", "==", "nil", "{", "defer", "f", ".", "Close", "(", ")", "\n", "if", "_", ",", "err", "=", "f", ".", "Readdirnames", "(", "1", ")", ";", "err", "==", "io", ".", "EOF", "{", "status", "=", "true", "\n", "err", "=", "nil", "\n", "}", "\n", "}", "\n\n", "return", "\n", "}" ]
// IsDirEmpty Check if a directory is empty
[ "IsDirEmpty", "Check", "if", "a", "directory", "is", "empty" ]
f0f156aca82e451c80b05d5be8eb01a04fee29dd
https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/pkg/ioutils/filepath.go#L28-L39
train
minio/mc
pkg/ioutils/filepath.go
FTW
func FTW(root string, walkFn FTWFunc) error { info, err := os.Lstat(root) if err != nil { return walkFn(root, nil, err) } return walk(root, info, walkFn) }
go
func FTW(root string, walkFn FTWFunc) error { info, err := os.Lstat(root) if err != nil { return walkFn(root, nil, err) } return walk(root, info, walkFn) }
[ "func", "FTW", "(", "root", "string", ",", "walkFn", "FTWFunc", ")", "error", "{", "info", ",", "err", ":=", "os", ".", "Lstat", "(", "root", ")", "\n", "if", "err", "!=", "nil", "{", "return", "walkFn", "(", "root", ",", "nil", ",", "err", ")", "\n", "}", "\n", "return", "walk", "(", "root", ",", "info", ",", "walkFn", ")", "\n", "}" ]
// FTW walks the file tree rooted at root, calling walkFn for each file or // directory in the tree, including root.
[ "FTW", "walks", "the", "file", "tree", "rooted", "at", "root", "calling", "walkFn", "for", "each", "file", "or", "directory", "in", "the", "tree", "including", "root", "." ]
f0f156aca82e451c80b05d5be8eb01a04fee29dd
https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/pkg/ioutils/filepath.go#L43-L49
train
minio/mc
pkg/ioutils/filepath.go
readDir
func readDir(dirname string) (fi []os.FileInfo, err error) { f, err := os.Open(dirname) if err == nil { defer f.Close() if fi, err = f.Readdir(-1); fi != nil { sort.Sort(byName(fi)) } } return }
go
func readDir(dirname string) (fi []os.FileInfo, err error) { f, err := os.Open(dirname) if err == nil { defer f.Close() if fi, err = f.Readdir(-1); fi != nil { sort.Sort(byName(fi)) } } return }
[ "func", "readDir", "(", "dirname", "string", ")", "(", "fi", "[", "]", "os", ".", "FileInfo", ",", "err", "error", ")", "{", "f", ",", "err", ":=", "os", ".", "Open", "(", "dirname", ")", "\n", "if", "err", "==", "nil", "{", "defer", "f", ".", "Close", "(", ")", "\n", "if", "fi", ",", "err", "=", "f", ".", "Readdir", "(", "-", "1", ")", ";", "fi", "!=", "nil", "{", "sort", ".", "Sort", "(", "byName", "(", "fi", ")", ")", "\n", "}", "\n", "}", "\n\n", "return", "\n", "}" ]
// readDir reads the directory named by dirname and returns // a sorted list of directory entries.
[ "readDir", "reads", "the", "directory", "named", "by", "dirname", "and", "returns", "a", "sorted", "list", "of", "directory", "entries", "." ]
f0f156aca82e451c80b05d5be8eb01a04fee29dd
https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/pkg/ioutils/filepath.go#L72-L82
train
minio/mc
cmd/config-host-list.go
printHosts
func printHosts(hosts ...hostMessage) { var maxAlias = 0 for _, host := range hosts { if len(host.Alias) > maxAlias { maxAlias = len(host.Alias) } } for _, host := range hosts { if !globalJSON { // Format properly for alignment based on alias length only in non json mode. host.Alias = fmt.Sprintf("%-*.*s", maxAlias, maxAlias, host.Alias) } if host.AccessKey == "" || host.SecretKey == "" { host.AccessKey = "" host.SecretKey = "" host.API = "" } printMsg(host) } }
go
func printHosts(hosts ...hostMessage) { var maxAlias = 0 for _, host := range hosts { if len(host.Alias) > maxAlias { maxAlias = len(host.Alias) } } for _, host := range hosts { if !globalJSON { // Format properly for alignment based on alias length only in non json mode. host.Alias = fmt.Sprintf("%-*.*s", maxAlias, maxAlias, host.Alias) } if host.AccessKey == "" || host.SecretKey == "" { host.AccessKey = "" host.SecretKey = "" host.API = "" } printMsg(host) } }
[ "func", "printHosts", "(", "hosts", "...", "hostMessage", ")", "{", "var", "maxAlias", "=", "0", "\n", "for", "_", ",", "host", ":=", "range", "hosts", "{", "if", "len", "(", "host", ".", "Alias", ")", ">", "maxAlias", "{", "maxAlias", "=", "len", "(", "host", ".", "Alias", ")", "\n", "}", "\n", "}", "\n", "for", "_", ",", "host", ":=", "range", "hosts", "{", "if", "!", "globalJSON", "{", "// Format properly for alignment based on alias length only in non json mode.", "host", ".", "Alias", "=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "maxAlias", ",", "maxAlias", ",", "host", ".", "Alias", ")", "\n", "}", "\n", "if", "host", ".", "AccessKey", "==", "\"", "\"", "||", "host", ".", "SecretKey", "==", "\"", "\"", "{", "host", ".", "AccessKey", "=", "\"", "\"", "\n", "host", ".", "SecretKey", "=", "\"", "\"", "\n", "host", ".", "API", "=", "\"", "\"", "\n", "}", "\n", "printMsg", "(", "host", ")", "\n", "}", "\n", "}" ]
// Prints all the hosts.
[ "Prints", "all", "the", "hosts", "." ]
f0f156aca82e451c80b05d5be8eb01a04fee29dd
https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/config-host-list.go#L88-L107
train
minio/mc
cmd/config-host-list.go
listHosts
func listHosts(alias string) { conf, err := loadMcConfig() fatalIf(err.Trace(globalMCConfigVersion), "Unable to load config version `"+globalMCConfigVersion+"`.") // If specific alias is requested, look for it and print. if alias != "" { if v, ok := conf.Hosts[alias]; ok { printHosts(hostMessage{ op: "list", prettyPrint: false, Alias: alias, URL: v.URL, AccessKey: v.AccessKey, SecretKey: v.SecretKey, API: v.API, Lookup: v.Lookup, }) return } fatalIf(errInvalidAliasedURL(alias), "No such alias `"+alias+"` found.") } var hosts []hostMessage for k, v := range conf.Hosts { hosts = append(hosts, hostMessage{ op: "list", prettyPrint: true, Alias: k, URL: v.URL, AccessKey: v.AccessKey, SecretKey: v.SecretKey, API: v.API, Lookup: v.Lookup, }) } // Sort hosts by alias names lexically. sort.Sort(byAlias(hosts)) // Display all the hosts. printHosts(hosts...) }
go
func listHosts(alias string) { conf, err := loadMcConfig() fatalIf(err.Trace(globalMCConfigVersion), "Unable to load config version `"+globalMCConfigVersion+"`.") // If specific alias is requested, look for it and print. if alias != "" { if v, ok := conf.Hosts[alias]; ok { printHosts(hostMessage{ op: "list", prettyPrint: false, Alias: alias, URL: v.URL, AccessKey: v.AccessKey, SecretKey: v.SecretKey, API: v.API, Lookup: v.Lookup, }) return } fatalIf(errInvalidAliasedURL(alias), "No such alias `"+alias+"` found.") } var hosts []hostMessage for k, v := range conf.Hosts { hosts = append(hosts, hostMessage{ op: "list", prettyPrint: true, Alias: k, URL: v.URL, AccessKey: v.AccessKey, SecretKey: v.SecretKey, API: v.API, Lookup: v.Lookup, }) } // Sort hosts by alias names lexically. sort.Sort(byAlias(hosts)) // Display all the hosts. printHosts(hosts...) }
[ "func", "listHosts", "(", "alias", "string", ")", "{", "conf", ",", "err", ":=", "loadMcConfig", "(", ")", "\n", "fatalIf", "(", "err", ".", "Trace", "(", "globalMCConfigVersion", ")", ",", "\"", "\"", "+", "globalMCConfigVersion", "+", "\"", "\"", ")", "\n\n", "// If specific alias is requested, look for it and print.", "if", "alias", "!=", "\"", "\"", "{", "if", "v", ",", "ok", ":=", "conf", ".", "Hosts", "[", "alias", "]", ";", "ok", "{", "printHosts", "(", "hostMessage", "{", "op", ":", "\"", "\"", ",", "prettyPrint", ":", "false", ",", "Alias", ":", "alias", ",", "URL", ":", "v", ".", "URL", ",", "AccessKey", ":", "v", ".", "AccessKey", ",", "SecretKey", ":", "v", ".", "SecretKey", ",", "API", ":", "v", ".", "API", ",", "Lookup", ":", "v", ".", "Lookup", ",", "}", ")", "\n", "return", "\n", "}", "\n", "fatalIf", "(", "errInvalidAliasedURL", "(", "alias", ")", ",", "\"", "\"", "+", "alias", "+", "\"", "\"", ")", "\n", "}", "\n\n", "var", "hosts", "[", "]", "hostMessage", "\n", "for", "k", ",", "v", ":=", "range", "conf", ".", "Hosts", "{", "hosts", "=", "append", "(", "hosts", ",", "hostMessage", "{", "op", ":", "\"", "\"", ",", "prettyPrint", ":", "true", ",", "Alias", ":", "k", ",", "URL", ":", "v", ".", "URL", ",", "AccessKey", ":", "v", ".", "AccessKey", ",", "SecretKey", ":", "v", ".", "SecretKey", ",", "API", ":", "v", ".", "API", ",", "Lookup", ":", "v", ".", "Lookup", ",", "}", ")", "\n", "}", "\n\n", "// Sort hosts by alias names lexically.", "sort", ".", "Sort", "(", "byAlias", "(", "hosts", ")", ")", "\n\n", "// Display all the hosts.", "printHosts", "(", "hosts", "...", ")", "\n", "}" ]
// listHosts - list all host URLs or a requested host.
[ "listHosts", "-", "list", "all", "host", "URLs", "or", "a", "requested", "host", "." ]
f0f156aca82e451c80b05d5be8eb01a04fee29dd
https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/config-host-list.go#L117-L158
train
minio/mc
cmd/session-resume.go
sessionExecute
func sessionExecute(s *sessionV8) { switch s.Header.CommandType { case "cp": sseKeys := s.Header.CommandStringFlags["encrypt-key"] sseServer := s.Header.CommandStringFlags["encrypt"] encKeyDB, _ := parseAndValidateEncryptionKeys(sseKeys, sseServer) doCopySession(s, encKeyDB) } }
go
func sessionExecute(s *sessionV8) { switch s.Header.CommandType { case "cp": sseKeys := s.Header.CommandStringFlags["encrypt-key"] sseServer := s.Header.CommandStringFlags["encrypt"] encKeyDB, _ := parseAndValidateEncryptionKeys(sseKeys, sseServer) doCopySession(s, encKeyDB) } }
[ "func", "sessionExecute", "(", "s", "*", "sessionV8", ")", "{", "switch", "s", ".", "Header", ".", "CommandType", "{", "case", "\"", "\"", ":", "sseKeys", ":=", "s", ".", "Header", ".", "CommandStringFlags", "[", "\"", "\"", "]", "\n", "sseServer", ":=", "s", ".", "Header", ".", "CommandStringFlags", "[", "\"", "\"", "]", "\n", "encKeyDB", ",", "_", ":=", "parseAndValidateEncryptionKeys", "(", "sseKeys", ",", "sseServer", ")", "\n", "doCopySession", "(", "s", ",", "encKeyDB", ")", "\n", "}", "\n", "}" ]
// sessionExecute - run a given session.
[ "sessionExecute", "-", "run", "a", "given", "session", "." ]
f0f156aca82e451c80b05d5be8eb01a04fee29dd
https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/session-resume.go#L63-L71
train
minio/mc
cmd/session-resume.go
findClosestSessions
func findClosestSessions(session string) []string { sessionsTree := trie.NewTrie() // Allocate a new trie for sessions strings. for _, sid := range getSessionIDs() { sessionsTree.Insert(sid) } var closestSessions []string for _, value := range sessionsTree.PrefixMatch(session) { closestSessions = append(closestSessions, value.(string)) } sort.Strings(closestSessions) return closestSessions }
go
func findClosestSessions(session string) []string { sessionsTree := trie.NewTrie() // Allocate a new trie for sessions strings. for _, sid := range getSessionIDs() { sessionsTree.Insert(sid) } var closestSessions []string for _, value := range sessionsTree.PrefixMatch(session) { closestSessions = append(closestSessions, value.(string)) } sort.Strings(closestSessions) return closestSessions }
[ "func", "findClosestSessions", "(", "session", "string", ")", "[", "]", "string", "{", "sessionsTree", ":=", "trie", ".", "NewTrie", "(", ")", "// Allocate a new trie for sessions strings.", "\n", "for", "_", ",", "sid", ":=", "range", "getSessionIDs", "(", ")", "{", "sessionsTree", ".", "Insert", "(", "sid", ")", "\n", "}", "\n", "var", "closestSessions", "[", "]", "string", "\n", "for", "_", ",", "value", ":=", "range", "sessionsTree", ".", "PrefixMatch", "(", "session", ")", "{", "closestSessions", "=", "append", "(", "closestSessions", ",", "value", ".", "(", "string", ")", ")", "\n", "}", "\n", "sort", ".", "Strings", "(", "closestSessions", ")", "\n", "return", "closestSessions", "\n", "}" ]
// findClosestSessions to match a given string with sessions trie tree.
[ "findClosestSessions", "to", "match", "a", "given", "string", "with", "sessions", "trie", "tree", "." ]
f0f156aca82e451c80b05d5be8eb01a04fee29dd
https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/session-resume.go#L74-L85
train
minio/mc
cmd/session-resume.go
checkSessionResumeSyntax
func checkSessionResumeSyntax(ctx *cli.Context) { if len(ctx.Args()) == 0 || len(ctx.Args()) > 2 { cli.ShowCommandHelpAndExit(ctx, "resume", 1) // last argument is exit code } }
go
func checkSessionResumeSyntax(ctx *cli.Context) { if len(ctx.Args()) == 0 || len(ctx.Args()) > 2 { cli.ShowCommandHelpAndExit(ctx, "resume", 1) // last argument is exit code } }
[ "func", "checkSessionResumeSyntax", "(", "ctx", "*", "cli", ".", "Context", ")", "{", "if", "len", "(", "ctx", ".", "Args", "(", ")", ")", "==", "0", "||", "len", "(", "ctx", ".", "Args", "(", ")", ")", ">", "2", "{", "cli", ".", "ShowCommandHelpAndExit", "(", "ctx", ",", "\"", "\"", ",", "1", ")", "// last argument is exit code", "\n", "}", "\n", "}" ]
// checkSessionResumeSyntax - Validate session resume command.
[ "checkSessionResumeSyntax", "-", "Validate", "session", "resume", "command", "." ]
f0f156aca82e451c80b05d5be8eb01a04fee29dd
https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/session-resume.go#L88-L92
train
minio/mc
cmd/session-resume.go
mainSessionResume
func mainSessionResume(ctx *cli.Context) error { // Validate session resume syntax. checkSessionResumeSyntax(ctx) // Additional command specific theme customization. console.SetColor("Command", color.New(color.FgWhite, color.Bold)) console.SetColor("SessionID", color.New(color.FgYellow, color.Bold)) console.SetColor("SessionTime", color.New(color.FgGreen)) if !isSessionDirExists() { fatalIf(createSessionDir().Trace(), "Unable to create session folder.") } sessionID := ctx.Args().Get(0) if !isSessionExists(sessionID) { closestSessions := findClosestSessions(sessionID) errorMsg := "Session `" + sessionID + "` not found." if len(closestSessions) > 0 { errorMsg += fmt.Sprintf("\n\nDid you mean?\n") for _, session := range closestSessions { errorMsg += fmt.Sprintf(" `mc resume session %s`", session) // break on the first one, it is good enough. break } } fatalIf(errDummy().Trace(sessionID), errorMsg) } resumeSession(sessionID) return nil }
go
func mainSessionResume(ctx *cli.Context) error { // Validate session resume syntax. checkSessionResumeSyntax(ctx) // Additional command specific theme customization. console.SetColor("Command", color.New(color.FgWhite, color.Bold)) console.SetColor("SessionID", color.New(color.FgYellow, color.Bold)) console.SetColor("SessionTime", color.New(color.FgGreen)) if !isSessionDirExists() { fatalIf(createSessionDir().Trace(), "Unable to create session folder.") } sessionID := ctx.Args().Get(0) if !isSessionExists(sessionID) { closestSessions := findClosestSessions(sessionID) errorMsg := "Session `" + sessionID + "` not found." if len(closestSessions) > 0 { errorMsg += fmt.Sprintf("\n\nDid you mean?\n") for _, session := range closestSessions { errorMsg += fmt.Sprintf(" `mc resume session %s`", session) // break on the first one, it is good enough. break } } fatalIf(errDummy().Trace(sessionID), errorMsg) } resumeSession(sessionID) return nil }
[ "func", "mainSessionResume", "(", "ctx", "*", "cli", ".", "Context", ")", "error", "{", "// Validate session resume syntax.", "checkSessionResumeSyntax", "(", "ctx", ")", "\n\n", "// Additional command specific theme customization.", "console", ".", "SetColor", "(", "\"", "\"", ",", "color", ".", "New", "(", "color", ".", "FgWhite", ",", "color", ".", "Bold", ")", ")", "\n", "console", ".", "SetColor", "(", "\"", "\"", ",", "color", ".", "New", "(", "color", ".", "FgYellow", ",", "color", ".", "Bold", ")", ")", "\n", "console", ".", "SetColor", "(", "\"", "\"", ",", "color", ".", "New", "(", "color", ".", "FgGreen", ")", ")", "\n\n", "if", "!", "isSessionDirExists", "(", ")", "{", "fatalIf", "(", "createSessionDir", "(", ")", ".", "Trace", "(", ")", ",", "\"", "\"", ")", "\n", "}", "\n\n", "sessionID", ":=", "ctx", ".", "Args", "(", ")", ".", "Get", "(", "0", ")", "\n", "if", "!", "isSessionExists", "(", "sessionID", ")", "{", "closestSessions", ":=", "findClosestSessions", "(", "sessionID", ")", "\n", "errorMsg", ":=", "\"", "\"", "+", "sessionID", "+", "\"", "\"", "\n", "if", "len", "(", "closestSessions", ")", ">", "0", "{", "errorMsg", "+=", "fmt", ".", "Sprintf", "(", "\"", "\\n", "\\n", "\\n", "\"", ")", "\n", "for", "_", ",", "session", ":=", "range", "closestSessions", "{", "errorMsg", "+=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "session", ")", "\n", "// break on the first one, it is good enough.", "break", "\n", "}", "\n", "}", "\n", "fatalIf", "(", "errDummy", "(", ")", ".", "Trace", "(", "sessionID", ")", ",", "errorMsg", ")", "\n", "}", "\n", "resumeSession", "(", "sessionID", ")", "\n", "return", "nil", "\n", "}" ]
// mainSessionResume - Main session resume function.
[ "mainSessionResume", "-", "Main", "session", "resume", "function", "." ]
f0f156aca82e451c80b05d5be8eb01a04fee29dd
https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/session-resume.go#L95-L124
train
minio/mc
cmd/session-resume.go
resumeSession
func resumeSession(sessionID string) { s, err := loadSessionV8(sessionID) fatalIf(err.Trace(sessionID), "Unable to load session.") // Restore the state of global variables from this previous session. s.restoreGlobals() savedCwd, e := os.Getwd() fatalIf(probe.NewError(e), "Unable to determine current working folder.") if s.Header.RootPath != "" { // change folder to RootPath. e = os.Chdir(s.Header.RootPath) fatalIf(probe.NewError(e), "Unable to change working folder to root path while resuming session.") } sessionExecute(s) err = s.Close() fatalIf(err.Trace(), "Unable to close session file properly.") err = s.Delete() fatalIf(err.Trace(), "Unable to clear session files properly.") // change folder back to saved path. e = os.Chdir(savedCwd) fatalIf(probe.NewError(e), "Unable to change working folder to saved path `"+savedCwd+"`.") }
go
func resumeSession(sessionID string) { s, err := loadSessionV8(sessionID) fatalIf(err.Trace(sessionID), "Unable to load session.") // Restore the state of global variables from this previous session. s.restoreGlobals() savedCwd, e := os.Getwd() fatalIf(probe.NewError(e), "Unable to determine current working folder.") if s.Header.RootPath != "" { // change folder to RootPath. e = os.Chdir(s.Header.RootPath) fatalIf(probe.NewError(e), "Unable to change working folder to root path while resuming session.") } sessionExecute(s) err = s.Close() fatalIf(err.Trace(), "Unable to close session file properly.") err = s.Delete() fatalIf(err.Trace(), "Unable to clear session files properly.") // change folder back to saved path. e = os.Chdir(savedCwd) fatalIf(probe.NewError(e), "Unable to change working folder to saved path `"+savedCwd+"`.") }
[ "func", "resumeSession", "(", "sessionID", "string", ")", "{", "s", ",", "err", ":=", "loadSessionV8", "(", "sessionID", ")", "\n", "fatalIf", "(", "err", ".", "Trace", "(", "sessionID", ")", ",", "\"", "\"", ")", "\n", "// Restore the state of global variables from this previous session.", "s", ".", "restoreGlobals", "(", ")", "\n\n", "savedCwd", ",", "e", ":=", "os", ".", "Getwd", "(", ")", "\n", "fatalIf", "(", "probe", ".", "NewError", "(", "e", ")", ",", "\"", "\"", ")", "\n\n", "if", "s", ".", "Header", ".", "RootPath", "!=", "\"", "\"", "{", "// change folder to RootPath.", "e", "=", "os", ".", "Chdir", "(", "s", ".", "Header", ".", "RootPath", ")", "\n", "fatalIf", "(", "probe", ".", "NewError", "(", "e", ")", ",", "\"", "\"", ")", "\n", "}", "\n", "sessionExecute", "(", "s", ")", "\n", "err", "=", "s", ".", "Close", "(", ")", "\n", "fatalIf", "(", "err", ".", "Trace", "(", ")", ",", "\"", "\"", ")", "\n\n", "err", "=", "s", ".", "Delete", "(", ")", "\n", "fatalIf", "(", "err", ".", "Trace", "(", ")", ",", "\"", "\"", ")", "\n\n", "// change folder back to saved path.", "e", "=", "os", ".", "Chdir", "(", "savedCwd", ")", "\n", "fatalIf", "(", "probe", ".", "NewError", "(", "e", ")", ",", "\"", "\"", "+", "savedCwd", "+", "\"", "\"", ")", "\n\n", "}" ]
// resumeSession - Resumes a session specified by sessionID.
[ "resumeSession", "-", "Resumes", "a", "session", "specified", "by", "sessionID", "." ]
f0f156aca82e451c80b05d5be8eb01a04fee29dd
https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/session-resume.go#L127-L152
train
minio/mc
cmd/signals.go
signalTrap
func signalTrap(sig ...os.Signal) <-chan bool { // channel to notify the caller. trapCh := make(chan bool, 1) go func(chan<- bool) { // channel to receive signals. sigCh := make(chan os.Signal, 1) defer close(sigCh) // `signal.Notify` registers the given channel to // receive notifications of the specified signals. signal.Notify(sigCh, sig...) // Wait for the signal. <-sigCh // Once signal has been received stop signal Notify handler. signal.Stop(sigCh) // Notify the caller. trapCh <- true }(trapCh) return trapCh }
go
func signalTrap(sig ...os.Signal) <-chan bool { // channel to notify the caller. trapCh := make(chan bool, 1) go func(chan<- bool) { // channel to receive signals. sigCh := make(chan os.Signal, 1) defer close(sigCh) // `signal.Notify` registers the given channel to // receive notifications of the specified signals. signal.Notify(sigCh, sig...) // Wait for the signal. <-sigCh // Once signal has been received stop signal Notify handler. signal.Stop(sigCh) // Notify the caller. trapCh <- true }(trapCh) return trapCh }
[ "func", "signalTrap", "(", "sig", "...", "os", ".", "Signal", ")", "<-", "chan", "bool", "{", "// channel to notify the caller.", "trapCh", ":=", "make", "(", "chan", "bool", ",", "1", ")", "\n\n", "go", "func", "(", "chan", "<-", "bool", ")", "{", "// channel to receive signals.", "sigCh", ":=", "make", "(", "chan", "os", ".", "Signal", ",", "1", ")", "\n", "defer", "close", "(", "sigCh", ")", "\n\n", "// `signal.Notify` registers the given channel to", "// receive notifications of the specified signals.", "signal", ".", "Notify", "(", "sigCh", ",", "sig", "...", ")", "\n\n", "// Wait for the signal.", "<-", "sigCh", "\n\n", "// Once signal has been received stop signal Notify handler.", "signal", ".", "Stop", "(", "sigCh", ")", "\n\n", "// Notify the caller.", "trapCh", "<-", "true", "\n", "}", "(", "trapCh", ")", "\n\n", "return", "trapCh", "\n", "}" ]
// signalTrap traps the registered signals and notifies the caller.
[ "signalTrap", "traps", "the", "registered", "signals", "and", "notifies", "the", "caller", "." ]
f0f156aca82e451c80b05d5be8eb01a04fee29dd
https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/signals.go#L25-L49
train
minio/mc
cmd/session-old.go
loadSessionV7
func loadSessionV7(sid string) (*sessionV7, *probe.Error) { if !isSessionDirExists() { return nil, errInvalidArgument().Trace() } sessionFile, err := getSessionFile(sid) if err != nil { return nil, err.Trace(sid) } if _, e := os.Stat(sessionFile); e != nil { return nil, probe.NewError(e) } s := &sessionV7{} s.Header = &sessionV7Header{} s.SessionID = sid s.Header.Version = "7" qs, e := quick.NewConfig(s.Header, nil) if e != nil { return nil, probe.NewError(e).Trace(sid, s.Header.Version) } e = qs.Load(sessionFile) if e != nil { return nil, probe.NewError(e).Trace(sid, s.Header.Version) } s.mutex = new(sync.Mutex) s.Header = qs.Data().(*sessionV7Header) sessionDataFile, err := getSessionDataFile(s.SessionID) if err != nil { return nil, err.Trace(sid, s.Header.Version) } dataFile, e := os.Open(sessionDataFile) if e != nil { return nil, probe.NewError(e) } s.DataFP = &sessionDataFP{false, dataFile} return s, nil }
go
func loadSessionV7(sid string) (*sessionV7, *probe.Error) { if !isSessionDirExists() { return nil, errInvalidArgument().Trace() } sessionFile, err := getSessionFile(sid) if err != nil { return nil, err.Trace(sid) } if _, e := os.Stat(sessionFile); e != nil { return nil, probe.NewError(e) } s := &sessionV7{} s.Header = &sessionV7Header{} s.SessionID = sid s.Header.Version = "7" qs, e := quick.NewConfig(s.Header, nil) if e != nil { return nil, probe.NewError(e).Trace(sid, s.Header.Version) } e = qs.Load(sessionFile) if e != nil { return nil, probe.NewError(e).Trace(sid, s.Header.Version) } s.mutex = new(sync.Mutex) s.Header = qs.Data().(*sessionV7Header) sessionDataFile, err := getSessionDataFile(s.SessionID) if err != nil { return nil, err.Trace(sid, s.Header.Version) } dataFile, e := os.Open(sessionDataFile) if e != nil { return nil, probe.NewError(e) } s.DataFP = &sessionDataFP{false, dataFile} return s, nil }
[ "func", "loadSessionV7", "(", "sid", "string", ")", "(", "*", "sessionV7", ",", "*", "probe", ".", "Error", ")", "{", "if", "!", "isSessionDirExists", "(", ")", "{", "return", "nil", ",", "errInvalidArgument", "(", ")", ".", "Trace", "(", ")", "\n", "}", "\n", "sessionFile", ",", "err", ":=", "getSessionFile", "(", "sid", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", ".", "Trace", "(", "sid", ")", "\n", "}", "\n\n", "if", "_", ",", "e", ":=", "os", ".", "Stat", "(", "sessionFile", ")", ";", "e", "!=", "nil", "{", "return", "nil", ",", "probe", ".", "NewError", "(", "e", ")", "\n", "}", "\n\n", "s", ":=", "&", "sessionV7", "{", "}", "\n", "s", ".", "Header", "=", "&", "sessionV7Header", "{", "}", "\n", "s", ".", "SessionID", "=", "sid", "\n", "s", ".", "Header", ".", "Version", "=", "\"", "\"", "\n", "qs", ",", "e", ":=", "quick", ".", "NewConfig", "(", "s", ".", "Header", ",", "nil", ")", "\n", "if", "e", "!=", "nil", "{", "return", "nil", ",", "probe", ".", "NewError", "(", "e", ")", ".", "Trace", "(", "sid", ",", "s", ".", "Header", ".", "Version", ")", "\n", "}", "\n", "e", "=", "qs", ".", "Load", "(", "sessionFile", ")", "\n", "if", "e", "!=", "nil", "{", "return", "nil", ",", "probe", ".", "NewError", "(", "e", ")", ".", "Trace", "(", "sid", ",", "s", ".", "Header", ".", "Version", ")", "\n", "}", "\n\n", "s", ".", "mutex", "=", "new", "(", "sync", ".", "Mutex", ")", "\n", "s", ".", "Header", "=", "qs", ".", "Data", "(", ")", ".", "(", "*", "sessionV7Header", ")", "\n\n", "sessionDataFile", ",", "err", ":=", "getSessionDataFile", "(", "s", ".", "SessionID", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", ".", "Trace", "(", "sid", ",", "s", ".", "Header", ".", "Version", ")", "\n", "}", "\n\n", "dataFile", ",", "e", ":=", "os", ".", "Open", "(", "sessionDataFile", ")", "\n", "if", "e", "!=", "nil", "{", "return", "nil", ",", "probe", ".", "NewError", "(", "e", ")", "\n", "}", "\n", "s", ".", "DataFP", "=", "&", "sessionDataFP", "{", "false", ",", "dataFile", "}", "\n\n", "return", "s", ",", "nil", "\n", "}" ]
// loadSessionV7 - reads session file if exists and re-initiates internal variables
[ "loadSessionV7", "-", "reads", "session", "file", "if", "exists", "and", "re", "-", "initiates", "internal", "variables" ]
f0f156aca82e451c80b05d5be8eb01a04fee29dd
https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/session-old.go#L108-L149
train
minio/mc
cmd/client-fs_linux.go
IsGetEvent
func IsGetEvent(event notify.Event) bool { for _, ev := range EventTypeGet { if event&ev != 0 { return true } } return false }
go
func IsGetEvent(event notify.Event) bool { for _, ev := range EventTypeGet { if event&ev != 0 { return true } } return false }
[ "func", "IsGetEvent", "(", "event", "notify", ".", "Event", ")", "bool", "{", "for", "_", ",", "ev", ":=", "range", "EventTypeGet", "{", "if", "event", "&", "ev", "!=", "0", "{", "return", "true", "\n", "}", "\n", "}", "\n", "return", "false", "\n", "}" ]
// IsGetEvent checks if the event return is a get event.
[ "IsGetEvent", "checks", "if", "the", "event", "return", "is", "a", "get", "event", "." ]
f0f156aca82e451c80b05d5be8eb01a04fee29dd
https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/client-fs_linux.go#L41-L48
train
minio/mc
cmd/client-fs_linux.go
IsPutEvent
func IsPutEvent(event notify.Event) bool { for _, ev := range EventTypePut { if event&ev != 0 { return true } } return false }
go
func IsPutEvent(event notify.Event) bool { for _, ev := range EventTypePut { if event&ev != 0 { return true } } return false }
[ "func", "IsPutEvent", "(", "event", "notify", ".", "Event", ")", "bool", "{", "for", "_", ",", "ev", ":=", "range", "EventTypePut", "{", "if", "event", "&", "ev", "!=", "0", "{", "return", "true", "\n", "}", "\n", "}", "\n", "return", "false", "\n", "}" ]
// IsPutEvent checks if the event returned is a put event
[ "IsPutEvent", "checks", "if", "the", "event", "returned", "is", "a", "put", "event" ]
f0f156aca82e451c80b05d5be8eb01a04fee29dd
https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/client-fs_linux.go#L51-L58
train
minio/mc
cmd/client-fs_linux.go
IsDeleteEvent
func IsDeleteEvent(event notify.Event) bool { for _, ev := range EventTypeDelete { if event&ev != 0 { return true } } return false }
go
func IsDeleteEvent(event notify.Event) bool { for _, ev := range EventTypeDelete { if event&ev != 0 { return true } } return false }
[ "func", "IsDeleteEvent", "(", "event", "notify", ".", "Event", ")", "bool", "{", "for", "_", ",", "ev", ":=", "range", "EventTypeDelete", "{", "if", "event", "&", "ev", "!=", "0", "{", "return", "true", "\n", "}", "\n", "}", "\n", "return", "false", "\n", "}" ]
// IsDeleteEvent checks if the event returned is a delete event
[ "IsDeleteEvent", "checks", "if", "the", "event", "returned", "is", "a", "delete", "event" ]
f0f156aca82e451c80b05d5be8eb01a04fee29dd
https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/client-fs_linux.go#L61-L68
train
minio/mc
cmd/client-fs_linux.go
getAllXattrs
func getAllXattrs(path string) (map[string]string, error) { xMetadata := make(map[string]string) list, e := xattr.List(path) if e != nil { if isNotSupported(e) { return nil, nil } return nil, e } for _, key := range list { // filter out system specific xattr if strings.HasPrefix(key, "system.") { continue } xMetadata[key], e = getXAttr(path, key) if e != nil { if isNotSupported(e) { return nil, nil } return nil, e } } return xMetadata, nil }
go
func getAllXattrs(path string) (map[string]string, error) { xMetadata := make(map[string]string) list, e := xattr.List(path) if e != nil { if isNotSupported(e) { return nil, nil } return nil, e } for _, key := range list { // filter out system specific xattr if strings.HasPrefix(key, "system.") { continue } xMetadata[key], e = getXAttr(path, key) if e != nil { if isNotSupported(e) { return nil, nil } return nil, e } } return xMetadata, nil }
[ "func", "getAllXattrs", "(", "path", "string", ")", "(", "map", "[", "string", "]", "string", ",", "error", ")", "{", "xMetadata", ":=", "make", "(", "map", "[", "string", "]", "string", ")", "\n", "list", ",", "e", ":=", "xattr", ".", "List", "(", "path", ")", "\n", "if", "e", "!=", "nil", "{", "if", "isNotSupported", "(", "e", ")", "{", "return", "nil", ",", "nil", "\n", "}", "\n", "return", "nil", ",", "e", "\n", "}", "\n", "for", "_", ",", "key", ":=", "range", "list", "{", "// filter out system specific xattr", "if", "strings", ".", "HasPrefix", "(", "key", ",", "\"", "\"", ")", "{", "continue", "\n", "}", "\n", "xMetadata", "[", "key", "]", ",", "e", "=", "getXAttr", "(", "path", ",", "key", ")", "\n", "if", "e", "!=", "nil", "{", "if", "isNotSupported", "(", "e", ")", "{", "return", "nil", ",", "nil", "\n", "}", "\n", "return", "nil", ",", "e", "\n", "}", "\n", "}", "\n", "return", "xMetadata", ",", "nil", "\n", "}" ]
// getAllXattrs returns the extended attributes for a file if supported // by the OS
[ "getAllXattrs", "returns", "the", "extended", "attributes", "for", "a", "file", "if", "supported", "by", "the", "OS" ]
f0f156aca82e451c80b05d5be8eb01a04fee29dd
https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/client-fs_linux.go#L85-L108
train
minio/mc
cmd/cat-main.go
newPrettyStdout
func newPrettyStdout(w io.Writer) *prettyStdout { return &prettyStdout{ writer: w, buffer: bytes.NewBuffer([]byte{}), } }
go
func newPrettyStdout(w io.Writer) *prettyStdout { return &prettyStdout{ writer: w, buffer: bytes.NewBuffer([]byte{}), } }
[ "func", "newPrettyStdout", "(", "w", "io", ".", "Writer", ")", "*", "prettyStdout", "{", "return", "&", "prettyStdout", "{", "writer", ":", "w", ",", "buffer", ":", "bytes", ".", "NewBuffer", "(", "[", "]", "byte", "{", "}", ")", ",", "}", "\n", "}" ]
// newPrettyStdout returns an initialized prettyStdout struct
[ "newPrettyStdout", "returns", "an", "initialized", "prettyStdout", "struct" ]
f0f156aca82e451c80b05d5be8eb01a04fee29dd
https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/cat-main.go#L88-L93
train
minio/mc
cmd/cat-main.go
checkCatSyntax
func checkCatSyntax(ctx *cli.Context) { args := ctx.Args() if !args.Present() { args = []string{"-"} } for _, arg := range args { if strings.HasPrefix(arg, "-") && len(arg) > 1 { fatalIf(probe.NewError(errors.New("")), fmt.Sprintf("Unknown flag `%s` passed.", arg)) } } }
go
func checkCatSyntax(ctx *cli.Context) { args := ctx.Args() if !args.Present() { args = []string{"-"} } for _, arg := range args { if strings.HasPrefix(arg, "-") && len(arg) > 1 { fatalIf(probe.NewError(errors.New("")), fmt.Sprintf("Unknown flag `%s` passed.", arg)) } } }
[ "func", "checkCatSyntax", "(", "ctx", "*", "cli", ".", "Context", ")", "{", "args", ":=", "ctx", ".", "Args", "(", ")", "\n", "if", "!", "args", ".", "Present", "(", ")", "{", "args", "=", "[", "]", "string", "{", "\"", "\"", "}", "\n", "}", "\n", "for", "_", ",", "arg", ":=", "range", "args", "{", "if", "strings", ".", "HasPrefix", "(", "arg", ",", "\"", "\"", ")", "&&", "len", "(", "arg", ")", ">", "1", "{", "fatalIf", "(", "probe", ".", "NewError", "(", "errors", ".", "New", "(", "\"", "\"", ")", ")", ",", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "arg", ")", ")", "\n", "}", "\n", "}", "\n", "}" ]
// checkCatSyntax performs command-line input validation for cat command.
[ "checkCatSyntax", "performs", "command", "-", "line", "input", "validation", "for", "cat", "command", "." ]
f0f156aca82e451c80b05d5be8eb01a04fee29dd
https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/cat-main.go#L127-L137
train
minio/mc
cmd/cat-main.go
catURL
func catURL(sourceURL string, encKeyDB map[string][]prefixSSEPair) *probe.Error { var reader io.ReadCloser size := int64(-1) switch sourceURL { case "-": reader = os.Stdin default: var err *probe.Error // Try to stat the object, the purpose is to extract the // size of S3 object so we can check if the size of the // downloaded object is equal to the original one. FS files // are ignored since some of them have zero size though they // have contents like files under /proc. client, content, err := url2Stat(sourceURL, false, encKeyDB) if err == nil && client.GetURL().Type == objectStorage { size = content.Size } if reader, err = getSourceStreamFromURL(sourceURL, encKeyDB); err != nil { return err.Trace(sourceURL) } defer reader.Close() } return catOut(reader, size).Trace(sourceURL) }
go
func catURL(sourceURL string, encKeyDB map[string][]prefixSSEPair) *probe.Error { var reader io.ReadCloser size := int64(-1) switch sourceURL { case "-": reader = os.Stdin default: var err *probe.Error // Try to stat the object, the purpose is to extract the // size of S3 object so we can check if the size of the // downloaded object is equal to the original one. FS files // are ignored since some of them have zero size though they // have contents like files under /proc. client, content, err := url2Stat(sourceURL, false, encKeyDB) if err == nil && client.GetURL().Type == objectStorage { size = content.Size } if reader, err = getSourceStreamFromURL(sourceURL, encKeyDB); err != nil { return err.Trace(sourceURL) } defer reader.Close() } return catOut(reader, size).Trace(sourceURL) }
[ "func", "catURL", "(", "sourceURL", "string", ",", "encKeyDB", "map", "[", "string", "]", "[", "]", "prefixSSEPair", ")", "*", "probe", ".", "Error", "{", "var", "reader", "io", ".", "ReadCloser", "\n", "size", ":=", "int64", "(", "-", "1", ")", "\n", "switch", "sourceURL", "{", "case", "\"", "\"", ":", "reader", "=", "os", ".", "Stdin", "\n", "default", ":", "var", "err", "*", "probe", ".", "Error", "\n", "// Try to stat the object, the purpose is to extract the", "// size of S3 object so we can check if the size of the", "// downloaded object is equal to the original one. FS files", "// are ignored since some of them have zero size though they", "// have contents like files under /proc.", "client", ",", "content", ",", "err", ":=", "url2Stat", "(", "sourceURL", ",", "false", ",", "encKeyDB", ")", "\n", "if", "err", "==", "nil", "&&", "client", ".", "GetURL", "(", ")", ".", "Type", "==", "objectStorage", "{", "size", "=", "content", ".", "Size", "\n", "}", "\n", "if", "reader", ",", "err", "=", "getSourceStreamFromURL", "(", "sourceURL", ",", "encKeyDB", ")", ";", "err", "!=", "nil", "{", "return", "err", ".", "Trace", "(", "sourceURL", ")", "\n", "}", "\n", "defer", "reader", ".", "Close", "(", ")", "\n", "}", "\n", "return", "catOut", "(", "reader", ",", "size", ")", ".", "Trace", "(", "sourceURL", ")", "\n", "}" ]
// catURL displays contents of a URL to stdout.
[ "catURL", "displays", "contents", "of", "a", "URL", "to", "stdout", "." ]
f0f156aca82e451c80b05d5be8eb01a04fee29dd
https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/cat-main.go#L140-L163
train
minio/mc
cmd/cat-main.go
mainCat
func mainCat(ctx *cli.Context) error { // Parse encryption keys per command. encKeyDB, err := getEncKeys(ctx) fatalIf(err, "Unable to parse encryption keys.") // check 'cat' cli arguments. checkCatSyntax(ctx) // Set command flags from context. stdinMode := false if !ctx.Args().Present() { stdinMode = true } // handle std input data. if stdinMode { fatalIf(catOut(os.Stdin, -1).Trace(), "Unable to read from standard input.") return nil } // if Args contain `-`, we need to preserve its order specially. args := []string(ctx.Args()) if ctx.Args().First() == "-" { for i, arg := range os.Args { if arg == "cat" { // Overwrite ctx.Args with os.Args. args = os.Args[i+1:] break } } } // Convert arguments to URLs: expand alias, fix format. for _, url := range args { fatalIf(catURL(url, encKeyDB).Trace(url), "Unable to read from `"+url+"`.") } return nil }
go
func mainCat(ctx *cli.Context) error { // Parse encryption keys per command. encKeyDB, err := getEncKeys(ctx) fatalIf(err, "Unable to parse encryption keys.") // check 'cat' cli arguments. checkCatSyntax(ctx) // Set command flags from context. stdinMode := false if !ctx.Args().Present() { stdinMode = true } // handle std input data. if stdinMode { fatalIf(catOut(os.Stdin, -1).Trace(), "Unable to read from standard input.") return nil } // if Args contain `-`, we need to preserve its order specially. args := []string(ctx.Args()) if ctx.Args().First() == "-" { for i, arg := range os.Args { if arg == "cat" { // Overwrite ctx.Args with os.Args. args = os.Args[i+1:] break } } } // Convert arguments to URLs: expand alias, fix format. for _, url := range args { fatalIf(catURL(url, encKeyDB).Trace(url), "Unable to read from `"+url+"`.") } return nil }
[ "func", "mainCat", "(", "ctx", "*", "cli", ".", "Context", ")", "error", "{", "// Parse encryption keys per command.", "encKeyDB", ",", "err", ":=", "getEncKeys", "(", "ctx", ")", "\n", "fatalIf", "(", "err", ",", "\"", "\"", ")", "\n\n", "// check 'cat' cli arguments.", "checkCatSyntax", "(", "ctx", ")", "\n\n", "// Set command flags from context.", "stdinMode", ":=", "false", "\n", "if", "!", "ctx", ".", "Args", "(", ")", ".", "Present", "(", ")", "{", "stdinMode", "=", "true", "\n", "}", "\n\n", "// handle std input data.", "if", "stdinMode", "{", "fatalIf", "(", "catOut", "(", "os", ".", "Stdin", ",", "-", "1", ")", ".", "Trace", "(", ")", ",", "\"", "\"", ")", "\n", "return", "nil", "\n", "}", "\n\n", "// if Args contain `-`, we need to preserve its order specially.", "args", ":=", "[", "]", "string", "(", "ctx", ".", "Args", "(", ")", ")", "\n", "if", "ctx", ".", "Args", "(", ")", ".", "First", "(", ")", "==", "\"", "\"", "{", "for", "i", ",", "arg", ":=", "range", "os", ".", "Args", "{", "if", "arg", "==", "\"", "\"", "{", "// Overwrite ctx.Args with os.Args.", "args", "=", "os", ".", "Args", "[", "i", "+", "1", ":", "]", "\n", "break", "\n", "}", "\n", "}", "\n", "}", "\n\n", "// Convert arguments to URLs: expand alias, fix format.", "for", "_", ",", "url", ":=", "range", "args", "{", "fatalIf", "(", "catURL", "(", "url", ",", "encKeyDB", ")", ".", "Trace", "(", "url", ")", ",", "\"", "\"", "+", "url", "+", "\"", "\"", ")", "\n", "}", "\n\n", "return", "nil", "\n", "}" ]
// mainCat is the main entry point for cat command.
[ "mainCat", "is", "the", "main", "entry", "point", "for", "cat", "command", "." ]
f0f156aca82e451c80b05d5be8eb01a04fee29dd
https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/cat-main.go#L211-L249
train
minio/mc
cmd/mb-main.go
mainMakeBucket
func mainMakeBucket(ctx *cli.Context) error { // check 'mb' cli arguments. checkMakeBucketSyntax(ctx) // Additional command speific theme customization. console.SetColor("MakeBucket", color.New(color.FgGreen, color.Bold)) // Save region. region := ctx.String("region") ignoreExisting := ctx.Bool("p") var cErr error for _, targetURL := range ctx.Args() { // Instantiate client for URL. clnt, err := newClient(targetURL) if err != nil { errorIf(err.Trace(targetURL), "Invalid target `"+targetURL+"`.") cErr = exitStatus(globalErrorExitStatus) continue } // Make bucket. err = clnt.MakeBucket(region, ignoreExisting) if err != nil { switch err.ToGoError().(type) { case BucketNameEmpty: errorIf(err.Trace(targetURL), "Unable to make bucket, please use `mc mb %s/<your-bucket-name>`.", targetURL) case BucketNameTopLevel: errorIf(err.Trace(targetURL), "Unable to make prefix, please use `mc mb %s/`.", targetURL) default: errorIf(err.Trace(targetURL), "Unable to make bucket `"+targetURL+"`.") } cErr = exitStatus(globalErrorExitStatus) continue } // Successfully created a bucket. printMsg(makeBucketMessage{Status: "success", Bucket: targetURL}) } return cErr }
go
func mainMakeBucket(ctx *cli.Context) error { // check 'mb' cli arguments. checkMakeBucketSyntax(ctx) // Additional command speific theme customization. console.SetColor("MakeBucket", color.New(color.FgGreen, color.Bold)) // Save region. region := ctx.String("region") ignoreExisting := ctx.Bool("p") var cErr error for _, targetURL := range ctx.Args() { // Instantiate client for URL. clnt, err := newClient(targetURL) if err != nil { errorIf(err.Trace(targetURL), "Invalid target `"+targetURL+"`.") cErr = exitStatus(globalErrorExitStatus) continue } // Make bucket. err = clnt.MakeBucket(region, ignoreExisting) if err != nil { switch err.ToGoError().(type) { case BucketNameEmpty: errorIf(err.Trace(targetURL), "Unable to make bucket, please use `mc mb %s/<your-bucket-name>`.", targetURL) case BucketNameTopLevel: errorIf(err.Trace(targetURL), "Unable to make prefix, please use `mc mb %s/`.", targetURL) default: errorIf(err.Trace(targetURL), "Unable to make bucket `"+targetURL+"`.") } cErr = exitStatus(globalErrorExitStatus) continue } // Successfully created a bucket. printMsg(makeBucketMessage{Status: "success", Bucket: targetURL}) } return cErr }
[ "func", "mainMakeBucket", "(", "ctx", "*", "cli", ".", "Context", ")", "error", "{", "// check 'mb' cli arguments.", "checkMakeBucketSyntax", "(", "ctx", ")", "\n\n", "// Additional command speific theme customization.", "console", ".", "SetColor", "(", "\"", "\"", ",", "color", ".", "New", "(", "color", ".", "FgGreen", ",", "color", ".", "Bold", ")", ")", "\n\n", "// Save region.", "region", ":=", "ctx", ".", "String", "(", "\"", "\"", ")", "\n", "ignoreExisting", ":=", "ctx", ".", "Bool", "(", "\"", "\"", ")", "\n\n", "var", "cErr", "error", "\n", "for", "_", ",", "targetURL", ":=", "range", "ctx", ".", "Args", "(", ")", "{", "// Instantiate client for URL.", "clnt", ",", "err", ":=", "newClient", "(", "targetURL", ")", "\n", "if", "err", "!=", "nil", "{", "errorIf", "(", "err", ".", "Trace", "(", "targetURL", ")", ",", "\"", "\"", "+", "targetURL", "+", "\"", "\"", ")", "\n", "cErr", "=", "exitStatus", "(", "globalErrorExitStatus", ")", "\n", "continue", "\n", "}", "\n\n", "// Make bucket.", "err", "=", "clnt", ".", "MakeBucket", "(", "region", ",", "ignoreExisting", ")", "\n", "if", "err", "!=", "nil", "{", "switch", "err", ".", "ToGoError", "(", ")", ".", "(", "type", ")", "{", "case", "BucketNameEmpty", ":", "errorIf", "(", "err", ".", "Trace", "(", "targetURL", ")", ",", "\"", "\"", ",", "targetURL", ")", "\n", "case", "BucketNameTopLevel", ":", "errorIf", "(", "err", ".", "Trace", "(", "targetURL", ")", ",", "\"", "\"", ",", "targetURL", ")", "\n", "default", ":", "errorIf", "(", "err", ".", "Trace", "(", "targetURL", ")", ",", "\"", "\"", "+", "targetURL", "+", "\"", "\"", ")", "\n", "}", "\n", "cErr", "=", "exitStatus", "(", "globalErrorExitStatus", ")", "\n", "continue", "\n", "}", "\n\n", "// Successfully created a bucket.", "printMsg", "(", "makeBucketMessage", "{", "Status", ":", "\"", "\"", ",", "Bucket", ":", "targetURL", "}", ")", "\n", "}", "\n", "return", "cErr", "\n", "}" ]
// mainMakeBucket is entry point for mb command.
[ "mainMakeBucket", "is", "entry", "point", "for", "mb", "command", "." ]
f0f156aca82e451c80b05d5be8eb01a04fee29dd
https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/mb-main.go#L104-L145
train
minio/mc
cmd/humanized-duration.go
timeDurationToHumanizedDuration
func timeDurationToHumanizedDuration(duration time.Duration) humanizedDuration { r := humanizedDuration{} if duration.Seconds() < 60.0 { r.Seconds = int64(duration.Seconds()) return r } if duration.Minutes() < 60.0 { remainingSeconds := math.Mod(duration.Seconds(), 60) r.Seconds = int64(remainingSeconds) r.Minutes = int64(duration.Minutes()) return r } if duration.Hours() < 24.0 { remainingMinutes := math.Mod(duration.Minutes(), 60) remainingSeconds := math.Mod(duration.Seconds(), 60) r.Seconds = int64(remainingSeconds) r.Minutes = int64(remainingMinutes) r.Hours = int64(duration.Hours()) return r } remainingHours := math.Mod(duration.Hours(), 24) remainingMinutes := math.Mod(duration.Minutes(), 60) remainingSeconds := math.Mod(duration.Seconds(), 60) r.Hours = int64(remainingHours) r.Minutes = int64(remainingMinutes) r.Seconds = int64(remainingSeconds) r.Days = int64(duration.Hours() / 24) return r }
go
func timeDurationToHumanizedDuration(duration time.Duration) humanizedDuration { r := humanizedDuration{} if duration.Seconds() < 60.0 { r.Seconds = int64(duration.Seconds()) return r } if duration.Minutes() < 60.0 { remainingSeconds := math.Mod(duration.Seconds(), 60) r.Seconds = int64(remainingSeconds) r.Minutes = int64(duration.Minutes()) return r } if duration.Hours() < 24.0 { remainingMinutes := math.Mod(duration.Minutes(), 60) remainingSeconds := math.Mod(duration.Seconds(), 60) r.Seconds = int64(remainingSeconds) r.Minutes = int64(remainingMinutes) r.Hours = int64(duration.Hours()) return r } remainingHours := math.Mod(duration.Hours(), 24) remainingMinutes := math.Mod(duration.Minutes(), 60) remainingSeconds := math.Mod(duration.Seconds(), 60) r.Hours = int64(remainingHours) r.Minutes = int64(remainingMinutes) r.Seconds = int64(remainingSeconds) r.Days = int64(duration.Hours() / 24) return r }
[ "func", "timeDurationToHumanizedDuration", "(", "duration", "time", ".", "Duration", ")", "humanizedDuration", "{", "r", ":=", "humanizedDuration", "{", "}", "\n", "if", "duration", ".", "Seconds", "(", ")", "<", "60.0", "{", "r", ".", "Seconds", "=", "int64", "(", "duration", ".", "Seconds", "(", ")", ")", "\n", "return", "r", "\n", "}", "\n", "if", "duration", ".", "Minutes", "(", ")", "<", "60.0", "{", "remainingSeconds", ":=", "math", ".", "Mod", "(", "duration", ".", "Seconds", "(", ")", ",", "60", ")", "\n", "r", ".", "Seconds", "=", "int64", "(", "remainingSeconds", ")", "\n", "r", ".", "Minutes", "=", "int64", "(", "duration", ".", "Minutes", "(", ")", ")", "\n", "return", "r", "\n", "}", "\n", "if", "duration", ".", "Hours", "(", ")", "<", "24.0", "{", "remainingMinutes", ":=", "math", ".", "Mod", "(", "duration", ".", "Minutes", "(", ")", ",", "60", ")", "\n", "remainingSeconds", ":=", "math", ".", "Mod", "(", "duration", ".", "Seconds", "(", ")", ",", "60", ")", "\n", "r", ".", "Seconds", "=", "int64", "(", "remainingSeconds", ")", "\n", "r", ".", "Minutes", "=", "int64", "(", "remainingMinutes", ")", "\n", "r", ".", "Hours", "=", "int64", "(", "duration", ".", "Hours", "(", ")", ")", "\n", "return", "r", "\n", "}", "\n", "remainingHours", ":=", "math", ".", "Mod", "(", "duration", ".", "Hours", "(", ")", ",", "24", ")", "\n", "remainingMinutes", ":=", "math", ".", "Mod", "(", "duration", ".", "Minutes", "(", ")", ",", "60", ")", "\n", "remainingSeconds", ":=", "math", ".", "Mod", "(", "duration", ".", "Seconds", "(", ")", ",", "60", ")", "\n", "r", ".", "Hours", "=", "int64", "(", "remainingHours", ")", "\n", "r", ".", "Minutes", "=", "int64", "(", "remainingMinutes", ")", "\n", "r", ".", "Seconds", "=", "int64", "(", "remainingSeconds", ")", "\n", "r", ".", "Days", "=", "int64", "(", "duration", ".", "Hours", "(", ")", "/", "24", ")", "\n", "return", "r", "\n", "}" ]
// timeDurationToHumanizedDuration convert golang time.Duration to a custom more readable humanizedDuration.
[ "timeDurationToHumanizedDuration", "convert", "golang", "time", ".", "Duration", "to", "a", "custom", "more", "readable", "humanizedDuration", "." ]
f0f156aca82e451c80b05d5be8eb01a04fee29dd
https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/humanized-duration.go#L60-L88
train
minio/mc
cmd/admin-heal-result-item.go
getObjectHCCChange
func (h hri) getObjectHCCChange() (b, a col, err error) { parityShards := h.ParityBlocks dataShards := h.DataBlocks onlineBefore, onlineAfter := h.GetOnlineCounts() surplusShardsBeforeHeal := onlineBefore - dataShards surplusShardsAfterHeal := onlineAfter - dataShards b, err = getHColCode(surplusShardsBeforeHeal, parityShards) if err != nil { return } a, err = getHColCode(surplusShardsAfterHeal, parityShards) return }
go
func (h hri) getObjectHCCChange() (b, a col, err error) { parityShards := h.ParityBlocks dataShards := h.DataBlocks onlineBefore, onlineAfter := h.GetOnlineCounts() surplusShardsBeforeHeal := onlineBefore - dataShards surplusShardsAfterHeal := onlineAfter - dataShards b, err = getHColCode(surplusShardsBeforeHeal, parityShards) if err != nil { return } a, err = getHColCode(surplusShardsAfterHeal, parityShards) return }
[ "func", "(", "h", "hri", ")", "getObjectHCCChange", "(", ")", "(", "b", ",", "a", "col", ",", "err", "error", ")", "{", "parityShards", ":=", "h", ".", "ParityBlocks", "\n", "dataShards", ":=", "h", ".", "DataBlocks", "\n\n", "onlineBefore", ",", "onlineAfter", ":=", "h", ".", "GetOnlineCounts", "(", ")", "\n", "surplusShardsBeforeHeal", ":=", "onlineBefore", "-", "dataShards", "\n", "surplusShardsAfterHeal", ":=", "onlineAfter", "-", "dataShards", "\n\n", "b", ",", "err", "=", "getHColCode", "(", "surplusShardsBeforeHeal", ",", "parityShards", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\n", "}", "\n", "a", ",", "err", "=", "getHColCode", "(", "surplusShardsAfterHeal", ",", "parityShards", ")", "\n", "return", "\n\n", "}" ]
// getObjectHCCChange - returns before and after color change for // objects
[ "getObjectHCCChange", "-", "returns", "before", "and", "after", "color", "change", "for", "objects" ]
f0f156aca82e451c80b05d5be8eb01a04fee29dd
https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/admin-heal-result-item.go#L35-L50
train
minio/mc
cmd/admin-heal-result-item.go
getReplicatedFileHCCChange
func (h hri) getReplicatedFileHCCChange() (b, a col, err error) { getColCode := func(numAvail int) (c col, err error) { // calculate color code for replicated object similar // to erasure coded objects quorum := h.DiskCount/h.SetCount/2 + 1 surplus := numAvail/h.SetCount - quorum parity := h.DiskCount/h.SetCount - quorum c, err = getHColCode(surplus, parity) return } onlineBefore, onlineAfter := h.GetOnlineCounts() b, err = getColCode(onlineBefore) if err != nil { return } a, err = getColCode(onlineAfter) return }
go
func (h hri) getReplicatedFileHCCChange() (b, a col, err error) { getColCode := func(numAvail int) (c col, err error) { // calculate color code for replicated object similar // to erasure coded objects quorum := h.DiskCount/h.SetCount/2 + 1 surplus := numAvail/h.SetCount - quorum parity := h.DiskCount/h.SetCount - quorum c, err = getHColCode(surplus, parity) return } onlineBefore, onlineAfter := h.GetOnlineCounts() b, err = getColCode(onlineBefore) if err != nil { return } a, err = getColCode(onlineAfter) return }
[ "func", "(", "h", "hri", ")", "getReplicatedFileHCCChange", "(", ")", "(", "b", ",", "a", "col", ",", "err", "error", ")", "{", "getColCode", ":=", "func", "(", "numAvail", "int", ")", "(", "c", "col", ",", "err", "error", ")", "{", "// calculate color code for replicated object similar", "// to erasure coded objects", "quorum", ":=", "h", ".", "DiskCount", "/", "h", ".", "SetCount", "/", "2", "+", "1", "\n", "surplus", ":=", "numAvail", "/", "h", ".", "SetCount", "-", "quorum", "\n", "parity", ":=", "h", ".", "DiskCount", "/", "h", ".", "SetCount", "-", "quorum", "\n", "c", ",", "err", "=", "getHColCode", "(", "surplus", ",", "parity", ")", "\n", "return", "\n", "}", "\n\n", "onlineBefore", ",", "onlineAfter", ":=", "h", ".", "GetOnlineCounts", "(", ")", "\n", "b", ",", "err", "=", "getColCode", "(", "onlineBefore", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\n", "}", "\n", "a", ",", "err", "=", "getColCode", "(", "onlineAfter", ")", "\n", "return", "\n", "}" ]
// getReplicatedFileHCCChange - fetches health color code for metadata // files that are replicated.
[ "getReplicatedFileHCCChange", "-", "fetches", "health", "color", "code", "for", "metadata", "files", "that", "are", "replicated", "." ]
f0f156aca82e451c80b05d5be8eb01a04fee29dd
https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/admin-heal-result-item.go#L54-L72
train
minio/mc
cmd/event-list.go
checkEventListSyntax
func checkEventListSyntax(ctx *cli.Context) { if len(ctx.Args()) != 2 && len(ctx.Args()) != 1 { cli.ShowCommandHelpAndExit(ctx, "list", 1) // last argument is exit code } }
go
func checkEventListSyntax(ctx *cli.Context) { if len(ctx.Args()) != 2 && len(ctx.Args()) != 1 { cli.ShowCommandHelpAndExit(ctx, "list", 1) // last argument is exit code } }
[ "func", "checkEventListSyntax", "(", "ctx", "*", "cli", ".", "Context", ")", "{", "if", "len", "(", "ctx", ".", "Args", "(", ")", ")", "!=", "2", "&&", "len", "(", "ctx", ".", "Args", "(", ")", ")", "!=", "1", "{", "cli", ".", "ShowCommandHelpAndExit", "(", "ctx", ",", "\"", "\"", ",", "1", ")", "// last argument is exit code", "\n", "}", "\n", "}" ]
// checkEventListSyntax - validate all the passed arguments
[ "checkEventListSyntax", "-", "validate", "all", "the", "passed", "arguments" ]
f0f156aca82e451c80b05d5be8eb01a04fee29dd
https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/event-list.go#L59-L63
train
minio/mc
cmd/config-host-add.go
checkConfigHostAddSyntax
func checkConfigHostAddSyntax(ctx *cli.Context) { args := ctx.Args() argsNr := len(args) if argsNr < 4 || argsNr > 5 { fatalIf(errInvalidArgument().Trace(ctx.Args().Tail()...), "Incorrect number of arguments for host add command.") } alias := args.Get(0) url := args.Get(1) accessKey := args.Get(2) secretKey := args.Get(3) api := ctx.String("api") bucketLookup := ctx.String("lookup") if !isValidAlias(alias) { fatalIf(errInvalidAlias(alias), "Invalid alias.") } if !isValidHostURL(url) { fatalIf(errInvalidURL(url), "Invalid URL.") } if !isValidAccessKey(accessKey) { fatalIf(errInvalidArgument().Trace(accessKey), "Invalid access key `"+accessKey+"`.") } if !isValidSecretKey(secretKey) { fatalIf(errInvalidArgument().Trace(secretKey), "Invalid secret key `"+secretKey+"`.") } if api != "" && !isValidAPI(api) { // Empty value set to default "S3v4". fatalIf(errInvalidArgument().Trace(api), "Unrecognized API signature. Valid options are `[S3v4, S3v2]`.") } if !isValidLookup(bucketLookup) { fatalIf(errInvalidArgument().Trace(bucketLookup), "Unrecognized bucket lookup. Valid options are `[dns,auto, path]`.") } }
go
func checkConfigHostAddSyntax(ctx *cli.Context) { args := ctx.Args() argsNr := len(args) if argsNr < 4 || argsNr > 5 { fatalIf(errInvalidArgument().Trace(ctx.Args().Tail()...), "Incorrect number of arguments for host add command.") } alias := args.Get(0) url := args.Get(1) accessKey := args.Get(2) secretKey := args.Get(3) api := ctx.String("api") bucketLookup := ctx.String("lookup") if !isValidAlias(alias) { fatalIf(errInvalidAlias(alias), "Invalid alias.") } if !isValidHostURL(url) { fatalIf(errInvalidURL(url), "Invalid URL.") } if !isValidAccessKey(accessKey) { fatalIf(errInvalidArgument().Trace(accessKey), "Invalid access key `"+accessKey+"`.") } if !isValidSecretKey(secretKey) { fatalIf(errInvalidArgument().Trace(secretKey), "Invalid secret key `"+secretKey+"`.") } if api != "" && !isValidAPI(api) { // Empty value set to default "S3v4". fatalIf(errInvalidArgument().Trace(api), "Unrecognized API signature. Valid options are `[S3v4, S3v2]`.") } if !isValidLookup(bucketLookup) { fatalIf(errInvalidArgument().Trace(bucketLookup), "Unrecognized bucket lookup. Valid options are `[dns,auto, path]`.") } }
[ "func", "checkConfigHostAddSyntax", "(", "ctx", "*", "cli", ".", "Context", ")", "{", "args", ":=", "ctx", ".", "Args", "(", ")", "\n", "argsNr", ":=", "len", "(", "args", ")", "\n", "if", "argsNr", "<", "4", "||", "argsNr", ">", "5", "{", "fatalIf", "(", "errInvalidArgument", "(", ")", ".", "Trace", "(", "ctx", ".", "Args", "(", ")", ".", "Tail", "(", ")", "...", ")", ",", "\"", "\"", ")", "\n", "}", "\n\n", "alias", ":=", "args", ".", "Get", "(", "0", ")", "\n", "url", ":=", "args", ".", "Get", "(", "1", ")", "\n", "accessKey", ":=", "args", ".", "Get", "(", "2", ")", "\n", "secretKey", ":=", "args", ".", "Get", "(", "3", ")", "\n", "api", ":=", "ctx", ".", "String", "(", "\"", "\"", ")", "\n", "bucketLookup", ":=", "ctx", ".", "String", "(", "\"", "\"", ")", "\n", "if", "!", "isValidAlias", "(", "alias", ")", "{", "fatalIf", "(", "errInvalidAlias", "(", "alias", ")", ",", "\"", "\"", ")", "\n", "}", "\n\n", "if", "!", "isValidHostURL", "(", "url", ")", "{", "fatalIf", "(", "errInvalidURL", "(", "url", ")", ",", "\"", "\"", ")", "\n", "}", "\n\n", "if", "!", "isValidAccessKey", "(", "accessKey", ")", "{", "fatalIf", "(", "errInvalidArgument", "(", ")", ".", "Trace", "(", "accessKey", ")", ",", "\"", "\"", "+", "accessKey", "+", "\"", "\"", ")", "\n", "}", "\n\n", "if", "!", "isValidSecretKey", "(", "secretKey", ")", "{", "fatalIf", "(", "errInvalidArgument", "(", ")", ".", "Trace", "(", "secretKey", ")", ",", "\"", "\"", "+", "secretKey", "+", "\"", "\"", ")", "\n", "}", "\n\n", "if", "api", "!=", "\"", "\"", "&&", "!", "isValidAPI", "(", "api", ")", "{", "// Empty value set to default \"S3v4\".", "fatalIf", "(", "errInvalidArgument", "(", ")", ".", "Trace", "(", "api", ")", ",", "\"", "\"", ")", "\n", "}", "\n\n", "if", "!", "isValidLookup", "(", "bucketLookup", ")", "{", "fatalIf", "(", "errInvalidArgument", "(", ")", ".", "Trace", "(", "bucketLookup", ")", ",", "\"", "\"", ")", "\n", "}", "\n", "}" ]
// checkConfigHostAddSyntax - verifies input arguments to 'config host add'.
[ "checkConfigHostAddSyntax", "-", "verifies", "input", "arguments", "to", "config", "host", "add", "." ]
f0f156aca82e451c80b05d5be8eb01a04fee29dd
https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/config-host-add.go#L87-L128
train
minio/mc
cmd/config-host-add.go
addHost
func addHost(alias string, hostCfgV9 hostConfigV9) { mcCfgV9, err := loadMcConfig() fatalIf(err.Trace(globalMCConfigVersion), "Unable to load config `"+mustGetMcConfigPath()+"`.") // Add new host. mcCfgV9.Hosts[alias] = hostCfgV9 err = saveMcConfig(mcCfgV9) fatalIf(err.Trace(alias), "Unable to update hosts in config version `"+mustGetMcConfigPath()+"`.") printMsg(hostMessage{ op: "add", Alias: alias, URL: hostCfgV9.URL, AccessKey: hostCfgV9.AccessKey, SecretKey: hostCfgV9.SecretKey, API: hostCfgV9.API, Lookup: hostCfgV9.Lookup, }) }
go
func addHost(alias string, hostCfgV9 hostConfigV9) { mcCfgV9, err := loadMcConfig() fatalIf(err.Trace(globalMCConfigVersion), "Unable to load config `"+mustGetMcConfigPath()+"`.") // Add new host. mcCfgV9.Hosts[alias] = hostCfgV9 err = saveMcConfig(mcCfgV9) fatalIf(err.Trace(alias), "Unable to update hosts in config version `"+mustGetMcConfigPath()+"`.") printMsg(hostMessage{ op: "add", Alias: alias, URL: hostCfgV9.URL, AccessKey: hostCfgV9.AccessKey, SecretKey: hostCfgV9.SecretKey, API: hostCfgV9.API, Lookup: hostCfgV9.Lookup, }) }
[ "func", "addHost", "(", "alias", "string", ",", "hostCfgV9", "hostConfigV9", ")", "{", "mcCfgV9", ",", "err", ":=", "loadMcConfig", "(", ")", "\n", "fatalIf", "(", "err", ".", "Trace", "(", "globalMCConfigVersion", ")", ",", "\"", "\"", "+", "mustGetMcConfigPath", "(", ")", "+", "\"", "\"", ")", "\n\n", "// Add new host.", "mcCfgV9", ".", "Hosts", "[", "alias", "]", "=", "hostCfgV9", "\n\n", "err", "=", "saveMcConfig", "(", "mcCfgV9", ")", "\n", "fatalIf", "(", "err", ".", "Trace", "(", "alias", ")", ",", "\"", "\"", "+", "mustGetMcConfigPath", "(", ")", "+", "\"", "\"", ")", "\n\n", "printMsg", "(", "hostMessage", "{", "op", ":", "\"", "\"", ",", "Alias", ":", "alias", ",", "URL", ":", "hostCfgV9", ".", "URL", ",", "AccessKey", ":", "hostCfgV9", ".", "AccessKey", ",", "SecretKey", ":", "hostCfgV9", ".", "SecretKey", ",", "API", ":", "hostCfgV9", ".", "API", ",", "Lookup", ":", "hostCfgV9", ".", "Lookup", ",", "}", ")", "\n", "}" ]
// addHost - add a host config.
[ "addHost", "-", "add", "a", "host", "config", "." ]
f0f156aca82e451c80b05d5be8eb01a04fee29dd
https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/config-host-add.go#L131-L150
train
minio/mc
cmd/config-host-add.go
buildS3Config
func buildS3Config(url, accessKey, secretKey, api, lookup string) (*Config, *probe.Error) { s3Config := newS3Config(url, &hostConfigV9{ AccessKey: accessKey, SecretKey: secretKey, URL: url, Lookup: lookup, }) // If api is provided we do not auto probe signature, this is // required in situations when signature type is provided by the user. if api != "" { s3Config.Signature = api return s3Config, nil } // Probe S3 signature version api, err := probeS3Signature(accessKey, secretKey, url) if err != nil { return nil, err.Trace(url, accessKey, secretKey, api, lookup) } s3Config.Signature = api // Success. return s3Config, nil }
go
func buildS3Config(url, accessKey, secretKey, api, lookup string) (*Config, *probe.Error) { s3Config := newS3Config(url, &hostConfigV9{ AccessKey: accessKey, SecretKey: secretKey, URL: url, Lookup: lookup, }) // If api is provided we do not auto probe signature, this is // required in situations when signature type is provided by the user. if api != "" { s3Config.Signature = api return s3Config, nil } // Probe S3 signature version api, err := probeS3Signature(accessKey, secretKey, url) if err != nil { return nil, err.Trace(url, accessKey, secretKey, api, lookup) } s3Config.Signature = api // Success. return s3Config, nil }
[ "func", "buildS3Config", "(", "url", ",", "accessKey", ",", "secretKey", ",", "api", ",", "lookup", "string", ")", "(", "*", "Config", ",", "*", "probe", ".", "Error", ")", "{", "s3Config", ":=", "newS3Config", "(", "url", ",", "&", "hostConfigV9", "{", "AccessKey", ":", "accessKey", ",", "SecretKey", ":", "secretKey", ",", "URL", ":", "url", ",", "Lookup", ":", "lookup", ",", "}", ")", "\n\n", "// If api is provided we do not auto probe signature, this is", "// required in situations when signature type is provided by the user.", "if", "api", "!=", "\"", "\"", "{", "s3Config", ".", "Signature", "=", "api", "\n", "return", "s3Config", ",", "nil", "\n", "}", "\n", "// Probe S3 signature version", "api", ",", "err", ":=", "probeS3Signature", "(", "accessKey", ",", "secretKey", ",", "url", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", ".", "Trace", "(", "url", ",", "accessKey", ",", "secretKey", ",", "api", ",", "lookup", ")", "\n", "}", "\n\n", "s3Config", ".", "Signature", "=", "api", "\n", "// Success.", "return", "s3Config", ",", "nil", "\n", "}" ]
// buildS3Config constructs an S3 Config and does // signature auto-probe when needed.
[ "buildS3Config", "constructs", "an", "S3", "Config", "and", "does", "signature", "auto", "-", "probe", "when", "needed", "." ]
f0f156aca82e451c80b05d5be8eb01a04fee29dd
https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/config-host-add.go#L198-L222
train
minio/mc
pkg/colorjson/scanner.go
eof
func (s *scanner) eof() int { if s.err != nil { return scanError } if s.endTop { return scanEnd } s.step(s, ' ') if s.endTop { return scanEnd } if s.err == nil { s.err = &SyntaxError{"unexpected end of JSON input", s.bytes} } return scanError }
go
func (s *scanner) eof() int { if s.err != nil { return scanError } if s.endTop { return scanEnd } s.step(s, ' ') if s.endTop { return scanEnd } if s.err == nil { s.err = &SyntaxError{"unexpected end of JSON input", s.bytes} } return scanError }
[ "func", "(", "s", "*", "scanner", ")", "eof", "(", ")", "int", "{", "if", "s", ".", "err", "!=", "nil", "{", "return", "scanError", "\n", "}", "\n", "if", "s", ".", "endTop", "{", "return", "scanEnd", "\n", "}", "\n", "s", ".", "step", "(", "s", ",", "' '", ")", "\n", "if", "s", ".", "endTop", "{", "return", "scanEnd", "\n", "}", "\n", "if", "s", ".", "err", "==", "nil", "{", "s", ".", "err", "=", "&", "SyntaxError", "{", "\"", "\"", ",", "s", ".", "bytes", "}", "\n", "}", "\n", "return", "scanError", "\n", "}" ]
// eof tells the scanner that the end of input has been reached. // It returns a scan status just as s.step does.
[ "eof", "tells", "the", "scanner", "that", "the", "end", "of", "input", "has", "been", "reached", ".", "It", "returns", "a", "scan", "status", "just", "as", "s", ".", "step", "does", "." ]
f0f156aca82e451c80b05d5be8eb01a04fee29dd
https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/pkg/colorjson/scanner.go#L137-L152
train
minio/mc
pkg/colorjson/scanner.go
stateBeginColorESC
func stateBeginColorESC(s *scanner, c byte) int { switch c { case '[': s.step = stateBeginColorRest return scanContinue } return s.error(c, "in string color escape code") }
go
func stateBeginColorESC(s *scanner, c byte) int { switch c { case '[': s.step = stateBeginColorRest return scanContinue } return s.error(c, "in string color escape code") }
[ "func", "stateBeginColorESC", "(", "s", "*", "scanner", ",", "c", "byte", ")", "int", "{", "switch", "c", "{", "case", "'['", ":", "s", ".", "step", "=", "stateBeginColorRest", "\n", "return", "scanContinue", "\n", "}", "\n", "return", "s", ".", "error", "(", "c", ",", "\"", "\"", ")", "\n", "}" ]
// stateInStringColorFirst is the state after reading the beginning of a color representation // which is \x1b
[ "stateInStringColorFirst", "is", "the", "state", "after", "reading", "the", "beginning", "of", "a", "color", "representation", "which", "is", "\\", "x1b" ]
f0f156aca82e451c80b05d5be8eb01a04fee29dd
https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/pkg/colorjson/scanner.go#L358-L365
train
minio/mc
pkg/colorjson/scanner.go
stateBeginColorRest
func stateBeginColorRest(s *scanner, c byte) int { if c <= ' ' && isSpace(c) { return scanSkipSpace } if '0' <= c && c <= '9' { s.step = stateBeginColorRest return scanContinue } switch c { case ';': s.step = stateBeginColorRest return scanContinue case 'm': s.step = stateBeginValue return scanContinue } return s.error(c, "in string color escape code") }
go
func stateBeginColorRest(s *scanner, c byte) int { if c <= ' ' && isSpace(c) { return scanSkipSpace } if '0' <= c && c <= '9' { s.step = stateBeginColorRest return scanContinue } switch c { case ';': s.step = stateBeginColorRest return scanContinue case 'm': s.step = stateBeginValue return scanContinue } return s.error(c, "in string color escape code") }
[ "func", "stateBeginColorRest", "(", "s", "*", "scanner", ",", "c", "byte", ")", "int", "{", "if", "c", "<=", "' '", "&&", "isSpace", "(", "c", ")", "{", "return", "scanSkipSpace", "\n", "}", "\n", "if", "'0'", "<=", "c", "&&", "c", "<=", "'9'", "{", "s", ".", "step", "=", "stateBeginColorRest", "\n", "return", "scanContinue", "\n", "}", "\n", "switch", "c", "{", "case", "';'", ":", "s", ".", "step", "=", "stateBeginColorRest", "\n", "return", "scanContinue", "\n", "case", "'m'", ":", "s", ".", "step", "=", "stateBeginValue", "\n", "return", "scanContinue", "\n", "}", "\n", "return", "s", ".", "error", "(", "c", ",", "\"", "\"", ")", "\n", "}" ]
// stateInStringColorSecond is the state after reading the second character of a color representation // which is \x1b[
[ "stateInStringColorSecond", "is", "the", "state", "after", "reading", "the", "second", "character", "of", "a", "color", "representation", "which", "is", "\\", "x1b", "[" ]
f0f156aca82e451c80b05d5be8eb01a04fee29dd
https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/pkg/colorjson/scanner.go#L369-L386
train
minio/mc
pkg/colorjson/scanner.go
stateInStringEscU
func stateInStringEscU(s *scanner, c byte) int { if '0' <= c && c <= '9' || 'a' <= c && c <= 'f' || 'A' <= c && c <= 'F' { s.step = stateInStringEscU1 return scanContinue } // numbers return s.error(c, "in \\u hexadecimal character escape") }
go
func stateInStringEscU(s *scanner, c byte) int { if '0' <= c && c <= '9' || 'a' <= c && c <= 'f' || 'A' <= c && c <= 'F' { s.step = stateInStringEscU1 return scanContinue } // numbers return s.error(c, "in \\u hexadecimal character escape") }
[ "func", "stateInStringEscU", "(", "s", "*", "scanner", ",", "c", "byte", ")", "int", "{", "if", "'0'", "<=", "c", "&&", "c", "<=", "'9'", "||", "'a'", "<=", "c", "&&", "c", "<=", "'f'", "||", "'A'", "<=", "c", "&&", "c", "<=", "'F'", "{", "s", ".", "step", "=", "stateInStringEscU1", "\n", "return", "scanContinue", "\n", "}", "\n", "// numbers", "return", "s", ".", "error", "(", "c", ",", "\"", "\\\\", "\"", ")", "\n", "}" ]
// stateInStringEscU is the state after reading `"\u` during a quoted string.
[ "stateInStringEscU", "is", "the", "state", "after", "reading", "\\", "u", "during", "a", "quoted", "string", "." ]
f0f156aca82e451c80b05d5be8eb01a04fee29dd
https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/pkg/colorjson/scanner.go#L407-L414
train
minio/mc
cmd/admin-info.go
checkAdminInfoSyntax
func checkAdminInfoSyntax(ctx *cli.Context) { if len(ctx.Args()) == 0 || len(ctx.Args()) > 2 { cli.ShowCommandHelpAndExit(ctx, "info", 1) // last argument is exit code } }
go
func checkAdminInfoSyntax(ctx *cli.Context) { if len(ctx.Args()) == 0 || len(ctx.Args()) > 2 { cli.ShowCommandHelpAndExit(ctx, "info", 1) // last argument is exit code } }
[ "func", "checkAdminInfoSyntax", "(", "ctx", "*", "cli", ".", "Context", ")", "{", "if", "len", "(", "ctx", ".", "Args", "(", ")", ")", "==", "0", "||", "len", "(", "ctx", ".", "Args", "(", ")", ")", ">", "2", "{", "cli", ".", "ShowCommandHelpAndExit", "(", "ctx", ",", "\"", "\"", ",", "1", ")", "// last argument is exit code", "\n", "}", "\n", "}" ]
// checkAdminInfoSyntax - validate all the passed arguments
[ "checkAdminInfoSyntax", "-", "validate", "all", "the", "passed", "arguments" ]
f0f156aca82e451c80b05d5be8eb01a04fee29dd
https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/admin-info.go#L204-L208
train
minio/mc
cmd/session-clear.go
String
func (c clearSessionMessage) String() string { msg := "Session `" + c.SessionID + "`" var colorizedMsg string switch c.Status { case "success": colorizedMsg = console.Colorize("ClearSession", msg+" cleared successfully.") case "forced": colorizedMsg = console.Colorize("ClearSession", msg+" cleared forcefully.") } return colorizedMsg }
go
func (c clearSessionMessage) String() string { msg := "Session `" + c.SessionID + "`" var colorizedMsg string switch c.Status { case "success": colorizedMsg = console.Colorize("ClearSession", msg+" cleared successfully.") case "forced": colorizedMsg = console.Colorize("ClearSession", msg+" cleared forcefully.") } return colorizedMsg }
[ "func", "(", "c", "clearSessionMessage", ")", "String", "(", ")", "string", "{", "msg", ":=", "\"", "\"", "+", "c", ".", "SessionID", "+", "\"", "\"", "\n", "var", "colorizedMsg", "string", "\n", "switch", "c", ".", "Status", "{", "case", "\"", "\"", ":", "colorizedMsg", "=", "console", ".", "Colorize", "(", "\"", "\"", ",", "msg", "+", "\"", "\"", ")", "\n", "case", "\"", "\"", ":", "colorizedMsg", "=", "console", ".", "Colorize", "(", "\"", "\"", ",", "msg", "+", "\"", "\"", ")", "\n", "}", "\n", "return", "colorizedMsg", "\n", "}" ]
// String colorized clear session message.
[ "String", "colorized", "clear", "session", "message", "." ]
f0f156aca82e451c80b05d5be8eb01a04fee29dd
https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/session-clear.go#L70-L80
train
minio/mc
cmd/session-clear.go
JSON
func (c clearSessionMessage) JSON() string { clearSessionJSONBytes, e := json.MarshalIndent(c, "", " ") fatalIf(probe.NewError(e), "Unable to marshal into JSON.") return string(clearSessionJSONBytes) }
go
func (c clearSessionMessage) JSON() string { clearSessionJSONBytes, e := json.MarshalIndent(c, "", " ") fatalIf(probe.NewError(e), "Unable to marshal into JSON.") return string(clearSessionJSONBytes) }
[ "func", "(", "c", "clearSessionMessage", ")", "JSON", "(", ")", "string", "{", "clearSessionJSONBytes", ",", "e", ":=", "json", ".", "MarshalIndent", "(", "c", ",", "\"", "\"", ",", "\"", "\"", ")", "\n", "fatalIf", "(", "probe", ".", "NewError", "(", "e", ")", ",", "\"", "\"", ")", "\n\n", "return", "string", "(", "clearSessionJSONBytes", ")", "\n", "}" ]
// JSON jsonified clear session message.
[ "JSON", "jsonified", "clear", "session", "message", "." ]
f0f156aca82e451c80b05d5be8eb01a04fee29dd
https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/session-clear.go#L83-L88
train
minio/mc
cmd/session-clear.go
clearSession
func clearSession(sid string, isForce bool) { var toRemove []string if sid == "all" { toRemove = getSessionIDs() } else { toRemove = append(toRemove, sid) } for _, sid := range toRemove { session, err := loadSessionV8(sid) if !isForce { fatalIf(err.Trace(sid), "Unable to load session `"+sid+"`. Use --force flag to remove obsolete session files.") fatalIf(session.Delete().Trace(sid), "Unable to remove session `"+sid+"`. Use --force flag to remove obsolete session files.") printMsg(clearSessionMessage{Status: "success", SessionID: sid}) continue } // Forced removal of a session. forceClear(sid, session) } return }
go
func clearSession(sid string, isForce bool) { var toRemove []string if sid == "all" { toRemove = getSessionIDs() } else { toRemove = append(toRemove, sid) } for _, sid := range toRemove { session, err := loadSessionV8(sid) if !isForce { fatalIf(err.Trace(sid), "Unable to load session `"+sid+"`. Use --force flag to remove obsolete session files.") fatalIf(session.Delete().Trace(sid), "Unable to remove session `"+sid+"`. Use --force flag to remove obsolete session files.") printMsg(clearSessionMessage{Status: "success", SessionID: sid}) continue } // Forced removal of a session. forceClear(sid, session) } return }
[ "func", "clearSession", "(", "sid", "string", ",", "isForce", "bool", ")", "{", "var", "toRemove", "[", "]", "string", "\n", "if", "sid", "==", "\"", "\"", "{", "toRemove", "=", "getSessionIDs", "(", ")", "\n", "}", "else", "{", "toRemove", "=", "append", "(", "toRemove", ",", "sid", ")", "\n", "}", "\n", "for", "_", ",", "sid", ":=", "range", "toRemove", "{", "session", ",", "err", ":=", "loadSessionV8", "(", "sid", ")", "\n", "if", "!", "isForce", "{", "fatalIf", "(", "err", ".", "Trace", "(", "sid", ")", ",", "\"", "\"", "+", "sid", "+", "\"", "\"", ")", "\n\n", "fatalIf", "(", "session", ".", "Delete", "(", ")", ".", "Trace", "(", "sid", ")", ",", "\"", "\"", "+", "sid", "+", "\"", "\"", ")", "\n\n", "printMsg", "(", "clearSessionMessage", "{", "Status", ":", "\"", "\"", ",", "SessionID", ":", "sid", "}", ")", "\n", "continue", "\n", "}", "\n", "// Forced removal of a session.", "forceClear", "(", "sid", ",", "session", ")", "\n", "}", "\n", "return", "\n", "}" ]
// clearSession clear sessions.
[ "clearSession", "clear", "sessions", "." ]
f0f156aca82e451c80b05d5be8eb01a04fee29dd
https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/session-clear.go#L107-L128
train
minio/mc
cmd/session-clear.go
checkSessionClearSyntax
func checkSessionClearSyntax(ctx *cli.Context) { if len(ctx.Args()) == 0 || len(ctx.Args()) > 2 { cli.ShowCommandHelpAndExit(ctx, "clear", 1) // last argument is exit code } }
go
func checkSessionClearSyntax(ctx *cli.Context) { if len(ctx.Args()) == 0 || len(ctx.Args()) > 2 { cli.ShowCommandHelpAndExit(ctx, "clear", 1) // last argument is exit code } }
[ "func", "checkSessionClearSyntax", "(", "ctx", "*", "cli", ".", "Context", ")", "{", "if", "len", "(", "ctx", ".", "Args", "(", ")", ")", "==", "0", "||", "len", "(", "ctx", ".", "Args", "(", ")", ")", ">", "2", "{", "cli", ".", "ShowCommandHelpAndExit", "(", "ctx", ",", "\"", "\"", ",", "1", ")", "// last argument is exit code", "\n", "}", "\n", "}" ]
// checkSessionClearSyntax - Check syntax of 'session clear sid'.
[ "checkSessionClearSyntax", "-", "Check", "syntax", "of", "session", "clear", "sid", "." ]
f0f156aca82e451c80b05d5be8eb01a04fee29dd
https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/session-clear.go#L131-L135
train
minio/mc
cmd/session-clear.go
mainSessionClear
func mainSessionClear(ctx *cli.Context) error { // Check command arguments checkSessionClearSyntax(ctx) // Additional command specific theme customization. console.SetColor("Command", color.New(color.FgWhite, color.Bold)) console.SetColor("SessionID", color.New(color.FgYellow, color.Bold)) console.SetColor("SessionTime", color.New(color.FgGreen)) console.SetColor("ClearSession", color.New(color.FgGreen, color.Bold)) if !isSessionDirExists() { fatalIf(createSessionDir().Trace(), "Unable to create session folder.") } // Set command flags. isForce := ctx.Bool("force") // Retrieve requested session id. sessionID := ctx.Args().Get(0) // Purge requested session id or all pending sessions. clearSession(sessionID, isForce) return nil }
go
func mainSessionClear(ctx *cli.Context) error { // Check command arguments checkSessionClearSyntax(ctx) // Additional command specific theme customization. console.SetColor("Command", color.New(color.FgWhite, color.Bold)) console.SetColor("SessionID", color.New(color.FgYellow, color.Bold)) console.SetColor("SessionTime", color.New(color.FgGreen)) console.SetColor("ClearSession", color.New(color.FgGreen, color.Bold)) if !isSessionDirExists() { fatalIf(createSessionDir().Trace(), "Unable to create session folder.") } // Set command flags. isForce := ctx.Bool("force") // Retrieve requested session id. sessionID := ctx.Args().Get(0) // Purge requested session id or all pending sessions. clearSession(sessionID, isForce) return nil }
[ "func", "mainSessionClear", "(", "ctx", "*", "cli", ".", "Context", ")", "error", "{", "// Check command arguments", "checkSessionClearSyntax", "(", "ctx", ")", "\n\n", "// Additional command specific theme customization.", "console", ".", "SetColor", "(", "\"", "\"", ",", "color", ".", "New", "(", "color", ".", "FgWhite", ",", "color", ".", "Bold", ")", ")", "\n", "console", ".", "SetColor", "(", "\"", "\"", ",", "color", ".", "New", "(", "color", ".", "FgYellow", ",", "color", ".", "Bold", ")", ")", "\n", "console", ".", "SetColor", "(", "\"", "\"", ",", "color", ".", "New", "(", "color", ".", "FgGreen", ")", ")", "\n", "console", ".", "SetColor", "(", "\"", "\"", ",", "color", ".", "New", "(", "color", ".", "FgGreen", ",", "color", ".", "Bold", ")", ")", "\n\n", "if", "!", "isSessionDirExists", "(", ")", "{", "fatalIf", "(", "createSessionDir", "(", ")", ".", "Trace", "(", ")", ",", "\"", "\"", ")", "\n", "}", "\n", "// Set command flags.", "isForce", ":=", "ctx", ".", "Bool", "(", "\"", "\"", ")", "\n\n", "// Retrieve requested session id.", "sessionID", ":=", "ctx", ".", "Args", "(", ")", ".", "Get", "(", "0", ")", "\n\n", "// Purge requested session id or all pending sessions.", "clearSession", "(", "sessionID", ",", "isForce", ")", "\n", "return", "nil", "\n", "}" ]
// mainSessionClear - Main session clear.
[ "mainSessionClear", "-", "Main", "session", "clear", "." ]
f0f156aca82e451c80b05d5be8eb01a04fee29dd
https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/session-clear.go#L138-L160
train
minio/mc
cmd/admin-monitor.go
checkAdminMonitorSyntax
func checkAdminMonitorSyntax(ctx *cli.Context) { if len(ctx.Args()) == 0 || len(ctx.Args()) > 1 { exit := globalErrorExitStatus cli.ShowCommandHelpAndExit(ctx, "monitor", exit) } }
go
func checkAdminMonitorSyntax(ctx *cli.Context) { if len(ctx.Args()) == 0 || len(ctx.Args()) > 1 { exit := globalErrorExitStatus cli.ShowCommandHelpAndExit(ctx, "monitor", exit) } }
[ "func", "checkAdminMonitorSyntax", "(", "ctx", "*", "cli", ".", "Context", ")", "{", "if", "len", "(", "ctx", ".", "Args", "(", ")", ")", "==", "0", "||", "len", "(", "ctx", ".", "Args", "(", ")", ")", ">", "1", "{", "exit", ":=", "globalErrorExitStatus", "\n", "cli", ".", "ShowCommandHelpAndExit", "(", "ctx", ",", "\"", "\"", ",", "exit", ")", "\n", "}", "\n", "}" ]
// checkAdminMonitorSyntax - validate all the passed arguments
[ "checkAdminMonitorSyntax", "-", "validate", "all", "the", "passed", "arguments" ]
f0f156aca82e451c80b05d5be8eb01a04fee29dd
https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/admin-monitor.go#L246-L252
train
minio/mc
cmd/client-admin.go
newAdminFactory
func newAdminFactory() func(config *Config) (*madmin.AdminClient, *probe.Error) { clientCache := make(map[uint32]*madmin.AdminClient) mutex := &sync.Mutex{} // Return New function. return func(config *Config) (*madmin.AdminClient, *probe.Error) { // Creates a parsed URL. targetURL, e := url.Parse(config.HostURL) if e != nil { return nil, probe.NewError(e) } // By default enable HTTPs. useTLS := true if targetURL.Scheme == "http" { useTLS = false } // Save if target supports virtual host style. hostName := targetURL.Host // Generate a hash out of s3Conf. confHash := fnv.New32a() confHash.Write([]byte(hostName + config.AccessKey + config.SecretKey)) confSum := confHash.Sum32() // Lookup previous cache by hash. mutex.Lock() defer mutex.Unlock() var api *madmin.AdminClient var found bool if api, found = clientCache[confSum]; !found { // Not found. Instantiate a new MinIO var e error api, e = madmin.New(hostName, config.AccessKey, config.SecretKey, useTLS) if e != nil { return nil, probe.NewError(e) } // Keep TLS config. tlsConfig := &tls.Config{RootCAs: globalRootCAs} if config.Insecure { tlsConfig.InsecureSkipVerify = true } var transport http.RoundTripper = &http.Transport{ Proxy: http.ProxyFromEnvironment, DialContext: (&net.Dialer{ Timeout: 30 * time.Second, KeepAlive: 30 * time.Second, }).DialContext, MaxIdleConns: 100, IdleConnTimeout: 90 * time.Second, TLSHandshakeTimeout: 10 * time.Second, ExpectContinueTimeout: 1 * time.Second, TLSClientConfig: tlsConfig, } if config.Debug { transport = httptracer.GetNewTraceTransport(newTraceV4(), transport) } // Set custom transport. api.SetCustomTransport(transport) // Set app info. api.SetAppInfo(config.AppName, config.AppVersion) // Cache the new MinIO Client with hash of config as key. clientCache[confSum] = api } // Store the new api object. return api, nil } }
go
func newAdminFactory() func(config *Config) (*madmin.AdminClient, *probe.Error) { clientCache := make(map[uint32]*madmin.AdminClient) mutex := &sync.Mutex{} // Return New function. return func(config *Config) (*madmin.AdminClient, *probe.Error) { // Creates a parsed URL. targetURL, e := url.Parse(config.HostURL) if e != nil { return nil, probe.NewError(e) } // By default enable HTTPs. useTLS := true if targetURL.Scheme == "http" { useTLS = false } // Save if target supports virtual host style. hostName := targetURL.Host // Generate a hash out of s3Conf. confHash := fnv.New32a() confHash.Write([]byte(hostName + config.AccessKey + config.SecretKey)) confSum := confHash.Sum32() // Lookup previous cache by hash. mutex.Lock() defer mutex.Unlock() var api *madmin.AdminClient var found bool if api, found = clientCache[confSum]; !found { // Not found. Instantiate a new MinIO var e error api, e = madmin.New(hostName, config.AccessKey, config.SecretKey, useTLS) if e != nil { return nil, probe.NewError(e) } // Keep TLS config. tlsConfig := &tls.Config{RootCAs: globalRootCAs} if config.Insecure { tlsConfig.InsecureSkipVerify = true } var transport http.RoundTripper = &http.Transport{ Proxy: http.ProxyFromEnvironment, DialContext: (&net.Dialer{ Timeout: 30 * time.Second, KeepAlive: 30 * time.Second, }).DialContext, MaxIdleConns: 100, IdleConnTimeout: 90 * time.Second, TLSHandshakeTimeout: 10 * time.Second, ExpectContinueTimeout: 1 * time.Second, TLSClientConfig: tlsConfig, } if config.Debug { transport = httptracer.GetNewTraceTransport(newTraceV4(), transport) } // Set custom transport. api.SetCustomTransport(transport) // Set app info. api.SetAppInfo(config.AppName, config.AppVersion) // Cache the new MinIO Client with hash of config as key. clientCache[confSum] = api } // Store the new api object. return api, nil } }
[ "func", "newAdminFactory", "(", ")", "func", "(", "config", "*", "Config", ")", "(", "*", "madmin", ".", "AdminClient", ",", "*", "probe", ".", "Error", ")", "{", "clientCache", ":=", "make", "(", "map", "[", "uint32", "]", "*", "madmin", ".", "AdminClient", ")", "\n", "mutex", ":=", "&", "sync", ".", "Mutex", "{", "}", "\n\n", "// Return New function.", "return", "func", "(", "config", "*", "Config", ")", "(", "*", "madmin", ".", "AdminClient", ",", "*", "probe", ".", "Error", ")", "{", "// Creates a parsed URL.", "targetURL", ",", "e", ":=", "url", ".", "Parse", "(", "config", ".", "HostURL", ")", "\n", "if", "e", "!=", "nil", "{", "return", "nil", ",", "probe", ".", "NewError", "(", "e", ")", "\n", "}", "\n", "// By default enable HTTPs.", "useTLS", ":=", "true", "\n", "if", "targetURL", ".", "Scheme", "==", "\"", "\"", "{", "useTLS", "=", "false", "\n", "}", "\n\n", "// Save if target supports virtual host style.", "hostName", ":=", "targetURL", ".", "Host", "\n\n", "// Generate a hash out of s3Conf.", "confHash", ":=", "fnv", ".", "New32a", "(", ")", "\n", "confHash", ".", "Write", "(", "[", "]", "byte", "(", "hostName", "+", "config", ".", "AccessKey", "+", "config", ".", "SecretKey", ")", ")", "\n", "confSum", ":=", "confHash", ".", "Sum32", "(", ")", "\n\n", "// Lookup previous cache by hash.", "mutex", ".", "Lock", "(", ")", "\n", "defer", "mutex", ".", "Unlock", "(", ")", "\n", "var", "api", "*", "madmin", ".", "AdminClient", "\n", "var", "found", "bool", "\n", "if", "api", ",", "found", "=", "clientCache", "[", "confSum", "]", ";", "!", "found", "{", "// Not found. Instantiate a new MinIO", "var", "e", "error", "\n", "api", ",", "e", "=", "madmin", ".", "New", "(", "hostName", ",", "config", ".", "AccessKey", ",", "config", ".", "SecretKey", ",", "useTLS", ")", "\n", "if", "e", "!=", "nil", "{", "return", "nil", ",", "probe", ".", "NewError", "(", "e", ")", "\n", "}", "\n\n", "// Keep TLS config.", "tlsConfig", ":=", "&", "tls", ".", "Config", "{", "RootCAs", ":", "globalRootCAs", "}", "\n", "if", "config", ".", "Insecure", "{", "tlsConfig", ".", "InsecureSkipVerify", "=", "true", "\n", "}", "\n\n", "var", "transport", "http", ".", "RoundTripper", "=", "&", "http", ".", "Transport", "{", "Proxy", ":", "http", ".", "ProxyFromEnvironment", ",", "DialContext", ":", "(", "&", "net", ".", "Dialer", "{", "Timeout", ":", "30", "*", "time", ".", "Second", ",", "KeepAlive", ":", "30", "*", "time", ".", "Second", ",", "}", ")", ".", "DialContext", ",", "MaxIdleConns", ":", "100", ",", "IdleConnTimeout", ":", "90", "*", "time", ".", "Second", ",", "TLSHandshakeTimeout", ":", "10", "*", "time", ".", "Second", ",", "ExpectContinueTimeout", ":", "1", "*", "time", ".", "Second", ",", "TLSClientConfig", ":", "tlsConfig", ",", "}", "\n\n", "if", "config", ".", "Debug", "{", "transport", "=", "httptracer", ".", "GetNewTraceTransport", "(", "newTraceV4", "(", ")", ",", "transport", ")", "\n", "}", "\n\n", "// Set custom transport.", "api", ".", "SetCustomTransport", "(", "transport", ")", "\n\n", "// Set app info.", "api", ".", "SetAppInfo", "(", "config", ".", "AppName", ",", "config", ".", "AppVersion", ")", "\n\n", "// Cache the new MinIO Client with hash of config as key.", "clientCache", "[", "confSum", "]", "=", "api", "\n", "}", "\n\n", "// Store the new api object.", "return", "api", ",", "nil", "\n", "}", "\n", "}" ]
// newAdminFactory encloses New function with client cache.
[ "newAdminFactory", "encloses", "New", "function", "with", "client", "cache", "." ]
f0f156aca82e451c80b05d5be8eb01a04fee29dd
https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/client-admin.go#L35-L109
train