id
int32
0
167k
repo
stringlengths
5
54
path
stringlengths
4
155
func_name
stringlengths
1
118
original_string
stringlengths
52
85.5k
language
stringclasses
1 value
code
stringlengths
52
85.5k
code_tokens
list
docstring
stringlengths
6
2.61k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
85
252
17,700
albrow/zoom
marshal.go
Marshal
func (gobMarshalerUnmarshaler) Marshal(v interface{}) ([]byte, error) { var buff bytes.Buffer enc := gob.NewEncoder(&buff) if err := enc.Encode(v); err != nil { return buff.Bytes(), err } return buff.Bytes(), nil }
go
func (gobMarshalerUnmarshaler) Marshal(v interface{}) ([]byte, error) { var buff bytes.Buffer enc := gob.NewEncoder(&buff) if err := enc.Encode(v); err != nil { return buff.Bytes(), err } return buff.Bytes(), nil }
[ "func", "(", "gobMarshalerUnmarshaler", ")", "Marshal", "(", "v", "interface", "{", "}", ")", "(", "[", "]", "byte", ",", "error", ")", "{", "var", "buff", "bytes", ".", "Buffer", "\n", "enc", ":=", "gob", ".", "NewEncoder", "(", "&", "buff", ")", ...
// Marshal returns the gob encoding of v.
[ "Marshal", "returns", "the", "gob", "encoding", "of", "v", "." ]
4cc9cdbf65ce1b2f60b11b765d3e6b3a5e7e8952
https://github.com/albrow/zoom/blob/4cc9cdbf65ce1b2f60b11b765d3e6b3a5e7e8952/marshal.go#L53-L60
17,701
albrow/zoom
marshal.go
Unmarshal
func (gobMarshalerUnmarshaler) Unmarshal(data []byte, v interface{}) error { buff := bytes.NewBuffer(data) dec := gob.NewDecoder(buff) if err := dec.Decode(v); err != nil { return err } return nil }
go
func (gobMarshalerUnmarshaler) Unmarshal(data []byte, v interface{}) error { buff := bytes.NewBuffer(data) dec := gob.NewDecoder(buff) if err := dec.Decode(v); err != nil { return err } return nil }
[ "func", "(", "gobMarshalerUnmarshaler", ")", "Unmarshal", "(", "data", "[", "]", "byte", ",", "v", "interface", "{", "}", ")", "error", "{", "buff", ":=", "bytes", ".", "NewBuffer", "(", "data", ")", "\n", "dec", ":=", "gob", ".", "NewDecoder", "(", ...
// Unmarshal parses the gob-encoded data and stores the result in the value // pointed to by v.
[ "Unmarshal", "parses", "the", "gob", "-", "encoded", "data", "and", "stores", "the", "result", "in", "the", "value", "pointed", "to", "by", "v", "." ]
4cc9cdbf65ce1b2f60b11b765d3e6b3a5e7e8952
https://github.com/albrow/zoom/blob/4cc9cdbf65ce1b2f60b11b765d3e6b3a5e7e8952/marshal.go#L64-L71
17,702
albrow/zoom
marshal.go
Unmarshal
func (jsonMarshalerUnmarshaler) Unmarshal(data []byte, v interface{}) error { return json.Unmarshal(data, v) }
go
func (jsonMarshalerUnmarshaler) Unmarshal(data []byte, v interface{}) error { return json.Unmarshal(data, v) }
[ "func", "(", "jsonMarshalerUnmarshaler", ")", "Unmarshal", "(", "data", "[", "]", "byte", ",", "v", "interface", "{", "}", ")", "error", "{", "return", "json", ".", "Unmarshal", "(", "data", ",", "v", ")", "\n", "}" ]
// Unmarshal parses the json-encoded data and stores the result in the value // pointed to by v.
[ "Unmarshal", "parses", "the", "json", "-", "encoded", "data", "and", "stores", "the", "result", "in", "the", "value", "pointed", "to", "by", "v", "." ]
4cc9cdbf65ce1b2f60b11b765d3e6b3a5e7e8952
https://github.com/albrow/zoom/blob/4cc9cdbf65ce1b2f60b11b765d3e6b3a5e7e8952/marshal.go#L80-L82
17,703
albrow/zoom
convert.go
scanModel
func scanModel(fieldNames []string, fieldValues []interface{}, mr *modelRef) error { ms := mr.spec if fieldValues == nil || len(fieldValues) == 0 { return newModelNotFoundError(mr) } for i, reply := range fieldValues { if reply == nil { continue } fieldName := fieldNames[i] replyBytes, err := redis.Bytes(reply, nil) if err != nil { return err } if fieldName == "-" { // The ID is signified by the field name "-" since that cannot // possibly collide with other field names. mr.model.SetModelID(string(replyBytes)) continue } fs, found := ms.fieldsByName[fieldName] if !found { return fmt.Errorf("zoom: Error in scanModel: Could not find field %s in %T", fieldName, mr.model) } fieldVal := mr.fieldValue(fieldName) switch fs.kind { case primativeField: if err := scanPrimitiveVal(replyBytes, fieldVal); err != nil { return err } case pointerField: if err := scanPointerVal(replyBytes, fieldVal); err != nil { return err } default: if err := scanInconvertibleVal(mr.spec.fallback, replyBytes, fieldVal); err != nil { return err } } } return nil }
go
func scanModel(fieldNames []string, fieldValues []interface{}, mr *modelRef) error { ms := mr.spec if fieldValues == nil || len(fieldValues) == 0 { return newModelNotFoundError(mr) } for i, reply := range fieldValues { if reply == nil { continue } fieldName := fieldNames[i] replyBytes, err := redis.Bytes(reply, nil) if err != nil { return err } if fieldName == "-" { // The ID is signified by the field name "-" since that cannot // possibly collide with other field names. mr.model.SetModelID(string(replyBytes)) continue } fs, found := ms.fieldsByName[fieldName] if !found { return fmt.Errorf("zoom: Error in scanModel: Could not find field %s in %T", fieldName, mr.model) } fieldVal := mr.fieldValue(fieldName) switch fs.kind { case primativeField: if err := scanPrimitiveVal(replyBytes, fieldVal); err != nil { return err } case pointerField: if err := scanPointerVal(replyBytes, fieldVal); err != nil { return err } default: if err := scanInconvertibleVal(mr.spec.fallback, replyBytes, fieldVal); err != nil { return err } } } return nil }
[ "func", "scanModel", "(", "fieldNames", "[", "]", "string", ",", "fieldValues", "[", "]", "interface", "{", "}", ",", "mr", "*", "modelRef", ")", "error", "{", "ms", ":=", "mr", ".", "spec", "\n", "if", "fieldValues", "==", "nil", "||", "len", "(", ...
// scanModel iterates through fieldValues, converts each value to the correct type, and // scans the value into the fields of mr.model. It expects fieldValues to be the output // from an HMGET command from redis, without the field names included. The order of the // values in fieldValues must match the order of the corresponding field names. The id // field is special and should have the field name "-", which will be set with the SetModelID // method. fieldNames should be the actual field names as they appear in the struct definition, // not the redis names which may be custom.
[ "scanModel", "iterates", "through", "fieldValues", "converts", "each", "value", "to", "the", "correct", "type", "and", "scans", "the", "value", "into", "the", "fields", "of", "mr", ".", "model", ".", "It", "expects", "fieldValues", "to", "be", "the", "output...
4cc9cdbf65ce1b2f60b11b765d3e6b3a5e7e8952
https://github.com/albrow/zoom/blob/4cc9cdbf65ce1b2f60b11b765d3e6b3a5e7e8952/convert.go#L25-L66
17,704
albrow/zoom
convert.go
scanPrimitiveVal
func scanPrimitiveVal(src []byte, dest reflect.Value) error { if len(src) == 0 { return nil // skip blanks } switch dest.Kind() { case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: srcInt, err := strconv.ParseInt(string(src), 10, 0) if err != nil { return fmt.Errorf("zoom: could not convert %s to int", string(src)) } dest.SetInt(srcInt) case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64: srcUint, err := strconv.ParseUint(string(src), 10, 0) if err != nil { return fmt.Errorf("zoom: could not convert %s to uint", string(src)) } dest.SetUint(srcUint) case reflect.Float32, reflect.Float64: srcFloat, err := strconv.ParseFloat(string(src), 64) if err != nil { return fmt.Errorf("zoom: could not convert %s to float", string(src)) } dest.SetFloat(srcFloat) case reflect.Bool: srcBool, err := strconv.ParseBool(string(src)) if err != nil { return fmt.Errorf("zoom: could not convert %s to bool", string(src)) } dest.SetBool(srcBool) case reflect.String: dest.SetString(string(src)) case reflect.Slice, reflect.Array: // Slice or array of bytes dest.SetBytes(src) default: return fmt.Errorf("zoom: don't know how to scan primitive type: %T", src) } return nil }
go
func scanPrimitiveVal(src []byte, dest reflect.Value) error { if len(src) == 0 { return nil // skip blanks } switch dest.Kind() { case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: srcInt, err := strconv.ParseInt(string(src), 10, 0) if err != nil { return fmt.Errorf("zoom: could not convert %s to int", string(src)) } dest.SetInt(srcInt) case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64: srcUint, err := strconv.ParseUint(string(src), 10, 0) if err != nil { return fmt.Errorf("zoom: could not convert %s to uint", string(src)) } dest.SetUint(srcUint) case reflect.Float32, reflect.Float64: srcFloat, err := strconv.ParseFloat(string(src), 64) if err != nil { return fmt.Errorf("zoom: could not convert %s to float", string(src)) } dest.SetFloat(srcFloat) case reflect.Bool: srcBool, err := strconv.ParseBool(string(src)) if err != nil { return fmt.Errorf("zoom: could not convert %s to bool", string(src)) } dest.SetBool(srcBool) case reflect.String: dest.SetString(string(src)) case reflect.Slice, reflect.Array: // Slice or array of bytes dest.SetBytes(src) default: return fmt.Errorf("zoom: don't know how to scan primitive type: %T", src) } return nil }
[ "func", "scanPrimitiveVal", "(", "src", "[", "]", "byte", ",", "dest", "reflect", ".", "Value", ")", "error", "{", "if", "len", "(", "src", ")", "==", "0", "{", "return", "nil", "// skip blanks", "\n", "}", "\n", "switch", "dest", ".", "Kind", "(", ...
// scanPrimitiveVal converts a slice of bytes response from redis into the type of dest // and then sets dest to that value
[ "scanPrimitiveVal", "converts", "a", "slice", "of", "bytes", "response", "from", "redis", "into", "the", "type", "of", "dest", "and", "then", "sets", "dest", "to", "that", "value" ]
4cc9cdbf65ce1b2f60b11b765d3e6b3a5e7e8952
https://github.com/albrow/zoom/blob/4cc9cdbf65ce1b2f60b11b765d3e6b3a5e7e8952/convert.go#L70-L109
17,705
albrow/zoom
convert.go
scanPointerVal
func scanPointerVal(src []byte, dest reflect.Value) error { // Skip empty or nil fields if string(src) == "NULL" { return nil } dest.Set(reflect.New(dest.Type().Elem())) return scanPrimitiveVal(src, dest.Elem()) }
go
func scanPointerVal(src []byte, dest reflect.Value) error { // Skip empty or nil fields if string(src) == "NULL" { return nil } dest.Set(reflect.New(dest.Type().Elem())) return scanPrimitiveVal(src, dest.Elem()) }
[ "func", "scanPointerVal", "(", "src", "[", "]", "byte", ",", "dest", "reflect", ".", "Value", ")", "error", "{", "// Skip empty or nil fields", "if", "string", "(", "src", ")", "==", "\"", "\"", "{", "return", "nil", "\n", "}", "\n", "dest", ".", "Set"...
// scanPointerVal works like scanVal but expects dest to be a pointer to some // primitive type
[ "scanPointerVal", "works", "like", "scanVal", "but", "expects", "dest", "to", "be", "a", "pointer", "to", "some", "primitive", "type" ]
4cc9cdbf65ce1b2f60b11b765d3e6b3a5e7e8952
https://github.com/albrow/zoom/blob/4cc9cdbf65ce1b2f60b11b765d3e6b3a5e7e8952/convert.go#L113-L120
17,706
albrow/zoom
convert.go
scanInconvertibleVal
func scanInconvertibleVal(marshalerUnmarshaler MarshalerUnmarshaler, src []byte, dest reflect.Value) error { // Skip empty or nil fields if len(src) == 0 || string(src) == "NULL" { return nil } // TODO: account for json, msgpack or other custom fallbacks if err := marshalerUnmarshaler.Unmarshal(src, dest.Addr().Interface()); err != nil { return err } return nil }
go
func scanInconvertibleVal(marshalerUnmarshaler MarshalerUnmarshaler, src []byte, dest reflect.Value) error { // Skip empty or nil fields if len(src) == 0 || string(src) == "NULL" { return nil } // TODO: account for json, msgpack or other custom fallbacks if err := marshalerUnmarshaler.Unmarshal(src, dest.Addr().Interface()); err != nil { return err } return nil }
[ "func", "scanInconvertibleVal", "(", "marshalerUnmarshaler", "MarshalerUnmarshaler", ",", "src", "[", "]", "byte", ",", "dest", "reflect", ".", "Value", ")", "error", "{", "// Skip empty or nil fields", "if", "len", "(", "src", ")", "==", "0", "||", "string", ...
// scanIncovertibleVal unmarshals src into dest using the given // MarshalerUnmarshaler
[ "scanIncovertibleVal", "unmarshals", "src", "into", "dest", "using", "the", "given", "MarshalerUnmarshaler" ]
4cc9cdbf65ce1b2f60b11b765d3e6b3a5e7e8952
https://github.com/albrow/zoom/blob/4cc9cdbf65ce1b2f60b11b765d3e6b3a5e7e8952/convert.go#L124-L134
17,707
albrow/zoom
pool.go
WithAddress
func (options PoolOptions) WithAddress(address string) PoolOptions { options.Address = address return options }
go
func (options PoolOptions) WithAddress(address string) PoolOptions { options.Address = address return options }
[ "func", "(", "options", "PoolOptions", ")", "WithAddress", "(", "address", "string", ")", "PoolOptions", "{", "options", ".", "Address", "=", "address", "\n", "return", "options", "\n", "}" ]
// WithAddress returns a new copy of the options with the Address property set // to the given value. It does not mutate the original options.
[ "WithAddress", "returns", "a", "new", "copy", "of", "the", "options", "with", "the", "Address", "property", "set", "to", "the", "given", "value", ".", "It", "does", "not", "mutate", "the", "original", "options", "." ]
4cc9cdbf65ce1b2f60b11b765d3e6b3a5e7e8952
https://github.com/albrow/zoom/blob/4cc9cdbf65ce1b2f60b11b765d3e6b3a5e7e8952/pool.go#L74-L77
17,708
albrow/zoom
pool.go
WithDatabase
func (options PoolOptions) WithDatabase(database int) PoolOptions { options.Database = database return options }
go
func (options PoolOptions) WithDatabase(database int) PoolOptions { options.Database = database return options }
[ "func", "(", "options", "PoolOptions", ")", "WithDatabase", "(", "database", "int", ")", "PoolOptions", "{", "options", ".", "Database", "=", "database", "\n", "return", "options", "\n", "}" ]
// WithDatabase returns a new copy of the options with the Database property set // to the given value. It does not mutate the original options.
[ "WithDatabase", "returns", "a", "new", "copy", "of", "the", "options", "with", "the", "Database", "property", "set", "to", "the", "given", "value", ".", "It", "does", "not", "mutate", "the", "original", "options", "." ]
4cc9cdbf65ce1b2f60b11b765d3e6b3a5e7e8952
https://github.com/albrow/zoom/blob/4cc9cdbf65ce1b2f60b11b765d3e6b3a5e7e8952/pool.go#L81-L84
17,709
albrow/zoom
pool.go
WithIdleTimeout
func (options PoolOptions) WithIdleTimeout(timeout time.Duration) PoolOptions { options.IdleTimeout = timeout return options }
go
func (options PoolOptions) WithIdleTimeout(timeout time.Duration) PoolOptions { options.IdleTimeout = timeout return options }
[ "func", "(", "options", "PoolOptions", ")", "WithIdleTimeout", "(", "timeout", "time", ".", "Duration", ")", "PoolOptions", "{", "options", ".", "IdleTimeout", "=", "timeout", "\n", "return", "options", "\n", "}" ]
// WithIdleTimeout returns a new copy of the options with the IdleTimeout // property set to the given value. It does not mutate the original options.
[ "WithIdleTimeout", "returns", "a", "new", "copy", "of", "the", "options", "with", "the", "IdleTimeout", "property", "set", "to", "the", "given", "value", ".", "It", "does", "not", "mutate", "the", "original", "options", "." ]
4cc9cdbf65ce1b2f60b11b765d3e6b3a5e7e8952
https://github.com/albrow/zoom/blob/4cc9cdbf65ce1b2f60b11b765d3e6b3a5e7e8952/pool.go#L88-L91
17,710
albrow/zoom
pool.go
WithMaxActive
func (options PoolOptions) WithMaxActive(maxActive int) PoolOptions { options.MaxActive = maxActive return options }
go
func (options PoolOptions) WithMaxActive(maxActive int) PoolOptions { options.MaxActive = maxActive return options }
[ "func", "(", "options", "PoolOptions", ")", "WithMaxActive", "(", "maxActive", "int", ")", "PoolOptions", "{", "options", ".", "MaxActive", "=", "maxActive", "\n", "return", "options", "\n", "}" ]
// WithMaxActive returns a new copy of the options with the MaxActive property // set to the given value. It does not mutate the original options.
[ "WithMaxActive", "returns", "a", "new", "copy", "of", "the", "options", "with", "the", "MaxActive", "property", "set", "to", "the", "given", "value", ".", "It", "does", "not", "mutate", "the", "original", "options", "." ]
4cc9cdbf65ce1b2f60b11b765d3e6b3a5e7e8952
https://github.com/albrow/zoom/blob/4cc9cdbf65ce1b2f60b11b765d3e6b3a5e7e8952/pool.go#L95-L98
17,711
albrow/zoom
pool.go
WithMaxIdle
func (options PoolOptions) WithMaxIdle(maxIdle int) PoolOptions { options.MaxIdle = maxIdle return options }
go
func (options PoolOptions) WithMaxIdle(maxIdle int) PoolOptions { options.MaxIdle = maxIdle return options }
[ "func", "(", "options", "PoolOptions", ")", "WithMaxIdle", "(", "maxIdle", "int", ")", "PoolOptions", "{", "options", ".", "MaxIdle", "=", "maxIdle", "\n", "return", "options", "\n", "}" ]
// WithMaxIdle returns a new copy of the options with the MaxIdle property set // to the given value. It does not mutate the original options.
[ "WithMaxIdle", "returns", "a", "new", "copy", "of", "the", "options", "with", "the", "MaxIdle", "property", "set", "to", "the", "given", "value", ".", "It", "does", "not", "mutate", "the", "original", "options", "." ]
4cc9cdbf65ce1b2f60b11b765d3e6b3a5e7e8952
https://github.com/albrow/zoom/blob/4cc9cdbf65ce1b2f60b11b765d3e6b3a5e7e8952/pool.go#L102-L105
17,712
albrow/zoom
pool.go
WithNetwork
func (options PoolOptions) WithNetwork(network string) PoolOptions { options.Network = network return options }
go
func (options PoolOptions) WithNetwork(network string) PoolOptions { options.Network = network return options }
[ "func", "(", "options", "PoolOptions", ")", "WithNetwork", "(", "network", "string", ")", "PoolOptions", "{", "options", ".", "Network", "=", "network", "\n", "return", "options", "\n", "}" ]
// WithNetwork returns a new copy of the options with the Network property set // to the given value. It does not mutate the original options.
[ "WithNetwork", "returns", "a", "new", "copy", "of", "the", "options", "with", "the", "Network", "property", "set", "to", "the", "given", "value", ".", "It", "does", "not", "mutate", "the", "original", "options", "." ]
4cc9cdbf65ce1b2f60b11b765d3e6b3a5e7e8952
https://github.com/albrow/zoom/blob/4cc9cdbf65ce1b2f60b11b765d3e6b3a5e7e8952/pool.go#L109-L112
17,713
albrow/zoom
pool.go
WithPassword
func (options PoolOptions) WithPassword(password string) PoolOptions { options.Password = password return options }
go
func (options PoolOptions) WithPassword(password string) PoolOptions { options.Password = password return options }
[ "func", "(", "options", "PoolOptions", ")", "WithPassword", "(", "password", "string", ")", "PoolOptions", "{", "options", ".", "Password", "=", "password", "\n", "return", "options", "\n", "}" ]
// WithPassword returns a new copy of the options with the Password property set // to the given value. It does not mutate the original options.
[ "WithPassword", "returns", "a", "new", "copy", "of", "the", "options", "with", "the", "Password", "property", "set", "to", "the", "given", "value", ".", "It", "does", "not", "mutate", "the", "original", "options", "." ]
4cc9cdbf65ce1b2f60b11b765d3e6b3a5e7e8952
https://github.com/albrow/zoom/blob/4cc9cdbf65ce1b2f60b11b765d3e6b3a5e7e8952/pool.go#L116-L119
17,714
albrow/zoom
pool.go
WithWait
func (options PoolOptions) WithWait(wait bool) PoolOptions { options.Wait = wait return options }
go
func (options PoolOptions) WithWait(wait bool) PoolOptions { options.Wait = wait return options }
[ "func", "(", "options", "PoolOptions", ")", "WithWait", "(", "wait", "bool", ")", "PoolOptions", "{", "options", ".", "Wait", "=", "wait", "\n", "return", "options", "\n", "}" ]
// WithWait returns a new copy of the options with the Wait property set to the // given value. It does not mutate the original options.
[ "WithWait", "returns", "a", "new", "copy", "of", "the", "options", "with", "the", "Wait", "property", "set", "to", "the", "given", "value", ".", "It", "does", "not", "mutate", "the", "original", "options", "." ]
4cc9cdbf65ce1b2f60b11b765d3e6b3a5e7e8952
https://github.com/albrow/zoom/blob/4cc9cdbf65ce1b2f60b11b765d3e6b3a5e7e8952/pool.go#L123-L126
17,715
albrow/zoom
pool.go
NewPoolWithOptions
func NewPoolWithOptions(options PoolOptions) *Pool { pool := &Pool{ options: options, modelTypeToSpec: map[reflect.Type]*modelSpec{}, modelNameToSpec: map[string]*modelSpec{}, } pool.redisPool = &redis.Pool{ MaxIdle: options.MaxIdle, MaxActive: options.MaxActive, IdleTimeout: options.IdleTimeout, Wait: options.Wait, Dial: func() (redis.Conn, error) { c, err := redis.Dial(options.Network, options.Address) if err != nil { return nil, err } // If a options.Password was provided, use the AUTH command to authenticate if options.Password != "" { if _, err := c.Do("AUTH", options.Password); err != nil { return nil, err } } // Select the database number provided by options.Database if _, err := c.Do("Select", options.Database); err != nil { _ = c.Close() return nil, err } return c, err }, } return pool }
go
func NewPoolWithOptions(options PoolOptions) *Pool { pool := &Pool{ options: options, modelTypeToSpec: map[reflect.Type]*modelSpec{}, modelNameToSpec: map[string]*modelSpec{}, } pool.redisPool = &redis.Pool{ MaxIdle: options.MaxIdle, MaxActive: options.MaxActive, IdleTimeout: options.IdleTimeout, Wait: options.Wait, Dial: func() (redis.Conn, error) { c, err := redis.Dial(options.Network, options.Address) if err != nil { return nil, err } // If a options.Password was provided, use the AUTH command to authenticate if options.Password != "" { if _, err := c.Do("AUTH", options.Password); err != nil { return nil, err } } // Select the database number provided by options.Database if _, err := c.Do("Select", options.Database); err != nil { _ = c.Close() return nil, err } return c, err }, } return pool }
[ "func", "NewPoolWithOptions", "(", "options", "PoolOptions", ")", "*", "Pool", "{", "pool", ":=", "&", "Pool", "{", "options", ":", "options", ",", "modelTypeToSpec", ":", "map", "[", "reflect", ".", "Type", "]", "*", "modelSpec", "{", "}", ",", "modelNa...
// NewPoolWithOptions initializes and returns a pool with the given options. You // can pass in DefaultOptions to use all the default options. Or cal the WithX // methods of DefaultOptions to change the options you want to change.
[ "NewPoolWithOptions", "initializes", "and", "returns", "a", "pool", "with", "the", "given", "options", ".", "You", "can", "pass", "in", "DefaultOptions", "to", "use", "all", "the", "default", "options", ".", "Or", "cal", "the", "WithX", "methods", "of", "Def...
4cc9cdbf65ce1b2f60b11b765d3e6b3a5e7e8952
https://github.com/albrow/zoom/blob/4cc9cdbf65ce1b2f60b11b765d3e6b3a5e7e8952/pool.go#L138-L169
17,716
albrow/zoom
transaction.go
NewTransaction
func (p *Pool) NewTransaction() *Transaction { t := &Transaction{ conn: p.NewConn(), } return t }
go
func (p *Pool) NewTransaction() *Transaction { t := &Transaction{ conn: p.NewConn(), } return t }
[ "func", "(", "p", "*", "Pool", ")", "NewTransaction", "(", ")", "*", "Transaction", "{", "t", ":=", "&", "Transaction", "{", "conn", ":", "p", ".", "NewConn", "(", ")", ",", "}", "\n", "return", "t", "\n", "}" ]
// NewTransaction instantiates and returns a new transaction.
[ "NewTransaction", "instantiates", "and", "returns", "a", "new", "transaction", "." ]
4cc9cdbf65ce1b2f60b11b765d3e6b3a5e7e8952
https://github.com/albrow/zoom/blob/4cc9cdbf65ce1b2f60b11b765d3e6b3a5e7e8952/transaction.go#L46-L51
17,717
albrow/zoom
transaction.go
setError
func (t *Transaction) setError(err error) { if t.err == nil { t.err = err } }
go
func (t *Transaction) setError(err error) { if t.err == nil { t.err = err } }
[ "func", "(", "t", "*", "Transaction", ")", "setError", "(", "err", "error", ")", "{", "if", "t", ".", "err", "==", "nil", "{", "t", ".", "err", "=", "err", "\n", "}", "\n", "}" ]
// SetError sets the err property of the transaction iff it was not already // set. This will cause exec to fail immediately.
[ "SetError", "sets", "the", "err", "property", "of", "the", "transaction", "iff", "it", "was", "not", "already", "set", ".", "This", "will", "cause", "exec", "to", "fail", "immediately", "." ]
4cc9cdbf65ce1b2f60b11b765d3e6b3a5e7e8952
https://github.com/albrow/zoom/blob/4cc9cdbf65ce1b2f60b11b765d3e6b3a5e7e8952/transaction.go#L55-L59
17,718
albrow/zoom
transaction.go
Watch
func (t *Transaction) Watch(model Model) error { if len(t.actions) != 0 { return fmt.Errorf("Cannot call Watch after other commands have been added to the transaction") } col, err := getCollectionForModel(model) if err != nil { return err } key := col.ModelKey(model.ModelID()) return t.WatchKey(key) }
go
func (t *Transaction) Watch(model Model) error { if len(t.actions) != 0 { return fmt.Errorf("Cannot call Watch after other commands have been added to the transaction") } col, err := getCollectionForModel(model) if err != nil { return err } key := col.ModelKey(model.ModelID()) return t.WatchKey(key) }
[ "func", "(", "t", "*", "Transaction", ")", "Watch", "(", "model", "Model", ")", "error", "{", "if", "len", "(", "t", ".", "actions", ")", "!=", "0", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n", "col", ",", "err", ...
// Watch issues a Redis WATCH command using the key for the given model. If the // model changes before the transaction is executed, Exec will return a // WatchError and the commands in the transaction will not be executed. Unlike // most other transaction methods, Watch does not use delayed execution. Because // of how the WATCH command works, Watch must send a command to Redis // immediately. You must call Watch or WatchKey before any other transaction // methods.
[ "Watch", "issues", "a", "Redis", "WATCH", "command", "using", "the", "key", "for", "the", "given", "model", ".", "If", "the", "model", "changes", "before", "the", "transaction", "is", "executed", "Exec", "will", "return", "a", "WatchError", "and", "the", "...
4cc9cdbf65ce1b2f60b11b765d3e6b3a5e7e8952
https://github.com/albrow/zoom/blob/4cc9cdbf65ce1b2f60b11b765d3e6b3a5e7e8952/transaction.go#L68-L78
17,719
albrow/zoom
transaction.go
WatchKey
func (t *Transaction) WatchKey(key string) error { if len(t.actions) != 0 { return fmt.Errorf("Cannot call WatchKey after other commands have been added to the transaction") } if _, err := t.conn.Do("WATCH", key); err != nil { return err } t.watching = append(t.watching, key) return nil }
go
func (t *Transaction) WatchKey(key string) error { if len(t.actions) != 0 { return fmt.Errorf("Cannot call WatchKey after other commands have been added to the transaction") } if _, err := t.conn.Do("WATCH", key); err != nil { return err } t.watching = append(t.watching, key) return nil }
[ "func", "(", "t", "*", "Transaction", ")", "WatchKey", "(", "key", "string", ")", "error", "{", "if", "len", "(", "t", ".", "actions", ")", "!=", "0", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n", "if", "_", ",", ...
// WatchKey issues a Redis WATCH command using the given key. If the key changes // before the transaction is executed, Exec will return a WatchError and the // commands in the transaction will not be executed. Unlike most other // transaction methods, WatchKey does not use delayed execution. Because of how // the WATCH command works, WatchKey must send a command to Redis immediately. // You must call Watch or WatchKey before any other transaction methods.
[ "WatchKey", "issues", "a", "Redis", "WATCH", "command", "using", "the", "given", "key", ".", "If", "the", "key", "changes", "before", "the", "transaction", "is", "executed", "Exec", "will", "return", "a", "WatchError", "and", "the", "commands", "in", "the", ...
4cc9cdbf65ce1b2f60b11b765d3e6b3a5e7e8952
https://github.com/albrow/zoom/blob/4cc9cdbf65ce1b2f60b11b765d3e6b3a5e7e8952/transaction.go#L86-L95
17,720
albrow/zoom
transaction.go
Command
func (t *Transaction) Command(name string, args redis.Args, handler ReplyHandler) { t.actions = append(t.actions, &Action{ kind: commandAction, name: name, args: args, handler: handler, }) }
go
func (t *Transaction) Command(name string, args redis.Args, handler ReplyHandler) { t.actions = append(t.actions, &Action{ kind: commandAction, name: name, args: args, handler: handler, }) }
[ "func", "(", "t", "*", "Transaction", ")", "Command", "(", "name", "string", ",", "args", "redis", ".", "Args", ",", "handler", "ReplyHandler", ")", "{", "t", ".", "actions", "=", "append", "(", "t", ".", "actions", ",", "&", "Action", "{", "kind", ...
// Command adds a command action to the transaction with the given args. // handler will be called with the reply from this specific command when // the transaction is executed.
[ "Command", "adds", "a", "command", "action", "to", "the", "transaction", "with", "the", "given", "args", ".", "handler", "will", "be", "called", "with", "the", "reply", "from", "this", "specific", "command", "when", "the", "transaction", "is", "executed", "....
4cc9cdbf65ce1b2f60b11b765d3e6b3a5e7e8952
https://github.com/albrow/zoom/blob/4cc9cdbf65ce1b2f60b11b765d3e6b3a5e7e8952/transaction.go#L100-L107
17,721
albrow/zoom
transaction.go
Script
func (t *Transaction) Script(script *redis.Script, args redis.Args, handler ReplyHandler) { t.actions = append(t.actions, &Action{ kind: scriptAction, script: script, args: args, handler: handler, }) }
go
func (t *Transaction) Script(script *redis.Script, args redis.Args, handler ReplyHandler) { t.actions = append(t.actions, &Action{ kind: scriptAction, script: script, args: args, handler: handler, }) }
[ "func", "(", "t", "*", "Transaction", ")", "Script", "(", "script", "*", "redis", ".", "Script", ",", "args", "redis", ".", "Args", ",", "handler", "ReplyHandler", ")", "{", "t", ".", "actions", "=", "append", "(", "t", ".", "actions", ",", "&", "A...
// Script adds a script action to the transaction with the given args. // handler will be called with the reply from this specific script when // the transaction is executed.
[ "Script", "adds", "a", "script", "action", "to", "the", "transaction", "with", "the", "given", "args", ".", "handler", "will", "be", "called", "with", "the", "reply", "from", "this", "specific", "script", "when", "the", "transaction", "is", "executed", "." ]
4cc9cdbf65ce1b2f60b11b765d3e6b3a5e7e8952
https://github.com/albrow/zoom/blob/4cc9cdbf65ce1b2f60b11b765d3e6b3a5e7e8952/transaction.go#L112-L119
17,722
albrow/zoom
transaction.go
Exec
func (t *Transaction) Exec() error { // Return the connection to the pool when we are done defer func() { _ = t.conn.Close() }() // If the transaction had an error from a previous command, return it // and don't continue if t.err != nil { return t.err } if len(t.actions) == 1 && len(t.watching) == 0 { // If there is only one command and no keys being watched, no need to use // MULTI/EXEC a := t.actions[0] reply, err := t.doAction(a) if err != nil { return err } if a.handler != nil { if err := a.handler(reply); err != nil { return err } } } else { // Send all the commands and scripts at once using MULTI/EXEC if err := t.conn.Send("MULTI"); err != nil { return err } for _, a := range t.actions { if err := t.sendAction(a); err != nil { return err } } // Invoke redis driver to execute the transaction replies, err := redis.Values(t.conn.Do("EXEC")) if err != nil { if err == redis.ErrNil && len(t.watching) > 0 { return WatchError{keys: t.watching} } return err } // Iterate through the replies, calling the corresponding handler functions for i, reply := range replies { a := t.actions[i] if err, ok := reply.(error); ok { return err } if a.handler != nil { if err := a.handler(reply); err != nil { return err } } } } return nil }
go
func (t *Transaction) Exec() error { // Return the connection to the pool when we are done defer func() { _ = t.conn.Close() }() // If the transaction had an error from a previous command, return it // and don't continue if t.err != nil { return t.err } if len(t.actions) == 1 && len(t.watching) == 0 { // If there is only one command and no keys being watched, no need to use // MULTI/EXEC a := t.actions[0] reply, err := t.doAction(a) if err != nil { return err } if a.handler != nil { if err := a.handler(reply); err != nil { return err } } } else { // Send all the commands and scripts at once using MULTI/EXEC if err := t.conn.Send("MULTI"); err != nil { return err } for _, a := range t.actions { if err := t.sendAction(a); err != nil { return err } } // Invoke redis driver to execute the transaction replies, err := redis.Values(t.conn.Do("EXEC")) if err != nil { if err == redis.ErrNil && len(t.watching) > 0 { return WatchError{keys: t.watching} } return err } // Iterate through the replies, calling the corresponding handler functions for i, reply := range replies { a := t.actions[i] if err, ok := reply.(error); ok { return err } if a.handler != nil { if err := a.handler(reply); err != nil { return err } } } } return nil }
[ "func", "(", "t", "*", "Transaction", ")", "Exec", "(", ")", "error", "{", "// Return the connection to the pool when we are done", "defer", "func", "(", ")", "{", "_", "=", "t", ".", "conn", ".", "Close", "(", ")", "\n", "}", "(", ")", "\n\n", "// If th...
// Exec executes the transaction, sequentially sending each action and // calling all the action handlers with the corresponding replies.
[ "Exec", "executes", "the", "transaction", "sequentially", "sending", "each", "action", "and", "calling", "all", "the", "action", "handlers", "with", "the", "corresponding", "replies", "." ]
4cc9cdbf65ce1b2f60b11b765d3e6b3a5e7e8952
https://github.com/albrow/zoom/blob/4cc9cdbf65ce1b2f60b11b765d3e6b3a5e7e8952/transaction.go#L146-L203
17,723
albrow/zoom
transaction.go
deleteStringIndex
func (t *Transaction) deleteStringIndex(collectionName, modelID, fieldName string) { t.Script(deleteStringIndexScript, redis.Args{collectionName, modelID, fieldName}, nil) }
go
func (t *Transaction) deleteStringIndex(collectionName, modelID, fieldName string) { t.Script(deleteStringIndexScript, redis.Args{collectionName, modelID, fieldName}, nil) }
[ "func", "(", "t", "*", "Transaction", ")", "deleteStringIndex", "(", "collectionName", ",", "modelID", ",", "fieldName", "string", ")", "{", "t", ".", "Script", "(", "deleteStringIndexScript", ",", "redis", ".", "Args", "{", "collectionName", ",", "modelID", ...
// deleteStringIndex is a small function wrapper around a Lua script. The script // will atomically remove the existing string index, if any, on the given // fieldName for the model with the given modelID. You can use the Name method // of a Collection to get its name. fieldName should be the name as it is stored // in Redis.
[ "deleteStringIndex", "is", "a", "small", "function", "wrapper", "around", "a", "Lua", "script", ".", "The", "script", "will", "atomically", "remove", "the", "existing", "string", "index", "if", "any", "on", "the", "given", "fieldName", "for", "the", "model", ...
4cc9cdbf65ce1b2f60b11b765d3e6b3a5e7e8952
https://github.com/albrow/zoom/blob/4cc9cdbf65ce1b2f60b11b765d3e6b3a5e7e8952/transaction.go#L222-L224
17,724
albrow/zoom
transaction.go
ExtractIDsFromFieldIndex
func (t *Transaction) ExtractIDsFromFieldIndex(setKey string, destKey string, min interface{}, max interface{}) { t.Script(extractIdsFromFieldIndexScript, redis.Args{setKey, destKey, min, max}, nil) }
go
func (t *Transaction) ExtractIDsFromFieldIndex(setKey string, destKey string, min interface{}, max interface{}) { t.Script(extractIdsFromFieldIndexScript, redis.Args{setKey, destKey, min, max}, nil) }
[ "func", "(", "t", "*", "Transaction", ")", "ExtractIDsFromFieldIndex", "(", "setKey", "string", ",", "destKey", "string", ",", "min", "interface", "{", "}", ",", "max", "interface", "{", "}", ")", "{", "t", ".", "Script", "(", "extractIdsFromFieldIndexScript...
// ExtractIDsFromFieldIndex is a small function wrapper around a Lua script. The // script will get all the ids from the sorted set identified by setKey using // ZRANGEBYSCORE with the given min and max, and then store them in a sorted set // identified by destKey. The members of the sorted set should be model ids. // Note that this method will not work on sorted sets that represents string // indexes because they are stored differently.
[ "ExtractIDsFromFieldIndex", "is", "a", "small", "function", "wrapper", "around", "a", "Lua", "script", ".", "The", "script", "will", "get", "all", "the", "ids", "from", "the", "sorted", "set", "identified", "by", "setKey", "using", "ZRANGEBYSCORE", "with", "th...
4cc9cdbf65ce1b2f60b11b765d3e6b3a5e7e8952
https://github.com/albrow/zoom/blob/4cc9cdbf65ce1b2f60b11b765d3e6b3a5e7e8952/transaction.go#L232-L234
17,725
albrow/zoom
scripts/main.go
findScripts
func findScripts(path string) ([]script, error) { filenames, err := filepath.Glob(filepath.Join(path, "*.lua")) if err != nil { return nil, err } scripts := []script{} for _, filename := range filenames { script := script{ VarName: convertUnderscoresToCamelCase(strings.TrimSuffix(filepath.Base(filename), ".lua")) + "Script", } src, err := ioutil.ReadFile(filename) if err != nil { return nil, err } script.Src = string(src) scripts = append(scripts, script) } return scripts, nil }
go
func findScripts(path string) ([]script, error) { filenames, err := filepath.Glob(filepath.Join(path, "*.lua")) if err != nil { return nil, err } scripts := []script{} for _, filename := range filenames { script := script{ VarName: convertUnderscoresToCamelCase(strings.TrimSuffix(filepath.Base(filename), ".lua")) + "Script", } src, err := ioutil.ReadFile(filename) if err != nil { return nil, err } script.Src = string(src) scripts = append(scripts, script) } return scripts, nil }
[ "func", "findScripts", "(", "path", "string", ")", "(", "[", "]", "script", ",", "error", ")", "{", "filenames", ",", "err", ":=", "filepath", ".", "Glob", "(", "filepath", ".", "Join", "(", "path", ",", "\"", "\"", ")", ")", "\n", "if", "err", "...
// findScripts finds all the .lua script files in the given path // and creates a script object for each one. It returns a slice of // scripts or an error if there was a problem reading any of the files.
[ "findScripts", "finds", "all", "the", ".", "lua", "script", "files", "in", "the", "given", "path", "and", "creates", "a", "script", "object", "for", "each", "one", ".", "It", "returns", "a", "slice", "of", "scripts", "or", "an", "error", "if", "there", ...
4cc9cdbf65ce1b2f60b11b765d3e6b3a5e7e8952
https://github.com/albrow/zoom/blob/4cc9cdbf65ce1b2f60b11b765d3e6b3a5e7e8952/scripts/main.go#L66-L84
17,726
albrow/zoom
util.go
indexOfStringSlice
func indexOfStringSlice(strings []string, s string) int { for i, b := range strings { if b == s { return i } } return -1 }
go
func indexOfStringSlice(strings []string, s string) int { for i, b := range strings { if b == s { return i } } return -1 }
[ "func", "indexOfStringSlice", "(", "strings", "[", "]", "string", ",", "s", "string", ")", "int", "{", "for", "i", ",", "b", ":=", "range", "strings", "{", "if", "b", "==", "s", "{", "return", "i", "\n", "}", "\n", "}", "\n", "return", "-", "1", ...
// indexOfStringSlice returns the index of s in strings, or // -1 if a is not found in strings
[ "indexOfStringSlice", "returns", "the", "index", "of", "s", "in", "strings", "or", "-", "1", "if", "a", "is", "not", "found", "in", "strings" ]
4cc9cdbf65ce1b2f60b11b765d3e6b3a5e7e8952
https://github.com/albrow/zoom/blob/4cc9cdbf65ce1b2f60b11b765d3e6b3a5e7e8952/util.go#L84-L91
17,727
albrow/zoom
util.go
removeElementFromStringSlice
func removeElementFromStringSlice(list []string, elem string) []string { for i, e := range list { if e == elem { return append(list[:i], list[i+1:]...) } } return list }
go
func removeElementFromStringSlice(list []string, elem string) []string { for i, e := range list { if e == elem { return append(list[:i], list[i+1:]...) } } return list }
[ "func", "removeElementFromStringSlice", "(", "list", "[", "]", "string", ",", "elem", "string", ")", "[", "]", "string", "{", "for", "i", ",", "e", ":=", "range", "list", "{", "if", "e", "==", "elem", "{", "return", "append", "(", "list", "[", ":", ...
// removeElementFromStringSlice removes elem from list and returns // the new slice.
[ "removeElementFromStringSlice", "removes", "elem", "from", "list", "and", "returns", "the", "new", "slice", "." ]
4cc9cdbf65ce1b2f60b11b765d3e6b3a5e7e8952
https://github.com/albrow/zoom/blob/4cc9cdbf65ce1b2f60b11b765d3e6b3a5e7e8952/util.go#L100-L107
17,728
albrow/zoom
util.go
typeIsSliceOrArray
func typeIsSliceOrArray(typ reflect.Type) bool { k := typ.Kind() return (k == reflect.Slice || k == reflect.Array) && typ.Elem().Kind() != reflect.Uint8 }
go
func typeIsSliceOrArray(typ reflect.Type) bool { k := typ.Kind() return (k == reflect.Slice || k == reflect.Array) && typ.Elem().Kind() != reflect.Uint8 }
[ "func", "typeIsSliceOrArray", "(", "typ", "reflect", ".", "Type", ")", "bool", "{", "k", ":=", "typ", ".", "Kind", "(", ")", "\n", "return", "(", "k", "==", "reflect", ".", "Slice", "||", "k", "==", "reflect", ".", "Array", ")", "&&", "typ", ".", ...
// typeIsSliceOrArray returns true iff typ is a slice or array
[ "typeIsSliceOrArray", "returns", "true", "iff", "typ", "is", "a", "slice", "or", "array" ]
4cc9cdbf65ce1b2f60b11b765d3e6b3a5e7e8952
https://github.com/albrow/zoom/blob/4cc9cdbf65ce1b2f60b11b765d3e6b3a5e7e8952/util.go#L110-L113
17,729
albrow/zoom
util.go
typeIsPointerToStruct
func typeIsPointerToStruct(typ reflect.Type) bool { return typ.Kind() == reflect.Ptr && typ.Elem().Kind() == reflect.Struct }
go
func typeIsPointerToStruct(typ reflect.Type) bool { return typ.Kind() == reflect.Ptr && typ.Elem().Kind() == reflect.Struct }
[ "func", "typeIsPointerToStruct", "(", "typ", "reflect", ".", "Type", ")", "bool", "{", "return", "typ", ".", "Kind", "(", ")", "==", "reflect", ".", "Ptr", "&&", "typ", ".", "Elem", "(", ")", ".", "Kind", "(", ")", "==", "reflect", ".", "Struct", "...
// typeIsPointerToStruct returns true iff typ is a pointer to a struct
[ "typeIsPointerToStruct", "returns", "true", "iff", "typ", "is", "a", "pointer", "to", "a", "struct" ]
4cc9cdbf65ce1b2f60b11b765d3e6b3a5e7e8952
https://github.com/albrow/zoom/blob/4cc9cdbf65ce1b2f60b11b765d3e6b3a5e7e8952/util.go#L116-L118
17,730
albrow/zoom
util.go
typeIsNumeric
func typeIsNumeric(typ reflect.Type) bool { k := typ.Kind() switch k { case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64, reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Float32, reflect.Float64: return true default: return false } }
go
func typeIsNumeric(typ reflect.Type) bool { k := typ.Kind() switch k { case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64, reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Float32, reflect.Float64: return true default: return false } }
[ "func", "typeIsNumeric", "(", "typ", "reflect", ".", "Type", ")", "bool", "{", "k", ":=", "typ", ".", "Kind", "(", ")", "\n", "switch", "k", "{", "case", "reflect", ".", "Int", ",", "reflect", ".", "Int8", ",", "reflect", ".", "Int16", ",", "reflec...
// typeIsNumeric returns true iff typ is one of the numeric primitive types
[ "typeIsNumeric", "returns", "true", "iff", "typ", "is", "one", "of", "the", "numeric", "primitive", "types" ]
4cc9cdbf65ce1b2f60b11b765d3e6b3a5e7e8952
https://github.com/albrow/zoom/blob/4cc9cdbf65ce1b2f60b11b765d3e6b3a5e7e8952/util.go#L128-L136
17,731
albrow/zoom
util.go
typeIsBool
func typeIsBool(typ reflect.Type) bool { k := typ.Kind() return k == reflect.Bool }
go
func typeIsBool(typ reflect.Type) bool { k := typ.Kind() return k == reflect.Bool }
[ "func", "typeIsBool", "(", "typ", "reflect", ".", "Type", ")", "bool", "{", "k", ":=", "typ", ".", "Kind", "(", ")", "\n", "return", "k", "==", "reflect", ".", "Bool", "\n", "}" ]
// typeIsBool returns true iff typ is a bool
[ "typeIsBool", "returns", "true", "iff", "typ", "is", "a", "bool" ]
4cc9cdbf65ce1b2f60b11b765d3e6b3a5e7e8952
https://github.com/albrow/zoom/blob/4cc9cdbf65ce1b2f60b11b765d3e6b3a5e7e8952/util.go#L139-L142
17,732
albrow/zoom
util.go
typeIsPrimative
func typeIsPrimative(typ reflect.Type) bool { return typeIsString(typ) || typeIsNumeric(typ) || typeIsBool(typ) }
go
func typeIsPrimative(typ reflect.Type) bool { return typeIsString(typ) || typeIsNumeric(typ) || typeIsBool(typ) }
[ "func", "typeIsPrimative", "(", "typ", "reflect", ".", "Type", ")", "bool", "{", "return", "typeIsString", "(", "typ", ")", "||", "typeIsNumeric", "(", "typ", ")", "||", "typeIsBool", "(", "typ", ")", "\n", "}" ]
// typeIsPrimative returns true iff typ is a primitive type, i.e. either a // string, bool, or numeric type.
[ "typeIsPrimative", "returns", "true", "iff", "typ", "is", "a", "primitive", "type", "i", ".", "e", ".", "either", "a", "string", "bool", "or", "numeric", "type", "." ]
4cc9cdbf65ce1b2f60b11b765d3e6b3a5e7e8952
https://github.com/albrow/zoom/blob/4cc9cdbf65ce1b2f60b11b765d3e6b3a5e7e8952/util.go#L146-L148
17,733
albrow/zoom
util.go
numericScore
func numericScore(val reflect.Value) float64 { for val.Kind() == reflect.Ptr { val = val.Elem() } switch val.Kind() { case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: integer := val.Int() return float64(integer) case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64: uinteger := val.Uint() return float64(uinteger) case reflect.Float32, reflect.Float64: return val.Float() default: msg := fmt.Sprintf("zoom: attempt to call numericScore on non-numeric type %s", val.Type().String()) panic(msg) } }
go
func numericScore(val reflect.Value) float64 { for val.Kind() == reflect.Ptr { val = val.Elem() } switch val.Kind() { case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: integer := val.Int() return float64(integer) case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64: uinteger := val.Uint() return float64(uinteger) case reflect.Float32, reflect.Float64: return val.Float() default: msg := fmt.Sprintf("zoom: attempt to call numericScore on non-numeric type %s", val.Type().String()) panic(msg) } }
[ "func", "numericScore", "(", "val", "reflect", ".", "Value", ")", "float64", "{", "for", "val", ".", "Kind", "(", ")", "==", "reflect", ".", "Ptr", "{", "val", "=", "val", ".", "Elem", "(", ")", "\n", "}", "\n", "switch", "val", ".", "Kind", "(",...
// numericScore returns a float64 which is the score for val in a sorted set. // If val is a pointer, it will keep dereferencing until it reaches the underlying // value. It panics if val is not a numeric type or a pointer to a numeric type.
[ "numericScore", "returns", "a", "float64", "which", "is", "the", "score", "for", "val", "in", "a", "sorted", "set", ".", "If", "val", "is", "a", "pointer", "it", "will", "keep", "dereferencing", "until", "it", "reaches", "the", "underlying", "value", ".", ...
4cc9cdbf65ce1b2f60b11b765d3e6b3a5e7e8952
https://github.com/albrow/zoom/blob/4cc9cdbf65ce1b2f60b11b765d3e6b3a5e7e8952/util.go#L153-L170
17,734
albrow/zoom
util.go
boolScore
func boolScore(val reflect.Value) int { for val.Kind() == reflect.Ptr { val = val.Elem() } if val.Kind() != reflect.Bool { msg := fmt.Sprintf("zoom: attempt to call boolScore on non-boolean type %s", val.Type().String()) panic(msg) } return convertBoolToInt(val.Bool()) }
go
func boolScore(val reflect.Value) int { for val.Kind() == reflect.Ptr { val = val.Elem() } if val.Kind() != reflect.Bool { msg := fmt.Sprintf("zoom: attempt to call boolScore on non-boolean type %s", val.Type().String()) panic(msg) } return convertBoolToInt(val.Bool()) }
[ "func", "boolScore", "(", "val", "reflect", ".", "Value", ")", "int", "{", "for", "val", ".", "Kind", "(", ")", "==", "reflect", ".", "Ptr", "{", "val", "=", "val", ".", "Elem", "(", ")", "\n", "}", "\n", "if", "val", ".", "Kind", "(", ")", "...
// boolScore returns an int which is the score for val in a sorted set. // If val is a pointer, it will keep dereferencing until it reaches the underlying // value. It panics if val is not a boolean or a pointer to a boolean.
[ "boolScore", "returns", "an", "int", "which", "is", "the", "score", "for", "val", "in", "a", "sorted", "set", ".", "If", "val", "is", "a", "pointer", "it", "will", "keep", "dereferencing", "until", "it", "reaches", "the", "underlying", "value", ".", "It"...
4cc9cdbf65ce1b2f60b11b765d3e6b3a5e7e8952
https://github.com/albrow/zoom/blob/4cc9cdbf65ce1b2f60b11b765d3e6b3a5e7e8952/util.go#L175-L184
17,735
albrow/zoom
util.go
modelIDs
func modelIDs(models []Model) []string { results := make([]string, len(models)) for i, m := range models { results[i] = m.ModelID() } return results }
go
func modelIDs(models []Model) []string { results := make([]string, len(models)) for i, m := range models { results[i] = m.ModelID() } return results }
[ "func", "modelIDs", "(", "models", "[", "]", "Model", ")", "[", "]", "string", "{", "results", ":=", "make", "(", "[", "]", "string", ",", "len", "(", "models", ")", ")", "\n", "for", "i", ",", "m", ":=", "range", "models", "{", "results", "[", ...
// modelIDs returns the ids for models
[ "modelIDs", "returns", "the", "ids", "for", "models" ]
4cc9cdbf65ce1b2f60b11b765d3e6b3a5e7e8952
https://github.com/albrow/zoom/blob/4cc9cdbf65ce1b2f60b11b765d3e6b3a5e7e8952/util.go#L197-L203
17,736
albrow/zoom
util.go
getTimeString
func getTimeString() string { timeInt := time.Now().UTC().Unix() timeBytes := base58.EncodeBig(nil, big.NewInt(timeInt)) return string(timeBytes) }
go
func getTimeString() string { timeInt := time.Now().UTC().Unix() timeBytes := base58.EncodeBig(nil, big.NewInt(timeInt)) return string(timeBytes) }
[ "func", "getTimeString", "(", ")", "string", "{", "timeInt", ":=", "time", ".", "Now", "(", ")", ".", "UTC", "(", ")", ".", "Unix", "(", ")", "\n", "timeBytes", ":=", "base58", ".", "EncodeBig", "(", "nil", ",", "big", ".", "NewInt", "(", "timeInt"...
// getTimeString returns the current UTC unix time with second precision encoded // with base58 encoding.
[ "getTimeString", "returns", "the", "current", "UTC", "unix", "time", "with", "second", "precision", "encoded", "with", "base58", "encoding", "." ]
4cc9cdbf65ce1b2f60b11b765d3e6b3a5e7e8952
https://github.com/albrow/zoom/blob/4cc9cdbf65ce1b2f60b11b765d3e6b3a5e7e8952/util.go#L219-L223
17,737
albrow/zoom
util.go
getAtomicCounter
func getAtomicCounter() string { atomic.AddInt32(&counter, 1) if counter > 58*58*58*58-1 { // Reset the counter if we're beyond what we // can represent with 4 base58 characters atomic.StoreInt32(&counter, 0) } counterBytes := base58.EncodeBig(nil, big.NewInt(int64(counter))) counterStr := string(counterBytes) switch len(counterStr) { case 0: return "0000" case 1: return "000" + counterStr case 2: return "00" + counterStr case 3: return "0" + counterStr default: return counterStr[0:4] } }
go
func getAtomicCounter() string { atomic.AddInt32(&counter, 1) if counter > 58*58*58*58-1 { // Reset the counter if we're beyond what we // can represent with 4 base58 characters atomic.StoreInt32(&counter, 0) } counterBytes := base58.EncodeBig(nil, big.NewInt(int64(counter))) counterStr := string(counterBytes) switch len(counterStr) { case 0: return "0000" case 1: return "000" + counterStr case 2: return "00" + counterStr case 3: return "0" + counterStr default: return counterStr[0:4] } }
[ "func", "getAtomicCounter", "(", ")", "string", "{", "atomic", ".", "AddInt32", "(", "&", "counter", ",", "1", ")", "\n", "if", "counter", ">", "58", "*", "58", "*", "58", "*", "58", "-", "1", "{", "// Reset the counter if we're beyond what we", "// can re...
// getAtomicCounter returns the base58 encoding of a counter which cycles through // the values in the range 0 to 11,316,495. This is the range that can be represented // with 4 base58 characters. The returned result will be padded with zeros such that // it is always 4 characters long.
[ "getAtomicCounter", "returns", "the", "base58", "encoding", "of", "a", "counter", "which", "cycles", "through", "the", "values", "in", "the", "range", "0", "to", "11", "316", "495", ".", "This", "is", "the", "range", "that", "can", "be", "represented", "wi...
4cc9cdbf65ce1b2f60b11b765d3e6b3a5e7e8952
https://github.com/albrow/zoom/blob/4cc9cdbf65ce1b2f60b11b765d3e6b3a5e7e8952/util.go#L261-L282
17,738
albrow/zoom
query.go
Limit
func (q *Query) Limit(amount uint) *Query { q.query.Limit(amount) return q }
go
func (q *Query) Limit(amount uint) *Query { q.query.Limit(amount) return q }
[ "func", "(", "q", "*", "Query", ")", "Limit", "(", "amount", "uint", ")", "*", "Query", "{", "q", ".", "query", ".", "Limit", "(", "amount", ")", "\n", "return", "q", "\n", "}" ]
// Limit specifies an upper limit on the number of models to return. If amount // is 0, no limit will be applied and any number of models may be returned. The // default value is 0.
[ "Limit", "specifies", "an", "upper", "limit", "on", "the", "number", "of", "models", "to", "return", ".", "If", "amount", "is", "0", "no", "limit", "will", "be", "applied", "and", "any", "number", "of", "models", "may", "be", "returned", ".", "The", "d...
4cc9cdbf65ce1b2f60b11b765d3e6b3a5e7e8952
https://github.com/albrow/zoom/blob/4cc9cdbf65ce1b2f60b11b765d3e6b3a5e7e8952/query.go#L42-L45
17,739
albrow/zoom
query.go
Include
func (q *Query) Include(fields ...string) *Query { q.query.Include(fields...) return q }
go
func (q *Query) Include(fields ...string) *Query { q.query.Include(fields...) return q }
[ "func", "(", "q", "*", "Query", ")", "Include", "(", "fields", "...", "string", ")", "*", "Query", "{", "q", ".", "query", ".", "Include", "(", "fields", "...", ")", "\n", "return", "q", "\n", "}" ]
// Include specifies one or more field names which will be read from the // database and scanned into the resulting models when the query is run. Field // names which are not specified in Include will not be read or scanned. You can // only use one of Include or Exclude, not both on the same query. Include will // set an error if you try to use it with Exclude on the same query. The error, // same as any other error that occurs during the lifetime of the query, is not // returned until the query is executed.
[ "Include", "specifies", "one", "or", "more", "field", "names", "which", "will", "be", "read", "from", "the", "database", "and", "scanned", "into", "the", "resulting", "models", "when", "the", "query", "is", "run", ".", "Field", "names", "which", "are", "no...
4cc9cdbf65ce1b2f60b11b765d3e6b3a5e7e8952
https://github.com/albrow/zoom/blob/4cc9cdbf65ce1b2f60b11b765d3e6b3a5e7e8952/query.go#L63-L66
17,740
albrow/zoom
internal_query.go
newQuery
func newQuery(collection *Collection) *query { q := &query{ collection: collection, pool: collection.pool, } // For now, only indexed collections are queryable. This might change in // future versions. if !collection.index { q.setError(fmt.Errorf("zoom: error in NewQuery: Only indexed collections are queryable")) return q } return q }
go
func newQuery(collection *Collection) *query { q := &query{ collection: collection, pool: collection.pool, } // For now, only indexed collections are queryable. This might change in // future versions. if !collection.index { q.setError(fmt.Errorf("zoom: error in NewQuery: Only indexed collections are queryable")) return q } return q }
[ "func", "newQuery", "(", "collection", "*", "Collection", ")", "*", "query", "{", "q", ":=", "&", "query", "{", "collection", ":", "collection", ",", "pool", ":", "collection", ".", "pool", ",", "}", "\n", "// For now, only indexed collections are queryable. Thi...
// newQuery creates and returns a new query with the given collection. It will // add an error to the query if the collection is not indexed.
[ "newQuery", "creates", "and", "returns", "a", "new", "query", "with", "the", "given", "collection", ".", "It", "will", "add", "an", "error", "to", "the", "query", "if", "the", "collection", "is", "not", "indexed", "." ]
4cc9cdbf65ce1b2f60b11b765d3e6b3a5e7e8952
https://github.com/albrow/zoom/blob/4cc9cdbf65ce1b2f60b11b765d3e6b3a5e7e8952/internal_query.go#L36-L48
17,741
albrow/zoom
internal_query.go
String
func (q *query) String() string { result := fmt.Sprintf("%s.NewQuery()", q.collection.Name()) for _, filter := range q.filters { result += fmt.Sprintf(".%s", filter) } if q.hasOrder() { result += fmt.Sprintf(".%s", q.order) } if q.hasOffset() { result += fmt.Sprintf(".Offset(%d)", q.offset) } if q.hasLimit() { result += fmt.Sprintf(".Limit(%d)", q.limit) } if q.hasIncludes() { result += fmt.Sprintf(`.Include("%s")`, strings.Join(q.includes, `", "`)) } else if q.hasExcludes() { result += fmt.Sprintf(`.Exclude("%s")`, strings.Join(q.excludes, `", "`)) } return result }
go
func (q *query) String() string { result := fmt.Sprintf("%s.NewQuery()", q.collection.Name()) for _, filter := range q.filters { result += fmt.Sprintf(".%s", filter) } if q.hasOrder() { result += fmt.Sprintf(".%s", q.order) } if q.hasOffset() { result += fmt.Sprintf(".Offset(%d)", q.offset) } if q.hasLimit() { result += fmt.Sprintf(".Limit(%d)", q.limit) } if q.hasIncludes() { result += fmt.Sprintf(`.Include("%s")`, strings.Join(q.includes, `", "`)) } else if q.hasExcludes() { result += fmt.Sprintf(`.Exclude("%s")`, strings.Join(q.excludes, `", "`)) } return result }
[ "func", "(", "q", "*", "query", ")", "String", "(", ")", "string", "{", "result", ":=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "q", ".", "collection", ".", "Name", "(", ")", ")", "\n", "for", "_", ",", "filter", ":=", "range", "q", ".", ...
// String satisfies fmt.Stringer and prints out the query in a format that // matches the go code used to declare it.
[ "String", "satisfies", "fmt", ".", "Stringer", "and", "prints", "out", "the", "query", "in", "a", "format", "that", "matches", "the", "go", "code", "used", "to", "declare", "it", "." ]
4cc9cdbf65ce1b2f60b11b765d3e6b3a5e7e8952
https://github.com/albrow/zoom/blob/4cc9cdbf65ce1b2f60b11b765d3e6b3a5e7e8952/internal_query.go#L52-L72
17,742
albrow/zoom
internal_query.go
setError
func (q *query) setError(e error) { if !q.hasError() { q.err = e } }
go
func (q *query) setError(e error) { if !q.hasError() { q.err = e } }
[ "func", "(", "q", "*", "query", ")", "setError", "(", "e", "error", ")", "{", "if", "!", "q", ".", "hasError", "(", ")", "{", "q", ".", "err", "=", "e", "\n", "}", "\n", "}" ]
// setError sets the err property of q only if it has not already been set
[ "setError", "sets", "the", "err", "property", "of", "q", "only", "if", "it", "has", "not", "already", "been", "set" ]
4cc9cdbf65ce1b2f60b11b765d3e6b3a5e7e8952
https://github.com/albrow/zoom/blob/4cc9cdbf65ce1b2f60b11b765d3e6b3a5e7e8952/internal_query.go#L156-L160
17,743
albrow/zoom
internal_query.go
checkValType
func (f filter) checkValType(value interface{}) error { // Here we iterate through pointer indirections. This is so you can // just pass in a primitive instead of a pointer to a primitive for // filtering on fields which have pointer values. valueType := reflect.TypeOf(value) valueVal := reflect.ValueOf(value) for valueType.Kind() == reflect.Ptr { valueType = valueType.Elem() valueVal = valueVal.Elem() if !valueVal.IsValid() { return errors.New("zoom: invalid value for Filter. Is it a nil pointer?") } } // Also dereference the field type to reach the underlying type. fieldType := f.fieldSpec.typ for fieldType.Kind() == reflect.Ptr { fieldType = fieldType.Elem() } if valueType != fieldType { return fmt.Errorf("zoom: invalid value for Filter on %s: type of value (%T) does not match type of field (%s)", f.fieldSpec.name, value, fieldType.String()) } return nil }
go
func (f filter) checkValType(value interface{}) error { // Here we iterate through pointer indirections. This is so you can // just pass in a primitive instead of a pointer to a primitive for // filtering on fields which have pointer values. valueType := reflect.TypeOf(value) valueVal := reflect.ValueOf(value) for valueType.Kind() == reflect.Ptr { valueType = valueType.Elem() valueVal = valueVal.Elem() if !valueVal.IsValid() { return errors.New("zoom: invalid value for Filter. Is it a nil pointer?") } } // Also dereference the field type to reach the underlying type. fieldType := f.fieldSpec.typ for fieldType.Kind() == reflect.Ptr { fieldType = fieldType.Elem() } if valueType != fieldType { return fmt.Errorf("zoom: invalid value for Filter on %s: type of value (%T) does not match type of field (%s)", f.fieldSpec.name, value, fieldType.String()) } return nil }
[ "func", "(", "f", "filter", ")", "checkValType", "(", "value", "interface", "{", "}", ")", "error", "{", "// Here we iterate through pointer indirections. This is so you can", "// just pass in a primitive instead of a pointer to a primitive for", "// filtering on fields which have po...
// checkValType returns an error if the type of value does not correspond to // filter.fieldSpec.
[ "checkValType", "returns", "an", "error", "if", "the", "type", "of", "value", "does", "not", "correspond", "to", "filter", ".", "fieldSpec", "." ]
4cc9cdbf65ce1b2f60b11b765d3e6b3a5e7e8952
https://github.com/albrow/zoom/blob/4cc9cdbf65ce1b2f60b11b765d3e6b3a5e7e8952/internal_query.go#L314-L336
17,744
albrow/zoom
internal_query.go
generateIDsSet
func generateIDsSet(q *query, tx *Transaction) (idsKey string, tmpKeys []interface{}, err error) { idsKey = q.collection.spec.indexKey() tmpKeys = []interface{}{} if q.hasOrder() { fieldIndexKey, err := q.collection.spec.fieldIndexKey(q.order.fieldName) if err != nil { return "", nil, err } fieldSpec := q.collection.spec.fieldsByName[q.order.fieldName] if fieldSpec.indexKind == stringIndex { // If the order is a string field, we need to extract the ids before // we use ZRANGE. Create a temporary set to store the ordered ids orderedIDsKey := generateRandomKey("tmp:order:" + q.order.fieldName) tmpKeys = append(tmpKeys, orderedIDsKey) idsKey = orderedIDsKey // TODO: as an optimization, if there is a filter on the same field, // pass the start and stop parameters to the script. tx.ExtractIDsFromStringIndex(fieldIndexKey, orderedIDsKey, "-", "+") } else { idsKey = fieldIndexKey } } if q.hasFilters() { filteredIDsKey := generateRandomKey("tmp:filter:all") tmpKeys = append(tmpKeys, filteredIDsKey) for i, filter := range q.filters { if i == 0 { // The first time, we should intersect with the ids key from above if err := intersectFilter(q, tx, filter, idsKey, filteredIDsKey); err != nil { return "", tmpKeys, err } } else { // All other times, we should intersect with the filteredIDsKey itself if err := intersectFilter(q, tx, filter, filteredIDsKey, filteredIDsKey); err != nil { return "", tmpKeys, err } } } idsKey = filteredIDsKey } return idsKey, tmpKeys, nil }
go
func generateIDsSet(q *query, tx *Transaction) (idsKey string, tmpKeys []interface{}, err error) { idsKey = q.collection.spec.indexKey() tmpKeys = []interface{}{} if q.hasOrder() { fieldIndexKey, err := q.collection.spec.fieldIndexKey(q.order.fieldName) if err != nil { return "", nil, err } fieldSpec := q.collection.spec.fieldsByName[q.order.fieldName] if fieldSpec.indexKind == stringIndex { // If the order is a string field, we need to extract the ids before // we use ZRANGE. Create a temporary set to store the ordered ids orderedIDsKey := generateRandomKey("tmp:order:" + q.order.fieldName) tmpKeys = append(tmpKeys, orderedIDsKey) idsKey = orderedIDsKey // TODO: as an optimization, if there is a filter on the same field, // pass the start and stop parameters to the script. tx.ExtractIDsFromStringIndex(fieldIndexKey, orderedIDsKey, "-", "+") } else { idsKey = fieldIndexKey } } if q.hasFilters() { filteredIDsKey := generateRandomKey("tmp:filter:all") tmpKeys = append(tmpKeys, filteredIDsKey) for i, filter := range q.filters { if i == 0 { // The first time, we should intersect with the ids key from above if err := intersectFilter(q, tx, filter, idsKey, filteredIDsKey); err != nil { return "", tmpKeys, err } } else { // All other times, we should intersect with the filteredIDsKey itself if err := intersectFilter(q, tx, filter, filteredIDsKey, filteredIDsKey); err != nil { return "", tmpKeys, err } } } idsKey = filteredIDsKey } return idsKey, tmpKeys, nil }
[ "func", "generateIDsSet", "(", "q", "*", "query", ",", "tx", "*", "Transaction", ")", "(", "idsKey", "string", ",", "tmpKeys", "[", "]", "interface", "{", "}", ",", "err", "error", ")", "{", "idsKey", "=", "q", ".", "collection", ".", "spec", ".", ...
// generateIDsSet will return the key of a set or sorted set that contains all the ids // which match the query criteria. It may also return some temporary keys which were created // during the process of creating the set of ids. Note that tmpKeys may contain idsKey itself, // so the temporary keys should not be deleted until after the ids have been read from idsKey.
[ "generateIDsSet", "will", "return", "the", "key", "of", "a", "set", "or", "sorted", "set", "that", "contains", "all", "the", "ids", "which", "match", "the", "query", "criteria", ".", "It", "may", "also", "return", "some", "temporary", "keys", "which", "wer...
4cc9cdbf65ce1b2f60b11b765d3e6b3a5e7e8952
https://github.com/albrow/zoom/blob/4cc9cdbf65ce1b2f60b11b765d3e6b3a5e7e8952/internal_query.go#L342-L383
17,745
albrow/zoom
internal_query.go
intersectFilter
func intersectFilter(q *query, tx *Transaction, filter filter, origKey string, destKey string) error { switch filter.fieldSpec.indexKind { case numericIndex: return intersectNumericFilter(q, tx, filter, origKey, destKey) case booleanIndex: return intersectBoolFilter(q, tx, filter, origKey, destKey) case stringIndex: return intersectStringFilter(q, tx, filter, origKey, destKey) } return nil }
go
func intersectFilter(q *query, tx *Transaction, filter filter, origKey string, destKey string) error { switch filter.fieldSpec.indexKind { case numericIndex: return intersectNumericFilter(q, tx, filter, origKey, destKey) case booleanIndex: return intersectBoolFilter(q, tx, filter, origKey, destKey) case stringIndex: return intersectStringFilter(q, tx, filter, origKey, destKey) } return nil }
[ "func", "intersectFilter", "(", "q", "*", "query", ",", "tx", "*", "Transaction", ",", "filter", "filter", ",", "origKey", "string", ",", "destKey", "string", ")", "error", "{", "switch", "filter", ".", "fieldSpec", ".", "indexKind", "{", "case", "numericI...
// intersectFilter adds commands to the query transaction which, when run, will create a // temporary set which contains all the ids that fit the given filter criteria. Then it will // intersect them with origKey and stores the result in destKey. The function will automatically // delete any temporary sets created since, in this case, they are guaranteed to not be needed // by any other transaction commands.
[ "intersectFilter", "adds", "commands", "to", "the", "query", "transaction", "which", "when", "run", "will", "create", "a", "temporary", "set", "which", "contains", "all", "the", "ids", "that", "fit", "the", "given", "filter", "criteria", ".", "Then", "it", "...
4cc9cdbf65ce1b2f60b11b765d3e6b3a5e7e8952
https://github.com/albrow/zoom/blob/4cc9cdbf65ce1b2f60b11b765d3e6b3a5e7e8952/internal_query.go#L390-L400
17,746
albrow/zoom
internal_query.go
intersectNumericFilter
func intersectNumericFilter(q *query, tx *Transaction, filter filter, origKey string, destKey string) error { fieldIndexKey, err := q.collection.spec.fieldIndexKey(filter.fieldSpec.name) if err != nil { return err } if filter.op == notEqualOp { // Special case for not equal. We need to use two separate commands valueExclusive := fmt.Sprintf("(%v", filter.value.Interface()) filterKey := generateRandomKey("tmp:filter:" + fieldIndexKey) // ZADD all ids greater than filter.value tx.ExtractIDsFromFieldIndex(fieldIndexKey, filterKey, valueExclusive, "+inf") // ZADD all ids less than filter.value tx.ExtractIDsFromFieldIndex(fieldIndexKey, filterKey, "-inf", valueExclusive) // Intersect filterKey with origKey and store result in destKey tx.Command("ZINTERSTORE", redis.Args{destKey, 2, origKey, filterKey, "WEIGHTS", 1, 0}, nil) // Delete the temporary key tx.Command("DEL", redis.Args{filterKey}, nil) } else { var min, max interface{} switch filter.op { case equalOp: min, max = filter.value.Interface(), filter.value.Interface() case lessOp: min = "-inf" // use "(" for exclusive max = fmt.Sprintf("(%v", filter.value.Interface()) case greaterOp: min = fmt.Sprintf("(%v", filter.value.Interface()) max = "+inf" case lessOrEqualOp: min = "-inf" max = filter.value.Interface() case greaterOrEqualOp: min = filter.value.Interface() max = "+inf" } // Get all the ids that fit the filter criteria and store them in a temporary key caled filterKey filterKey := generateRandomKey("tmp:filter:" + fieldIndexKey) tx.ExtractIDsFromFieldIndex(fieldIndexKey, filterKey, min, max) // Intersect filterKey with origKey and store result in destKey tx.Command("ZINTERSTORE", redis.Args{destKey, 2, origKey, filterKey, "WEIGHTS", 1, 0}, nil) // Delete the temporary key tx.Command("DEL", redis.Args{filterKey}, nil) } return nil }
go
func intersectNumericFilter(q *query, tx *Transaction, filter filter, origKey string, destKey string) error { fieldIndexKey, err := q.collection.spec.fieldIndexKey(filter.fieldSpec.name) if err != nil { return err } if filter.op == notEqualOp { // Special case for not equal. We need to use two separate commands valueExclusive := fmt.Sprintf("(%v", filter.value.Interface()) filterKey := generateRandomKey("tmp:filter:" + fieldIndexKey) // ZADD all ids greater than filter.value tx.ExtractIDsFromFieldIndex(fieldIndexKey, filterKey, valueExclusive, "+inf") // ZADD all ids less than filter.value tx.ExtractIDsFromFieldIndex(fieldIndexKey, filterKey, "-inf", valueExclusive) // Intersect filterKey with origKey and store result in destKey tx.Command("ZINTERSTORE", redis.Args{destKey, 2, origKey, filterKey, "WEIGHTS", 1, 0}, nil) // Delete the temporary key tx.Command("DEL", redis.Args{filterKey}, nil) } else { var min, max interface{} switch filter.op { case equalOp: min, max = filter.value.Interface(), filter.value.Interface() case lessOp: min = "-inf" // use "(" for exclusive max = fmt.Sprintf("(%v", filter.value.Interface()) case greaterOp: min = fmt.Sprintf("(%v", filter.value.Interface()) max = "+inf" case lessOrEqualOp: min = "-inf" max = filter.value.Interface() case greaterOrEqualOp: min = filter.value.Interface() max = "+inf" } // Get all the ids that fit the filter criteria and store them in a temporary key caled filterKey filterKey := generateRandomKey("tmp:filter:" + fieldIndexKey) tx.ExtractIDsFromFieldIndex(fieldIndexKey, filterKey, min, max) // Intersect filterKey with origKey and store result in destKey tx.Command("ZINTERSTORE", redis.Args{destKey, 2, origKey, filterKey, "WEIGHTS", 1, 0}, nil) // Delete the temporary key tx.Command("DEL", redis.Args{filterKey}, nil) } return nil }
[ "func", "intersectNumericFilter", "(", "q", "*", "query", ",", "tx", "*", "Transaction", ",", "filter", "filter", ",", "origKey", "string", ",", "destKey", "string", ")", "error", "{", "fieldIndexKey", ",", "err", ":=", "q", ".", "collection", ".", "spec",...
// intersectNumericFilter adds commands to the query transaction which, when run, will // create a temporary set which contains all the ids of models which match the given // numeric filter criteria, then intersect those ids with origKey and store the result // in destKey.
[ "intersectNumericFilter", "adds", "commands", "to", "the", "query", "transaction", "which", "when", "run", "will", "create", "a", "temporary", "set", "which", "contains", "all", "the", "ids", "of", "models", "which", "match", "the", "given", "numeric", "filter",...
4cc9cdbf65ce1b2f60b11b765d3e6b3a5e7e8952
https://github.com/albrow/zoom/blob/4cc9cdbf65ce1b2f60b11b765d3e6b3a5e7e8952/internal_query.go#L406-L451
17,747
albrow/zoom
internal_query.go
intersectBoolFilter
func intersectBoolFilter(q *query, tx *Transaction, filter filter, origKey string, destKey string) error { fieldIndexKey, err := q.collection.spec.fieldIndexKey(filter.fieldSpec.name) if err != nil { return err } var min, max interface{} switch filter.op { case equalOp: if filter.value.Bool() { min, max = 1, 1 } else { min, max = 0, 0 } case lessOp: if filter.value.Bool() { // Only false is less than true min, max = 0, 0 } else { // No models are less than false, // so we should eliminate all models min, max = -1, -1 } case greaterOp: if filter.value.Bool() { // No models are greater than true, // so we should eliminate all models min, max = -1, -1 } else { // Only true is greater than false min, max = 1, 1 } case lessOrEqualOp: if filter.value.Bool() { // All models are <= true min, max = 0, 1 } else { // Only false is <= false min, max = 0, 0 } case greaterOrEqualOp: if filter.value.Bool() { // Only true is >= true min, max = 1, 1 } else { // All models are >= false min, max = 0, 1 } case notEqualOp: if filter.value.Bool() { min, max = 0, 0 } else { min, max = 1, 1 } } // Get all the ids that fit the filter criteria and store them in a temporary key caled filterKey filterKey := generateRandomKey("tmp:filter:" + fieldIndexKey) tx.ExtractIDsFromFieldIndex(fieldIndexKey, filterKey, min, max) // Intersect filterKey with origKey and store result in destKey tx.Command("ZINTERSTORE", redis.Args{destKey, 2, origKey, filterKey, "WEIGHTS", 1, 0}, nil) // Delete the temporary key tx.Command("DEL", redis.Args{filterKey}, nil) return nil }
go
func intersectBoolFilter(q *query, tx *Transaction, filter filter, origKey string, destKey string) error { fieldIndexKey, err := q.collection.spec.fieldIndexKey(filter.fieldSpec.name) if err != nil { return err } var min, max interface{} switch filter.op { case equalOp: if filter.value.Bool() { min, max = 1, 1 } else { min, max = 0, 0 } case lessOp: if filter.value.Bool() { // Only false is less than true min, max = 0, 0 } else { // No models are less than false, // so we should eliminate all models min, max = -1, -1 } case greaterOp: if filter.value.Bool() { // No models are greater than true, // so we should eliminate all models min, max = -1, -1 } else { // Only true is greater than false min, max = 1, 1 } case lessOrEqualOp: if filter.value.Bool() { // All models are <= true min, max = 0, 1 } else { // Only false is <= false min, max = 0, 0 } case greaterOrEqualOp: if filter.value.Bool() { // Only true is >= true min, max = 1, 1 } else { // All models are >= false min, max = 0, 1 } case notEqualOp: if filter.value.Bool() { min, max = 0, 0 } else { min, max = 1, 1 } } // Get all the ids that fit the filter criteria and store them in a temporary key caled filterKey filterKey := generateRandomKey("tmp:filter:" + fieldIndexKey) tx.ExtractIDsFromFieldIndex(fieldIndexKey, filterKey, min, max) // Intersect filterKey with origKey and store result in destKey tx.Command("ZINTERSTORE", redis.Args{destKey, 2, origKey, filterKey, "WEIGHTS", 1, 0}, nil) // Delete the temporary key tx.Command("DEL", redis.Args{filterKey}, nil) return nil }
[ "func", "intersectBoolFilter", "(", "q", "*", "query", ",", "tx", "*", "Transaction", ",", "filter", "filter", ",", "origKey", "string", ",", "destKey", "string", ")", "error", "{", "fieldIndexKey", ",", "err", ":=", "q", ".", "collection", ".", "spec", ...
// intersectBoolFilter adds commands to the query transaction which, when run, will // create a temporary set which contains all the ids of models which match the given // bool filter criteria, then intersect those ids with origKey and store the result // in destKey.
[ "intersectBoolFilter", "adds", "commands", "to", "the", "query", "transaction", "which", "when", "run", "will", "create", "a", "temporary", "set", "which", "contains", "all", "the", "ids", "of", "models", "which", "match", "the", "given", "bool", "filter", "cr...
4cc9cdbf65ce1b2f60b11b765d3e6b3a5e7e8952
https://github.com/albrow/zoom/blob/4cc9cdbf65ce1b2f60b11b765d3e6b3a5e7e8952/internal_query.go#L457-L519
17,748
albrow/zoom
internal_query.go
intersectStringFilter
func intersectStringFilter(q *query, tx *Transaction, filter filter, origKey string, destKey string) error { fieldIndexKey, err := q.collection.spec.fieldIndexKey(filter.fieldSpec.name) if err != nil { return err } valString := filter.value.String() if filter.op == notEqualOp { // Special case for not equal. We need to use two separate commands filterKey := generateRandomKey("tmp:filter:" + fieldIndexKey) // ZADD all ids greater than filter.value min := "(" + valString + nullString + delString tx.ExtractIDsFromStringIndex(fieldIndexKey, filterKey, min, "+") // ZADD all ids less than filter.value max := "(" + valString tx.ExtractIDsFromStringIndex(fieldIndexKey, filterKey, "-", max) // Intersect filterKey with origKey and store result in destKey tx.Command("ZINTERSTORE", redis.Args{destKey, 2, origKey, filterKey, "WEIGHTS", 1, 0}, nil) // Delete the temporary key tx.Command("DEL", redis.Args{filterKey}, nil) } else { var min, max string switch filter.op { case equalOp: min = "[" + valString max = "(" + valString + nullString + delString case lessOp: min = "-" max = "(" + valString case greaterOp: min = "(" + valString + nullString + delString max = "+" case lessOrEqualOp: min = "-" max = "(" + valString + nullString + delString case greaterOrEqualOp: min = "[" + valString max = "+" } // Get all the ids that fit the filter criteria and store them in a temporary key caled filterKey filterKey := generateRandomKey("tmp:filter:" + fieldIndexKey) tx.ExtractIDsFromStringIndex(fieldIndexKey, filterKey, min, max) // Intersect filterKey with origKey and store result in destKey tx.Command("ZINTERSTORE", redis.Args{destKey, 2, origKey, filterKey, "WEIGHTS", 1, 0}, nil) // Delete the temporary key tx.Command("DEL", redis.Args{filterKey}, nil) } return nil }
go
func intersectStringFilter(q *query, tx *Transaction, filter filter, origKey string, destKey string) error { fieldIndexKey, err := q.collection.spec.fieldIndexKey(filter.fieldSpec.name) if err != nil { return err } valString := filter.value.String() if filter.op == notEqualOp { // Special case for not equal. We need to use two separate commands filterKey := generateRandomKey("tmp:filter:" + fieldIndexKey) // ZADD all ids greater than filter.value min := "(" + valString + nullString + delString tx.ExtractIDsFromStringIndex(fieldIndexKey, filterKey, min, "+") // ZADD all ids less than filter.value max := "(" + valString tx.ExtractIDsFromStringIndex(fieldIndexKey, filterKey, "-", max) // Intersect filterKey with origKey and store result in destKey tx.Command("ZINTERSTORE", redis.Args{destKey, 2, origKey, filterKey, "WEIGHTS", 1, 0}, nil) // Delete the temporary key tx.Command("DEL", redis.Args{filterKey}, nil) } else { var min, max string switch filter.op { case equalOp: min = "[" + valString max = "(" + valString + nullString + delString case lessOp: min = "-" max = "(" + valString case greaterOp: min = "(" + valString + nullString + delString max = "+" case lessOrEqualOp: min = "-" max = "(" + valString + nullString + delString case greaterOrEqualOp: min = "[" + valString max = "+" } // Get all the ids that fit the filter criteria and store them in a temporary key caled filterKey filterKey := generateRandomKey("tmp:filter:" + fieldIndexKey) tx.ExtractIDsFromStringIndex(fieldIndexKey, filterKey, min, max) // Intersect filterKey with origKey and store result in destKey tx.Command("ZINTERSTORE", redis.Args{destKey, 2, origKey, filterKey, "WEIGHTS", 1, 0}, nil) // Delete the temporary key tx.Command("DEL", redis.Args{filterKey}, nil) } return nil }
[ "func", "intersectStringFilter", "(", "q", "*", "query", ",", "tx", "*", "Transaction", ",", "filter", "filter", ",", "origKey", "string", ",", "destKey", "string", ")", "error", "{", "fieldIndexKey", ",", "err", ":=", "q", ".", "collection", ".", "spec", ...
// intersectStringFilter adds commands to the query transaction which, when run, will // create a temporary set which contains all the ids of models which match the given // string filter criteria, then intersect those ids with origKey and store the result // in destKey.
[ "intersectStringFilter", "adds", "commands", "to", "the", "query", "transaction", "which", "when", "run", "will", "create", "a", "temporary", "set", "which", "contains", "all", "the", "ids", "of", "models", "which", "match", "the", "given", "string", "filter", ...
4cc9cdbf65ce1b2f60b11b765d3e6b3a5e7e8952
https://github.com/albrow/zoom/blob/4cc9cdbf65ce1b2f60b11b765d3e6b3a5e7e8952/internal_query.go#L525-L572
17,749
albrow/zoom
internal_query.go
fieldNames
func (q *query) fieldNames() []string { switch { case q.hasIncludes(): return q.includes case q.hasExcludes(): results := q.collection.spec.fieldNames() for _, name := range q.excludes { results = removeElementFromStringSlice(results, name) } return results default: return q.collection.spec.fieldNames() } }
go
func (q *query) fieldNames() []string { switch { case q.hasIncludes(): return q.includes case q.hasExcludes(): results := q.collection.spec.fieldNames() for _, name := range q.excludes { results = removeElementFromStringSlice(results, name) } return results default: return q.collection.spec.fieldNames() } }
[ "func", "(", "q", "*", "query", ")", "fieldNames", "(", ")", "[", "]", "string", "{", "switch", "{", "case", "q", ".", "hasIncludes", "(", ")", ":", "return", "q", ".", "includes", "\n", "case", "q", ".", "hasExcludes", "(", ")", ":", "results", ...
// fieldNames parses the includes and excludes properties to return a list of // field names which should be included in all find operations. If there are no // includes or excludes, it returns all the field names.
[ "fieldNames", "parses", "the", "includes", "and", "excludes", "properties", "to", "return", "a", "list", "of", "field", "names", "which", "should", "be", "included", "in", "all", "find", "operations", ".", "If", "there", "are", "no", "includes", "or", "exclu...
4cc9cdbf65ce1b2f60b11b765d3e6b3a5e7e8952
https://github.com/albrow/zoom/blob/4cc9cdbf65ce1b2f60b11b765d3e6b3a5e7e8952/internal_query.go#L577-L590
17,750
albrow/zoom
internal_query.go
redisFieldNames
func (q *query) redisFieldNames() []string { fieldNames := q.fieldNames() redisNames := []string{} for _, fieldName := range fieldNames { redisNames = append(redisNames, q.collection.spec.fieldsByName[fieldName].redisName) } return redisNames }
go
func (q *query) redisFieldNames() []string { fieldNames := q.fieldNames() redisNames := []string{} for _, fieldName := range fieldNames { redisNames = append(redisNames, q.collection.spec.fieldsByName[fieldName].redisName) } return redisNames }
[ "func", "(", "q", "*", "query", ")", "redisFieldNames", "(", ")", "[", "]", "string", "{", "fieldNames", ":=", "q", ".", "fieldNames", "(", ")", "\n", "redisNames", ":=", "[", "]", "string", "{", "}", "\n", "for", "_", ",", "fieldName", ":=", "rang...
// redisFieldNames parses the includes and excludes properties to return a list of // redis names for each field which should be included in all find operations. If // there are no includes or excludes, it returns the redis names for all fields.
[ "redisFieldNames", "parses", "the", "includes", "and", "excludes", "properties", "to", "return", "a", "list", "of", "redis", "names", "for", "each", "field", "which", "should", "be", "included", "in", "all", "find", "operations", ".", "If", "there", "are", "...
4cc9cdbf65ce1b2f60b11b765d3e6b3a5e7e8952
https://github.com/albrow/zoom/blob/4cc9cdbf65ce1b2f60b11b765d3e6b3a5e7e8952/internal_query.go#L595-L602
17,751
albrow/zoom
internal_query.go
getStartStop
func (q *query) getStartStop() (start int, stop int) { start = int(q.offset) stop = -1 if q.hasLimit() { stop = start + int(q.limit) - 1 } return start, stop }
go
func (q *query) getStartStop() (start int, stop int) { start = int(q.offset) stop = -1 if q.hasLimit() { stop = start + int(q.limit) - 1 } return start, stop }
[ "func", "(", "q", "*", "query", ")", "getStartStop", "(", ")", "(", "start", "int", ",", "stop", "int", ")", "{", "start", "=", "int", "(", "q", ".", "offset", ")", "\n", "stop", "=", "-", "1", "\n", "if", "q", ".", "hasLimit", "(", ")", "{",...
// converts limit and offset to start and stop values for cases where redis // requires them. NOTE start cannot be negative, but stop can be
[ "converts", "limit", "and", "offset", "to", "start", "and", "stop", "values", "for", "cases", "where", "redis", "requires", "them", ".", "NOTE", "start", "cannot", "be", "negative", "but", "stop", "can", "be" ]
4cc9cdbf65ce1b2f60b11b765d3e6b3a5e7e8952
https://github.com/albrow/zoom/blob/4cc9cdbf65ce1b2f60b11b765d3e6b3a5e7e8952/internal_query.go#L606-L613
17,752
albrow/zoom
handlers.go
newModelExistsHandler
func newModelExistsHandler(collection *Collection, modelID string) ReplyHandler { return func(reply interface{}) error { exists, err := redis.Bool(reply, nil) if err != nil { return err } if !exists { return ModelNotFoundError{ Collection: collection, Msg: fmt.Sprintf("Could not find %s with id = %s", collection.spec.name, modelID), } } return nil } }
go
func newModelExistsHandler(collection *Collection, modelID string) ReplyHandler { return func(reply interface{}) error { exists, err := redis.Bool(reply, nil) if err != nil { return err } if !exists { return ModelNotFoundError{ Collection: collection, Msg: fmt.Sprintf("Could not find %s with id = %s", collection.spec.name, modelID), } } return nil } }
[ "func", "newModelExistsHandler", "(", "collection", "*", "Collection", ",", "modelID", "string", ")", "ReplyHandler", "{", "return", "func", "(", "reply", "interface", "{", "}", ")", "error", "{", "exists", ",", "err", ":=", "redis", ".", "Bool", "(", "rep...
// newModelExistsHandler returns a reply handler which will return a // ModelNotFound error if the value of reply is false. It is expected to be // used as the reply handler for an EXISTS command.
[ "newModelExistsHandler", "returns", "a", "reply", "handler", "which", "will", "return", "a", "ModelNotFound", "error", "if", "the", "value", "of", "reply", "is", "false", ".", "It", "is", "expected", "to", "be", "used", "as", "the", "reply", "handler", "for"...
4cc9cdbf65ce1b2f60b11b765d3e6b3a5e7e8952
https://github.com/albrow/zoom/blob/4cc9cdbf65ce1b2f60b11b765d3e6b3a5e7e8952/handlers.go#L26-L40
17,753
albrow/zoom
handlers.go
NewScanIntHandler
func NewScanIntHandler(i *int) ReplyHandler { return func(reply interface{}) error { var err error (*i), err = redis.Int(reply, nil) if err != nil { return err } return nil } }
go
func NewScanIntHandler(i *int) ReplyHandler { return func(reply interface{}) error { var err error (*i), err = redis.Int(reply, nil) if err != nil { return err } return nil } }
[ "func", "NewScanIntHandler", "(", "i", "*", "int", ")", "ReplyHandler", "{", "return", "func", "(", "reply", "interface", "{", "}", ")", "error", "{", "var", "err", "error", "\n", "(", "*", "i", ")", ",", "err", "=", "redis", ".", "Int", "(", "repl...
// NewScanIntHandler returns a ReplyHandler which will convert the reply to an // integer and set the value of i to the converted integer. The ReplyHandler // will return an error if there was a problem converting the reply.
[ "NewScanIntHandler", "returns", "a", "ReplyHandler", "which", "will", "convert", "the", "reply", "to", "an", "integer", "and", "set", "the", "value", "of", "i", "to", "the", "converted", "integer", ".", "The", "ReplyHandler", "will", "return", "an", "error", ...
4cc9cdbf65ce1b2f60b11b765d3e6b3a5e7e8952
https://github.com/albrow/zoom/blob/4cc9cdbf65ce1b2f60b11b765d3e6b3a5e7e8952/handlers.go#L45-L54
17,754
albrow/zoom
handlers.go
NewScanBoolHandler
func NewScanBoolHandler(b *bool) ReplyHandler { return func(reply interface{}) error { var err error (*b), err = redis.Bool(reply, nil) if err != nil { return err } return nil } }
go
func NewScanBoolHandler(b *bool) ReplyHandler { return func(reply interface{}) error { var err error (*b), err = redis.Bool(reply, nil) if err != nil { return err } return nil } }
[ "func", "NewScanBoolHandler", "(", "b", "*", "bool", ")", "ReplyHandler", "{", "return", "func", "(", "reply", "interface", "{", "}", ")", "error", "{", "var", "err", "error", "\n", "(", "*", "b", ")", ",", "err", "=", "redis", ".", "Bool", "(", "r...
// NewScanBoolHandler returns a ReplyHandler which will convert the reply to a // bool and set the value of i to the converted bool. The ReplyHandler // will return an error if there was a problem converting the reply.
[ "NewScanBoolHandler", "returns", "a", "ReplyHandler", "which", "will", "convert", "the", "reply", "to", "a", "bool", "and", "set", "the", "value", "of", "i", "to", "the", "converted", "bool", ".", "The", "ReplyHandler", "will", "return", "an", "error", "if",...
4cc9cdbf65ce1b2f60b11b765d3e6b3a5e7e8952
https://github.com/albrow/zoom/blob/4cc9cdbf65ce1b2f60b11b765d3e6b3a5e7e8952/handlers.go#L59-L68
17,755
albrow/zoom
handlers.go
NewScanStringHandler
func NewScanStringHandler(s *string) ReplyHandler { return func(reply interface{}) error { var err error (*s), err = redis.String(reply, nil) if err != nil { return err } return nil } }
go
func NewScanStringHandler(s *string) ReplyHandler { return func(reply interface{}) error { var err error (*s), err = redis.String(reply, nil) if err != nil { return err } return nil } }
[ "func", "NewScanStringHandler", "(", "s", "*", "string", ")", "ReplyHandler", "{", "return", "func", "(", "reply", "interface", "{", "}", ")", "error", "{", "var", "err", "error", "\n", "(", "*", "s", ")", ",", "err", "=", "redis", ".", "String", "("...
// NewScanStringHandler returns a ReplyHandler which will convert the reply to // a string and set the value of i to the converted string. The ReplyHandler // will return an error if there was a problem converting the reply.
[ "NewScanStringHandler", "returns", "a", "ReplyHandler", "which", "will", "convert", "the", "reply", "to", "a", "string", "and", "set", "the", "value", "of", "i", "to", "the", "converted", "string", ".", "The", "ReplyHandler", "will", "return", "an", "error", ...
4cc9cdbf65ce1b2f60b11b765d3e6b3a5e7e8952
https://github.com/albrow/zoom/blob/4cc9cdbf65ce1b2f60b11b765d3e6b3a5e7e8952/handlers.go#L73-L82
17,756
albrow/zoom
handlers.go
NewScanFloat64Handler
func NewScanFloat64Handler(f *float64) ReplyHandler { return func(reply interface{}) error { var err error (*f), err = redis.Float64(reply, nil) if err != nil { return err } return nil } }
go
func NewScanFloat64Handler(f *float64) ReplyHandler { return func(reply interface{}) error { var err error (*f), err = redis.Float64(reply, nil) if err != nil { return err } return nil } }
[ "func", "NewScanFloat64Handler", "(", "f", "*", "float64", ")", "ReplyHandler", "{", "return", "func", "(", "reply", "interface", "{", "}", ")", "error", "{", "var", "err", "error", "\n", "(", "*", "f", ")", ",", "err", "=", "redis", ".", "Float64", ...
// NewScanFloat64Handler returns a ReplyHandler which will convert the reply to a // float64 and set the value of f to the converted value. The ReplyHandler // will return an error if there was a problem converting the reply.
[ "NewScanFloat64Handler", "returns", "a", "ReplyHandler", "which", "will", "convert", "the", "reply", "to", "a", "float64", "and", "set", "the", "value", "of", "f", "to", "the", "converted", "value", ".", "The", "ReplyHandler", "will", "return", "an", "error", ...
4cc9cdbf65ce1b2f60b11b765d3e6b3a5e7e8952
https://github.com/albrow/zoom/blob/4cc9cdbf65ce1b2f60b11b765d3e6b3a5e7e8952/handlers.go#L87-L96
17,757
albrow/zoom
handlers.go
NewScanStringsHandler
func NewScanStringsHandler(strings *[]string) ReplyHandler { return func(reply interface{}) error { var err error (*strings), err = redis.Strings(reply, nil) if err != nil { return err } return nil } }
go
func NewScanStringsHandler(strings *[]string) ReplyHandler { return func(reply interface{}) error { var err error (*strings), err = redis.Strings(reply, nil) if err != nil { return err } return nil } }
[ "func", "NewScanStringsHandler", "(", "strings", "*", "[", "]", "string", ")", "ReplyHandler", "{", "return", "func", "(", "reply", "interface", "{", "}", ")", "error", "{", "var", "err", "error", "\n", "(", "*", "strings", ")", ",", "err", "=", "redis...
// NewScanStringsHandler returns a ReplyHandler which will convert the reply to // a slice of strings and set the value of strings to the converted value. The // returned ReplyHandler will grow or shrink strings as needed. The ReplyHandler // will return an error if there was a problem converting the reply.
[ "NewScanStringsHandler", "returns", "a", "ReplyHandler", "which", "will", "convert", "the", "reply", "to", "a", "slice", "of", "strings", "and", "set", "the", "value", "of", "strings", "to", "the", "converted", "value", ".", "The", "returned", "ReplyHandler", ...
4cc9cdbf65ce1b2f60b11b765d3e6b3a5e7e8952
https://github.com/albrow/zoom/blob/4cc9cdbf65ce1b2f60b11b765d3e6b3a5e7e8952/handlers.go#L102-L111
17,758
albrow/zoom
transaction_query.go
Order
func (q *TransactionQuery) Order(fieldName string) *TransactionQuery { q.query.Order(fieldName) return q }
go
func (q *TransactionQuery) Order(fieldName string) *TransactionQuery { q.query.Order(fieldName) return q }
[ "func", "(", "q", "*", "TransactionQuery", ")", "Order", "(", "fieldName", "string", ")", "*", "TransactionQuery", "{", "q", ".", "query", ".", "Order", "(", "fieldName", ")", "\n", "return", "q", "\n", "}" ]
// Order works exactly like Query.Order. See the documentation for Query.Order // for a full description.
[ "Order", "works", "exactly", "like", "Query", ".", "Order", ".", "See", "the", "documentation", "for", "Query", ".", "Order", "for", "a", "full", "description", "." ]
4cc9cdbf65ce1b2f60b11b765d3e6b3a5e7e8952
https://github.com/albrow/zoom/blob/4cc9cdbf65ce1b2f60b11b765d3e6b3a5e7e8952/transaction_query.go#L48-L51
17,759
albrow/zoom
transaction_query.go
Limit
func (q *TransactionQuery) Limit(amount uint) *TransactionQuery { q.query.Limit(amount) return q }
go
func (q *TransactionQuery) Limit(amount uint) *TransactionQuery { q.query.Limit(amount) return q }
[ "func", "(", "q", "*", "TransactionQuery", ")", "Limit", "(", "amount", "uint", ")", "*", "TransactionQuery", "{", "q", ".", "query", ".", "Limit", "(", "amount", ")", "\n", "return", "q", "\n", "}" ]
// Limit works exactly like Query.Limit. See the documentation for Query.Limit // for more information.
[ "Limit", "works", "exactly", "like", "Query", ".", "Limit", ".", "See", "the", "documentation", "for", "Query", ".", "Limit", "for", "more", "information", "." ]
4cc9cdbf65ce1b2f60b11b765d3e6b3a5e7e8952
https://github.com/albrow/zoom/blob/4cc9cdbf65ce1b2f60b11b765d3e6b3a5e7e8952/transaction_query.go#L55-L58
17,760
albrow/zoom
transaction_query.go
Offset
func (q *TransactionQuery) Offset(amount uint) *TransactionQuery { q.query.Offset(amount) return q }
go
func (q *TransactionQuery) Offset(amount uint) *TransactionQuery { q.query.Offset(amount) return q }
[ "func", "(", "q", "*", "TransactionQuery", ")", "Offset", "(", "amount", "uint", ")", "*", "TransactionQuery", "{", "q", ".", "query", ".", "Offset", "(", "amount", ")", "\n", "return", "q", "\n", "}" ]
// Offset works exactly like Query.Offset. See the documentation for // Query.Offset for more information.
[ "Offset", "works", "exactly", "like", "Query", ".", "Offset", ".", "See", "the", "documentation", "for", "Query", ".", "Offset", "for", "more", "information", "." ]
4cc9cdbf65ce1b2f60b11b765d3e6b3a5e7e8952
https://github.com/albrow/zoom/blob/4cc9cdbf65ce1b2f60b11b765d3e6b3a5e7e8952/transaction_query.go#L62-L65
17,761
albrow/zoom
transaction_query.go
Include
func (q *TransactionQuery) Include(fields ...string) *TransactionQuery { q.query.Include(fields...) return q }
go
func (q *TransactionQuery) Include(fields ...string) *TransactionQuery { q.query.Include(fields...) return q }
[ "func", "(", "q", "*", "TransactionQuery", ")", "Include", "(", "fields", "...", "string", ")", "*", "TransactionQuery", "{", "q", ".", "query", ".", "Include", "(", "fields", "...", ")", "\n", "return", "q", "\n", "}" ]
// Include works exactly like Query.Include. See the documentation for // Query.Include for more information.
[ "Include", "works", "exactly", "like", "Query", ".", "Include", ".", "See", "the", "documentation", "for", "Query", ".", "Include", "for", "more", "information", "." ]
4cc9cdbf65ce1b2f60b11b765d3e6b3a5e7e8952
https://github.com/albrow/zoom/blob/4cc9cdbf65ce1b2f60b11b765d3e6b3a5e7e8952/transaction_query.go#L69-L72
17,762
albrow/zoom
transaction_query.go
Exclude
func (q *TransactionQuery) Exclude(fields ...string) *TransactionQuery { q.query.Exclude(fields...) return q }
go
func (q *TransactionQuery) Exclude(fields ...string) *TransactionQuery { q.query.Exclude(fields...) return q }
[ "func", "(", "q", "*", "TransactionQuery", ")", "Exclude", "(", "fields", "...", "string", ")", "*", "TransactionQuery", "{", "q", ".", "query", ".", "Exclude", "(", "fields", "...", ")", "\n", "return", "q", "\n", "}" ]
// Exclude works exactly like Query.Exclude. See the documentation for // Query.Exclude for more information.
[ "Exclude", "works", "exactly", "like", "Query", ".", "Exclude", ".", "See", "the", "documentation", "for", "Query", ".", "Exclude", "for", "more", "information", "." ]
4cc9cdbf65ce1b2f60b11b765d3e6b3a5e7e8952
https://github.com/albrow/zoom/blob/4cc9cdbf65ce1b2f60b11b765d3e6b3a5e7e8952/transaction_query.go#L76-L79
17,763
albrow/zoom
transaction_query.go
Filter
func (q *TransactionQuery) Filter(filterString string, value interface{}) *TransactionQuery { q.query.Filter(filterString, value) return q }
go
func (q *TransactionQuery) Filter(filterString string, value interface{}) *TransactionQuery { q.query.Filter(filterString, value) return q }
[ "func", "(", "q", "*", "TransactionQuery", ")", "Filter", "(", "filterString", "string", ",", "value", "interface", "{", "}", ")", "*", "TransactionQuery", "{", "q", ".", "query", ".", "Filter", "(", "filterString", ",", "value", ")", "\n", "return", "q"...
// Filter works exactly like Query.Filter. See the documentation for // Query.Filter for more information.
[ "Filter", "works", "exactly", "like", "Query", ".", "Filter", ".", "See", "the", "documentation", "for", "Query", ".", "Filter", "for", "more", "information", "." ]
4cc9cdbf65ce1b2f60b11b765d3e6b3a5e7e8952
https://github.com/albrow/zoom/blob/4cc9cdbf65ce1b2f60b11b765d3e6b3a5e7e8952/transaction_query.go#L83-L86
17,764
zpatrick/rclient
options.go
RequestOptions
func RequestOptions(options ...RequestOption) ClientOption { return func(r *RestClient) { r.RequestOptions = append(r.RequestOptions, options...) } }
go
func RequestOptions(options ...RequestOption) ClientOption { return func(r *RestClient) { r.RequestOptions = append(r.RequestOptions, options...) } }
[ "func", "RequestOptions", "(", "options", "...", "RequestOption", ")", "ClientOption", "{", "return", "func", "(", "r", "*", "RestClient", ")", "{", "r", ".", "RequestOptions", "=", "append", "(", "r", ".", "RequestOptions", ",", "options", "...", ")", "\n...
// RequestOptions sets the RequestOptions field of a RestClient.
[ "RequestOptions", "sets", "the", "RequestOptions", "field", "of", "a", "RestClient", "." ]
9beeebe8a6ae76b178a912f34e7394d9add8b781
https://github.com/zpatrick/rclient/blob/9beeebe8a6ae76b178a912f34e7394d9add8b781/options.go#L33-L37
17,765
zpatrick/rclient
options.go
BasicAuth
func BasicAuth(user, pass string) RequestOption { return func(req *http.Request) error { req.SetBasicAuth(user, pass) return nil } }
go
func BasicAuth(user, pass string) RequestOption { return func(req *http.Request) error { req.SetBasicAuth(user, pass) return nil } }
[ "func", "BasicAuth", "(", "user", ",", "pass", "string", ")", "RequestOption", "{", "return", "func", "(", "req", "*", "http", ".", "Request", ")", "error", "{", "req", ".", "SetBasicAuth", "(", "user", ",", "pass", ")", "\n", "return", "nil", "\n", ...
// BasicAuth adds the specified username and password as basic auth to a request.
[ "BasicAuth", "adds", "the", "specified", "username", "and", "password", "as", "basic", "auth", "to", "a", "request", "." ]
9beeebe8a6ae76b178a912f34e7394d9add8b781
https://github.com/zpatrick/rclient/blob/9beeebe8a6ae76b178a912f34e7394d9add8b781/options.go#L43-L48
17,766
zpatrick/rclient
options.go
Header
func Header(name, val string) RequestOption { return func(req *http.Request) error { req.Header.Add(name, val) return nil } }
go
func Header(name, val string) RequestOption { return func(req *http.Request) error { req.Header.Add(name, val) return nil } }
[ "func", "Header", "(", "name", ",", "val", "string", ")", "RequestOption", "{", "return", "func", "(", "req", "*", "http", ".", "Request", ")", "error", "{", "req", ".", "Header", ".", "Add", "(", "name", ",", "val", ")", "\n", "return", "nil", "\n...
// Header adds the specified name and value as a header to a request.
[ "Header", "adds", "the", "specified", "name", "and", "value", "as", "a", "header", "to", "a", "request", "." ]
9beeebe8a6ae76b178a912f34e7394d9add8b781
https://github.com/zpatrick/rclient/blob/9beeebe8a6ae76b178a912f34e7394d9add8b781/options.go#L51-L56
17,767
zpatrick/rclient
options.go
Query
func Query(query url.Values) RequestOption { return func(req *http.Request) error { req.URL.RawQuery = query.Encode() return nil } }
go
func Query(query url.Values) RequestOption { return func(req *http.Request) error { req.URL.RawQuery = query.Encode() return nil } }
[ "func", "Query", "(", "query", "url", ".", "Values", ")", "RequestOption", "{", "return", "func", "(", "req", "*", "http", ".", "Request", ")", "error", "{", "req", ".", "URL", ".", "RawQuery", "=", "query", ".", "Encode", "(", ")", "\n", "return", ...
// Query adds the specified query to a request.
[ "Query", "adds", "the", "specified", "query", "to", "a", "request", "." ]
9beeebe8a6ae76b178a912f34e7394d9add8b781
https://github.com/zpatrick/rclient/blob/9beeebe8a6ae76b178a912f34e7394d9add8b781/options.go#L70-L75
17,768
zpatrick/rclient
client.go
NewRestClient
func NewRestClient(host string, options ...ClientOption) *RestClient { r := &RestClient{ Host: host, RequestBuilder: BuildJSONRequest, RequestDoer: http.DefaultClient, ResponseReader: ReadJSONResponse, RequestOptions: []RequestOption{}, } for _, option := range options { option(r) } return r }
go
func NewRestClient(host string, options ...ClientOption) *RestClient { r := &RestClient{ Host: host, RequestBuilder: BuildJSONRequest, RequestDoer: http.DefaultClient, ResponseReader: ReadJSONResponse, RequestOptions: []RequestOption{}, } for _, option := range options { option(r) } return r }
[ "func", "NewRestClient", "(", "host", "string", ",", "options", "...", "ClientOption", ")", "*", "RestClient", "{", "r", ":=", "&", "RestClient", "{", "Host", ":", "host", ",", "RequestBuilder", ":", "BuildJSONRequest", ",", "RequestDoer", ":", "http", ".", ...
// NewRestClient returns a new RestClient with all of the default fields. // Any of the default fields can be changed with the options param.
[ "NewRestClient", "returns", "a", "new", "RestClient", "with", "all", "of", "the", "default", "fields", ".", "Any", "of", "the", "default", "fields", "can", "be", "changed", "with", "the", "options", "param", "." ]
9beeebe8a6ae76b178a912f34e7394d9add8b781
https://github.com/zpatrick/rclient/blob/9beeebe8a6ae76b178a912f34e7394d9add8b781/client.go#L19-L33
17,769
zpatrick/rclient
client.go
Do
func (r *RestClient) Do(method, path string, body, v interface{}, options ...RequestOption) error { url := fmt.Sprintf("%s%s", r.Host, path) options = append(r.RequestOptions, options...) req, err := r.RequestBuilder(method, url, body, options...) if err != nil { return err } resp, err := r.RequestDoer.Do(req) if err != nil { return err } return r.ResponseReader(resp, v) }
go
func (r *RestClient) Do(method, path string, body, v interface{}, options ...RequestOption) error { url := fmt.Sprintf("%s%s", r.Host, path) options = append(r.RequestOptions, options...) req, err := r.RequestBuilder(method, url, body, options...) if err != nil { return err } resp, err := r.RequestDoer.Do(req) if err != nil { return err } return r.ResponseReader(resp, v) }
[ "func", "(", "r", "*", "RestClient", ")", "Do", "(", "method", ",", "path", "string", ",", "body", ",", "v", "interface", "{", "}", ",", "options", "...", "RequestOption", ")", "error", "{", "url", ":=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",",...
// Do orchestrates building, performing, and reading http requests and responses.
[ "Do", "orchestrates", "building", "performing", "and", "reading", "http", "requests", "and", "responses", "." ]
9beeebe8a6ae76b178a912f34e7394d9add8b781
https://github.com/zpatrick/rclient/blob/9beeebe8a6ae76b178a912f34e7394d9add8b781/client.go#L61-L76
17,770
zpatrick/rclient
request_doer.go
Do
func (d RequestDoerFunc) Do(req *http.Request) (*http.Response, error) { return d(req) }
go
func (d RequestDoerFunc) Do(req *http.Request) (*http.Response, error) { return d(req) }
[ "func", "(", "d", "RequestDoerFunc", ")", "Do", "(", "req", "*", "http", ".", "Request", ")", "(", "*", "http", ".", "Response", ",", "error", ")", "{", "return", "d", "(", "req", ")", "\n", "}" ]
// Do executes the RequestDoerFunc.
[ "Do", "executes", "the", "RequestDoerFunc", "." ]
9beeebe8a6ae76b178a912f34e7394d9add8b781
https://github.com/zpatrick/rclient/blob/9beeebe8a6ae76b178a912f34e7394d9add8b781/request_doer.go#L16-L18
17,771
zpatrick/rclient
response_reader.go
ReadJSONResponse
func ReadJSONResponse(resp *http.Response, v interface{}) error { defer resp.Body.Close() switch { case resp.StatusCode < 200, resp.StatusCode > 299: return NewResponseErrorf(resp, "Invalid status code: %d", resp.StatusCode) case v == nil: return nil default: if err := json.NewDecoder(resp.Body).Decode(v); err != nil { return NewResponseError(resp, err.Error()) } } return nil }
go
func ReadJSONResponse(resp *http.Response, v interface{}) error { defer resp.Body.Close() switch { case resp.StatusCode < 200, resp.StatusCode > 299: return NewResponseErrorf(resp, "Invalid status code: %d", resp.StatusCode) case v == nil: return nil default: if err := json.NewDecoder(resp.Body).Decode(v); err != nil { return NewResponseError(resp, err.Error()) } } return nil }
[ "func", "ReadJSONResponse", "(", "resp", "*", "http", ".", "Response", ",", "v", "interface", "{", "}", ")", "error", "{", "defer", "resp", ".", "Body", ".", "Close", "(", ")", "\n\n", "switch", "{", "case", "resp", ".", "StatusCode", "<", "200", ","...
// ReadJSONResponse attempts to marshal the response body into v // if and only if the response StatusCode is in the 200 range. // Otherwise, an error is thrown. // It assumes the response body is in JSON format.
[ "ReadJSONResponse", "attempts", "to", "marshal", "the", "response", "body", "into", "v", "if", "and", "only", "if", "the", "response", "StatusCode", "is", "in", "the", "200", "range", ".", "Otherwise", "an", "error", "is", "thrown", ".", "It", "assumes", "...
9beeebe8a6ae76b178a912f34e7394d9add8b781
https://github.com/zpatrick/rclient/blob/9beeebe8a6ae76b178a912f34e7394d9add8b781/response_reader.go#L15-L30
17,772
atlassian/ctrl
handlers/controlled_resource_handler.go
rebuildControllerByName
func (g *ControlledResourceHandler) rebuildControllerByName(logger *zap.Logger, namespace, controllerName string) { if controllerName == "" { logger.Debug("Object has no controller, so nothing was enqueued") return } logger. With(logz.DelegateName(controllerName)). With(logz.DelegateGk(g.ControllerGvk.GroupKind())). Info("Enqueuing controller") g.WorkQueue.Add(ctrl.QueueKey{ Namespace: namespace, Name: controllerName, }) }
go
func (g *ControlledResourceHandler) rebuildControllerByName(logger *zap.Logger, namespace, controllerName string) { if controllerName == "" { logger.Debug("Object has no controller, so nothing was enqueued") return } logger. With(logz.DelegateName(controllerName)). With(logz.DelegateGk(g.ControllerGvk.GroupKind())). Info("Enqueuing controller") g.WorkQueue.Add(ctrl.QueueKey{ Namespace: namespace, Name: controllerName, }) }
[ "func", "(", "g", "*", "ControlledResourceHandler", ")", "rebuildControllerByName", "(", "logger", "*", "zap", ".", "Logger", ",", "namespace", ",", "controllerName", "string", ")", "{", "if", "controllerName", "==", "\"", "\"", "{", "logger", ".", "Debug", ...
// This method may be called with an empty controllerName.
[ "This", "method", "may", "be", "called", "with", "an", "empty", "controllerName", "." ]
1cea8338282d871a8fd8c2cebd24ad177b25240e
https://github.com/atlassian/ctrl/blob/1cea8338282d871a8fd8c2cebd24ad177b25240e/handlers/controlled_resource_handler.go#L96-L109
17,773
atlassian/ctrl
handlers/controlled_resource_handler.go
getControllerNameAndNamespace
func (g *ControlledResourceHandler) getControllerNameAndNamespace(obj meta_v1.Object) (string, string) { var name string ref := meta_v1.GetControllerOf(obj) if ref != nil && ref.APIVersion == g.ControllerGvk.GroupVersion().String() && ref.Kind == g.ControllerGvk.Kind { name = ref.Name } return name, obj.GetNamespace() }
go
func (g *ControlledResourceHandler) getControllerNameAndNamespace(obj meta_v1.Object) (string, string) { var name string ref := meta_v1.GetControllerOf(obj) if ref != nil && ref.APIVersion == g.ControllerGvk.GroupVersion().String() && ref.Kind == g.ControllerGvk.Kind { name = ref.Name } return name, obj.GetNamespace() }
[ "func", "(", "g", "*", "ControlledResourceHandler", ")", "getControllerNameAndNamespace", "(", "obj", "meta_v1", ".", "Object", ")", "(", "string", ",", "string", ")", "{", "var", "name", "string", "\n", "ref", ":=", "meta_v1", ".", "GetControllerOf", "(", "...
// getControllerNameAndNamespace returns name and namespace of the object's controller. // Returned name may be empty if the object does not have a controller owner reference.
[ "getControllerNameAndNamespace", "returns", "name", "and", "namespace", "of", "the", "object", "s", "controller", ".", "Returned", "name", "may", "be", "empty", "if", "the", "object", "does", "not", "have", "a", "controller", "owner", "reference", "." ]
1cea8338282d871a8fd8c2cebd24ad177b25240e
https://github.com/atlassian/ctrl/blob/1cea8338282d871a8fd8c2cebd24ad177b25240e/handlers/controlled_resource_handler.go#L113-L120
17,774
atlassian/ctrl
handlers/lookup_handler.go
loggerForObj
func (e *LookupHandler) loggerForObj(logger *zap.Logger, obj meta_v1.Object) *zap.Logger { return logger.With(logz.Namespace(obj), logz.Object(obj), logz.ObjectGk(e.Gvk.GroupKind())) }
go
func (e *LookupHandler) loggerForObj(logger *zap.Logger, obj meta_v1.Object) *zap.Logger { return logger.With(logz.Namespace(obj), logz.Object(obj), logz.ObjectGk(e.Gvk.GroupKind())) }
[ "func", "(", "e", "*", "LookupHandler", ")", "loggerForObj", "(", "logger", "*", "zap", ".", "Logger", ",", "obj", "meta_v1", ".", "Object", ")", "*", "zap", ".", "Logger", "{", "return", "logger", ".", "With", "(", "logz", ".", "Namespace", "(", "ob...
// loggerForObj returns a logger with fields for a controlled object.
[ "loggerForObj", "returns", "a", "logger", "with", "fields", "for", "a", "controlled", "object", "." ]
1cea8338282d871a8fd8c2cebd24ad177b25240e
https://github.com/atlassian/ctrl/blob/1cea8338282d871a8fd8c2cebd24ad177b25240e/handlers/lookup_handler.go#L76-L80
17,775
atlassian/ctrl
options/leader_election.go
DoLeaderElection
func DoLeaderElection(ctx context.Context, logger *zap.Logger, component string, config LeaderElectionOptions, configMapsGetter core_v1client.ConfigMapsGetter, recorder record.EventRecorder) (context.Context, error) { id, err := os.Hostname() if err != nil { return nil, err } ctxRet, cancel := context.WithCancel(ctx) startedLeading := make(chan struct{}) le, err := leaderelection.NewLeaderElector(leaderelection.LeaderElectionConfig{ Lock: &resourcelock.ConfigMapLock{ ConfigMapMeta: meta_v1.ObjectMeta{ Namespace: config.ConfigMapNamespace, Name: config.ConfigMapName, }, Client: configMapsGetter, LockConfig: resourcelock.ResourceLockConfig{ Identity: id + "-" + component, EventRecorder: recorder, }, }, LeaseDuration: config.LeaseDuration, RenewDeadline: config.RenewDeadline, RetryPeriod: config.RetryPeriod, Callbacks: leaderelection.LeaderCallbacks{ OnStartedLeading: func(ctx context.Context) { logger.Info("Started leading") close(startedLeading) }, OnStoppedLeading: func() { logger.Info("Leader status lost") cancel() }, }, }) if err != nil { cancel() return nil, err } go func() { // note: because le.Run() also adds a logging panic handler panics with be logged 3 times defer logz.LogStructuredPanic() le.Run(ctx) }() select { case <-ctx.Done(): return nil, ctx.Err() case <-startedLeading: return ctxRet, nil } }
go
func DoLeaderElection(ctx context.Context, logger *zap.Logger, component string, config LeaderElectionOptions, configMapsGetter core_v1client.ConfigMapsGetter, recorder record.EventRecorder) (context.Context, error) { id, err := os.Hostname() if err != nil { return nil, err } ctxRet, cancel := context.WithCancel(ctx) startedLeading := make(chan struct{}) le, err := leaderelection.NewLeaderElector(leaderelection.LeaderElectionConfig{ Lock: &resourcelock.ConfigMapLock{ ConfigMapMeta: meta_v1.ObjectMeta{ Namespace: config.ConfigMapNamespace, Name: config.ConfigMapName, }, Client: configMapsGetter, LockConfig: resourcelock.ResourceLockConfig{ Identity: id + "-" + component, EventRecorder: recorder, }, }, LeaseDuration: config.LeaseDuration, RenewDeadline: config.RenewDeadline, RetryPeriod: config.RetryPeriod, Callbacks: leaderelection.LeaderCallbacks{ OnStartedLeading: func(ctx context.Context) { logger.Info("Started leading") close(startedLeading) }, OnStoppedLeading: func() { logger.Info("Leader status lost") cancel() }, }, }) if err != nil { cancel() return nil, err } go func() { // note: because le.Run() also adds a logging panic handler panics with be logged 3 times defer logz.LogStructuredPanic() le.Run(ctx) }() select { case <-ctx.Done(): return nil, ctx.Err() case <-startedLeading: return ctxRet, nil } }
[ "func", "DoLeaderElection", "(", "ctx", "context", ".", "Context", ",", "logger", "*", "zap", ".", "Logger", ",", "component", "string", ",", "config", "LeaderElectionOptions", ",", "configMapsGetter", "core_v1client", ".", "ConfigMapsGetter", ",", "recorder", "re...
// DoLeaderElection starts leader election and blocks until it acquires the lease. // Returned context is cancelled once the lease is lost or ctx signals done.
[ "DoLeaderElection", "starts", "leader", "election", "and", "blocks", "until", "it", "acquires", "the", "lease", ".", "Returned", "context", "is", "cancelled", "once", "the", "lease", "is", "lost", "or", "ctx", "signals", "done", "." ]
1cea8338282d871a8fd8c2cebd24ad177b25240e
https://github.com/atlassian/ctrl/blob/1cea8338282d871a8fd8c2cebd24ad177b25240e/options/leader_election.go#L37-L85
17,776
atlassian/ctrl
logz/crash.go
logStructuredPanic
func logStructuredPanic(out io.Writer, panicValue interface{}, now time.Time, stack []byte) { bytes, err := json.Marshal(struct { Level string `json:"level"` Time string `json:"time"` Message string `json:"msg"` Stack string `json:"stack"` }{ Level: "fatal", Time: now.Format(time.RFC3339), Message: fmt.Sprintf("%v", panicValue), Stack: string(stack), }) if err != nil { fmt.Fprintf(out, "error while serializing panic: %+v\n", err) // nolint: errcheck, gas fmt.Fprintf(out, "original panic: %+v\n", panicValue) // nolint: errcheck, gas return } fmt.Fprintf(out, "%s\n", bytes) // nolint: errcheck, gas }
go
func logStructuredPanic(out io.Writer, panicValue interface{}, now time.Time, stack []byte) { bytes, err := json.Marshal(struct { Level string `json:"level"` Time string `json:"time"` Message string `json:"msg"` Stack string `json:"stack"` }{ Level: "fatal", Time: now.Format(time.RFC3339), Message: fmt.Sprintf("%v", panicValue), Stack: string(stack), }) if err != nil { fmt.Fprintf(out, "error while serializing panic: %+v\n", err) // nolint: errcheck, gas fmt.Fprintf(out, "original panic: %+v\n", panicValue) // nolint: errcheck, gas return } fmt.Fprintf(out, "%s\n", bytes) // nolint: errcheck, gas }
[ "func", "logStructuredPanic", "(", "out", "io", ".", "Writer", ",", "panicValue", "interface", "{", "}", ",", "now", "time", ".", "Time", ",", "stack", "[", "]", "byte", ")", "{", "bytes", ",", "err", ":=", "json", ".", "Marshal", "(", "struct", "{",...
// internally zap is overly opinionated about what to do when the log level is fatal or panic // it chooses to call os.exit or panic if the level is set. There does not appear to be a simple // way to work around that choice so we build the log message by hand instead.
[ "internally", "zap", "is", "overly", "opinionated", "about", "what", "to", "do", "when", "the", "log", "level", "is", "fatal", "or", "panic", "it", "chooses", "to", "call", "os", ".", "exit", "or", "panic", "if", "the", "level", "is", "set", ".", "Ther...
1cea8338282d871a8fd8c2cebd24ad177b25240e
https://github.com/atlassian/ctrl/blob/1cea8338282d871a8fd8c2cebd24ad177b25240e/logz/crash.go#L22-L40
17,777
atlassian/ctrl
app/app.go
CancelOnInterrupt
func CancelOnInterrupt(ctx context.Context, f context.CancelFunc) { c := make(chan os.Signal, 1) signal.Notify(c, os.Interrupt, syscall.SIGTERM) go func() { select { case <-ctx.Done(): case <-c: f() } }() }
go
func CancelOnInterrupt(ctx context.Context, f context.CancelFunc) { c := make(chan os.Signal, 1) signal.Notify(c, os.Interrupt, syscall.SIGTERM) go func() { select { case <-ctx.Done(): case <-c: f() } }() }
[ "func", "CancelOnInterrupt", "(", "ctx", "context", ".", "Context", ",", "f", "context", ".", "CancelFunc", ")", "{", "c", ":=", "make", "(", "chan", "os", ".", "Signal", ",", "1", ")", "\n", "signal", ".", "Notify", "(", "c", ",", "os", ".", "Inte...
// CancelOnInterrupt calls f when os.Interrupt or SIGTERM is received. // It ignores subsequent interrupts on purpose - program should exit correctly after the first signal.
[ "CancelOnInterrupt", "calls", "f", "when", "os", ".", "Interrupt", "or", "SIGTERM", "is", "received", ".", "It", "ignores", "subsequent", "interrupts", "on", "purpose", "-", "program", "should", "exit", "correctly", "after", "the", "first", "signal", "." ]
1cea8338282d871a8fd8c2cebd24ad177b25240e
https://github.com/atlassian/ctrl/blob/1cea8338282d871a8fd8c2cebd24ad177b25240e/app/app.go#L141-L151
17,778
atlassian/ctrl
apis/condition/v1/zz_generated.deepcopy.go
DeepCopy
func (in *Condition) DeepCopy() *Condition { if in == nil { return nil } out := new(Condition) in.DeepCopyInto(out) return out }
go
func (in *Condition) DeepCopy() *Condition { if in == nil { return nil } out := new(Condition) in.DeepCopyInto(out) return out }
[ "func", "(", "in", "*", "Condition", ")", "DeepCopy", "(", ")", "*", "Condition", "{", "if", "in", "==", "nil", "{", "return", "nil", "\n", "}", "\n", "out", ":=", "new", "(", "Condition", ")", "\n", "in", ".", "DeepCopyInto", "(", "out", ")", "\...
// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new Condition.
[ "DeepCopy", "is", "an", "autogenerated", "deepcopy", "function", "copying", "the", "receiver", "creating", "a", "new", "Condition", "." ]
1cea8338282d871a8fd8c2cebd24ad177b25240e
https://github.com/atlassian/ctrl/blob/1cea8338282d871a8fd8c2cebd24ad177b25240e/apis/condition/v1/zz_generated.deepcopy.go#L17-L24
17,779
davecheney/gpio
rpi/gpio.go
OpenPin
func OpenPin(number int, mode gpio.Mode) (gpio.Pin, error) { initOnce.Do(initRPi) p, err := gpio.OpenPin(number, mode) return &pin{Pin: p, pin: uint8(number)}, err }
go
func OpenPin(number int, mode gpio.Mode) (gpio.Pin, error) { initOnce.Do(initRPi) p, err := gpio.OpenPin(number, mode) return &pin{Pin: p, pin: uint8(number)}, err }
[ "func", "OpenPin", "(", "number", "int", ",", "mode", "gpio", ".", "Mode", ")", "(", "gpio", ".", "Pin", ",", "error", ")", "{", "initOnce", ".", "Do", "(", "initRPi", ")", "\n", "p", ",", "err", ":=", "gpio", ".", "OpenPin", "(", "number", ",", ...
// OpenPin returns a gpio.Pin implementation specalised for the RPi.
[ "OpenPin", "returns", "a", "gpio", ".", "Pin", "implementation", "specalised", "for", "the", "RPi", "." ]
a6de66e7e47065fca1a55c62c3f3cab3144694e6
https://github.com/davecheney/gpio/blob/a6de66e7e47065fca1a55c62c3f3cab3144694e6/rpi/gpio.go#L50-L54
17,780
davecheney/gpio
gpio_linux.go
setupEpoll
func setupEpoll() { var err error epollFD, err = syscall.EpollCreate1(0) if err != nil { fmt.Println("Unable to create epoll FD: ", err.Error()) os.Exit(1) } go func() { var epollEvents [GPIOCount]syscall.EpollEvent for { numEvents, err := syscall.EpollWait(epollFD, epollEvents[:], -1) if err != nil { if err == syscall.EAGAIN { continue } panic(fmt.Sprintf("EpollWait error: %v", err)) } for i := 0; i < numEvents; i++ { if eventPin, exists := watchEventCallbacks[int(epollEvents[i].Fd)]; exists { if eventPin.initial { eventPin.initial = false } else { eventPin.callback() } } } } }() }
go
func setupEpoll() { var err error epollFD, err = syscall.EpollCreate1(0) if err != nil { fmt.Println("Unable to create epoll FD: ", err.Error()) os.Exit(1) } go func() { var epollEvents [GPIOCount]syscall.EpollEvent for { numEvents, err := syscall.EpollWait(epollFD, epollEvents[:], -1) if err != nil { if err == syscall.EAGAIN { continue } panic(fmt.Sprintf("EpollWait error: %v", err)) } for i := 0; i < numEvents; i++ { if eventPin, exists := watchEventCallbacks[int(epollEvents[i].Fd)]; exists { if eventPin.initial { eventPin.initial = false } else { eventPin.callback() } } } } }() }
[ "func", "setupEpoll", "(", ")", "{", "var", "err", "error", "\n", "epollFD", ",", "err", "=", "syscall", ".", "EpollCreate1", "(", "0", ")", "\n", "if", "err", "!=", "nil", "{", "fmt", ".", "Println", "(", "\"", "\"", ",", "err", ".", "Error", "(...
// setupEpoll sets up epoll for use
[ "setupEpoll", "sets", "up", "epoll", "for", "use" ]
a6de66e7e47065fca1a55c62c3f3cab3144694e6
https://github.com/davecheney/gpio/blob/a6de66e7e47065fca1a55c62c3f3cab3144694e6/gpio_linux.go#L59-L92
17,781
davecheney/gpio
gpio_linux.go
OpenPin
func OpenPin(n int, mode Mode) (Pin, error) { // export this pin to create the virtual files on the system pinBase, err := expose(n) if err != nil { return nil, err } value, err := os.OpenFile(filepath.Join(pinBase, "value"), os.O_RDWR, 0600) if err != nil { return nil, err } p := &pin{ number: n, modePath: filepath.Join(pinBase, "direction"), edgePath: filepath.Join(pinBase, "edge"), valueFile: value, initial: true, } if err := p.setMode(mode); err != nil { p.Close() return nil, err } return p, nil }
go
func OpenPin(n int, mode Mode) (Pin, error) { // export this pin to create the virtual files on the system pinBase, err := expose(n) if err != nil { return nil, err } value, err := os.OpenFile(filepath.Join(pinBase, "value"), os.O_RDWR, 0600) if err != nil { return nil, err } p := &pin{ number: n, modePath: filepath.Join(pinBase, "direction"), edgePath: filepath.Join(pinBase, "edge"), valueFile: value, initial: true, } if err := p.setMode(mode); err != nil { p.Close() return nil, err } return p, nil }
[ "func", "OpenPin", "(", "n", "int", ",", "mode", "Mode", ")", "(", "Pin", ",", "error", ")", "{", "// export this pin to create the virtual files on the system", "pinBase", ",", "err", ":=", "expose", "(", "n", ")", "\n", "if", "err", "!=", "nil", "{", "re...
// OpenPin exports the pin, creating the virtual files necessary for interacting with the pin. // It also sets the mode for the pin, making it ready for use.
[ "OpenPin", "exports", "the", "pin", "creating", "the", "virtual", "files", "necessary", "for", "interacting", "with", "the", "pin", ".", "It", "also", "sets", "the", "mode", "for", "the", "pin", "making", "it", "ready", "for", "use", "." ]
a6de66e7e47065fca1a55c62c3f3cab3144694e6
https://github.com/davecheney/gpio/blob/a6de66e7e47065fca1a55c62c3f3cab3144694e6/gpio_linux.go#L108-L130
17,782
davecheney/gpio
gpio_linux.go
write
func write(buf []byte, path string) error { file, err := os.OpenFile(path, os.O_WRONLY, 0600) if err != nil { return err } if _, err := file.Write(buf); err != nil { return err } return file.Close() }
go
func write(buf []byte, path string) error { file, err := os.OpenFile(path, os.O_WRONLY, 0600) if err != nil { return err } if _, err := file.Write(buf); err != nil { return err } return file.Close() }
[ "func", "write", "(", "buf", "[", "]", "byte", ",", "path", "string", ")", "error", "{", "file", ",", "err", ":=", "os", ".", "OpenFile", "(", "path", ",", "os", ".", "O_WRONLY", ",", "0600", ")", "\n", "if", "err", "!=", "nil", "{", "return", ...
// write opens a file for writing, writes the byte slice to it and closes the // file.
[ "write", "opens", "a", "file", "for", "writing", "writes", "the", "byte", "slice", "to", "it", "and", "closes", "the", "file", "." ]
a6de66e7e47065fca1a55c62c3f3cab3144694e6
https://github.com/davecheney/gpio/blob/a6de66e7e47065fca1a55c62c3f3cab3144694e6/gpio_linux.go#L134-L143
17,783
davecheney/gpio
gpio_linux.go
Close
func (p *pin) Close() error { return writeFile(filepath.Join(gpiobase, "unexport"), "%d", p.number) }
go
func (p *pin) Close() error { return writeFile(filepath.Join(gpiobase, "unexport"), "%d", p.number) }
[ "func", "(", "p", "*", "pin", ")", "Close", "(", ")", "error", "{", "return", "writeFile", "(", "filepath", ".", "Join", "(", "gpiobase", ",", "\"", "\"", ")", ",", "\"", "\"", ",", "p", ".", "number", ")", "\n", "}" ]
// Close destroys the virtual files on the filesystem, unexporting the pin.
[ "Close", "destroys", "the", "virtual", "files", "on", "the", "filesystem", "unexporting", "the", "pin", "." ]
a6de66e7e47065fca1a55c62c3f3cab3144694e6
https://github.com/davecheney/gpio/blob/a6de66e7e47065fca1a55c62c3f3cab3144694e6/gpio_linux.go#L151-L153
17,784
davecheney/gpio
gpio_linux.go
Mode
func (p *pin) Mode() Mode { var mode string mode, p.err = readFile(p.modePath) return Mode(mode) }
go
func (p *pin) Mode() Mode { var mode string mode, p.err = readFile(p.modePath) return Mode(mode) }
[ "func", "(", "p", "*", "pin", ")", "Mode", "(", ")", "Mode", "{", "var", "mode", "string", "\n", "mode", ",", "p", ".", "err", "=", "readFile", "(", "p", ".", "modePath", ")", "\n", "return", "Mode", "(", "mode", ")", "\n", "}" ]
// Mode retrieves the current mode of the pin.
[ "Mode", "retrieves", "the", "current", "mode", "of", "the", "pin", "." ]
a6de66e7e47065fca1a55c62c3f3cab3144694e6
https://github.com/davecheney/gpio/blob/a6de66e7e47065fca1a55c62c3f3cab3144694e6/gpio_linux.go#L156-L160
17,785
davecheney/gpio
gpio_linux.go
SetMode
func (p *pin) SetMode(mode Mode) { p.err = p.setMode(mode) }
go
func (p *pin) SetMode(mode Mode) { p.err = p.setMode(mode) }
[ "func", "(", "p", "*", "pin", ")", "SetMode", "(", "mode", "Mode", ")", "{", "p", ".", "err", "=", "p", ".", "setMode", "(", "mode", ")", "\n", "}" ]
// SetMode sets the mode of the pin.
[ "SetMode", "sets", "the", "mode", "of", "the", "pin", "." ]
a6de66e7e47065fca1a55c62c3f3cab3144694e6
https://github.com/davecheney/gpio/blob/a6de66e7e47065fca1a55c62c3f3cab3144694e6/gpio_linux.go#L163-L165
17,786
davecheney/gpio
gpio_linux.go
Set
func (p *pin) Set() { _, p.err = p.valueFile.Write(bytesSet) }
go
func (p *pin) Set() { _, p.err = p.valueFile.Write(bytesSet) }
[ "func", "(", "p", "*", "pin", ")", "Set", "(", ")", "{", "_", ",", "p", ".", "err", "=", "p", ".", "valueFile", ".", "Write", "(", "bytesSet", ")", "\n", "}" ]
// Set sets the pin level high.
[ "Set", "sets", "the", "pin", "level", "high", "." ]
a6de66e7e47065fca1a55c62c3f3cab3144694e6
https://github.com/davecheney/gpio/blob/a6de66e7e47065fca1a55c62c3f3cab3144694e6/gpio_linux.go#L182-L184
17,787
davecheney/gpio
gpio_linux.go
Clear
func (p *pin) Clear() { _, p.err = p.valueFile.Write(bytesClear) }
go
func (p *pin) Clear() { _, p.err = p.valueFile.Write(bytesClear) }
[ "func", "(", "p", "*", "pin", ")", "Clear", "(", ")", "{", "_", ",", "p", ".", "err", "=", "p", ".", "valueFile", ".", "Write", "(", "bytesClear", ")", "\n", "}" ]
// Clear sets the pin level low.
[ "Clear", "sets", "the", "pin", "level", "low", "." ]
a6de66e7e47065fca1a55c62c3f3cab3144694e6
https://github.com/davecheney/gpio/blob/a6de66e7e47065fca1a55c62c3f3cab3144694e6/gpio_linux.go#L187-L189
17,788
davecheney/gpio
gpio_linux.go
Get
func (p *pin) Get() bool { bytes := make([]byte, 1) _, p.err = p.valueFile.ReadAt(bytes, 0) return bytes[0] == bytesSet[0] }
go
func (p *pin) Get() bool { bytes := make([]byte, 1) _, p.err = p.valueFile.ReadAt(bytes, 0) return bytes[0] == bytesSet[0] }
[ "func", "(", "p", "*", "pin", ")", "Get", "(", ")", "bool", "{", "bytes", ":=", "make", "(", "[", "]", "byte", ",", "1", ")", "\n", "_", ",", "p", ".", "err", "=", "p", ".", "valueFile", ".", "ReadAt", "(", "bytes", ",", "0", ")", "\n", "...
// Get retrieves the current pin level.
[ "Get", "retrieves", "the", "current", "pin", "level", "." ]
a6de66e7e47065fca1a55c62c3f3cab3144694e6
https://github.com/davecheney/gpio/blob/a6de66e7e47065fca1a55c62c3f3cab3144694e6/gpio_linux.go#L192-L196
17,789
davecheney/gpio
gpio_linux.go
BeginWatch
func (p *pin) BeginWatch(edge Edge, callback IRQEvent) error { p.SetMode(ModeInput) if err := write([]byte(edge), p.edgePath); err != nil { return err } var event syscall.EpollEvent event.Events = syscall.EPOLLIN | (syscall.EPOLLET & 0xffffffff) | syscall.EPOLLPRI fd := int(p.valueFile.Fd()) p.callback = callback watchEventCallbacks[fd] = p if err := syscall.SetNonblock(fd, true); err != nil { return err } event.Fd = int32(fd) if err := syscall.EpollCtl(epollFD, syscall.EPOLL_CTL_ADD, fd, &event); err != nil { return err } return nil }
go
func (p *pin) BeginWatch(edge Edge, callback IRQEvent) error { p.SetMode(ModeInput) if err := write([]byte(edge), p.edgePath); err != nil { return err } var event syscall.EpollEvent event.Events = syscall.EPOLLIN | (syscall.EPOLLET & 0xffffffff) | syscall.EPOLLPRI fd := int(p.valueFile.Fd()) p.callback = callback watchEventCallbacks[fd] = p if err := syscall.SetNonblock(fd, true); err != nil { return err } event.Fd = int32(fd) if err := syscall.EpollCtl(epollFD, syscall.EPOLL_CTL_ADD, fd, &event); err != nil { return err } return nil }
[ "func", "(", "p", "*", "pin", ")", "BeginWatch", "(", "edge", "Edge", ",", "callback", "IRQEvent", ")", "error", "{", "p", ".", "SetMode", "(", "ModeInput", ")", "\n", "if", "err", ":=", "write", "(", "[", "]", "byte", "(", "edge", ")", ",", "p",...
// Watch waits for the edge level to be triggered and then calls the callback // Watch sets the pin mode to input on your behalf, then establishes the interrupt on // the edge provided
[ "Watch", "waits", "for", "the", "edge", "level", "to", "be", "triggered", "and", "then", "calls", "the", "callback", "Watch", "sets", "the", "pin", "mode", "to", "input", "on", "your", "behalf", "then", "establishes", "the", "interrupt", "on", "the", "edge...
a6de66e7e47065fca1a55c62c3f3cab3144694e6
https://github.com/davecheney/gpio/blob/a6de66e7e47065fca1a55c62c3f3cab3144694e6/gpio_linux.go#L202-L228
17,790
davecheney/gpio
gpio_linux.go
EndWatch
func (p *pin) EndWatch() error { fd := int(p.valueFile.Fd()) if err := syscall.EpollCtl(epollFD, syscall.EPOLL_CTL_DEL, fd, nil); err != nil { return err } if err := syscall.SetNonblock(fd, false); err != nil { return err } delete(watchEventCallbacks, fd) return nil }
go
func (p *pin) EndWatch() error { fd := int(p.valueFile.Fd()) if err := syscall.EpollCtl(epollFD, syscall.EPOLL_CTL_DEL, fd, nil); err != nil { return err } if err := syscall.SetNonblock(fd, false); err != nil { return err } delete(watchEventCallbacks, fd) return nil }
[ "func", "(", "p", "*", "pin", ")", "EndWatch", "(", ")", "error", "{", "fd", ":=", "int", "(", "p", ".", "valueFile", ".", "Fd", "(", ")", ")", "\n\n", "if", "err", ":=", "syscall", ".", "EpollCtl", "(", "epollFD", ",", "syscall", ".", "EPOLL_CTL...
// EndWatch stops watching the pin
[ "EndWatch", "stops", "watching", "the", "pin" ]
a6de66e7e47065fca1a55c62c3f3cab3144694e6
https://github.com/davecheney/gpio/blob/a6de66e7e47065fca1a55c62c3f3cab3144694e6/gpio_linux.go#L231-L247
17,791
tobischo/gokeepasslib
encoder.go
Encode
func (e *Encoder) Encode(db *Database) error { // Calculate transformed key to make HMAC and encrypt transformedKey, err := db.getTransformedKey() if err != nil { return err } // Write header then hashes before decode content (necessary to update HeaderHash) // db.Header writeTo will change its hash if err = db.Header.writeTo(e.w); err != nil { return err } // Update header hash into db.Hashes then write the data hash := db.Header.GetSha256() if db.Header.IsKdbx4() { db.Hashes.Sha256 = hash hmacKey := buildHmacKey(db, transformedKey) hmacHash := db.Header.GetHmacSha256(hmacKey) db.Hashes.Hmac = hmacHash if err = db.Hashes.writeTo(e.w); err != nil { return err } } else { db.Content.Meta.HeaderHash = base64.StdEncoding.EncodeToString(hash[:]) } // Encode xml and append header to the top rawContent, err := xml.MarshalIndent(db.Content, "", "\t") if err != nil { return err } rawContent = append(xmlHeader, rawContent...) // Write InnerHeader (Kdbx v4) if db.Header.IsKdbx4() { var ih bytes.Buffer if err = db.Content.InnerHeader.writeTo(&ih); err != nil { return err } rawContent = append(ih.Bytes(), rawContent...) } // Encode raw content encodedContent, err := encodeRawContent(db, rawContent, transformedKey) if err != nil { return err } // Writes the encrypted database content _, err = e.w.Write(encodedContent) return err }
go
func (e *Encoder) Encode(db *Database) error { // Calculate transformed key to make HMAC and encrypt transformedKey, err := db.getTransformedKey() if err != nil { return err } // Write header then hashes before decode content (necessary to update HeaderHash) // db.Header writeTo will change its hash if err = db.Header.writeTo(e.w); err != nil { return err } // Update header hash into db.Hashes then write the data hash := db.Header.GetSha256() if db.Header.IsKdbx4() { db.Hashes.Sha256 = hash hmacKey := buildHmacKey(db, transformedKey) hmacHash := db.Header.GetHmacSha256(hmacKey) db.Hashes.Hmac = hmacHash if err = db.Hashes.writeTo(e.w); err != nil { return err } } else { db.Content.Meta.HeaderHash = base64.StdEncoding.EncodeToString(hash[:]) } // Encode xml and append header to the top rawContent, err := xml.MarshalIndent(db.Content, "", "\t") if err != nil { return err } rawContent = append(xmlHeader, rawContent...) // Write InnerHeader (Kdbx v4) if db.Header.IsKdbx4() { var ih bytes.Buffer if err = db.Content.InnerHeader.writeTo(&ih); err != nil { return err } rawContent = append(ih.Bytes(), rawContent...) } // Encode raw content encodedContent, err := encodeRawContent(db, rawContent, transformedKey) if err != nil { return err } // Writes the encrypted database content _, err = e.w.Write(encodedContent) return err }
[ "func", "(", "e", "*", "Encoder", ")", "Encode", "(", "db", "*", "Database", ")", "error", "{", "// Calculate transformed key to make HMAC and encrypt", "transformedKey", ",", "err", ":=", "db", ".", "getTransformedKey", "(", ")", "\n", "if", "err", "!=", "nil...
// Encode writes db to e's internal writer
[ "Encode", "writes", "db", "to", "e", "s", "internal", "writer" ]
8892e349f7674fa2214afba77de81fd6dfc44507
https://github.com/tobischo/gokeepasslib/blob/8892e349f7674fa2214afba77de81fd6dfc44507/encoder.go#L25-L80
17,792
tobischo/gokeepasslib
credentials.go
NewPasswordCredentials
func NewPasswordCredentials(password string) *DBCredentials { hashedpw := sha256.Sum256([]byte(password)) return &DBCredentials{Passphrase: hashedpw[:]} }
go
func NewPasswordCredentials(password string) *DBCredentials { hashedpw := sha256.Sum256([]byte(password)) return &DBCredentials{Passphrase: hashedpw[:]} }
[ "func", "NewPasswordCredentials", "(", "password", "string", ")", "*", "DBCredentials", "{", "hashedpw", ":=", "sha256", ".", "Sum256", "(", "[", "]", "byte", "(", "password", ")", ")", "\n", "return", "&", "DBCredentials", "{", "Passphrase", ":", "hashedpw"...
// NewPasswordCredentials builds a new DBCredentials from a Password string
[ "NewPasswordCredentials", "builds", "a", "new", "DBCredentials", "from", "a", "Password", "string" ]
8892e349f7674fa2214afba77de81fd6dfc44507
https://github.com/tobischo/gokeepasslib/blob/8892e349f7674fa2214afba77de81fd6dfc44507/credentials.go#L130-L133
17,793
tobischo/gokeepasslib
credentials.go
ParseKeyFile
func ParseKeyFile(location string) ([]byte, error) { r, err := regexp.Compile(`<Data>(.+)</Data>`) if err != nil { return nil, err } file, err := os.Open(location) if err != nil { return nil, err } var data []byte if data, err = ioutil.ReadAll(file); err != nil { return nil, err } if r.Match(data) { //If keyfile is in xml form, extract key data base := r.FindSubmatch(data)[1] data = make([]byte, base64.StdEncoding.DecodedLen(len(base))) if _, err := base64.StdEncoding.Decode(data, base); err != nil { return nil, err } } // Slice necessary due to padding at the end of the hash return data[:32], nil }
go
func ParseKeyFile(location string) ([]byte, error) { r, err := regexp.Compile(`<Data>(.+)</Data>`) if err != nil { return nil, err } file, err := os.Open(location) if err != nil { return nil, err } var data []byte if data, err = ioutil.ReadAll(file); err != nil { return nil, err } if r.Match(data) { //If keyfile is in xml form, extract key data base := r.FindSubmatch(data)[1] data = make([]byte, base64.StdEncoding.DecodedLen(len(base))) if _, err := base64.StdEncoding.Decode(data, base); err != nil { return nil, err } } // Slice necessary due to padding at the end of the hash return data[:32], nil }
[ "func", "ParseKeyFile", "(", "location", "string", ")", "(", "[", "]", "byte", ",", "error", ")", "{", "r", ",", "err", ":=", "regexp", ".", "Compile", "(", "`<Data>(.+)</Data>`", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err",...
// ParseKeyFile returns the hashed key from a key file at the path specified by location, parsing xml if needed
[ "ParseKeyFile", "returns", "the", "hashed", "key", "from", "a", "key", "file", "at", "the", "path", "specified", "by", "location", "parsing", "xml", "if", "needed" ]
8892e349f7674fa2214afba77de81fd6dfc44507
https://github.com/tobischo/gokeepasslib/blob/8892e349f7674fa2214afba77de81fd6dfc44507/credentials.go#L136-L158
17,794
tobischo/gokeepasslib
credentials.go
NewKeyCredentials
func NewKeyCredentials(location string) (*DBCredentials, error) { key, err := ParseKeyFile(location) if err != nil { return nil, err } return &DBCredentials{Key: key}, nil }
go
func NewKeyCredentials(location string) (*DBCredentials, error) { key, err := ParseKeyFile(location) if err != nil { return nil, err } return &DBCredentials{Key: key}, nil }
[ "func", "NewKeyCredentials", "(", "location", "string", ")", "(", "*", "DBCredentials", ",", "error", ")", "{", "key", ",", "err", ":=", "ParseKeyFile", "(", "location", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", ...
// NewKeyCredentials builds a new DBCredentials from a key file at the path specified by location
[ "NewKeyCredentials", "builds", "a", "new", "DBCredentials", "from", "a", "key", "file", "at", "the", "path", "specified", "by", "location" ]
8892e349f7674fa2214afba77de81fd6dfc44507
https://github.com/tobischo/gokeepasslib/blob/8892e349f7674fa2214afba77de81fd6dfc44507/credentials.go#L161-L168
17,795
tobischo/gokeepasslib
credentials.go
NewPasswordAndKeyCredentials
func NewPasswordAndKeyCredentials(password, location string) (*DBCredentials, error) { key, err := ParseKeyFile(location) if err != nil { return nil, err } hashedpw := sha256.Sum256([]byte(password)) return &DBCredentials{ Passphrase: hashedpw[:], Key: key, }, nil }
go
func NewPasswordAndKeyCredentials(password, location string) (*DBCredentials, error) { key, err := ParseKeyFile(location) if err != nil { return nil, err } hashedpw := sha256.Sum256([]byte(password)) return &DBCredentials{ Passphrase: hashedpw[:], Key: key, }, nil }
[ "func", "NewPasswordAndKeyCredentials", "(", "password", ",", "location", "string", ")", "(", "*", "DBCredentials", ",", "error", ")", "{", "key", ",", "err", ":=", "ParseKeyFile", "(", "location", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil",...
// NewPasswordAndKeyCredentials builds a new DBCredentials from a password and the key file at the path specified by location
[ "NewPasswordAndKeyCredentials", "builds", "a", "new", "DBCredentials", "from", "a", "password", "and", "the", "key", "file", "at", "the", "path", "specified", "by", "location" ]
8892e349f7674fa2214afba77de81fd6dfc44507
https://github.com/tobischo/gokeepasslib/blob/8892e349f7674fa2214afba77de81fd6dfc44507/credentials.go#L171-L183
17,796
tobischo/gokeepasslib
xml.go
NewMetaData
func NewMetaData() *MetaData { now := w.Now() return &MetaData{ MasterKeyChanged: &now, MasterKeyChangeRec: -1, MasterKeyChangeForce: -1, HistoryMaxItems: 10, HistoryMaxSize: 6291456, // 6 MB MaintenanceHistoryDays: 365, } }
go
func NewMetaData() *MetaData { now := w.Now() return &MetaData{ MasterKeyChanged: &now, MasterKeyChangeRec: -1, MasterKeyChangeForce: -1, HistoryMaxItems: 10, HistoryMaxSize: 6291456, // 6 MB MaintenanceHistoryDays: 365, } }
[ "func", "NewMetaData", "(", ")", "*", "MetaData", "{", "now", ":=", "w", ".", "Now", "(", ")", "\n\n", "return", "&", "MetaData", "{", "MasterKeyChanged", ":", "&", "now", ",", "MasterKeyChangeRec", ":", "-", "1", ",", "MasterKeyChangeForce", ":", "-", ...
// NewMetaData creates a MetaData struct with some defaults set
[ "NewMetaData", "creates", "a", "MetaData", "struct", "with", "some", "defaults", "set" ]
8892e349f7674fa2214afba77de81fd6dfc44507
https://github.com/tobischo/gokeepasslib/blob/8892e349f7674fa2214afba77de81fd6dfc44507/xml.go#L149-L160
17,797
tobischo/gokeepasslib
xml.go
NewRootData
func NewRootData() *RootData { root := new(RootData) group := NewGroup() group.Name = "NewDatabase" entry := NewEntry() entry.Values = append(entry.Values, ValueData{Key: "Title", Value: V{Content: "Sample Entry"}}) group.Entries = append(group.Entries, entry) root.Groups = append(root.Groups, group) return root }
go
func NewRootData() *RootData { root := new(RootData) group := NewGroup() group.Name = "NewDatabase" entry := NewEntry() entry.Values = append(entry.Values, ValueData{Key: "Title", Value: V{Content: "Sample Entry"}}) group.Entries = append(group.Entries, entry) root.Groups = append(root.Groups, group) return root }
[ "func", "NewRootData", "(", ")", "*", "RootData", "{", "root", ":=", "new", "(", "RootData", ")", "\n", "group", ":=", "NewGroup", "(", ")", "\n", "group", ".", "Name", "=", "\"", "\"", "\n", "entry", ":=", "NewEntry", "(", ")", "\n", "entry", ".",...
// NewRootData returns a RootData struct with good defaults
[ "NewRootData", "returns", "a", "RootData", "struct", "with", "good", "defaults" ]
8892e349f7674fa2214afba77de81fd6dfc44507
https://github.com/tobischo/gokeepasslib/blob/8892e349f7674fa2214afba77de81fd6dfc44507/xml.go#L163-L172
17,798
tobischo/gokeepasslib
xml.go
NewGroup
func NewGroup() Group { return Group{ EnableAutoType: w.BoolWrapper(true), EnableSearching: w.BoolWrapper(true), Times: NewTimeData(), UUID: NewUUID(), } }
go
func NewGroup() Group { return Group{ EnableAutoType: w.BoolWrapper(true), EnableSearching: w.BoolWrapper(true), Times: NewTimeData(), UUID: NewUUID(), } }
[ "func", "NewGroup", "(", ")", "Group", "{", "return", "Group", "{", "EnableAutoType", ":", "w", ".", "BoolWrapper", "(", "true", ")", ",", "EnableSearching", ":", "w", ".", "BoolWrapper", "(", "true", ")", ",", "Times", ":", "NewTimeData", "(", ")", ",...
// NewGroup returns a new group with time data and uuid set
[ "NewGroup", "returns", "a", "new", "group", "with", "time", "data", "and", "uuid", "set" ]
8892e349f7674fa2214afba77de81fd6dfc44507
https://github.com/tobischo/gokeepasslib/blob/8892e349f7674fa2214afba77de81fd6dfc44507/xml.go#L182-L189
17,799
tobischo/gokeepasslib
xml.go
NewEntry
func NewEntry() Entry { e := Entry{} e.Times = NewTimeData() e.UUID = NewUUID() return e }
go
func NewEntry() Entry { e := Entry{} e.Times = NewTimeData() e.UUID = NewUUID() return e }
[ "func", "NewEntry", "(", ")", "Entry", "{", "e", ":=", "Entry", "{", "}", "\n", "e", ".", "Times", "=", "NewTimeData", "(", ")", "\n", "e", ".", "UUID", "=", "NewUUID", "(", ")", "\n", "return", "e", "\n", "}" ]
// NewEntry return a new entry with time data and uuid set
[ "NewEntry", "return", "a", "new", "entry", "with", "time", "data", "and", "uuid", "set" ]
8892e349f7674fa2214afba77de81fd6dfc44507
https://github.com/tobischo/gokeepasslib/blob/8892e349f7674fa2214afba77de81fd6dfc44507/xml.go#L205-L210