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,600 | sabhiram/go-wol | cmd/wol/usage.go | getAllOptions | func getAllOptions() string {
options := ""
for _, o := range validOptions {
options += fmt.Sprintf(" <yellow>-%s --%-8s</yellow> %s\n", o.short, o.long, o.description)
}
return options
} | go | func getAllOptions() string {
options := ""
for _, o := range validOptions {
options += fmt.Sprintf(" <yellow>-%s --%-8s</yellow> %s\n", o.short, o.long, o.description)
}
return options
} | [
"func",
"getAllOptions",
"(",
")",
"string",
"{",
"options",
":=",
"\"",
"\"",
"\n",
"for",
"_",
",",
"o",
":=",
"range",
"validOptions",
"{",
"options",
"+=",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\\n",
"\"",
",",
"o",
".",
"short",
",",
"o",
".",
... | // Build an option string from the above valid ones. | [
"Build",
"an",
"option",
"string",
"from",
"the",
"above",
"valid",
"ones",
"."
] | 5d8c3d0e40c5501b39f110ee4dec02a8db671913 | https://github.com/sabhiram/go-wol/blob/5d8c3d0e40c5501b39f110ee4dec02a8db671913/cmd/wol/usage.go#L77-L83 |
17,601 | sabhiram/go-wol | cmd/wol/usage.go | getAppUsageString | func getAppUsageString() string {
return colorize.Colorize(fmt.Sprintf(usageString, getAllCommands(), getAllOptions(), wol.Version))
} | go | func getAppUsageString() string {
return colorize.Colorize(fmt.Sprintf(usageString, getAllCommands(), getAllOptions(), wol.Version))
} | [
"func",
"getAppUsageString",
"(",
")",
"string",
"{",
"return",
"colorize",
".",
"Colorize",
"(",
"fmt",
".",
"Sprintf",
"(",
"usageString",
",",
"getAllCommands",
"(",
")",
",",
"getAllOptions",
"(",
")",
",",
"wol",
".",
"Version",
")",
")",
"\n",
"}"
... | // Returns the Usage string for this application. | [
"Returns",
"the",
"Usage",
"string",
"for",
"this",
"application",
"."
] | 5d8c3d0e40c5501b39f110ee4dec02a8db671913 | https://github.com/sabhiram/go-wol/blob/5d8c3d0e40c5501b39f110ee4dec02a8db671913/cmd/wol/usage.go#L86-L88 |
17,602 | sabhiram/go-wol | cmd/wol/wol.go | listCmd | func listCmd(args []string, aliases *Aliases) error {
mp, err := aliases.List()
if err != nil {
fmt.Fprintf(os.Stderr, "Failed to get list of aliases: %v\n", err)
return err
}
if len(mp) == 0 {
fmt.Printf("No aliases found! Add one with \"wol alias <name> <mac>\"\n")
} else {
for alias, mi := range mp {
fmt.Printf(" %s - %s %s\n", alias, mi.Mac, mi.Iface)
}
}
return nil
} | go | func listCmd(args []string, aliases *Aliases) error {
mp, err := aliases.List()
if err != nil {
fmt.Fprintf(os.Stderr, "Failed to get list of aliases: %v\n", err)
return err
}
if len(mp) == 0 {
fmt.Printf("No aliases found! Add one with \"wol alias <name> <mac>\"\n")
} else {
for alias, mi := range mp {
fmt.Printf(" %s - %s %s\n", alias, mi.Mac, mi.Iface)
}
}
return nil
} | [
"func",
"listCmd",
"(",
"args",
"[",
"]",
"string",
",",
"aliases",
"*",
"Aliases",
")",
"error",
"{",
"mp",
",",
"err",
":=",
"aliases",
".",
"List",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"fmt",
".",
"Fprintf",
"(",
"os",
".",
"Stderr",... | // Run the list command. | [
"Run",
"the",
"list",
"command",
"."
] | 5d8c3d0e40c5501b39f110ee4dec02a8db671913 | https://github.com/sabhiram/go-wol/blob/5d8c3d0e40c5501b39f110ee4dec02a8db671913/cmd/wol/wol.go#L85-L99 |
17,603 | sabhiram/go-wol | cmd/wol/wol.go | removeCmd | func removeCmd(args []string, aliases *Aliases) error {
if len(args) > 0 {
alias := args[0]
return aliases.Del(alias)
}
return errors.New("remove command requires a <name> of an alias")
} | go | func removeCmd(args []string, aliases *Aliases) error {
if len(args) > 0 {
alias := args[0]
return aliases.Del(alias)
}
return errors.New("remove command requires a <name> of an alias")
} | [
"func",
"removeCmd",
"(",
"args",
"[",
"]",
"string",
",",
"aliases",
"*",
"Aliases",
")",
"error",
"{",
"if",
"len",
"(",
"args",
")",
">",
"0",
"{",
"alias",
":=",
"args",
"[",
"0",
"]",
"\n",
"return",
"aliases",
".",
"Del",
"(",
"alias",
")",... | // Run the remove command. | [
"Run",
"the",
"remove",
"command",
"."
] | 5d8c3d0e40c5501b39f110ee4dec02a8db671913 | https://github.com/sabhiram/go-wol/blob/5d8c3d0e40c5501b39f110ee4dec02a8db671913/cmd/wol/wol.go#L102-L108 |
17,604 | sabhiram/go-wol | cmd/wol/wol.go | wakeCmd | func wakeCmd(args []string, aliases *Aliases) error {
if len(args) <= 0 {
return errors.New("No mac address specified to wake command")
}
// bcastInterface can be "eth0", "eth1", etc.. An empty string implies
// that we use the default interface when sending the UDP packet (nil).
bcastInterface := ""
macAddr := args[0]
// First we need to see if this macAddr is actually an alias, if it is:
// we set the eth interface based on the stored item, and set the macAddr
// based on the alias of the entry.
mi, err := aliases.Get(macAddr)
if err == nil {
macAddr = mi.Mac
bcastInterface = mi.Iface
}
// Always use the interface specified in the command line, if it exists.
if cliFlags.BroadcastInterface != "" {
bcastInterface = cliFlags.BroadcastInterface
}
// Populate the local address in the event that the broadcast interface has
// been set.
var localAddr *net.UDPAddr
if bcastInterface != "" {
localAddr, err = ipFromInterface(bcastInterface)
if err != nil {
return err
}
}
// The address to broadcast to is usually the default `255.255.255.255` but
// can be overloaded by specifying an override in the CLI arguments.
bcastAddr := fmt.Sprintf("%s:%s", cliFlags.BroadcastIP, cliFlags.UDPPort)
udpAddr, err := net.ResolveUDPAddr("udp", bcastAddr)
if err != nil {
return err
}
// Build the magic packet.
mp, err := wol.New(macAddr)
if err != nil {
return err
}
// Grab a stream of bytes to send.
bs, err := mp.Marshal()
if err != nil {
return err
}
// Grab a UDP connection to send our packet of bytes.
conn, err := net.DialUDP("udp", localAddr, udpAddr)
if err != nil {
return err
}
defer conn.Close()
fmt.Printf("Attempting to send a magic packet to MAC %s\n", macAddr)
fmt.Printf("... Broadcasting to: %s\n", bcastAddr)
n, err := conn.Write(bs)
if err == nil && n != 102 {
err = fmt.Errorf("magic packet sent was %d bytes (expected 102 bytes sent)", n)
}
if err != nil {
return err
}
fmt.Printf("Magic packet sent successfully to %s\n", macAddr)
return nil
} | go | func wakeCmd(args []string, aliases *Aliases) error {
if len(args) <= 0 {
return errors.New("No mac address specified to wake command")
}
// bcastInterface can be "eth0", "eth1", etc.. An empty string implies
// that we use the default interface when sending the UDP packet (nil).
bcastInterface := ""
macAddr := args[0]
// First we need to see if this macAddr is actually an alias, if it is:
// we set the eth interface based on the stored item, and set the macAddr
// based on the alias of the entry.
mi, err := aliases.Get(macAddr)
if err == nil {
macAddr = mi.Mac
bcastInterface = mi.Iface
}
// Always use the interface specified in the command line, if it exists.
if cliFlags.BroadcastInterface != "" {
bcastInterface = cliFlags.BroadcastInterface
}
// Populate the local address in the event that the broadcast interface has
// been set.
var localAddr *net.UDPAddr
if bcastInterface != "" {
localAddr, err = ipFromInterface(bcastInterface)
if err != nil {
return err
}
}
// The address to broadcast to is usually the default `255.255.255.255` but
// can be overloaded by specifying an override in the CLI arguments.
bcastAddr := fmt.Sprintf("%s:%s", cliFlags.BroadcastIP, cliFlags.UDPPort)
udpAddr, err := net.ResolveUDPAddr("udp", bcastAddr)
if err != nil {
return err
}
// Build the magic packet.
mp, err := wol.New(macAddr)
if err != nil {
return err
}
// Grab a stream of bytes to send.
bs, err := mp.Marshal()
if err != nil {
return err
}
// Grab a UDP connection to send our packet of bytes.
conn, err := net.DialUDP("udp", localAddr, udpAddr)
if err != nil {
return err
}
defer conn.Close()
fmt.Printf("Attempting to send a magic packet to MAC %s\n", macAddr)
fmt.Printf("... Broadcasting to: %s\n", bcastAddr)
n, err := conn.Write(bs)
if err == nil && n != 102 {
err = fmt.Errorf("magic packet sent was %d bytes (expected 102 bytes sent)", n)
}
if err != nil {
return err
}
fmt.Printf("Magic packet sent successfully to %s\n", macAddr)
return nil
} | [
"func",
"wakeCmd",
"(",
"args",
"[",
"]",
"string",
",",
"aliases",
"*",
"Aliases",
")",
"error",
"{",
"if",
"len",
"(",
"args",
")",
"<=",
"0",
"{",
"return",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"// bcastInterface can be \... | // Run the wake command. | [
"Run",
"the",
"wake",
"command",
"."
] | 5d8c3d0e40c5501b39f110ee4dec02a8db671913 | https://github.com/sabhiram/go-wol/blob/5d8c3d0e40c5501b39f110ee4dec02a8db671913/cmd/wol/wol.go#L111-L184 |
17,605 | sabhiram/go-wol | cmd/wol/wol.go | main | func main() {
var args []string
// Detect the current user to figure out what their ~ is.
usr, err := user.Current()
fatalOnError(err)
// Load the list of aliases from the file at dbPath.
aliases, err := LoadAliases(path.Join(usr.HomeDir, dbPath))
fatalOnError(err)
defer aliases.Close()
// Parse arguments which might get passed to "wol".
parser := flags.NewParser(&cliFlags, flags.Default & ^flags.HelpFlag)
args, err = parser.Parse()
ec := 0
switch {
// Parse Error, print usage.
case err != nil:
ec = printUsageGetExitCode("", 1)
// No arguments, or help requested, print usage.
case len(os.Args) == 1 || cliFlags.Help:
ec = printUsageGetExitCode("", 0)
// "--version" requested.
case cliFlags.Version:
fmt.Printf("%s\n", wol.Version)
// Make sure we are being asked to run a something.
case len(args) == 0:
ec = printUsageGetExitCode("No command specified, see usage:\n", 1)
// All other cases go here.
case true:
cmd, cmdArgs := strings.ToLower(args[0]), args[1:]
if fn, ok := cmdMap[cmd]; ok {
err = fn(cmdArgs, aliases)
} else {
err = wakeCmd(args, aliases)
}
fatalOnError(err)
}
os.Exit(ec)
} | go | func main() {
var args []string
// Detect the current user to figure out what their ~ is.
usr, err := user.Current()
fatalOnError(err)
// Load the list of aliases from the file at dbPath.
aliases, err := LoadAliases(path.Join(usr.HomeDir, dbPath))
fatalOnError(err)
defer aliases.Close()
// Parse arguments which might get passed to "wol".
parser := flags.NewParser(&cliFlags, flags.Default & ^flags.HelpFlag)
args, err = parser.Parse()
ec := 0
switch {
// Parse Error, print usage.
case err != nil:
ec = printUsageGetExitCode("", 1)
// No arguments, or help requested, print usage.
case len(os.Args) == 1 || cliFlags.Help:
ec = printUsageGetExitCode("", 0)
// "--version" requested.
case cliFlags.Version:
fmt.Printf("%s\n", wol.Version)
// Make sure we are being asked to run a something.
case len(args) == 0:
ec = printUsageGetExitCode("No command specified, see usage:\n", 1)
// All other cases go here.
case true:
cmd, cmdArgs := strings.ToLower(args[0]), args[1:]
if fn, ok := cmdMap[cmd]; ok {
err = fn(cmdArgs, aliases)
} else {
err = wakeCmd(args, aliases)
}
fatalOnError(err)
}
os.Exit(ec)
} | [
"func",
"main",
"(",
")",
"{",
"var",
"args",
"[",
"]",
"string",
"\n\n",
"// Detect the current user to figure out what their ~ is.",
"usr",
",",
"err",
":=",
"user",
".",
"Current",
"(",
")",
"\n",
"fatalOnError",
"(",
"err",
")",
"\n\n",
"// Load the list of ... | // Main entry point for binary. | [
"Main",
"entry",
"point",
"for",
"binary",
"."
] | 5d8c3d0e40c5501b39f110ee4dec02a8db671913 | https://github.com/sabhiram/go-wol/blob/5d8c3d0e40c5501b39f110ee4dec02a8db671913/cmd/wol/wol.go#L217-L263 |
17,606 | sabhiram/go-wol | cmd/wol/alias.go | DecodeToMacIface | func DecodeToMacIface(buf *bytes.Buffer) (MacIface, error) {
var entry MacIface
decoder := gob.NewDecoder(buf)
err := decoder.Decode(&entry)
return entry, err
} | go | func DecodeToMacIface(buf *bytes.Buffer) (MacIface, error) {
var entry MacIface
decoder := gob.NewDecoder(buf)
err := decoder.Decode(&entry)
return entry, err
} | [
"func",
"DecodeToMacIface",
"(",
"buf",
"*",
"bytes",
".",
"Buffer",
")",
"(",
"MacIface",
",",
"error",
")",
"{",
"var",
"entry",
"MacIface",
"\n",
"decoder",
":=",
"gob",
".",
"NewDecoder",
"(",
"buf",
")",
"\n",
"err",
":=",
"decoder",
".",
"Decode"... | // DecodeToMacIface takes a byte buffer and converts decodes it using the gob
// package to a MacIface entry. | [
"DecodeToMacIface",
"takes",
"a",
"byte",
"buffer",
"and",
"converts",
"decodes",
"it",
"using",
"the",
"gob",
"package",
"to",
"a",
"MacIface",
"entry",
"."
] | 5d8c3d0e40c5501b39f110ee4dec02a8db671913 | https://github.com/sabhiram/go-wol/blob/5d8c3d0e40c5501b39f110ee4dec02a8db671913/cmd/wol/alias.go#L33-L38 |
17,607 | sabhiram/go-wol | cmd/wol/alias.go | EncodeFromMacIface | func EncodeFromMacIface(mac, iface string) (*bytes.Buffer, error) {
buf := bytes.NewBuffer(nil)
entry := MacIface{mac, iface}
err := gob.NewEncoder(buf).Encode(entry)
return buf, err
} | go | func EncodeFromMacIface(mac, iface string) (*bytes.Buffer, error) {
buf := bytes.NewBuffer(nil)
entry := MacIface{mac, iface}
err := gob.NewEncoder(buf).Encode(entry)
return buf, err
} | [
"func",
"EncodeFromMacIface",
"(",
"mac",
",",
"iface",
"string",
")",
"(",
"*",
"bytes",
".",
"Buffer",
",",
"error",
")",
"{",
"buf",
":=",
"bytes",
".",
"NewBuffer",
"(",
"nil",
")",
"\n",
"entry",
":=",
"MacIface",
"{",
"mac",
",",
"iface",
"}",
... | // EncodeFromMacIface takes a MAC and an Iface and encodes a gob with a MacIface
// entry. | [
"EncodeFromMacIface",
"takes",
"a",
"MAC",
"and",
"an",
"Iface",
"and",
"encodes",
"a",
"gob",
"with",
"a",
"MacIface",
"entry",
"."
] | 5d8c3d0e40c5501b39f110ee4dec02a8db671913 | https://github.com/sabhiram/go-wol/blob/5d8c3d0e40c5501b39f110ee4dec02a8db671913/cmd/wol/alias.go#L42-L47 |
17,608 | sabhiram/go-wol | cmd/wol/alias.go | LoadAliases | func LoadAliases(dbpath string) (*Aliases, error) {
err := os.MkdirAll(path.Dir(dbpath), os.ModePerm)
if os.IsNotExist(err) {
return nil, err
}
db, err := bolt.Open(dbpath, 0660, nil)
if err != nil {
return nil, err
}
if err := db.Update(func(tx *bolt.Tx) error {
if _, lerr := tx.CreateBucketIfNotExists([]byte(bucketName)); lerr != nil {
return lerr
}
return nil
}); err != nil {
return nil, err
}
return &Aliases{
mtx: &sync.Mutex{},
db: db,
}, nil
} | go | func LoadAliases(dbpath string) (*Aliases, error) {
err := os.MkdirAll(path.Dir(dbpath), os.ModePerm)
if os.IsNotExist(err) {
return nil, err
}
db, err := bolt.Open(dbpath, 0660, nil)
if err != nil {
return nil, err
}
if err := db.Update(func(tx *bolt.Tx) error {
if _, lerr := tx.CreateBucketIfNotExists([]byte(bucketName)); lerr != nil {
return lerr
}
return nil
}); err != nil {
return nil, err
}
return &Aliases{
mtx: &sync.Mutex{},
db: db,
}, nil
} | [
"func",
"LoadAliases",
"(",
"dbpath",
"string",
")",
"(",
"*",
"Aliases",
",",
"error",
")",
"{",
"err",
":=",
"os",
".",
"MkdirAll",
"(",
"path",
".",
"Dir",
"(",
"dbpath",
")",
",",
"os",
".",
"ModePerm",
")",
"\n",
"if",
"os",
".",
"IsNotExist",... | // LoadAliases fetches a boltDb entity at a given `dbpath`. The db just contains
// a default bucket called `Aliases` which is where the alias entries are
// stored. | [
"LoadAliases",
"fetches",
"a",
"boltDb",
"entity",
"at",
"a",
"given",
"dbpath",
".",
"The",
"db",
"just",
"contains",
"a",
"default",
"bucket",
"called",
"Aliases",
"which",
"is",
"where",
"the",
"alias",
"entries",
"are",
"stored",
"."
] | 5d8c3d0e40c5501b39f110ee4dec02a8db671913 | https://github.com/sabhiram/go-wol/blob/5d8c3d0e40c5501b39f110ee4dec02a8db671913/cmd/wol/alias.go#L61-L85 |
17,609 | sabhiram/go-wol | cmd/wol/alias.go | Add | func (a *Aliases) Add(alias, mac, iface string) error {
a.mtx.Lock()
defer a.mtx.Unlock()
// Create a buffer to store the encoded MAC, interface pair.
buf, err := EncodeFromMacIface(mac, iface)
if err != nil {
return err
}
// We don't have to worry about the key existing, as we will update it
// provided it exists.
return a.db.Update(func(tx *bolt.Tx) error {
bucket := tx.Bucket([]byte(bucketName))
return bucket.Put([]byte(alias), buf.Bytes())
})
} | go | func (a *Aliases) Add(alias, mac, iface string) error {
a.mtx.Lock()
defer a.mtx.Unlock()
// Create a buffer to store the encoded MAC, interface pair.
buf, err := EncodeFromMacIface(mac, iface)
if err != nil {
return err
}
// We don't have to worry about the key existing, as we will update it
// provided it exists.
return a.db.Update(func(tx *bolt.Tx) error {
bucket := tx.Bucket([]byte(bucketName))
return bucket.Put([]byte(alias), buf.Bytes())
})
} | [
"func",
"(",
"a",
"*",
"Aliases",
")",
"Add",
"(",
"alias",
",",
"mac",
",",
"iface",
"string",
")",
"error",
"{",
"a",
".",
"mtx",
".",
"Lock",
"(",
")",
"\n",
"defer",
"a",
".",
"mtx",
".",
"Unlock",
"(",
")",
"\n\n",
"// Create a buffer to store... | // Add updates an alias entry or adds a new alias entry. If the alias already
// exists it is just overwritten. | [
"Add",
"updates",
"an",
"alias",
"entry",
"or",
"adds",
"a",
"new",
"alias",
"entry",
".",
"If",
"the",
"alias",
"already",
"exists",
"it",
"is",
"just",
"overwritten",
"."
] | 5d8c3d0e40c5501b39f110ee4dec02a8db671913 | https://github.com/sabhiram/go-wol/blob/5d8c3d0e40c5501b39f110ee4dec02a8db671913/cmd/wol/alias.go#L89-L105 |
17,610 | sabhiram/go-wol | cmd/wol/alias.go | Del | func (a *Aliases) Del(alias string) error {
a.mtx.Lock()
defer a.mtx.Unlock()
return a.db.Update(func(tx *bolt.Tx) error {
bucket := tx.Bucket([]byte(bucketName))
return bucket.Delete([]byte(alias))
})
} | go | func (a *Aliases) Del(alias string) error {
a.mtx.Lock()
defer a.mtx.Unlock()
return a.db.Update(func(tx *bolt.Tx) error {
bucket := tx.Bucket([]byte(bucketName))
return bucket.Delete([]byte(alias))
})
} | [
"func",
"(",
"a",
"*",
"Aliases",
")",
"Del",
"(",
"alias",
"string",
")",
"error",
"{",
"a",
".",
"mtx",
".",
"Lock",
"(",
")",
"\n",
"defer",
"a",
".",
"mtx",
".",
"Unlock",
"(",
")",
"\n\n",
"return",
"a",
".",
"db",
".",
"Update",
"(",
"f... | // Del removes an alias from the store based on the alias string. | [
"Del",
"removes",
"an",
"alias",
"from",
"the",
"store",
"based",
"on",
"the",
"alias",
"string",
"."
] | 5d8c3d0e40c5501b39f110ee4dec02a8db671913 | https://github.com/sabhiram/go-wol/blob/5d8c3d0e40c5501b39f110ee4dec02a8db671913/cmd/wol/alias.go#L108-L116 |
17,611 | sabhiram/go-wol | cmd/wol/alias.go | Get | func (a *Aliases) Get(alias string) (MacIface, error) {
a.mtx.Lock()
defer a.mtx.Unlock()
var entry MacIface
err := a.db.View(func(tx *bolt.Tx) error {
var err error
bucket := tx.Bucket([]byte(bucketName))
value := bucket.Get([]byte(alias))
if value == nil {
return fmt.Errorf("alias (%s) not found in db", alias)
}
entry, err = DecodeToMacIface(bytes.NewBuffer(value))
return err
})
return entry, err
} | go | func (a *Aliases) Get(alias string) (MacIface, error) {
a.mtx.Lock()
defer a.mtx.Unlock()
var entry MacIface
err := a.db.View(func(tx *bolt.Tx) error {
var err error
bucket := tx.Bucket([]byte(bucketName))
value := bucket.Get([]byte(alias))
if value == nil {
return fmt.Errorf("alias (%s) not found in db", alias)
}
entry, err = DecodeToMacIface(bytes.NewBuffer(value))
return err
})
return entry, err
} | [
"func",
"(",
"a",
"*",
"Aliases",
")",
"Get",
"(",
"alias",
"string",
")",
"(",
"MacIface",
",",
"error",
")",
"{",
"a",
".",
"mtx",
".",
"Lock",
"(",
")",
"\n",
"defer",
"a",
".",
"mtx",
".",
"Unlock",
"(",
")",
"\n\n",
"var",
"entry",
"MacIfa... | // Get retrieves a MacIface from the store based on an alias string. | [
"Get",
"retrieves",
"a",
"MacIface",
"from",
"the",
"store",
"based",
"on",
"an",
"alias",
"string",
"."
] | 5d8c3d0e40c5501b39f110ee4dec02a8db671913 | https://github.com/sabhiram/go-wol/blob/5d8c3d0e40c5501b39f110ee4dec02a8db671913/cmd/wol/alias.go#L119-L137 |
17,612 | sabhiram/go-wol | cmd/wol/alias.go | List | func (a *Aliases) List() (map[string]MacIface, error) {
a.mtx.Lock()
defer a.mtx.Unlock()
aliasMap := make(map[string]MacIface, 1)
err := a.db.View(func(tx *bolt.Tx) error {
bucket := tx.Bucket([]byte(bucketName))
cursor := bucket.Cursor()
for k, v := cursor.First(); k != nil; k, v = cursor.Next() {
if entry, err := DecodeToMacIface(bytes.NewBuffer(v)); err == nil {
aliasMap[string(k)] = entry
} else {
return err
}
}
return nil
})
return aliasMap, err
} | go | func (a *Aliases) List() (map[string]MacIface, error) {
a.mtx.Lock()
defer a.mtx.Unlock()
aliasMap := make(map[string]MacIface, 1)
err := a.db.View(func(tx *bolt.Tx) error {
bucket := tx.Bucket([]byte(bucketName))
cursor := bucket.Cursor()
for k, v := cursor.First(); k != nil; k, v = cursor.Next() {
if entry, err := DecodeToMacIface(bytes.NewBuffer(v)); err == nil {
aliasMap[string(k)] = entry
} else {
return err
}
}
return nil
})
return aliasMap, err
} | [
"func",
"(",
"a",
"*",
"Aliases",
")",
"List",
"(",
")",
"(",
"map",
"[",
"string",
"]",
"MacIface",
",",
"error",
")",
"{",
"a",
".",
"mtx",
".",
"Lock",
"(",
")",
"\n",
"defer",
"a",
".",
"mtx",
".",
"Unlock",
"(",
")",
"\n\n",
"aliasMap",
... | // List returns a map containing all alias MacIface pairs. | [
"List",
"returns",
"a",
"map",
"containing",
"all",
"alias",
"MacIface",
"pairs",
"."
] | 5d8c3d0e40c5501b39f110ee4dec02a8db671913 | https://github.com/sabhiram/go-wol/blob/5d8c3d0e40c5501b39f110ee4dec02a8db671913/cmd/wol/alias.go#L140-L158 |
17,613 | sabhiram/go-wol | cmd/wol/alias.go | Close | func (a *Aliases) Close() error {
a.mtx.Lock()
defer a.mtx.Unlock()
return a.db.Close()
} | go | func (a *Aliases) Close() error {
a.mtx.Lock()
defer a.mtx.Unlock()
return a.db.Close()
} | [
"func",
"(",
"a",
"*",
"Aliases",
")",
"Close",
"(",
")",
"error",
"{",
"a",
".",
"mtx",
".",
"Lock",
"(",
")",
"\n",
"defer",
"a",
".",
"mtx",
".",
"Unlock",
"(",
")",
"\n\n",
"return",
"a",
".",
"db",
".",
"Close",
"(",
")",
"\n",
"}"
] | // Close closes the alias store. | [
"Close",
"closes",
"the",
"alias",
"store",
"."
] | 5d8c3d0e40c5501b39f110ee4dec02a8db671913 | https://github.com/sabhiram/go-wol/blob/5d8c3d0e40c5501b39f110ee4dec02a8db671913/cmd/wol/alias.go#L161-L166 |
17,614 | sabhiram/go-wol | magic_packet.go | New | func New(mac string) (*MagicPacket, error) {
var packet MagicPacket
var macAddr MACAddress
hwAddr, err := net.ParseMAC(mac)
if err != nil {
return nil, err
}
// We only support 6 byte MAC addresses since it is much harder to use the
// binary.Write(...) interface when the size of the MagicPacket is dynamic.
if !reMAC.MatchString(mac) {
return nil, fmt.Errorf("%s is not a IEEE 802 MAC-48 address", mac)
}
// Copy bytes from the returned HardwareAddr -> a fixed size MACAddress.
for idx := range macAddr {
macAddr[idx] = hwAddr[idx]
}
// Setup the header which is 6 repetitions of 0xFF.
for idx := range packet.header {
packet.header[idx] = 0xFF
}
// Setup the payload which is 16 repetitions of the MAC addr.
for idx := range packet.payload {
packet.payload[idx] = macAddr
}
return &packet, nil
} | go | func New(mac string) (*MagicPacket, error) {
var packet MagicPacket
var macAddr MACAddress
hwAddr, err := net.ParseMAC(mac)
if err != nil {
return nil, err
}
// We only support 6 byte MAC addresses since it is much harder to use the
// binary.Write(...) interface when the size of the MagicPacket is dynamic.
if !reMAC.MatchString(mac) {
return nil, fmt.Errorf("%s is not a IEEE 802 MAC-48 address", mac)
}
// Copy bytes from the returned HardwareAddr -> a fixed size MACAddress.
for idx := range macAddr {
macAddr[idx] = hwAddr[idx]
}
// Setup the header which is 6 repetitions of 0xFF.
for idx := range packet.header {
packet.header[idx] = 0xFF
}
// Setup the payload which is 16 repetitions of the MAC addr.
for idx := range packet.payload {
packet.payload[idx] = macAddr
}
return &packet, nil
} | [
"func",
"New",
"(",
"mac",
"string",
")",
"(",
"*",
"MagicPacket",
",",
"error",
")",
"{",
"var",
"packet",
"MagicPacket",
"\n",
"var",
"macAddr",
"MACAddress",
"\n\n",
"hwAddr",
",",
"err",
":=",
"net",
".",
"ParseMAC",
"(",
"mac",
")",
"\n",
"if",
... | // New returns a magic packet based on a mac address string. | [
"New",
"returns",
"a",
"magic",
"packet",
"based",
"on",
"a",
"mac",
"address",
"string",
"."
] | 5d8c3d0e40c5501b39f110ee4dec02a8db671913 | https://github.com/sabhiram/go-wol/blob/5d8c3d0e40c5501b39f110ee4dec02a8db671913/magic_packet.go#L33-L64 |
17,615 | sabhiram/go-wol | magic_packet.go | Marshal | func (mp *MagicPacket) Marshal() ([]byte, error) {
var buf bytes.Buffer
if err := binary.Write(&buf, binary.BigEndian, mp); err != nil {
return nil, err
}
return buf.Bytes(), nil
} | go | func (mp *MagicPacket) Marshal() ([]byte, error) {
var buf bytes.Buffer
if err := binary.Write(&buf, binary.BigEndian, mp); err != nil {
return nil, err
}
return buf.Bytes(), nil
} | [
"func",
"(",
"mp",
"*",
"MagicPacket",
")",
"Marshal",
"(",
")",
"(",
"[",
"]",
"byte",
",",
"error",
")",
"{",
"var",
"buf",
"bytes",
".",
"Buffer",
"\n",
"if",
"err",
":=",
"binary",
".",
"Write",
"(",
"&",
"buf",
",",
"binary",
".",
"BigEndian... | // Marshal serializes the magic packet structure into a 102 byte slice. | [
"Marshal",
"serializes",
"the",
"magic",
"packet",
"structure",
"into",
"a",
"102",
"byte",
"slice",
"."
] | 5d8c3d0e40c5501b39f110ee4dec02a8db671913 | https://github.com/sabhiram/go-wol/blob/5d8c3d0e40c5501b39f110ee4dec02a8db671913/magic_packet.go#L67-L74 |
17,616 | xyproto/permissionbolt | permissionbolt.go | New | func New() (*Permissions, error) {
state, err := NewUserStateSimple()
if err != nil {
return nil, err
}
return NewPermissions(state), nil
} | go | func New() (*Permissions, error) {
state, err := NewUserStateSimple()
if err != nil {
return nil, err
}
return NewPermissions(state), nil
} | [
"func",
"New",
"(",
")",
"(",
"*",
"Permissions",
",",
"error",
")",
"{",
"state",
",",
"err",
":=",
"NewUserStateSimple",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"return",
"NewPermissions",
"(",
... | // New initializes a Permissions struct with all the default settings. | [
"New",
"initializes",
"a",
"Permissions",
"struct",
"with",
"all",
"the",
"default",
"settings",
"."
] | fa6f8f62b01d8724f393ef19cd128850c16fb7dc | https://github.com/xyproto/permissionbolt/blob/fa6f8f62b01d8724f393ef19cd128850c16fb7dc/permissionbolt.go#L26-L32 |
17,617 | xyproto/permissionbolt | examples/http/main.go | ServeHTTP | func (ph *permissionHandler) ServeHTTP(w http.ResponseWriter, req *http.Request) {
// Check if the user has the right admin/user rights
if ph.perm.Rejected(w, req) {
// Let the user know, by calling the custom "permission denied" function
ph.perm.DenyFunction()(w, req)
// Reject the request by not calling the next handler below
return
}
// Serve the requested page if permissions were granted
ph.mux.ServeHTTP(w, req)
} | go | func (ph *permissionHandler) ServeHTTP(w http.ResponseWriter, req *http.Request) {
// Check if the user has the right admin/user rights
if ph.perm.Rejected(w, req) {
// Let the user know, by calling the custom "permission denied" function
ph.perm.DenyFunction()(w, req)
// Reject the request by not calling the next handler below
return
}
// Serve the requested page if permissions were granted
ph.mux.ServeHTTP(w, req)
} | [
"func",
"(",
"ph",
"*",
"permissionHandler",
")",
"ServeHTTP",
"(",
"w",
"http",
".",
"ResponseWriter",
",",
"req",
"*",
"http",
".",
"Request",
")",
"{",
"// Check if the user has the right admin/user rights",
"if",
"ph",
".",
"perm",
".",
"Rejected",
"(",
"w... | // Implement the ServeHTTP method to make a permissionHandler a http.Handler | [
"Implement",
"the",
"ServeHTTP",
"method",
"to",
"make",
"a",
"permissionHandler",
"a",
"http",
".",
"Handler"
] | fa6f8f62b01d8724f393ef19cd128850c16fb7dc | https://github.com/xyproto/permissionbolt/blob/fa6f8f62b01d8724f393ef19cd128850c16fb7dc/examples/http/main.go#L27-L37 |
17,618 | gholt/ring | buildernode.go | Capacity | func (n *BuilderNode) Capacity() int {
return n.builder.ring.NodeToCapacity[n.index]
} | go | func (n *BuilderNode) Capacity() int {
return n.builder.ring.NodeToCapacity[n.index]
} | [
"func",
"(",
"n",
"*",
"BuilderNode",
")",
"Capacity",
"(",
")",
"int",
"{",
"return",
"n",
".",
"builder",
".",
"ring",
".",
"NodeToCapacity",
"[",
"n",
".",
"index",
"]",
"\n",
"}"
] | // Capacity specifies, relative to other nodes, how many assignments the node
// should have. | [
"Capacity",
"specifies",
"relative",
"to",
"other",
"nodes",
"how",
"many",
"assignments",
"the",
"node",
"should",
"have",
"."
] | 76a793e37f4c30e4c8c4e58d54db72dfe49c0edc | https://github.com/gholt/ring/blob/76a793e37f4c30e4c8c4e58d54db72dfe49c0edc/buildernode.go#L28-L30 |
17,619 | gholt/ring | buildernode.go | SetCapacity | func (n *BuilderNode) SetCapacity(v int) {
n.builder.ring.NodeToCapacity[n.index] = v
} | go | func (n *BuilderNode) SetCapacity(v int) {
n.builder.ring.NodeToCapacity[n.index] = v
} | [
"func",
"(",
"n",
"*",
"BuilderNode",
")",
"SetCapacity",
"(",
"v",
"int",
")",
"{",
"n",
".",
"builder",
".",
"ring",
".",
"NodeToCapacity",
"[",
"n",
".",
"index",
"]",
"=",
"v",
"\n",
"}"
] | // SetCapacity specifies, relative to other nodes, how many assignments the
// node should have. | [
"SetCapacity",
"specifies",
"relative",
"to",
"other",
"nodes",
"how",
"many",
"assignments",
"the",
"node",
"should",
"have",
"."
] | 76a793e37f4c30e4c8c4e58d54db72dfe49c0edc | https://github.com/gholt/ring/blob/76a793e37f4c30e4c8c4e58d54db72dfe49c0edc/buildernode.go#L34-L36 |
17,620 | gholt/ring | buildernode.go | Group | func (n *BuilderNode) Group() *BuilderGroup {
return n.builder.groups[n.builder.ring.NodeToGroup[n.index]]
} | go | func (n *BuilderNode) Group() *BuilderGroup {
return n.builder.groups[n.builder.ring.NodeToGroup[n.index]]
} | [
"func",
"(",
"n",
"*",
"BuilderNode",
")",
"Group",
"(",
")",
"*",
"BuilderGroup",
"{",
"return",
"n",
".",
"builder",
".",
"groups",
"[",
"n",
".",
"builder",
".",
"ring",
".",
"NodeToGroup",
"[",
"n",
".",
"index",
"]",
"]",
"\n",
"}"
] | // Group returns the parent group of the node; it may return nil if there is no
// parent group. | [
"Group",
"returns",
"the",
"parent",
"group",
"of",
"the",
"node",
";",
"it",
"may",
"return",
"nil",
"if",
"there",
"is",
"no",
"parent",
"group",
"."
] | 76a793e37f4c30e4c8c4e58d54db72dfe49c0edc | https://github.com/gholt/ring/blob/76a793e37f4c30e4c8c4e58d54db72dfe49c0edc/buildernode.go#L40-L42 |
17,621 | gholt/ring | buildernode.go | SetGroup | func (n *BuilderNode) SetGroup(group *BuilderGroup) {
n.builder.ring.NodeToGroup[n.index] = group.index
} | go | func (n *BuilderNode) SetGroup(group *BuilderGroup) {
n.builder.ring.NodeToGroup[n.index] = group.index
} | [
"func",
"(",
"n",
"*",
"BuilderNode",
")",
"SetGroup",
"(",
"group",
"*",
"BuilderGroup",
")",
"{",
"n",
".",
"builder",
".",
"ring",
".",
"NodeToGroup",
"[",
"n",
".",
"index",
"]",
"=",
"group",
".",
"index",
"\n",
"}"
] | // SetGroup sets the parent group of the node; it may be set to nil to have no
// parent group. | [
"SetGroup",
"sets",
"the",
"parent",
"group",
"of",
"the",
"node",
";",
"it",
"may",
"be",
"set",
"to",
"nil",
"to",
"have",
"no",
"parent",
"group",
"."
] | 76a793e37f4c30e4c8c4e58d54db72dfe49c0edc | https://github.com/gholt/ring/blob/76a793e37f4c30e4c8c4e58d54db72dfe49c0edc/buildernode.go#L46-L48 |
17,622 | gholt/ring | buildernode.go | Partitions | func (n *BuilderNode) Partitions() []int {
n.builder.ring.FillReplicaToNodeToPartitions()
var partitions holdme.OrderedIntsNoDups
for _, nodeToPartitions := range n.builder.ring.ReplicaToNodeToPartitions {
for _, partition := range nodeToPartitions[n.index] {
partitions.Add(int(partition))
}
}
return partitions
} | go | func (n *BuilderNode) Partitions() []int {
n.builder.ring.FillReplicaToNodeToPartitions()
var partitions holdme.OrderedIntsNoDups
for _, nodeToPartitions := range n.builder.ring.ReplicaToNodeToPartitions {
for _, partition := range nodeToPartitions[n.index] {
partitions.Add(int(partition))
}
}
return partitions
} | [
"func",
"(",
"n",
"*",
"BuilderNode",
")",
"Partitions",
"(",
")",
"[",
"]",
"int",
"{",
"n",
".",
"builder",
".",
"ring",
".",
"FillReplicaToNodeToPartitions",
"(",
")",
"\n",
"var",
"partitions",
"holdme",
".",
"OrderedIntsNoDups",
"\n",
"for",
"_",
",... | // Partitions returns the list of partitions assigned to this node; the list
// will be in ascending order with no duplicates. | [
"Partitions",
"returns",
"the",
"list",
"of",
"partitions",
"assigned",
"to",
"this",
"node",
";",
"the",
"list",
"will",
"be",
"in",
"ascending",
"order",
"with",
"no",
"duplicates",
"."
] | 76a793e37f4c30e4c8c4e58d54db72dfe49c0edc | https://github.com/gholt/ring/blob/76a793e37f4c30e4c8c4e58d54db72dfe49c0edc/buildernode.go#L52-L61 |
17,623 | gholt/ring | buildernode.go | ReplicaPartitions | func (n *BuilderNode) ReplicaPartitions(replica int) []int {
n.builder.ring.FillReplicaToNodeToPartitions()
partitions := make([]int, len(n.builder.ring.ReplicaToNodeToPartitions[replica][n.index]))
for i, partition := range n.builder.ring.ReplicaToNodeToPartitions[replica][n.index] {
partitions[i] = int(partition)
}
return partitions
} | go | func (n *BuilderNode) ReplicaPartitions(replica int) []int {
n.builder.ring.FillReplicaToNodeToPartitions()
partitions := make([]int, len(n.builder.ring.ReplicaToNodeToPartitions[replica][n.index]))
for i, partition := range n.builder.ring.ReplicaToNodeToPartitions[replica][n.index] {
partitions[i] = int(partition)
}
return partitions
} | [
"func",
"(",
"n",
"*",
"BuilderNode",
")",
"ReplicaPartitions",
"(",
"replica",
"int",
")",
"[",
"]",
"int",
"{",
"n",
".",
"builder",
".",
"ring",
".",
"FillReplicaToNodeToPartitions",
"(",
")",
"\n",
"partitions",
":=",
"make",
"(",
"[",
"]",
"int",
... | // ReplicaPartitions returns the list of partitions assigned to this node for
// the given replica; the list will be in ascending order with no duplicates. | [
"ReplicaPartitions",
"returns",
"the",
"list",
"of",
"partitions",
"assigned",
"to",
"this",
"node",
"for",
"the",
"given",
"replica",
";",
"the",
"list",
"will",
"be",
"in",
"ascending",
"order",
"with",
"no",
"duplicates",
"."
] | 76a793e37f4c30e4c8c4e58d54db72dfe49c0edc | https://github.com/gholt/ring/blob/76a793e37f4c30e4c8c4e58d54db72dfe49c0edc/buildernode.go#L65-L72 |
17,624 | gholt/ring | buildernode.go | Responsible | func (n *BuilderNode) Responsible(key int) int {
partition := key % len(n.builder.ring.ReplicaToPartitionToNode[0])
for replica, partitionToNode := range n.builder.ring.ReplicaToPartitionToNode {
if int(partitionToNode[partition]) == n.index {
return replica
}
}
return -1
} | go | func (n *BuilderNode) Responsible(key int) int {
partition := key % len(n.builder.ring.ReplicaToPartitionToNode[0])
for replica, partitionToNode := range n.builder.ring.ReplicaToPartitionToNode {
if int(partitionToNode[partition]) == n.index {
return replica
}
}
return -1
} | [
"func",
"(",
"n",
"*",
"BuilderNode",
")",
"Responsible",
"(",
"key",
"int",
")",
"int",
"{",
"partition",
":=",
"key",
"%",
"len",
"(",
"n",
".",
"builder",
".",
"ring",
".",
"ReplicaToPartitionToNode",
"[",
"0",
"]",
")",
"\n",
"for",
"replica",
",... | // Responsible returns the replica number this node is responsible for with
// respect to the key given; will return -1 if this node is not responsible for
// any replica for the key. | [
"Responsible",
"returns",
"the",
"replica",
"number",
"this",
"node",
"is",
"responsible",
"for",
"with",
"respect",
"to",
"the",
"key",
"given",
";",
"will",
"return",
"-",
"1",
"if",
"this",
"node",
"is",
"not",
"responsible",
"for",
"any",
"replica",
"f... | 76a793e37f4c30e4c8c4e58d54db72dfe49c0edc | https://github.com/gholt/ring/blob/76a793e37f4c30e4c8c4e58d54db72dfe49c0edc/buildernode.go#L77-L85 |
17,625 | gholt/ring | buildernode.go | ResponsibleForReplicaPartition | func (n *BuilderNode) ResponsibleForReplicaPartition(replica, partition int) bool {
for _, partitionToNode := range n.builder.ring.ReplicaToPartitionToNode {
if int(partitionToNode[partition]) == n.index {
return true
}
}
return false
} | go | func (n *BuilderNode) ResponsibleForReplicaPartition(replica, partition int) bool {
for _, partitionToNode := range n.builder.ring.ReplicaToPartitionToNode {
if int(partitionToNode[partition]) == n.index {
return true
}
}
return false
} | [
"func",
"(",
"n",
"*",
"BuilderNode",
")",
"ResponsibleForReplicaPartition",
"(",
"replica",
",",
"partition",
"int",
")",
"bool",
"{",
"for",
"_",
",",
"partitionToNode",
":=",
"range",
"n",
".",
"builder",
".",
"ring",
".",
"ReplicaToPartitionToNode",
"{",
... | // ResponsibleForReplicaPartition returns true if this node is reponsible for
// the specific replica and partition given. | [
"ResponsibleForReplicaPartition",
"returns",
"true",
"if",
"this",
"node",
"is",
"reponsible",
"for",
"the",
"specific",
"replica",
"and",
"partition",
"given",
"."
] | 76a793e37f4c30e4c8c4e58d54db72dfe49c0edc | https://github.com/gholt/ring/blob/76a793e37f4c30e4c8c4e58d54db72dfe49c0edc/buildernode.go#L89-L96 |
17,626 | gholt/ring | buildernode.go | Assign | func (n *BuilderNode) Assign(replica, partition int) {
n.builder.Assign(replica, partition, n)
} | go | func (n *BuilderNode) Assign(replica, partition int) {
n.builder.Assign(replica, partition, n)
} | [
"func",
"(",
"n",
"*",
"BuilderNode",
")",
"Assign",
"(",
"replica",
",",
"partition",
"int",
")",
"{",
"n",
".",
"builder",
".",
"Assign",
"(",
"replica",
",",
"partition",
",",
"n",
")",
"\n",
"}"
] | // Assign will override the current builder's assignment and set a specific
// replica of a partition to this specific node. This is mostly just useful for
// testing, as future calls to Rebalance may move this assignment. | [
"Assign",
"will",
"override",
"the",
"current",
"builder",
"s",
"assignment",
"and",
"set",
"a",
"specific",
"replica",
"of",
"a",
"partition",
"to",
"this",
"specific",
"node",
".",
"This",
"is",
"mostly",
"just",
"useful",
"for",
"testing",
"as",
"future",... | 76a793e37f4c30e4c8c4e58d54db72dfe49c0edc | https://github.com/gholt/ring/blob/76a793e37f4c30e4c8c4e58d54db72dfe49c0edc/buildernode.go#L101-L103 |
17,627 | gholt/ring | builder.go | NewBuilder | func NewBuilder(replicaCount int) *Builder {
if replicaCount < 1 {
replicaCount = 1
}
if replicaCount > 127 {
replicaCount = 127
}
b := &Builder{ring: lowring.New(replicaCount), randIntn: rand.New(rand.NewSource(0)).Intn}
b.groups = []*BuilderGroup{{builder: b}}
return b
} | go | func NewBuilder(replicaCount int) *Builder {
if replicaCount < 1 {
replicaCount = 1
}
if replicaCount > 127 {
replicaCount = 127
}
b := &Builder{ring: lowring.New(replicaCount), randIntn: rand.New(rand.NewSource(0)).Intn}
b.groups = []*BuilderGroup{{builder: b}}
return b
} | [
"func",
"NewBuilder",
"(",
"replicaCount",
"int",
")",
"*",
"Builder",
"{",
"if",
"replicaCount",
"<",
"1",
"{",
"replicaCount",
"=",
"1",
"\n",
"}",
"\n",
"if",
"replicaCount",
">",
"127",
"{",
"replicaCount",
"=",
"127",
"\n",
"}",
"\n",
"b",
":=",
... | // NewBuilder creates a new builder with the initial replica count given. | [
"NewBuilder",
"creates",
"a",
"new",
"builder",
"with",
"the",
"initial",
"replica",
"count",
"given",
"."
] | 76a793e37f4c30e4c8c4e58d54db72dfe49c0edc | https://github.com/gholt/ring/blob/76a793e37f4c30e4c8c4e58d54db72dfe49c0edc/builder.go#L25-L35 |
17,628 | gholt/ring | builder.go | Ring | func (b *Builder) Ring() *Ring {
ring := &Ring{
nodes: make([]*Node, len(b.nodes)),
groups: make([]*Group, len(b.groups)),
nodeToGroup: make([]int, len(b.nodes)),
groupToGroup: make([]int, len(b.groups)),
replicaToPartitionToNode: make([][]lowring.Node, len(b.ring.ReplicaToPartitionToNode)),
rebalanced: b.ring.Rebalanced,
}
for i, n := range b.nodes {
ring.nodes[i] = &Node{
ring: ring,
index: i,
info: n.info,
capacity: b.ring.NodeToCapacity[i],
}
}
for i, g := range b.groups {
ring.groups[i] = &Group{
ring: ring,
index: i,
info: g.info,
}
}
copy(ring.nodeToGroup, b.ring.NodeToGroup)
copy(ring.groupToGroup, b.ring.GroupToGroup)
replicaCount := len(b.ring.ReplicaToPartitionToNode)
partitionCount := len(b.ring.ReplicaToPartitionToNode[0])
for replica := 0; replica < replicaCount; replica++ {
ring.replicaToPartitionToNode[replica] = make([]lowring.Node, partitionCount)
copy(ring.replicaToPartitionToNode[replica], b.ring.ReplicaToPartitionToNode[replica])
}
return ring
} | go | func (b *Builder) Ring() *Ring {
ring := &Ring{
nodes: make([]*Node, len(b.nodes)),
groups: make([]*Group, len(b.groups)),
nodeToGroup: make([]int, len(b.nodes)),
groupToGroup: make([]int, len(b.groups)),
replicaToPartitionToNode: make([][]lowring.Node, len(b.ring.ReplicaToPartitionToNode)),
rebalanced: b.ring.Rebalanced,
}
for i, n := range b.nodes {
ring.nodes[i] = &Node{
ring: ring,
index: i,
info: n.info,
capacity: b.ring.NodeToCapacity[i],
}
}
for i, g := range b.groups {
ring.groups[i] = &Group{
ring: ring,
index: i,
info: g.info,
}
}
copy(ring.nodeToGroup, b.ring.NodeToGroup)
copy(ring.groupToGroup, b.ring.GroupToGroup)
replicaCount := len(b.ring.ReplicaToPartitionToNode)
partitionCount := len(b.ring.ReplicaToPartitionToNode[0])
for replica := 0; replica < replicaCount; replica++ {
ring.replicaToPartitionToNode[replica] = make([]lowring.Node, partitionCount)
copy(ring.replicaToPartitionToNode[replica], b.ring.ReplicaToPartitionToNode[replica])
}
return ring
} | [
"func",
"(",
"b",
"*",
"Builder",
")",
"Ring",
"(",
")",
"*",
"Ring",
"{",
"ring",
":=",
"&",
"Ring",
"{",
"nodes",
":",
"make",
"(",
"[",
"]",
"*",
"Node",
",",
"len",
"(",
"b",
".",
"nodes",
")",
")",
",",
"groups",
":",
"make",
"(",
"[",... | // Ring returns an immutable copy of the assignment information contained in
// the builder. | [
"Ring",
"returns",
"an",
"immutable",
"copy",
"of",
"the",
"assignment",
"information",
"contained",
"in",
"the",
"builder",
"."
] | 76a793e37f4c30e4c8c4e58d54db72dfe49c0edc | https://github.com/gholt/ring/blob/76a793e37f4c30e4c8c4e58d54db72dfe49c0edc/builder.go#L39-L72 |
17,629 | gholt/ring | builder.go | Nodes | func (b *Builder) Nodes() []*BuilderNode {
nodes := make([]*BuilderNode, len(b.nodes))
copy(nodes, b.nodes)
return nodes
} | go | func (b *Builder) Nodes() []*BuilderNode {
nodes := make([]*BuilderNode, len(b.nodes))
copy(nodes, b.nodes)
return nodes
} | [
"func",
"(",
"b",
"*",
"Builder",
")",
"Nodes",
"(",
")",
"[",
"]",
"*",
"BuilderNode",
"{",
"nodes",
":=",
"make",
"(",
"[",
"]",
"*",
"BuilderNode",
",",
"len",
"(",
"b",
".",
"nodes",
")",
")",
"\n",
"copy",
"(",
"nodes",
",",
"b",
".",
"n... | // Nodes returns a slice of all the nodes in the builder. | [
"Nodes",
"returns",
"a",
"slice",
"of",
"all",
"the",
"nodes",
"in",
"the",
"builder",
"."
] | 76a793e37f4c30e4c8c4e58d54db72dfe49c0edc | https://github.com/gholt/ring/blob/76a793e37f4c30e4c8c4e58d54db72dfe49c0edc/builder.go#L75-L79 |
17,630 | gholt/ring | builder.go | AddNode | func (b *Builder) AddNode(info string, capacity int, group *BuilderGroup) *BuilderNode {
groupIndex := 0
if group != nil {
groupIndex = group.index
}
node := &BuilderNode{builder: b, index: int(b.ring.AddNode(capacity, groupIndex)), info: info}
b.nodes = append(b.nodes, node)
return node
} | go | func (b *Builder) AddNode(info string, capacity int, group *BuilderGroup) *BuilderNode {
groupIndex := 0
if group != nil {
groupIndex = group.index
}
node := &BuilderNode{builder: b, index: int(b.ring.AddNode(capacity, groupIndex)), info: info}
b.nodes = append(b.nodes, node)
return node
} | [
"func",
"(",
"b",
"*",
"Builder",
")",
"AddNode",
"(",
"info",
"string",
",",
"capacity",
"int",
",",
"group",
"*",
"BuilderGroup",
")",
"*",
"BuilderNode",
"{",
"groupIndex",
":=",
"0",
"\n",
"if",
"group",
"!=",
"nil",
"{",
"groupIndex",
"=",
"group"... | // AddNode adds another node to the builder. Info is a user-defined string and
// is not used directly by the builder. Capacity specifies, relative to other
// nodes, how many assignments the node should have. The group indicates which
// group the node is in; the builder will do its best to keep similar
// assignments in dissimilar groups. The group may be nil. | [
"AddNode",
"adds",
"another",
"node",
"to",
"the",
"builder",
".",
"Info",
"is",
"a",
"user",
"-",
"defined",
"string",
"and",
"is",
"not",
"used",
"directly",
"by",
"the",
"builder",
".",
"Capacity",
"specifies",
"relative",
"to",
"other",
"nodes",
"how",... | 76a793e37f4c30e4c8c4e58d54db72dfe49c0edc | https://github.com/gholt/ring/blob/76a793e37f4c30e4c8c4e58d54db72dfe49c0edc/builder.go#L86-L94 |
17,631 | gholt/ring | builder.go | Groups | func (b *Builder) Groups() []*BuilderGroup {
groups := make([]*BuilderGroup, len(b.groups))
copy(groups, b.groups)
return groups
} | go | func (b *Builder) Groups() []*BuilderGroup {
groups := make([]*BuilderGroup, len(b.groups))
copy(groups, b.groups)
return groups
} | [
"func",
"(",
"b",
"*",
"Builder",
")",
"Groups",
"(",
")",
"[",
"]",
"*",
"BuilderGroup",
"{",
"groups",
":=",
"make",
"(",
"[",
"]",
"*",
"BuilderGroup",
",",
"len",
"(",
"b",
".",
"groups",
")",
")",
"\n",
"copy",
"(",
"groups",
",",
"b",
"."... | // Groups returns a slice of all the groups in use by the builder. | [
"Groups",
"returns",
"a",
"slice",
"of",
"all",
"the",
"groups",
"in",
"use",
"by",
"the",
"builder",
"."
] | 76a793e37f4c30e4c8c4e58d54db72dfe49c0edc | https://github.com/gholt/ring/blob/76a793e37f4c30e4c8c4e58d54db72dfe49c0edc/builder.go#L97-L101 |
17,632 | gholt/ring | builder.go | AddGroup | func (b *Builder) AddGroup(info string, parent *BuilderGroup) *BuilderGroup {
parentIndex := 0
if parent != nil {
parentIndex = parent.index
}
index := len(b.ring.GroupToGroup)
b.ring.GroupToGroup = append(b.ring.GroupToGroup, parentIndex)
group := &BuilderGroup{builder: b, index: index, info: info}
b.groups = append(b.groups, group)
return group
} | go | func (b *Builder) AddGroup(info string, parent *BuilderGroup) *BuilderGroup {
parentIndex := 0
if parent != nil {
parentIndex = parent.index
}
index := len(b.ring.GroupToGroup)
b.ring.GroupToGroup = append(b.ring.GroupToGroup, parentIndex)
group := &BuilderGroup{builder: b, index: index, info: info}
b.groups = append(b.groups, group)
return group
} | [
"func",
"(",
"b",
"*",
"Builder",
")",
"AddGroup",
"(",
"info",
"string",
",",
"parent",
"*",
"BuilderGroup",
")",
"*",
"BuilderGroup",
"{",
"parentIndex",
":=",
"0",
"\n",
"if",
"parent",
"!=",
"nil",
"{",
"parentIndex",
"=",
"parent",
".",
"index",
"... | // AddGroup adds another group to the builder. Info is a user-defined string
// and is not used directly by the builder. The parent group offers a way to
// tier groups; the builder will do its best to keep similar assignments in
// dissimilar groups at each tier level. The parent may be nil. Cycles are not
// allowed, where the parent of a group would end up being a child of the same
// group. | [
"AddGroup",
"adds",
"another",
"group",
"to",
"the",
"builder",
".",
"Info",
"is",
"a",
"user",
"-",
"defined",
"string",
"and",
"is",
"not",
"used",
"directly",
"by",
"the",
"builder",
".",
"The",
"parent",
"group",
"offers",
"a",
"way",
"to",
"tier",
... | 76a793e37f4c30e4c8c4e58d54db72dfe49c0edc | https://github.com/gholt/ring/blob/76a793e37f4c30e4c8c4e58d54db72dfe49c0edc/builder.go#L109-L119 |
17,633 | gholt/ring | builder.go | SetReplicaCount | func (b *Builder) SetReplicaCount(v int) {
if v < 1 {
v = 1
}
if v > 127 {
v = 127
}
b.ring.SetReplicaCount(v)
} | go | func (b *Builder) SetReplicaCount(v int) {
if v < 1 {
v = 1
}
if v > 127 {
v = 127
}
b.ring.SetReplicaCount(v)
} | [
"func",
"(",
"b",
"*",
"Builder",
")",
"SetReplicaCount",
"(",
"v",
"int",
")",
"{",
"if",
"v",
"<",
"1",
"{",
"v",
"=",
"1",
"\n",
"}",
"\n",
"if",
"v",
">",
"127",
"{",
"v",
"=",
"127",
"\n",
"}",
"\n",
"b",
".",
"ring",
".",
"SetReplicaC... | // SetReplicaCount changes the replica count of the builder. Lowering the
// replica count will simply discard the higher replicas. Raising the replica
// count will create new higher replicas that will be completely unassigned and
// will require a call to Rebalance to become assigned. | [
"SetReplicaCount",
"changes",
"the",
"replica",
"count",
"of",
"the",
"builder",
".",
"Lowering",
"the",
"replica",
"count",
"will",
"simply",
"discard",
"the",
"higher",
"replicas",
".",
"Raising",
"the",
"replica",
"count",
"will",
"create",
"new",
"higher",
... | 76a793e37f4c30e4c8c4e58d54db72dfe49c0edc | https://github.com/gholt/ring/blob/76a793e37f4c30e4c8c4e58d54db72dfe49c0edc/builder.go#L130-L138 |
17,634 | gholt/ring | builder.go | SetMaxPartitionCount | func (b *Builder) SetMaxPartitionCount(v int) {
if v < 1 {
v = 1
}
b.ring.MaxPartitionCount = v
} | go | func (b *Builder) SetMaxPartitionCount(v int) {
if v < 1 {
v = 1
}
b.ring.MaxPartitionCount = v
} | [
"func",
"(",
"b",
"*",
"Builder",
")",
"SetMaxPartitionCount",
"(",
"v",
"int",
")",
"{",
"if",
"v",
"<",
"1",
"{",
"v",
"=",
"1",
"\n",
"}",
"\n",
"b",
".",
"ring",
".",
"MaxPartitionCount",
"=",
"v",
"\n",
"}"
] | // SetMaxPartitionCount sets the maximum partition count the builder will
// auto-grow to. | [
"SetMaxPartitionCount",
"sets",
"the",
"maximum",
"partition",
"count",
"the",
"builder",
"will",
"auto",
"-",
"grow",
"to",
"."
] | 76a793e37f4c30e4c8c4e58d54db72dfe49c0edc | https://github.com/gholt/ring/blob/76a793e37f4c30e4c8c4e58d54db72dfe49c0edc/builder.go#L153-L158 |
17,635 | gholt/ring | builder.go | PretendElapsed | func (b *Builder) PretendElapsed(d time.Duration) {
minutesElapsed := int64(d / time.Minute)
replicaCount := len(b.ring.ReplicaToPartitionToNode)
partitionCount := len(b.ring.ReplicaToPartitionToNode[0])
if minutesElapsed >= int64(b.ring.ReassignmentWait) || minutesElapsed >= int64(math.MaxUint16) {
for replica := 0; replica < replicaCount; replica++ {
partitionToWait := b.ring.ReplicaToPartitionToWait[replica]
for partition := 0; partition < partitionCount; partition++ {
partitionToWait[partition] = 0
}
}
} else if minutesElapsed > 0 {
for replica := 0; replica < replicaCount; replica++ {
partitionToWait := b.ring.ReplicaToPartitionToWait[replica]
for partition := 0; partition < partitionCount; partition++ {
wait64 := int64(partitionToWait[0]) - minutesElapsed
if wait64 < 0 {
wait64 = 0
}
partitionToWait[partition] = uint16(wait64)
}
}
}
} | go | func (b *Builder) PretendElapsed(d time.Duration) {
minutesElapsed := int64(d / time.Minute)
replicaCount := len(b.ring.ReplicaToPartitionToNode)
partitionCount := len(b.ring.ReplicaToPartitionToNode[0])
if minutesElapsed >= int64(b.ring.ReassignmentWait) || minutesElapsed >= int64(math.MaxUint16) {
for replica := 0; replica < replicaCount; replica++ {
partitionToWait := b.ring.ReplicaToPartitionToWait[replica]
for partition := 0; partition < partitionCount; partition++ {
partitionToWait[partition] = 0
}
}
} else if minutesElapsed > 0 {
for replica := 0; replica < replicaCount; replica++ {
partitionToWait := b.ring.ReplicaToPartitionToWait[replica]
for partition := 0; partition < partitionCount; partition++ {
wait64 := int64(partitionToWait[0]) - minutesElapsed
if wait64 < 0 {
wait64 = 0
}
partitionToWait[partition] = uint16(wait64)
}
}
}
} | [
"func",
"(",
"b",
"*",
"Builder",
")",
"PretendElapsed",
"(",
"d",
"time",
".",
"Duration",
")",
"{",
"minutesElapsed",
":=",
"int64",
"(",
"d",
"/",
"time",
".",
"Minute",
")",
"\n",
"replicaCount",
":=",
"len",
"(",
"b",
".",
"ring",
".",
"ReplicaT... | // PretendElapsed is mostly used for testing and will make the builder pretend
// the time duration has elapsed, usually freeing up time based reassignment
// restrictions. | [
"PretendElapsed",
"is",
"mostly",
"used",
"for",
"testing",
"and",
"will",
"make",
"the",
"builder",
"pretend",
"the",
"time",
"duration",
"has",
"elapsed",
"usually",
"freeing",
"up",
"time",
"based",
"reassignment",
"restrictions",
"."
] | 76a793e37f4c30e4c8c4e58d54db72dfe49c0edc | https://github.com/gholt/ring/blob/76a793e37f4c30e4c8c4e58d54db72dfe49c0edc/builder.go#L180-L203 |
17,636 | gholt/ring | builder.go | ReplicaPartitionNode | func (b *Builder) ReplicaPartitionNode(replica, partition int) *BuilderNode {
return b.nodes[b.ring.ReplicaToPartitionToNode[replica][partition]]
} | go | func (b *Builder) ReplicaPartitionNode(replica, partition int) *BuilderNode {
return b.nodes[b.ring.ReplicaToPartitionToNode[replica][partition]]
} | [
"func",
"(",
"b",
"*",
"Builder",
")",
"ReplicaPartitionNode",
"(",
"replica",
",",
"partition",
"int",
")",
"*",
"BuilderNode",
"{",
"return",
"b",
".",
"nodes",
"[",
"b",
".",
"ring",
".",
"ReplicaToPartitionToNode",
"[",
"replica",
"]",
"[",
"partition"... | // ReplicaPartitionNode returns the node responsible for a specific replica of
// a partition. | [
"ReplicaPartitionNode",
"returns",
"the",
"node",
"responsible",
"for",
"a",
"specific",
"replica",
"of",
"a",
"partition",
"."
] | 76a793e37f4c30e4c8c4e58d54db72dfe49c0edc | https://github.com/gholt/ring/blob/76a793e37f4c30e4c8c4e58d54db72dfe49c0edc/builder.go#L219-L221 |
17,637 | gholt/ring | builder.go | IsMoving | func (b *Builder) IsMoving(replica, partition int) bool {
return b.ring.ReplicaToPartitionToWait[replica][partition] > 0
} | go | func (b *Builder) IsMoving(replica, partition int) bool {
return b.ring.ReplicaToPartitionToWait[replica][partition] > 0
} | [
"func",
"(",
"b",
"*",
"Builder",
")",
"IsMoving",
"(",
"replica",
",",
"partition",
"int",
")",
"bool",
"{",
"return",
"b",
".",
"ring",
".",
"ReplicaToPartitionToWait",
"[",
"replica",
"]",
"[",
"partition",
"]",
">",
"0",
"\n",
"}"
] | // IsMoving returns true if the specific replica of the partition is currently
// in "reassignment wait", where a recent rebalance had reassigned the replica
// to a different node and so is giving time for the data to be moved. | [
"IsMoving",
"returns",
"true",
"if",
"the",
"specific",
"replica",
"of",
"the",
"partition",
"is",
"currently",
"in",
"reassignment",
"wait",
"where",
"a",
"recent",
"rebalance",
"had",
"reassigned",
"the",
"replica",
"to",
"a",
"different",
"node",
"and",
"so... | 76a793e37f4c30e4c8c4e58d54db72dfe49c0edc | https://github.com/gholt/ring/blob/76a793e37f4c30e4c8c4e58d54db72dfe49c0edc/builder.go#L226-L228 |
17,638 | gholt/ring | builder.go | MovingAssignmentCount | func (b *Builder) MovingAssignmentCount() int {
replicaCount := len(b.ring.ReplicaToPartitionToNode)
partitionCount := len(b.ring.ReplicaToPartitionToNode[0])
moving := 0
for replica := 0; replica < replicaCount; replica++ {
partitionToWait := b.ring.ReplicaToPartitionToWait[replica]
for partition := 0; partition < partitionCount; partition++ {
if partitionToWait[partition] > 0 {
moving++
}
}
}
return moving
} | go | func (b *Builder) MovingAssignmentCount() int {
replicaCount := len(b.ring.ReplicaToPartitionToNode)
partitionCount := len(b.ring.ReplicaToPartitionToNode[0])
moving := 0
for replica := 0; replica < replicaCount; replica++ {
partitionToWait := b.ring.ReplicaToPartitionToWait[replica]
for partition := 0; partition < partitionCount; partition++ {
if partitionToWait[partition] > 0 {
moving++
}
}
}
return moving
} | [
"func",
"(",
"b",
"*",
"Builder",
")",
"MovingAssignmentCount",
"(",
")",
"int",
"{",
"replicaCount",
":=",
"len",
"(",
"b",
".",
"ring",
".",
"ReplicaToPartitionToNode",
")",
"\n",
"partitionCount",
":=",
"len",
"(",
"b",
".",
"ring",
".",
"ReplicaToParti... | // MovingAssignmentCount returns the number of assignments that are currently
// "in motion". If you were to call IsMoving for every replica of every
// partition and count the true responses, that would equal the
// MovingAssignmentCount. | [
"MovingAssignmentCount",
"returns",
"the",
"number",
"of",
"assignments",
"that",
"are",
"currently",
"in",
"motion",
".",
"If",
"you",
"were",
"to",
"call",
"IsMoving",
"for",
"every",
"replica",
"of",
"every",
"partition",
"and",
"count",
"the",
"true",
"res... | 76a793e37f4c30e4c8c4e58d54db72dfe49c0edc | https://github.com/gholt/ring/blob/76a793e37f4c30e4c8c4e58d54db72dfe49c0edc/builder.go#L234-L247 |
17,639 | gholt/ring | builder.go | ReassignmentWait | func (b *Builder) ReassignmentWait() time.Duration {
return time.Duration(b.ring.ReassignmentWait) * time.Minute
} | go | func (b *Builder) ReassignmentWait() time.Duration {
return time.Duration(b.ring.ReassignmentWait) * time.Minute
} | [
"func",
"(",
"b",
"*",
"Builder",
")",
"ReassignmentWait",
"(",
")",
"time",
".",
"Duration",
"{",
"return",
"time",
".",
"Duration",
"(",
"b",
".",
"ring",
".",
"ReassignmentWait",
")",
"*",
"time",
".",
"Minute",
"\n",
"}"
] | // ReassignmentWait is the time duration the builder will wait after making an
// assignment before considering reassigning that same data. | [
"ReassignmentWait",
"is",
"the",
"time",
"duration",
"the",
"builder",
"will",
"wait",
"after",
"making",
"an",
"assignment",
"before",
"considering",
"reassigning",
"that",
"same",
"data",
"."
] | 76a793e37f4c30e4c8c4e58d54db72dfe49c0edc | https://github.com/gholt/ring/blob/76a793e37f4c30e4c8c4e58d54db72dfe49c0edc/builder.go#L251-L253 |
17,640 | gholt/ring | builder.go | SetReassignmentWait | func (b *Builder) SetReassignmentWait(v time.Duration) {
i := int(v / time.Minute)
if i < 1 {
i = 1
}
if i > math.MaxUint16 {
i = math.MaxUint16
}
b.ring.ReassignmentWait = uint16(i)
} | go | func (b *Builder) SetReassignmentWait(v time.Duration) {
i := int(v / time.Minute)
if i < 1 {
i = 1
}
if i > math.MaxUint16 {
i = math.MaxUint16
}
b.ring.ReassignmentWait = uint16(i)
} | [
"func",
"(",
"b",
"*",
"Builder",
")",
"SetReassignmentWait",
"(",
"v",
"time",
".",
"Duration",
")",
"{",
"i",
":=",
"int",
"(",
"v",
"/",
"time",
".",
"Minute",
")",
"\n",
"if",
"i",
"<",
"1",
"{",
"i",
"=",
"1",
"\n",
"}",
"\n",
"if",
"i",... | // SetReassignmentWait sets the time duration the builder will wait after
// making an assignment before considering reassigning that same data. | [
"SetReassignmentWait",
"sets",
"the",
"time",
"duration",
"the",
"builder",
"will",
"wait",
"after",
"making",
"an",
"assignment",
"before",
"considering",
"reassigning",
"that",
"same",
"data",
"."
] | 76a793e37f4c30e4c8c4e58d54db72dfe49c0edc | https://github.com/gholt/ring/blob/76a793e37f4c30e4c8c4e58d54db72dfe49c0edc/builder.go#L257-L266 |
17,641 | gholt/ring | builder.go | SetMaxReplicaReassignableCount | func (b *Builder) SetMaxReplicaReassignableCount(v int) {
if v < 1 {
v = 1
}
if v > 127 {
v = 127
}
b.ring.MaxReplicaReassignableCount = int8(v)
} | go | func (b *Builder) SetMaxReplicaReassignableCount(v int) {
if v < 1 {
v = 1
}
if v > 127 {
v = 127
}
b.ring.MaxReplicaReassignableCount = int8(v)
} | [
"func",
"(",
"b",
"*",
"Builder",
")",
"SetMaxReplicaReassignableCount",
"(",
"v",
"int",
")",
"{",
"if",
"v",
"<",
"1",
"{",
"v",
"=",
"1",
"\n",
"}",
"\n",
"if",
"v",
">",
"127",
"{",
"v",
"=",
"127",
"\n",
"}",
"\n",
"b",
".",
"ring",
".",... | // SetMaxReplicaReassignableCount sets the maximum number of replicas of a
// partition the builder will set "in motion" during the reassignment wait
// period.
//
// For a full replica use case, you probably want to set this to no more than
// one less of the majority of replicas so that a majority are always in place
// at any given time.
//
// For an erasure coding use case, you probably want to set this to no more
// than the number of parity shards so that there are always enough shards in
// place at any given time. | [
"SetMaxReplicaReassignableCount",
"sets",
"the",
"maximum",
"number",
"of",
"replicas",
"of",
"a",
"partition",
"the",
"builder",
"will",
"set",
"in",
"motion",
"during",
"the",
"reassignment",
"wait",
"period",
".",
"For",
"a",
"full",
"replica",
"use",
"case",... | 76a793e37f4c30e4c8c4e58d54db72dfe49c0edc | https://github.com/gholt/ring/blob/76a793e37f4c30e4c8c4e58d54db72dfe49c0edc/builder.go#L286-L294 |
17,642 | gholt/ring | builder.go | Assign | func (b *Builder) Assign(replica, partition int, node *BuilderNode) {
b.ring.ReplicaToPartitionToNode[replica][partition] = lowring.Node(node.index)
b.ring.ReplicaToPartitionToWait[replica][partition] = 0
} | go | func (b *Builder) Assign(replica, partition int, node *BuilderNode) {
b.ring.ReplicaToPartitionToNode[replica][partition] = lowring.Node(node.index)
b.ring.ReplicaToPartitionToWait[replica][partition] = 0
} | [
"func",
"(",
"b",
"*",
"Builder",
")",
"Assign",
"(",
"replica",
",",
"partition",
"int",
",",
"node",
"*",
"BuilderNode",
")",
"{",
"b",
".",
"ring",
".",
"ReplicaToPartitionToNode",
"[",
"replica",
"]",
"[",
"partition",
"]",
"=",
"lowring",
".",
"No... | // Assign will override the current builder's assignment and set a specific
// replica of a partition to a specific node. This is mostly just useful for
// testing, as future calls to Rebalance may move this assignment. | [
"Assign",
"will",
"override",
"the",
"current",
"builder",
"s",
"assignment",
"and",
"set",
"a",
"specific",
"replica",
"of",
"a",
"partition",
"to",
"a",
"specific",
"node",
".",
"This",
"is",
"mostly",
"just",
"useful",
"for",
"testing",
"as",
"future",
... | 76a793e37f4c30e4c8c4e58d54db72dfe49c0edc | https://github.com/gholt/ring/blob/76a793e37f4c30e4c8c4e58d54db72dfe49c0edc/builder.go#L299-L302 |
17,643 | gholt/ring | builder.go | Marshal | func (b *Builder) Marshal(w io.Writer) error {
var nodeType lowring.Node
j := &builderJSON{
MarshalVersion: 0,
NodeType: int(unsafe.Sizeof(nodeType)) * 8,
ReplicaCount: len(b.ring.ReplicaToPartitionToNode),
PartitionCount: len(b.ring.ReplicaToPartitionToNode[0]),
Nodes: make([]*builderNodeJSON, len(b.nodes)),
Groups: make([]*builderGroupJSON, len(b.groups)),
MaxPartitionCount: b.ring.MaxPartitionCount,
Rebalanced: b.ring.Rebalanced.UnixNano(),
ReassignmentWait: int(b.ring.ReassignmentWait),
MaxReplicaReassignableCount: int(b.ring.MaxReplicaReassignableCount),
}
for i, n := range b.nodes {
j.Nodes[i] = &builderNodeJSON{
Info: n.info,
Capacity: b.ring.NodeToCapacity[n.index],
Group: b.ring.NodeToGroup[n.index],
}
}
for i, g := range b.groups {
j.Groups[i] = &builderGroupJSON{
Info: g.info,
Parent: b.ring.GroupToGroup[g.index],
}
}
if err := json.NewEncoder(w).Encode(j); err != nil {
return err
}
// This 0 byte is written as a preface to the raw ring data and will let
// the unmarshaler get past any trailing whitespace, newlines, etc. that
// the JSON encoder may or may not have written.
if _, err := w.Write([]byte{0}); err != nil {
return err
}
for _, partitionToNode := range b.ring.ReplicaToPartitionToNode {
if err := binary.Write(w, binary.LittleEndian, partitionToNode); err != nil {
return err
}
}
for _, partitionToWait := range b.ring.ReplicaToPartitionToWait {
if err := binary.Write(w, binary.LittleEndian, partitionToWait); err != nil {
return err
}
}
return nil
} | go | func (b *Builder) Marshal(w io.Writer) error {
var nodeType lowring.Node
j := &builderJSON{
MarshalVersion: 0,
NodeType: int(unsafe.Sizeof(nodeType)) * 8,
ReplicaCount: len(b.ring.ReplicaToPartitionToNode),
PartitionCount: len(b.ring.ReplicaToPartitionToNode[0]),
Nodes: make([]*builderNodeJSON, len(b.nodes)),
Groups: make([]*builderGroupJSON, len(b.groups)),
MaxPartitionCount: b.ring.MaxPartitionCount,
Rebalanced: b.ring.Rebalanced.UnixNano(),
ReassignmentWait: int(b.ring.ReassignmentWait),
MaxReplicaReassignableCount: int(b.ring.MaxReplicaReassignableCount),
}
for i, n := range b.nodes {
j.Nodes[i] = &builderNodeJSON{
Info: n.info,
Capacity: b.ring.NodeToCapacity[n.index],
Group: b.ring.NodeToGroup[n.index],
}
}
for i, g := range b.groups {
j.Groups[i] = &builderGroupJSON{
Info: g.info,
Parent: b.ring.GroupToGroup[g.index],
}
}
if err := json.NewEncoder(w).Encode(j); err != nil {
return err
}
// This 0 byte is written as a preface to the raw ring data and will let
// the unmarshaler get past any trailing whitespace, newlines, etc. that
// the JSON encoder may or may not have written.
if _, err := w.Write([]byte{0}); err != nil {
return err
}
for _, partitionToNode := range b.ring.ReplicaToPartitionToNode {
if err := binary.Write(w, binary.LittleEndian, partitionToNode); err != nil {
return err
}
}
for _, partitionToWait := range b.ring.ReplicaToPartitionToWait {
if err := binary.Write(w, binary.LittleEndian, partitionToWait); err != nil {
return err
}
}
return nil
} | [
"func",
"(",
"b",
"*",
"Builder",
")",
"Marshal",
"(",
"w",
"io",
".",
"Writer",
")",
"error",
"{",
"var",
"nodeType",
"lowring",
".",
"Node",
"\n",
"j",
":=",
"&",
"builderJSON",
"{",
"MarshalVersion",
":",
"0",
",",
"NodeType",
":",
"int",
"(",
"... | // Marshal will write a JSON+binary encoded version of its contents to the
// io.Writer. You can use UnmarshalBuilder to read it back later. | [
"Marshal",
"will",
"write",
"a",
"JSON",
"+",
"binary",
"encoded",
"version",
"of",
"its",
"contents",
"to",
"the",
"io",
".",
"Writer",
".",
"You",
"can",
"use",
"UnmarshalBuilder",
"to",
"read",
"it",
"back",
"later",
"."
] | 76a793e37f4c30e4c8c4e58d54db72dfe49c0edc | https://github.com/gholt/ring/blob/76a793e37f4c30e4c8c4e58d54db72dfe49c0edc/builder.go#L330-L377 |
17,644 | gholt/ring | buildergroup.go | Parent | func (g *BuilderGroup) Parent() *BuilderGroup {
parent := g.builder.ring.GroupToGroup[g.index]
if parent == 0 {
return nil
}
return g.builder.groups[parent]
} | go | func (g *BuilderGroup) Parent() *BuilderGroup {
parent := g.builder.ring.GroupToGroup[g.index]
if parent == 0 {
return nil
}
return g.builder.groups[parent]
} | [
"func",
"(",
"g",
"*",
"BuilderGroup",
")",
"Parent",
"(",
")",
"*",
"BuilderGroup",
"{",
"parent",
":=",
"g",
".",
"builder",
".",
"ring",
".",
"GroupToGroup",
"[",
"g",
".",
"index",
"]",
"\n",
"if",
"parent",
"==",
"0",
"{",
"return",
"nil",
"\n... | // Parent returns the parent group, or nil if there is no parent, of the group. | [
"Parent",
"returns",
"the",
"parent",
"group",
"or",
"nil",
"if",
"there",
"is",
"no",
"parent",
"of",
"the",
"group",
"."
] | 76a793e37f4c30e4c8c4e58d54db72dfe49c0edc | https://github.com/gholt/ring/blob/76a793e37f4c30e4c8c4e58d54db72dfe49c0edc/buildergroup.go#L24-L30 |
17,645 | gholt/ring | buildergroup.go | SetParent | func (g *BuilderGroup) SetParent(v *BuilderGroup) {
g.builder.ring.GroupToGroup[g.index] = v.index
} | go | func (g *BuilderGroup) SetParent(v *BuilderGroup) {
g.builder.ring.GroupToGroup[g.index] = v.index
} | [
"func",
"(",
"g",
"*",
"BuilderGroup",
")",
"SetParent",
"(",
"v",
"*",
"BuilderGroup",
")",
"{",
"g",
".",
"builder",
".",
"ring",
".",
"GroupToGroup",
"[",
"g",
".",
"index",
"]",
"=",
"v",
".",
"index",
"\n",
"}"
] | // SetParent sets the parent group of this group; it may be nil to indicate
// this group is a top-level group. | [
"SetParent",
"sets",
"the",
"parent",
"group",
"of",
"this",
"group",
";",
"it",
"may",
"be",
"nil",
"to",
"indicate",
"this",
"group",
"is",
"a",
"top",
"-",
"level",
"group",
"."
] | 76a793e37f4c30e4c8c4e58d54db72dfe49c0edc | https://github.com/gholt/ring/blob/76a793e37f4c30e4c8c4e58d54db72dfe49c0edc/buildergroup.go#L34-L36 |
17,646 | gholt/ring | buildergroup.go | Nodes | func (g *BuilderGroup) Nodes() []*BuilderNode {
nodes := []*BuilderNode{}
for node, group := range g.builder.ring.NodeToGroup {
if group == g.index {
nodes = append(nodes, g.builder.nodes[node])
}
}
return nodes
} | go | func (g *BuilderGroup) Nodes() []*BuilderNode {
nodes := []*BuilderNode{}
for node, group := range g.builder.ring.NodeToGroup {
if group == g.index {
nodes = append(nodes, g.builder.nodes[node])
}
}
return nodes
} | [
"func",
"(",
"g",
"*",
"BuilderGroup",
")",
"Nodes",
"(",
")",
"[",
"]",
"*",
"BuilderNode",
"{",
"nodes",
":=",
"[",
"]",
"*",
"BuilderNode",
"{",
"}",
"\n",
"for",
"node",
",",
"group",
":=",
"range",
"g",
".",
"builder",
".",
"ring",
".",
"Nod... | // Nodes returns the slice of nodes within this group and all its child groups. | [
"Nodes",
"returns",
"the",
"slice",
"of",
"nodes",
"within",
"this",
"group",
"and",
"all",
"its",
"child",
"groups",
"."
] | 76a793e37f4c30e4c8c4e58d54db72dfe49c0edc | https://github.com/gholt/ring/blob/76a793e37f4c30e4c8c4e58d54db72dfe49c0edc/buildergroup.go#L39-L47 |
17,647 | gholt/ring | buildergroup.go | AddNode | func (g *BuilderGroup) AddNode(info string, capacity int) *BuilderNode {
return g.builder.AddNode(info, capacity, g)
} | go | func (g *BuilderGroup) AddNode(info string, capacity int) *BuilderNode {
return g.builder.AddNode(info, capacity, g)
} | [
"func",
"(",
"g",
"*",
"BuilderGroup",
")",
"AddNode",
"(",
"info",
"string",
",",
"capacity",
"int",
")",
"*",
"BuilderNode",
"{",
"return",
"g",
".",
"builder",
".",
"AddNode",
"(",
"info",
",",
"capacity",
",",
"g",
")",
"\n",
"}"
] | // AddNode will create a new node in the associated builder with this group set
// as the node's parent. Info is a user-defined string and is not used directly
// by the builder. Capacity specifies, relative to other nodes, how many
// assignments the node should have. | [
"AddNode",
"will",
"create",
"a",
"new",
"node",
"in",
"the",
"associated",
"builder",
"with",
"this",
"group",
"set",
"as",
"the",
"node",
"s",
"parent",
".",
"Info",
"is",
"a",
"user",
"-",
"defined",
"string",
"and",
"is",
"not",
"used",
"directly",
... | 76a793e37f4c30e4c8c4e58d54db72dfe49c0edc | https://github.com/gholt/ring/blob/76a793e37f4c30e4c8c4e58d54db72dfe49c0edc/buildergroup.go#L53-L55 |
17,648 | gholt/ring | buildergroup.go | Groups | func (g *BuilderGroup) Groups() []*BuilderGroup {
groups := []*BuilderGroup{}
for child, parent := range g.builder.ring.GroupToGroup {
if parent == g.index {
groups = append(groups, g.builder.groups[child])
}
}
return groups
} | go | func (g *BuilderGroup) Groups() []*BuilderGroup {
groups := []*BuilderGroup{}
for child, parent := range g.builder.ring.GroupToGroup {
if parent == g.index {
groups = append(groups, g.builder.groups[child])
}
}
return groups
} | [
"func",
"(",
"g",
"*",
"BuilderGroup",
")",
"Groups",
"(",
")",
"[",
"]",
"*",
"BuilderGroup",
"{",
"groups",
":=",
"[",
"]",
"*",
"BuilderGroup",
"{",
"}",
"\n",
"for",
"child",
",",
"parent",
":=",
"range",
"g",
".",
"builder",
".",
"ring",
".",
... | // Groups returns the slice of groups that are the direct children of this
// group. | [
"Groups",
"returns",
"the",
"slice",
"of",
"groups",
"that",
"are",
"the",
"direct",
"children",
"of",
"this",
"group",
"."
] | 76a793e37f4c30e4c8c4e58d54db72dfe49c0edc | https://github.com/gholt/ring/blob/76a793e37f4c30e4c8c4e58d54db72dfe49c0edc/buildergroup.go#L59-L67 |
17,649 | gholt/ring | buildergroup.go | AddGroup | func (g *BuilderGroup) AddGroup(info string) *BuilderGroup {
return g.builder.AddGroup(info, g)
} | go | func (g *BuilderGroup) AddGroup(info string) *BuilderGroup {
return g.builder.AddGroup(info, g)
} | [
"func",
"(",
"g",
"*",
"BuilderGroup",
")",
"AddGroup",
"(",
"info",
"string",
")",
"*",
"BuilderGroup",
"{",
"return",
"g",
".",
"builder",
".",
"AddGroup",
"(",
"info",
",",
"g",
")",
"\n",
"}"
] | // AddGroup adds a new group to the associated builder with this group set as
// the new group's parent. Info is a user-defined string and is not used
// directly by the builder. | [
"AddGroup",
"adds",
"a",
"new",
"group",
"to",
"the",
"associated",
"builder",
"with",
"this",
"group",
"set",
"as",
"the",
"new",
"group",
"s",
"parent",
".",
"Info",
"is",
"a",
"user",
"-",
"defined",
"string",
"and",
"is",
"not",
"used",
"directly",
... | 76a793e37f4c30e4c8c4e58d54db72dfe49c0edc | https://github.com/gholt/ring/blob/76a793e37f4c30e4c8c4e58d54db72dfe49c0edc/buildergroup.go#L72-L74 |
17,650 | bitrise-io/envman | envman/configs.go | saveConfigs | func saveConfigs(configModel ConfigsModel) error {
if err := ensureEnvmanConfigDirExists(); err != nil {
return err
}
bytes, err := json.Marshal(configModel)
if err != nil {
return err
}
configsPth := getEnvmanConfigsFilePath()
return fileutil.WriteBytesToFile(configsPth, bytes)
} | go | func saveConfigs(configModel ConfigsModel) error {
if err := ensureEnvmanConfigDirExists(); err != nil {
return err
}
bytes, err := json.Marshal(configModel)
if err != nil {
return err
}
configsPth := getEnvmanConfigsFilePath()
return fileutil.WriteBytesToFile(configsPth, bytes)
} | [
"func",
"saveConfigs",
"(",
"configModel",
"ConfigsModel",
")",
"error",
"{",
"if",
"err",
":=",
"ensureEnvmanConfigDirExists",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"bytes",
",",
"err",
":=",
"json",
".",
"Marshal",
... | // saveConfigs ...
// only used for unit testing at the moment | [
"saveConfigs",
"...",
"only",
"used",
"for",
"unit",
"testing",
"at",
"the",
"moment"
] | dce389aa0508c35e26577e66970433e9e6750c14 | https://github.com/bitrise-io/envman/blob/dce389aa0508c35e26577e66970433e9e6750c14/envman/configs.go#L88-L99 |
17,651 | bitrise-io/envman | cli/cli.go | Run | func Run() {
cli.HelpFlag = cli.BoolFlag{Name: HelpKey + ", " + helpKeyShort, Usage: "Show help."}
cli.AppHelpTemplate = helpTemplate
cli.VersionFlag = cli.BoolFlag{Name: VersionKey + ", " + versionKeyShort, Usage: "Print the version."}
cli.VersionPrinter = func(c *cli.Context) { fmt.Println(c.App.Version) }
app := cli.NewApp()
app.Name = path.Base(os.Args[0])
app.Usage = "Environment variable manager"
app.Version = version.VERSION
app.Author = ""
app.Email = ""
app.Before = before
app.Flags = flags
app.Commands = commands
if err := app.Run(os.Args); err != nil {
log.Fatal("[ENVMAN] - Finished:", err)
}
} | go | func Run() {
cli.HelpFlag = cli.BoolFlag{Name: HelpKey + ", " + helpKeyShort, Usage: "Show help."}
cli.AppHelpTemplate = helpTemplate
cli.VersionFlag = cli.BoolFlag{Name: VersionKey + ", " + versionKeyShort, Usage: "Print the version."}
cli.VersionPrinter = func(c *cli.Context) { fmt.Println(c.App.Version) }
app := cli.NewApp()
app.Name = path.Base(os.Args[0])
app.Usage = "Environment variable manager"
app.Version = version.VERSION
app.Author = ""
app.Email = ""
app.Before = before
app.Flags = flags
app.Commands = commands
if err := app.Run(os.Args); err != nil {
log.Fatal("[ENVMAN] - Finished:", err)
}
} | [
"func",
"Run",
"(",
")",
"{",
"cli",
".",
"HelpFlag",
"=",
"cli",
".",
"BoolFlag",
"{",
"Name",
":",
"HelpKey",
"+",
"\"",
"\"",
"+",
"helpKeyShort",
",",
"Usage",
":",
"\"",
"\"",
"}",
"\n",
"cli",
".",
"AppHelpTemplate",
"=",
"helpTemplate",
"\n\n"... | // Run the Envman CLI. | [
"Run",
"the",
"Envman",
"CLI",
"."
] | dce389aa0508c35e26577e66970433e9e6750c14 | https://github.com/bitrise-io/envman/blob/dce389aa0508c35e26577e66970433e9e6750c14/cli/cli.go#L73-L96 |
17,652 | xyproto/permissionsql | permissionsql.go | NewWithConf | func NewWithConf(connectionString string) (*Permissions, error) {
state, err := NewUserState(connectionString, true)
if err != nil {
return nil, err
}
return NewPermissions(state), nil
} | go | func NewWithConf(connectionString string) (*Permissions, error) {
state, err := NewUserState(connectionString, true)
if err != nil {
return nil, err
}
return NewPermissions(state), nil
} | [
"func",
"NewWithConf",
"(",
"connectionString",
"string",
")",
"(",
"*",
"Permissions",
",",
"error",
")",
"{",
"state",
",",
"err",
":=",
"NewUserState",
"(",
"connectionString",
",",
"true",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",... | // Initialize a Permissions struct with a database connection string | [
"Initialize",
"a",
"Permissions",
"struct",
"with",
"a",
"database",
"connection",
"string"
] | d55e4b7cdf90a57c965c4ca2a3eb2abba4116533 | https://github.com/xyproto/permissionsql/blob/d55e4b7cdf90a57c965c4ca2a3eb2abba4116533/permissionsql.go#L36-L42 |
17,653 | xyproto/permissionsql | permissionsql.go | NewWithDSN | func NewWithDSN(connectionString string, database_name string) (*Permissions, error) {
state, err := NewUserStateWithDSN(connectionString, database_name, true)
if err != nil {
return nil, err
}
return NewPermissions(state), nil
} | go | func NewWithDSN(connectionString string, database_name string) (*Permissions, error) {
state, err := NewUserStateWithDSN(connectionString, database_name, true)
if err != nil {
return nil, err
}
return NewPermissions(state), nil
} | [
"func",
"NewWithDSN",
"(",
"connectionString",
"string",
",",
"database_name",
"string",
")",
"(",
"*",
"Permissions",
",",
"error",
")",
"{",
"state",
",",
"err",
":=",
"NewUserStateWithDSN",
"(",
"connectionString",
",",
"database_name",
",",
"true",
")",
"\... | // Initialize a Permissions struct with a dsn | [
"Initialize",
"a",
"Permissions",
"struct",
"with",
"a",
"dsn"
] | d55e4b7cdf90a57c965c4ca2a3eb2abba4116533 | https://github.com/xyproto/permissionsql/blob/d55e4b7cdf90a57c965c4ca2a3eb2abba4116533/permissionsql.go#L45-L51 |
17,654 | xyproto/permissionsql | permissionsql.go | Rejected | func (perm *Permissions) Rejected(w http.ResponseWriter, req *http.Request) bool {
reject := false
path := req.URL.Path // the path of the url that the user wish to visit
// If it's not "/" and set to be public regardless of permissions
if !(perm.rootIsPublic && path == "/") {
// Reject if it is an admin page and user does not have admin permissions
for _, prefix := range perm.adminPathPrefixes {
if strings.HasPrefix(path, prefix) {
if !perm.state.AdminRights(req) {
reject = true
break
}
}
}
if !reject {
// Reject if it's a user page and the user does not have user rights
for _, prefix := range perm.userPathPrefixes {
if strings.HasPrefix(path, prefix) {
if !perm.state.UserRights(req) {
reject = true
break
}
}
}
}
if !reject {
// Reject if it's not a public page
found := false
for _, prefix := range perm.publicPathPrefixes {
if strings.HasPrefix(path, prefix) {
found = true
break
}
}
if !found {
reject = true
}
}
}
return reject
} | go | func (perm *Permissions) Rejected(w http.ResponseWriter, req *http.Request) bool {
reject := false
path := req.URL.Path // the path of the url that the user wish to visit
// If it's not "/" and set to be public regardless of permissions
if !(perm.rootIsPublic && path == "/") {
// Reject if it is an admin page and user does not have admin permissions
for _, prefix := range perm.adminPathPrefixes {
if strings.HasPrefix(path, prefix) {
if !perm.state.AdminRights(req) {
reject = true
break
}
}
}
if !reject {
// Reject if it's a user page and the user does not have user rights
for _, prefix := range perm.userPathPrefixes {
if strings.HasPrefix(path, prefix) {
if !perm.state.UserRights(req) {
reject = true
break
}
}
}
}
if !reject {
// Reject if it's not a public page
found := false
for _, prefix := range perm.publicPathPrefixes {
if strings.HasPrefix(path, prefix) {
found = true
break
}
}
if !found {
reject = true
}
}
}
return reject
} | [
"func",
"(",
"perm",
"*",
"Permissions",
")",
"Rejected",
"(",
"w",
"http",
".",
"ResponseWriter",
",",
"req",
"*",
"http",
".",
"Request",
")",
"bool",
"{",
"reject",
":=",
"false",
"\n",
"path",
":=",
"req",
".",
"URL",
".",
"Path",
"// the path of t... | // Check if a given request should be rejected. | [
"Check",
"if",
"a",
"given",
"request",
"should",
"be",
"rejected",
"."
] | d55e4b7cdf90a57c965c4ca2a3eb2abba4116533 | https://github.com/xyproto/permissionsql/blob/d55e4b7cdf90a57c965c4ca2a3eb2abba4116533/permissionsql.go#L123-L169 |
17,655 | xyproto/permissionsql | userstate.go | UsernameCookie | func (state *UserState) UsernameCookie(req *http.Request) (string, error) {
username, ok := cookie.SecureCookie(req, "user", state.cookieSecret)
if ok && (username != "") {
return username, nil
}
return "", ErrCookieGetUsername
} | go | func (state *UserState) UsernameCookie(req *http.Request) (string, error) {
username, ok := cookie.SecureCookie(req, "user", state.cookieSecret)
if ok && (username != "") {
return username, nil
}
return "", ErrCookieGetUsername
} | [
"func",
"(",
"state",
"*",
"UserState",
")",
"UsernameCookie",
"(",
"req",
"*",
"http",
".",
"Request",
")",
"(",
"string",
",",
"error",
")",
"{",
"username",
",",
"ok",
":=",
"cookie",
".",
"SecureCookie",
"(",
"req",
",",
"\"",
"\"",
",",
"state",... | // Retrieve the username that is stored in a cookie in the browser, if available. | [
"Retrieve",
"the",
"username",
"that",
"is",
"stored",
"in",
"a",
"cookie",
"in",
"the",
"browser",
"if",
"available",
"."
] | d55e4b7cdf90a57c965c4ca2a3eb2abba4116533 | https://github.com/xyproto/permissionsql/blob/d55e4b7cdf90a57c965c4ca2a3eb2abba4116533/userstate.go#L254-L261 |
17,656 | xyproto/permissionsql | userstate.go | SetUsernameCookie | func (state *UserState) SetUsernameCookie(w http.ResponseWriter, username string) error {
if username == "" {
return ErrCookieEmptyUsername
}
if !state.HasUser(username) {
return ErrCookieUserMissing
}
// Create a cookie that lasts for a while ("timeout" seconds),
// this is the equivivalent of a session for a given username.
cookie.SetSecureCookiePath(w, "user", username, state.cookieTime, "/", state.cookieSecret)
return nil
} | go | func (state *UserState) SetUsernameCookie(w http.ResponseWriter, username string) error {
if username == "" {
return ErrCookieEmptyUsername
}
if !state.HasUser(username) {
return ErrCookieUserMissing
}
// Create a cookie that lasts for a while ("timeout" seconds),
// this is the equivivalent of a session for a given username.
cookie.SetSecureCookiePath(w, "user", username, state.cookieTime, "/", state.cookieSecret)
return nil
} | [
"func",
"(",
"state",
"*",
"UserState",
")",
"SetUsernameCookie",
"(",
"w",
"http",
".",
"ResponseWriter",
",",
"username",
"string",
")",
"error",
"{",
"if",
"username",
"==",
"\"",
"\"",
"{",
"return",
"ErrCookieEmptyUsername",
"\n",
"}",
"\n",
"if",
"!"... | // Store the given username in a cookie in the browser, if possible.
// The user must exist. | [
"Store",
"the",
"given",
"username",
"in",
"a",
"cookie",
"in",
"the",
"browser",
"if",
"possible",
".",
"The",
"user",
"must",
"exist",
"."
] | d55e4b7cdf90a57c965c4ca2a3eb2abba4116533 | https://github.com/xyproto/permissionsql/blob/d55e4b7cdf90a57c965c4ca2a3eb2abba4116533/userstate.go#L265-L276 |
17,657 | xyproto/permissionsql | userstate.go | addUserUnchecked | func (state *UserState) addUserUnchecked(username, passwordHash, email string) {
// Add the user
state.usernames.Add(username)
// Add password and email
state.users.Set(username, "password", passwordHash)
state.users.Set(username, "email", email)
// Addditional fields
additionalfields := []string{"loggedin", "confirmed", "admin"}
for _, fieldname := range additionalfields {
state.users.Set(username, fieldname, "false")
}
} | go | func (state *UserState) addUserUnchecked(username, passwordHash, email string) {
// Add the user
state.usernames.Add(username)
// Add password and email
state.users.Set(username, "password", passwordHash)
state.users.Set(username, "email", email)
// Addditional fields
additionalfields := []string{"loggedin", "confirmed", "admin"}
for _, fieldname := range additionalfields {
state.users.Set(username, fieldname, "false")
}
} | [
"func",
"(",
"state",
"*",
"UserState",
")",
"addUserUnchecked",
"(",
"username",
",",
"passwordHash",
",",
"email",
"string",
")",
"{",
"// Add the user",
"state",
".",
"usernames",
".",
"Add",
"(",
"username",
")",
"\n\n",
"// Add password and email",
"state",... | // Creates a user from the username and password hash, does not check for rights. | [
"Creates",
"a",
"user",
"from",
"the",
"username",
"and",
"password",
"hash",
"does",
"not",
"check",
"for",
"rights",
"."
] | d55e4b7cdf90a57c965c4ca2a3eb2abba4116533 | https://github.com/xyproto/permissionsql/blob/d55e4b7cdf90a57c965c4ca2a3eb2abba4116533/userstate.go#L344-L357 |
17,658 | xyproto/permissionsql | userstate.go | stored_hash | func (state *UserState) stored_hash(username string) []byte {
hashString, err := state.PasswordHash(username)
if err != nil {
return []byte{}
}
return []byte(hashString)
} | go | func (state *UserState) stored_hash(username string) []byte {
hashString, err := state.PasswordHash(username)
if err != nil {
return []byte{}
}
return []byte(hashString)
} | [
"func",
"(",
"state",
"*",
"UserState",
")",
"stored_hash",
"(",
"username",
"string",
")",
"[",
"]",
"byte",
"{",
"hashString",
",",
"err",
":=",
"state",
".",
"PasswordHash",
"(",
"username",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"[",
... | // Return the stored hash, or an empty byte slice. | [
"Return",
"the",
"stored",
"hash",
"or",
"an",
"empty",
"byte",
"slice",
"."
] | d55e4b7cdf90a57c965c4ca2a3eb2abba4116533 | https://github.com/xyproto/permissionsql/blob/d55e4b7cdf90a57c965c4ca2a3eb2abba4116533/userstate.go#L465-L471 |
17,659 | xyproto/permissionsql | userstate.go | CorrectPassword | func (state *UserState) CorrectPassword(username, password string) bool {
if !state.HasUser(username) {
return false
}
// Retrieve the stored password hash
hash := state.stored_hash(username)
if len(hash) == 0 {
return false
}
// Check the password with the right password algorithm
switch state.passwordAlgorithm {
case "sha256":
return correct_sha256(hash, state.cookieSecret, username, password)
case "bcrypt":
return correct_bcrypt(hash, password)
case "bcrypt+": // for backwards compatibility with sha256
if is_sha256(hash) && correct_sha256(hash, state.cookieSecret, username, password) {
return true
}
return correct_bcrypt(hash, password)
}
return false
} | go | func (state *UserState) CorrectPassword(username, password string) bool {
if !state.HasUser(username) {
return false
}
// Retrieve the stored password hash
hash := state.stored_hash(username)
if len(hash) == 0 {
return false
}
// Check the password with the right password algorithm
switch state.passwordAlgorithm {
case "sha256":
return correct_sha256(hash, state.cookieSecret, username, password)
case "bcrypt":
return correct_bcrypt(hash, password)
case "bcrypt+": // for backwards compatibility with sha256
if is_sha256(hash) && correct_sha256(hash, state.cookieSecret, username, password) {
return true
}
return correct_bcrypt(hash, password)
}
return false
} | [
"func",
"(",
"state",
"*",
"UserState",
")",
"CorrectPassword",
"(",
"username",
",",
"password",
"string",
")",
"bool",
"{",
"if",
"!",
"state",
".",
"HasUser",
"(",
"username",
")",
"{",
"return",
"false",
"\n",
"}",
"\n\n",
"// Retrieve the stored passwor... | // Check if a password is correct. username is needed because it is part of the hash. | [
"Check",
"if",
"a",
"password",
"is",
"correct",
".",
"username",
"is",
"needed",
"because",
"it",
"is",
"part",
"of",
"the",
"hash",
"."
] | d55e4b7cdf90a57c965c4ca2a3eb2abba4116533 | https://github.com/xyproto/permissionsql/blob/d55e4b7cdf90a57c965c4ca2a3eb2abba4116533/userstate.go#L474-L499 |
17,660 | xyproto/permissionsql | userstate.go | ConfirmUserByConfirmationCode | func (state *UserState) ConfirmUserByConfirmationCode(confirmationcode string) error {
username, err := state.FindUserByConfirmationCode(confirmationcode)
if err != nil {
return err
}
state.Confirm(username)
return nil
} | go | func (state *UserState) ConfirmUserByConfirmationCode(confirmationcode string) error {
username, err := state.FindUserByConfirmationCode(confirmationcode)
if err != nil {
return err
}
state.Confirm(username)
return nil
} | [
"func",
"(",
"state",
"*",
"UserState",
")",
"ConfirmUserByConfirmationCode",
"(",
"confirmationcode",
"string",
")",
"error",
"{",
"username",
",",
"err",
":=",
"state",
".",
"FindUserByConfirmationCode",
"(",
"confirmationcode",
")",
"\n",
"if",
"err",
"!=",
"... | // Take a confirmation code and mark the corresponding unconfirmed user as confirmed. | [
"Take",
"a",
"confirmation",
"code",
"and",
"mark",
"the",
"corresponding",
"unconfirmed",
"user",
"as",
"confirmed",
"."
] | d55e4b7cdf90a57c965c4ca2a3eb2abba4116533 | https://github.com/xyproto/permissionsql/blob/d55e4b7cdf90a57c965c4ca2a3eb2abba4116533/userstate.go#L565-L572 |
17,661 | xyproto/permissionsql | userstate.go | GenerateUniqueConfirmationCode | func (state *UserState) GenerateUniqueConfirmationCode() (string, error) {
const maxConfirmationCodeLength = 100 // when are the generated confirmation codes unreasonably long
length := minConfirmationCodeLength
confirmationCode := cookie.RandomHumanFriendlyString(length)
for state.AlreadyHasConfirmationCode(confirmationCode) {
// Increase the length of the confirmationCode random string every time there is a collision
length++
confirmationCode = cookie.RandomHumanFriendlyString(length)
if length > maxConfirmationCodeLength {
// This should never happen
return confirmationCode, ErrOutOfConfirmationCodes
}
}
return confirmationCode, nil
} | go | func (state *UserState) GenerateUniqueConfirmationCode() (string, error) {
const maxConfirmationCodeLength = 100 // when are the generated confirmation codes unreasonably long
length := minConfirmationCodeLength
confirmationCode := cookie.RandomHumanFriendlyString(length)
for state.AlreadyHasConfirmationCode(confirmationCode) {
// Increase the length of the confirmationCode random string every time there is a collision
length++
confirmationCode = cookie.RandomHumanFriendlyString(length)
if length > maxConfirmationCodeLength {
// This should never happen
return confirmationCode, ErrOutOfConfirmationCodes
}
}
return confirmationCode, nil
} | [
"func",
"(",
"state",
"*",
"UserState",
")",
"GenerateUniqueConfirmationCode",
"(",
")",
"(",
"string",
",",
"error",
")",
"{",
"const",
"maxConfirmationCodeLength",
"=",
"100",
"// when are the generated confirmation codes unreasonably long",
"\n",
"length",
":=",
"min... | // Generate a unique confirmation code that can be used for confirming users. | [
"Generate",
"a",
"unique",
"confirmation",
"code",
"that",
"can",
"be",
"used",
"for",
"confirming",
"users",
"."
] | d55e4b7cdf90a57c965c4ca2a3eb2abba4116533 | https://github.com/xyproto/permissionsql/blob/d55e4b7cdf90a57c965c4ca2a3eb2abba4116533/userstate.go#L580-L594 |
17,662 | albrow/zoom | model.go | ModelID | func (r *RandomID) ModelID() string {
if r.ID == "" {
r.ID = generateRandomID()
}
return r.ID
} | go | func (r *RandomID) ModelID() string {
if r.ID == "" {
r.ID = generateRandomID()
}
return r.ID
} | [
"func",
"(",
"r",
"*",
"RandomID",
")",
"ModelID",
"(",
")",
"string",
"{",
"if",
"r",
".",
"ID",
"==",
"\"",
"\"",
"{",
"r",
".",
"ID",
"=",
"generateRandomID",
"(",
")",
"\n",
"}",
"\n",
"return",
"r",
".",
"ID",
"\n",
"}"
] | // ModelID returns the id of the model, satisfying the Model interface.
// If r.ID is an empty string, it will generate a pseudo-random id which
// is highly likely to be unique. | [
"ModelID",
"returns",
"the",
"id",
"of",
"the",
"model",
"satisfying",
"the",
"Model",
"interface",
".",
"If",
"r",
".",
"ID",
"is",
"an",
"empty",
"string",
"it",
"will",
"generate",
"a",
"pseudo",
"-",
"random",
"id",
"which",
"is",
"highly",
"likely",... | 4cc9cdbf65ce1b2f60b11b765d3e6b3a5e7e8952 | https://github.com/albrow/zoom/blob/4cc9cdbf65ce1b2f60b11b765d3e6b3a5e7e8952/model.go#L38-L43 |
17,663 | albrow/zoom | model.go | compileModelSpec | func compileModelSpec(typ reflect.Type) (*modelSpec, error) {
ms := &modelSpec{
name: getDefaultModelSpecName(typ),
fieldsByName: map[string]*fieldSpec{},
typ: typ,
}
// Iterate through fields
elem := typ.Elem()
numFields := elem.NumField()
for i := 0; i < numFields; i++ {
field := elem.Field(i)
// Skip unexported fields. Prior to go 1.6, field.PkgPath won't give us
// the behavior we want. Unlike packages such as encoding/json and
// encoding/gob, Zoom does not save unexported embedded structs with
// exported fields. So instead, we check if the first character of the
// field name is lowercase.
if strings.ToLower(field.Name[0:1]) == field.Name[0:1] {
continue
}
// Skip the RandomID field
if field.Type == reflect.TypeOf(RandomID{}) {
continue
}
// Parse the "redis" tag
tag := field.Tag
redisTag := tag.Get("redis")
if redisTag == "-" {
continue // skip field
}
fs := &fieldSpec{name: field.Name, typ: field.Type}
ms.fieldsByName[fs.name] = fs
ms.fields = append(ms.fields, fs)
if redisTag != "" {
fs.redisName = redisTag
} else {
fs.redisName = fs.name
}
// Parse the "zoom" tag (currently only "index" is supported)
zoomTag := tag.Get("zoom")
shouldIndex := false
if zoomTag != "" {
options := strings.Split(zoomTag, ",")
for _, op := range options {
switch op {
case "index":
shouldIndex = true
default:
return nil, fmt.Errorf("zoom: unrecognized option specified in struct tag: %s", op)
}
}
}
// Detect the kind of the field and (if applicable) the kind of the index
if typeIsPrimative(field.Type) {
// Primitive
fs.kind = primativeField
if shouldIndex {
if err := setIndexKind(fs, field.Type); err != nil {
return nil, err
}
}
} else if field.Type.Kind() == reflect.Ptr && typeIsPrimative(field.Type.Elem()) {
// Pointer to a primitive
fs.kind = pointerField
if shouldIndex {
if err := setIndexKind(fs, field.Type.Elem()); err != nil {
return nil, err
}
}
} else {
// All other types are considered inconvertible
if shouldIndex {
return nil, fmt.Errorf("zoom: Requested index on unsupported type %s", field.Type)
}
fs.kind = inconvertibleField
}
}
return ms, nil
} | go | func compileModelSpec(typ reflect.Type) (*modelSpec, error) {
ms := &modelSpec{
name: getDefaultModelSpecName(typ),
fieldsByName: map[string]*fieldSpec{},
typ: typ,
}
// Iterate through fields
elem := typ.Elem()
numFields := elem.NumField()
for i := 0; i < numFields; i++ {
field := elem.Field(i)
// Skip unexported fields. Prior to go 1.6, field.PkgPath won't give us
// the behavior we want. Unlike packages such as encoding/json and
// encoding/gob, Zoom does not save unexported embedded structs with
// exported fields. So instead, we check if the first character of the
// field name is lowercase.
if strings.ToLower(field.Name[0:1]) == field.Name[0:1] {
continue
}
// Skip the RandomID field
if field.Type == reflect.TypeOf(RandomID{}) {
continue
}
// Parse the "redis" tag
tag := field.Tag
redisTag := tag.Get("redis")
if redisTag == "-" {
continue // skip field
}
fs := &fieldSpec{name: field.Name, typ: field.Type}
ms.fieldsByName[fs.name] = fs
ms.fields = append(ms.fields, fs)
if redisTag != "" {
fs.redisName = redisTag
} else {
fs.redisName = fs.name
}
// Parse the "zoom" tag (currently only "index" is supported)
zoomTag := tag.Get("zoom")
shouldIndex := false
if zoomTag != "" {
options := strings.Split(zoomTag, ",")
for _, op := range options {
switch op {
case "index":
shouldIndex = true
default:
return nil, fmt.Errorf("zoom: unrecognized option specified in struct tag: %s", op)
}
}
}
// Detect the kind of the field and (if applicable) the kind of the index
if typeIsPrimative(field.Type) {
// Primitive
fs.kind = primativeField
if shouldIndex {
if err := setIndexKind(fs, field.Type); err != nil {
return nil, err
}
}
} else if field.Type.Kind() == reflect.Ptr && typeIsPrimative(field.Type.Elem()) {
// Pointer to a primitive
fs.kind = pointerField
if shouldIndex {
if err := setIndexKind(fs, field.Type.Elem()); err != nil {
return nil, err
}
}
} else {
// All other types are considered inconvertible
if shouldIndex {
return nil, fmt.Errorf("zoom: Requested index on unsupported type %s", field.Type)
}
fs.kind = inconvertibleField
}
}
return ms, nil
} | [
"func",
"compileModelSpec",
"(",
"typ",
"reflect",
".",
"Type",
")",
"(",
"*",
"modelSpec",
",",
"error",
")",
"{",
"ms",
":=",
"&",
"modelSpec",
"{",
"name",
":",
"getDefaultModelSpecName",
"(",
"typ",
")",
",",
"fieldsByName",
":",
"map",
"[",
"string"... | // compilesModelSpec examines typ using reflection, parses its fields,
// and returns a modelSpec. | [
"compilesModelSpec",
"examines",
"typ",
"using",
"reflection",
"parses",
"its",
"fields",
"and",
"returns",
"a",
"modelSpec",
"."
] | 4cc9cdbf65ce1b2f60b11b765d3e6b3a5e7e8952 | https://github.com/albrow/zoom/blob/4cc9cdbf65ce1b2f60b11b765d3e6b3a5e7e8952/model.go#L91-L173 |
17,664 | albrow/zoom | model.go | getDefaultModelSpecName | func getDefaultModelSpecName(typ reflect.Type) string {
// Strip any dereference operators
for typ.Kind() == reflect.Ptr {
typ = typ.Elem()
}
nameWithPackage := typ.String()
// Strip the package name
return strings.Join(strings.Split(nameWithPackage, ".")[1:], "")
} | go | func getDefaultModelSpecName(typ reflect.Type) string {
// Strip any dereference operators
for typ.Kind() == reflect.Ptr {
typ = typ.Elem()
}
nameWithPackage := typ.String()
// Strip the package name
return strings.Join(strings.Split(nameWithPackage, ".")[1:], "")
} | [
"func",
"getDefaultModelSpecName",
"(",
"typ",
"reflect",
".",
"Type",
")",
"string",
"{",
"// Strip any dereference operators",
"for",
"typ",
".",
"Kind",
"(",
")",
"==",
"reflect",
".",
"Ptr",
"{",
"typ",
"=",
"typ",
".",
"Elem",
"(",
")",
"\n",
"}",
"... | // getDefaultModelSpecName returns the default name for the given type, which is
// simply the name of the type without the package prefix or dereference
// operators. | [
"getDefaultModelSpecName",
"returns",
"the",
"default",
"name",
"for",
"the",
"given",
"type",
"which",
"is",
"simply",
"the",
"name",
"of",
"the",
"type",
"without",
"the",
"package",
"prefix",
"or",
"dereference",
"operators",
"."
] | 4cc9cdbf65ce1b2f60b11b765d3e6b3a5e7e8952 | https://github.com/albrow/zoom/blob/4cc9cdbf65ce1b2f60b11b765d3e6b3a5e7e8952/model.go#L178-L186 |
17,665 | albrow/zoom | model.go | setIndexKind | func setIndexKind(fs *fieldSpec, fieldType reflect.Type) error {
switch {
case typeIsNumeric(fieldType):
fs.indexKind = numericIndex
case typeIsString(fieldType):
fs.indexKind = stringIndex
case typeIsBool(fieldType):
fs.indexKind = booleanIndex
default:
return fmt.Errorf("zoom: Requested index on unsupported type %s", fieldType.String())
}
return nil
} | go | func setIndexKind(fs *fieldSpec, fieldType reflect.Type) error {
switch {
case typeIsNumeric(fieldType):
fs.indexKind = numericIndex
case typeIsString(fieldType):
fs.indexKind = stringIndex
case typeIsBool(fieldType):
fs.indexKind = booleanIndex
default:
return fmt.Errorf("zoom: Requested index on unsupported type %s", fieldType.String())
}
return nil
} | [
"func",
"setIndexKind",
"(",
"fs",
"*",
"fieldSpec",
",",
"fieldType",
"reflect",
".",
"Type",
")",
"error",
"{",
"switch",
"{",
"case",
"typeIsNumeric",
"(",
"fieldType",
")",
":",
"fs",
".",
"indexKind",
"=",
"numericIndex",
"\n",
"case",
"typeIsString",
... | // setIndexKind sets the indexKind field of fs based on fieldType. | [
"setIndexKind",
"sets",
"the",
"indexKind",
"field",
"of",
"fs",
"based",
"on",
"fieldType",
"."
] | 4cc9cdbf65ce1b2f60b11b765d3e6b3a5e7e8952 | https://github.com/albrow/zoom/blob/4cc9cdbf65ce1b2f60b11b765d3e6b3a5e7e8952/model.go#L189-L201 |
17,666 | albrow/zoom | model.go | modelKey | func (ms *modelSpec) modelKey(id string) (string, error) {
if id == "" {
return "", fmt.Errorf("zoom: Error in modelKey: id was empty")
}
return ms.name + ":" + id, nil
} | go | func (ms *modelSpec) modelKey(id string) (string, error) {
if id == "" {
return "", fmt.Errorf("zoom: Error in modelKey: id was empty")
}
return ms.name + ":" + id, nil
} | [
"func",
"(",
"ms",
"*",
"modelSpec",
")",
"modelKey",
"(",
"id",
"string",
")",
"(",
"string",
",",
"error",
")",
"{",
"if",
"id",
"==",
"\"",
"\"",
"{",
"return",
"\"",
"\"",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
... | // modelKey returns the key that identifies a hash in the database
// which contains all the fields of the model corresponding to the given
// id. It returns an error iff id is empty. | [
"modelKey",
"returns",
"the",
"key",
"that",
"identifies",
"a",
"hash",
"in",
"the",
"database",
"which",
"contains",
"all",
"the",
"fields",
"of",
"the",
"model",
"corresponding",
"to",
"the",
"given",
"id",
".",
"It",
"returns",
"an",
"error",
"iff",
"id... | 4cc9cdbf65ce1b2f60b11b765d3e6b3a5e7e8952 | https://github.com/albrow/zoom/blob/4cc9cdbf65ce1b2f60b11b765d3e6b3a5e7e8952/model.go#L212-L217 |
17,667 | albrow/zoom | model.go | fieldNames | func (ms modelSpec) fieldNames() []string {
names := make([]string, len(ms.fields))
count := 0
for _, field := range ms.fields {
names[count] = field.name
count++
}
return names
} | go | func (ms modelSpec) fieldNames() []string {
names := make([]string, len(ms.fields))
count := 0
for _, field := range ms.fields {
names[count] = field.name
count++
}
return names
} | [
"func",
"(",
"ms",
"modelSpec",
")",
"fieldNames",
"(",
")",
"[",
"]",
"string",
"{",
"names",
":=",
"make",
"(",
"[",
"]",
"string",
",",
"len",
"(",
"ms",
".",
"fields",
")",
")",
"\n",
"count",
":=",
"0",
"\n",
"for",
"_",
",",
"field",
":="... | // fieldNames returns all the field names for the given modelSpec | [
"fieldNames",
"returns",
"all",
"the",
"field",
"names",
"for",
"the",
"given",
"modelSpec"
] | 4cc9cdbf65ce1b2f60b11b765d3e6b3a5e7e8952 | https://github.com/albrow/zoom/blob/4cc9cdbf65ce1b2f60b11b765d3e6b3a5e7e8952/model.go#L220-L228 |
17,668 | albrow/zoom | model.go | fieldIndexKey | func (ms *modelSpec) fieldIndexKey(fieldName string) (string, error) {
fs, found := ms.fieldsByName[fieldName]
if !found {
return "", fmt.Errorf("Type %s has no field named %s", ms.typ.Name(), fieldName)
} else if fs.indexKind == noIndex {
return "", fmt.Errorf("%s.%s is not an indexed field", ms.typ.Name(), fieldName)
}
return ms.name + ":" + fs.redisName, nil
} | go | func (ms *modelSpec) fieldIndexKey(fieldName string) (string, error) {
fs, found := ms.fieldsByName[fieldName]
if !found {
return "", fmt.Errorf("Type %s has no field named %s", ms.typ.Name(), fieldName)
} else if fs.indexKind == noIndex {
return "", fmt.Errorf("%s.%s is not an indexed field", ms.typ.Name(), fieldName)
}
return ms.name + ":" + fs.redisName, nil
} | [
"func",
"(",
"ms",
"*",
"modelSpec",
")",
"fieldIndexKey",
"(",
"fieldName",
"string",
")",
"(",
"string",
",",
"error",
")",
"{",
"fs",
",",
"found",
":=",
"ms",
".",
"fieldsByName",
"[",
"fieldName",
"]",
"\n",
"if",
"!",
"found",
"{",
"return",
"\... | // fieldIndexKey returns the key for the sorted set used to index the field identified
// by fieldName. It returns an error if fieldName does not identify a field in the spec
// or if the field it identifies is not an indexed field. | [
"fieldIndexKey",
"returns",
"the",
"key",
"for",
"the",
"sorted",
"set",
"used",
"to",
"index",
"the",
"field",
"identified",
"by",
"fieldName",
".",
"It",
"returns",
"an",
"error",
"if",
"fieldName",
"does",
"not",
"identify",
"a",
"field",
"in",
"the",
"... | 4cc9cdbf65ce1b2f60b11b765d3e6b3a5e7e8952 | https://github.com/albrow/zoom/blob/4cc9cdbf65ce1b2f60b11b765d3e6b3a5e7e8952/model.go#L257-L265 |
17,669 | albrow/zoom | model.go | sortArgs | func (ms *modelSpec) sortArgs(idsKey string, redisFieldNames []string, limit int, offset uint, reverse bool) redis.Args {
args := redis.Args{idsKey, "BY", "nosort"}
for _, fieldName := range redisFieldNames {
args = append(args, "GET", ms.name+":*->"+fieldName)
}
// We always want to get the id
args = append(args, "GET", "#")
if !(limit == 0 && offset == 0) {
args = append(args, "LIMIT", offset, limit)
}
if reverse {
args = append(args, "DESC")
} else {
args = append(args, "ASC")
}
return args
} | go | func (ms *modelSpec) sortArgs(idsKey string, redisFieldNames []string, limit int, offset uint, reverse bool) redis.Args {
args := redis.Args{idsKey, "BY", "nosort"}
for _, fieldName := range redisFieldNames {
args = append(args, "GET", ms.name+":*->"+fieldName)
}
// We always want to get the id
args = append(args, "GET", "#")
if !(limit == 0 && offset == 0) {
args = append(args, "LIMIT", offset, limit)
}
if reverse {
args = append(args, "DESC")
} else {
args = append(args, "ASC")
}
return args
} | [
"func",
"(",
"ms",
"*",
"modelSpec",
")",
"sortArgs",
"(",
"idsKey",
"string",
",",
"redisFieldNames",
"[",
"]",
"string",
",",
"limit",
"int",
",",
"offset",
"uint",
",",
"reverse",
"bool",
")",
"redis",
".",
"Args",
"{",
"args",
":=",
"redis",
".",
... | // sortArgs returns arguments that can be used to get all the fields in includeFields
// for all the models which have corresponding ids in setKey. Any fields not in
// includeFields will not be included in the arguments and will not be retrieved from
// redis when the command is eventually run. If limit or offset are not 0, the LIMIT
// option will be added to the arguments with the given limit and offset. setKey must
// be the key of a set or a sorted set which consists of model ids. The arguments
// use they "BY nosort" option, so if a specific order is required, the setKey should be
// a sorted set. | [
"sortArgs",
"returns",
"arguments",
"that",
"can",
"be",
"used",
"to",
"get",
"all",
"the",
"fields",
"in",
"includeFields",
"for",
"all",
"the",
"models",
"which",
"have",
"corresponding",
"ids",
"in",
"setKey",
".",
"Any",
"fields",
"not",
"in",
"includeFi... | 4cc9cdbf65ce1b2f60b11b765d3e6b3a5e7e8952 | https://github.com/albrow/zoom/blob/4cc9cdbf65ce1b2f60b11b765d3e6b3a5e7e8952/model.go#L275-L291 |
17,670 | albrow/zoom | model.go | checkModelType | func (ms *modelSpec) checkModelType(model Model) error {
if reflect.TypeOf(model) != ms.typ {
return fmt.Errorf("model was the wrong type. Expected %s but got %T", ms.typ.String(), model)
}
return nil
} | go | func (ms *modelSpec) checkModelType(model Model) error {
if reflect.TypeOf(model) != ms.typ {
return fmt.Errorf("model was the wrong type. Expected %s but got %T", ms.typ.String(), model)
}
return nil
} | [
"func",
"(",
"ms",
"*",
"modelSpec",
")",
"checkModelType",
"(",
"model",
"Model",
")",
"error",
"{",
"if",
"reflect",
".",
"TypeOf",
"(",
"model",
")",
"!=",
"ms",
".",
"typ",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"ms",
".",
... | // checkModelType returns an error iff model is not of the registered type that
// corresponds to modelSpec. | [
"checkModelType",
"returns",
"an",
"error",
"iff",
"model",
"is",
"not",
"of",
"the",
"registered",
"type",
"that",
"corresponds",
"to",
"modelSpec",
"."
] | 4cc9cdbf65ce1b2f60b11b765d3e6b3a5e7e8952 | https://github.com/albrow/zoom/blob/4cc9cdbf65ce1b2f60b11b765d3e6b3a5e7e8952/model.go#L295-L300 |
17,671 | albrow/zoom | model.go | checkModelsType | func (ms *modelSpec) checkModelsType(models interface{}) error {
if reflect.TypeOf(models).Kind() != reflect.Ptr {
return fmt.Errorf("models should be a pointer to a slice or array of models")
}
modelsVal := reflect.ValueOf(models).Elem()
elemType := modelsVal.Type().Elem()
switch {
case !typeIsSliceOrArray(modelsVal.Type()):
return fmt.Errorf("models should be a pointer to a slice or array of models")
case !typeIsPointerToStruct(elemType):
return fmt.Errorf("the elements in models should be pointers to structs")
case elemType != ms.typ:
return fmt.Errorf("models were the wrong type. Expected slice or array of %s but got %T", ms.typ.String(), models)
}
return nil
} | go | func (ms *modelSpec) checkModelsType(models interface{}) error {
if reflect.TypeOf(models).Kind() != reflect.Ptr {
return fmt.Errorf("models should be a pointer to a slice or array of models")
}
modelsVal := reflect.ValueOf(models).Elem()
elemType := modelsVal.Type().Elem()
switch {
case !typeIsSliceOrArray(modelsVal.Type()):
return fmt.Errorf("models should be a pointer to a slice or array of models")
case !typeIsPointerToStruct(elemType):
return fmt.Errorf("the elements in models should be pointers to structs")
case elemType != ms.typ:
return fmt.Errorf("models were the wrong type. Expected slice or array of %s but got %T", ms.typ.String(), models)
}
return nil
} | [
"func",
"(",
"ms",
"*",
"modelSpec",
")",
"checkModelsType",
"(",
"models",
"interface",
"{",
"}",
")",
"error",
"{",
"if",
"reflect",
".",
"TypeOf",
"(",
"models",
")",
".",
"Kind",
"(",
")",
"!=",
"reflect",
".",
"Ptr",
"{",
"return",
"fmt",
".",
... | // checkModelsType returns an error iff models is not a pointer to a slice of models of the
// registered type that corresponds to modelSpec. | [
"checkModelsType",
"returns",
"an",
"error",
"iff",
"models",
"is",
"not",
"a",
"pointer",
"to",
"a",
"slice",
"of",
"models",
"of",
"the",
"registered",
"type",
"that",
"corresponds",
"to",
"modelSpec",
"."
] | 4cc9cdbf65ce1b2f60b11b765d3e6b3a5e7e8952 | https://github.com/albrow/zoom/blob/4cc9cdbf65ce1b2f60b11b765d3e6b3a5e7e8952/model.go#L304-L319 |
17,672 | albrow/zoom | model.go | elemValue | func (mr *modelRef) elemValue() reflect.Value {
if mr.value().IsNil() {
msg := fmt.Sprintf("zoom: panic in elemValue(). Model of type %T was nil", mr.model)
panic(msg)
}
return mr.value().Elem()
} | go | func (mr *modelRef) elemValue() reflect.Value {
if mr.value().IsNil() {
msg := fmt.Sprintf("zoom: panic in elemValue(). Model of type %T was nil", mr.model)
panic(msg)
}
return mr.value().Elem()
} | [
"func",
"(",
"mr",
"*",
"modelRef",
")",
"elemValue",
"(",
")",
"reflect",
".",
"Value",
"{",
"if",
"mr",
".",
"value",
"(",
")",
".",
"IsNil",
"(",
")",
"{",
"msg",
":=",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"mr",
".",
"model",
")",
... | // elemValue dereferences the model and returns the
// underlying struct. If the model is a nil pointer,
// it will panic if the model is a nil pointer | [
"elemValue",
"dereferences",
"the",
"model",
"and",
"returns",
"the",
"underlying",
"struct",
".",
"If",
"the",
"model",
"is",
"a",
"nil",
"pointer",
"it",
"will",
"panic",
"if",
"the",
"model",
"is",
"a",
"nil",
"pointer"
] | 4cc9cdbf65ce1b2f60b11b765d3e6b3a5e7e8952 | https://github.com/albrow/zoom/blob/4cc9cdbf65ce1b2f60b11b765d3e6b3a5e7e8952/model.go#L338-L344 |
17,673 | albrow/zoom | model.go | key | func (mr *modelRef) key() string {
return mr.spec.name + ":" + mr.model.ModelID()
} | go | func (mr *modelRef) key() string {
return mr.spec.name + ":" + mr.model.ModelID()
} | [
"func",
"(",
"mr",
"*",
"modelRef",
")",
"key",
"(",
")",
"string",
"{",
"return",
"mr",
".",
"spec",
".",
"name",
"+",
"\"",
"\"",
"+",
"mr",
".",
"model",
".",
"ModelID",
"(",
")",
"\n",
"}"
] | // key returns a key which is used in redis to store the model | [
"key",
"returns",
"a",
"key",
"which",
"is",
"used",
"in",
"redis",
"to",
"store",
"the",
"model"
] | 4cc9cdbf65ce1b2f60b11b765d3e6b3a5e7e8952 | https://github.com/albrow/zoom/blob/4cc9cdbf65ce1b2f60b11b765d3e6b3a5e7e8952/model.go#L354-L356 |
17,674 | albrow/zoom | model.go | mainHashArgs | func (mr *modelRef) mainHashArgs() (redis.Args, error) {
return mr.mainHashArgsForFields(mr.spec.fieldNames())
} | go | func (mr *modelRef) mainHashArgs() (redis.Args, error) {
return mr.mainHashArgsForFields(mr.spec.fieldNames())
} | [
"func",
"(",
"mr",
"*",
"modelRef",
")",
"mainHashArgs",
"(",
")",
"(",
"redis",
".",
"Args",
",",
"error",
")",
"{",
"return",
"mr",
".",
"mainHashArgsForFields",
"(",
"mr",
".",
"spec",
".",
"fieldNames",
"(",
")",
")",
"\n",
"}"
] | // mainHashArgs returns the args for the main hash for this model. Typically
// these args should part of an HMSET command. | [
"mainHashArgs",
"returns",
"the",
"args",
"for",
"the",
"main",
"hash",
"for",
"this",
"model",
".",
"Typically",
"these",
"args",
"should",
"part",
"of",
"an",
"HMSET",
"command",
"."
] | 4cc9cdbf65ce1b2f60b11b765d3e6b3a5e7e8952 | https://github.com/albrow/zoom/blob/4cc9cdbf65ce1b2f60b11b765d3e6b3a5e7e8952/model.go#L360-L362 |
17,675 | albrow/zoom | model.go | mainHashArgsForFields | func (mr *modelRef) mainHashArgsForFields(fieldNames []string) (redis.Args, error) {
args := redis.Args{mr.key()}
ms := mr.spec
for _, fs := range ms.fields {
// Skip fields whose names do not appear in fieldNames.
if !stringSliceContains(fieldNames, fs.name) {
continue
}
fieldVal := mr.fieldValue(fs.name)
switch fs.kind {
case primativeField:
// Add a special case for time.Duration. By default, the redigo driver
// will fall back to fmt.Sprintf, but we want to save it as an int64 in
// this case.
if fs.typ == reflect.TypeOf(time.Duration(0)) {
args = args.Add(fs.redisName, int64(fieldVal.Interface().(time.Duration)))
} else {
args = args.Add(fs.redisName, fieldVal.Interface())
}
case pointerField:
if !fieldVal.IsNil() {
args = args.Add(fs.redisName, fieldVal.Elem().Interface())
} else {
args = args.Add(fs.redisName, "NULL")
}
case inconvertibleField:
switch fieldVal.Type().Kind() {
// For nilable types that are nil store NULL
case reflect.Ptr, reflect.Slice, reflect.Map, reflect.Interface:
if fieldVal.IsNil() {
args = args.Add(fs.redisName, "NULL")
continue
}
}
// For inconvertibles, that are not nil, convert the value to bytes
// using the gob package.
valBytes, err := mr.spec.fallback.Marshal(fieldVal.Interface())
if err != nil {
return nil, err
}
args = args.Add(fs.redisName, valBytes)
}
}
return args, nil
} | go | func (mr *modelRef) mainHashArgsForFields(fieldNames []string) (redis.Args, error) {
args := redis.Args{mr.key()}
ms := mr.spec
for _, fs := range ms.fields {
// Skip fields whose names do not appear in fieldNames.
if !stringSliceContains(fieldNames, fs.name) {
continue
}
fieldVal := mr.fieldValue(fs.name)
switch fs.kind {
case primativeField:
// Add a special case for time.Duration. By default, the redigo driver
// will fall back to fmt.Sprintf, but we want to save it as an int64 in
// this case.
if fs.typ == reflect.TypeOf(time.Duration(0)) {
args = args.Add(fs.redisName, int64(fieldVal.Interface().(time.Duration)))
} else {
args = args.Add(fs.redisName, fieldVal.Interface())
}
case pointerField:
if !fieldVal.IsNil() {
args = args.Add(fs.redisName, fieldVal.Elem().Interface())
} else {
args = args.Add(fs.redisName, "NULL")
}
case inconvertibleField:
switch fieldVal.Type().Kind() {
// For nilable types that are nil store NULL
case reflect.Ptr, reflect.Slice, reflect.Map, reflect.Interface:
if fieldVal.IsNil() {
args = args.Add(fs.redisName, "NULL")
continue
}
}
// For inconvertibles, that are not nil, convert the value to bytes
// using the gob package.
valBytes, err := mr.spec.fallback.Marshal(fieldVal.Interface())
if err != nil {
return nil, err
}
args = args.Add(fs.redisName, valBytes)
}
}
return args, nil
} | [
"func",
"(",
"mr",
"*",
"modelRef",
")",
"mainHashArgsForFields",
"(",
"fieldNames",
"[",
"]",
"string",
")",
"(",
"redis",
".",
"Args",
",",
"error",
")",
"{",
"args",
":=",
"redis",
".",
"Args",
"{",
"mr",
".",
"key",
"(",
")",
"}",
"\n",
"ms",
... | // mainHashArgsForFields is like mainHashArgs but only returns the hash
// fields which match the given fieldNames. | [
"mainHashArgsForFields",
"is",
"like",
"mainHashArgs",
"but",
"only",
"returns",
"the",
"hash",
"fields",
"which",
"match",
"the",
"given",
"fieldNames",
"."
] | 4cc9cdbf65ce1b2f60b11b765d3e6b3a5e7e8952 | https://github.com/albrow/zoom/blob/4cc9cdbf65ce1b2f60b11b765d3e6b3a5e7e8952/model.go#L366-L410 |
17,676 | albrow/zoom | collection.go | WithFallbackMarshalerUnmarshaler | func (options CollectionOptions) WithFallbackMarshalerUnmarshaler(fallback MarshalerUnmarshaler) CollectionOptions {
options.FallbackMarshalerUnmarshaler = fallback
return options
} | go | func (options CollectionOptions) WithFallbackMarshalerUnmarshaler(fallback MarshalerUnmarshaler) CollectionOptions {
options.FallbackMarshalerUnmarshaler = fallback
return options
} | [
"func",
"(",
"options",
"CollectionOptions",
")",
"WithFallbackMarshalerUnmarshaler",
"(",
"fallback",
"MarshalerUnmarshaler",
")",
"CollectionOptions",
"{",
"options",
".",
"FallbackMarshalerUnmarshaler",
"=",
"fallback",
"\n",
"return",
"options",
"\n",
"}"
] | // WithFallbackMarshalerUnmarshaler returns a new copy of the options with the
// FallbackMarshalerUnmarshaler property set to the given value. It does not
// mutate the original options. | [
"WithFallbackMarshalerUnmarshaler",
"returns",
"a",
"new",
"copy",
"of",
"the",
"options",
"with",
"the",
"FallbackMarshalerUnmarshaler",
"property",
"set",
"to",
"the",
"given",
"value",
".",
"It",
"does",
"not",
"mutate",
"the",
"original",
"options",
"."
] | 4cc9cdbf65ce1b2f60b11b765d3e6b3a5e7e8952 | https://github.com/albrow/zoom/blob/4cc9cdbf65ce1b2f60b11b765d3e6b3a5e7e8952/collection.go#L66-L69 |
17,677 | albrow/zoom | collection.go | WithIndex | func (options CollectionOptions) WithIndex(index bool) CollectionOptions {
options.Index = index
return options
} | go | func (options CollectionOptions) WithIndex(index bool) CollectionOptions {
options.Index = index
return options
} | [
"func",
"(",
"options",
"CollectionOptions",
")",
"WithIndex",
"(",
"index",
"bool",
")",
"CollectionOptions",
"{",
"options",
".",
"Index",
"=",
"index",
"\n",
"return",
"options",
"\n",
"}"
] | // WithIndex returns a new copy of the options with the Index property set to
// the given value. It does not mutate the original options. | [
"WithIndex",
"returns",
"a",
"new",
"copy",
"of",
"the",
"options",
"with",
"the",
"Index",
"property",
"set",
"to",
"the",
"given",
"value",
".",
"It",
"does",
"not",
"mutate",
"the",
"original",
"options",
"."
] | 4cc9cdbf65ce1b2f60b11b765d3e6b3a5e7e8952 | https://github.com/albrow/zoom/blob/4cc9cdbf65ce1b2f60b11b765d3e6b3a5e7e8952/collection.go#L73-L76 |
17,678 | albrow/zoom | collection.go | WithName | func (options CollectionOptions) WithName(name string) CollectionOptions {
options.Name = name
return options
} | go | func (options CollectionOptions) WithName(name string) CollectionOptions {
options.Name = name
return options
} | [
"func",
"(",
"options",
"CollectionOptions",
")",
"WithName",
"(",
"name",
"string",
")",
"CollectionOptions",
"{",
"options",
".",
"Name",
"=",
"name",
"\n",
"return",
"options",
"\n",
"}"
] | // WithName returns a new copy of the options with the Name property set to the
// given value. It does not mutate the original options. | [
"WithName",
"returns",
"a",
"new",
"copy",
"of",
"the",
"options",
"with",
"the",
"Name",
"property",
"set",
"to",
"the",
"given",
"value",
".",
"It",
"does",
"not",
"mutate",
"the",
"original",
"options",
"."
] | 4cc9cdbf65ce1b2f60b11b765d3e6b3a5e7e8952 | https://github.com/albrow/zoom/blob/4cc9cdbf65ce1b2f60b11b765d3e6b3a5e7e8952/collection.go#L80-L83 |
17,679 | albrow/zoom | collection.go | NewCollection | func (p *Pool) NewCollection(model Model) (*Collection, error) {
return p.NewCollectionWithOptions(model, DefaultCollectionOptions)
} | go | func (p *Pool) NewCollection(model Model) (*Collection, error) {
return p.NewCollectionWithOptions(model, DefaultCollectionOptions)
} | [
"func",
"(",
"p",
"*",
"Pool",
")",
"NewCollection",
"(",
"model",
"Model",
")",
"(",
"*",
"Collection",
",",
"error",
")",
"{",
"return",
"p",
".",
"NewCollectionWithOptions",
"(",
"model",
",",
"DefaultCollectionOptions",
")",
"\n",
"}"
] | // NewCollection registers and returns a new collection of the given model type.
// You must create a collection for each model type you want to save. The type
// of model must be unique, i.e., not already registered, and must be a pointer
// to a struct. NewCollection will use all the default options for the
// collection, which are specified in DefaultCollectionOptions. If you want to
// specify different options, use the NewCollectionWithOptions method. | [
"NewCollection",
"registers",
"and",
"returns",
"a",
"new",
"collection",
"of",
"the",
"given",
"model",
"type",
".",
"You",
"must",
"create",
"a",
"collection",
"for",
"each",
"model",
"type",
"you",
"want",
"to",
"save",
".",
"The",
"type",
"of",
"model"... | 4cc9cdbf65ce1b2f60b11b765d3e6b3a5e7e8952 | https://github.com/albrow/zoom/blob/4cc9cdbf65ce1b2f60b11b765d3e6b3a5e7e8952/collection.go#L91-L93 |
17,680 | albrow/zoom | collection.go | NewCollectionWithOptions | func (p *Pool) NewCollectionWithOptions(model Model, options CollectionOptions) (*Collection, error) {
typ := reflect.TypeOf(model)
// If options.Name is empty use the name of the concrete model type (without
// the package prefix).
if options.Name == "" {
options.Name = getDefaultModelSpecName(typ)
} else if strings.Contains(options.Name, ":") {
return nil, fmt.Errorf("zoom: CollectionOptions.Name cannot contain a colon. Got: %s", options.Name)
}
// Make sure the name and type have not been previously registered
switch {
case p.typeIsRegistered(typ):
return nil, fmt.Errorf("zoom: Error in NewCollection: The type %T has already been registered", model)
case p.nameIsRegistered(options.Name):
return nil, fmt.Errorf("zoom: Error in NewCollection: The name %s has already been registered", options.Name)
case !typeIsPointerToStruct(typ):
return nil, fmt.Errorf("zoom: NewCollection requires a pointer to a struct as an argument. Got type %T", model)
}
// Compile the spec for this model and store it in the maps
spec, err := compileModelSpec(typ)
if err != nil {
return nil, err
}
spec.name = options.Name
spec.fallback = options.FallbackMarshalerUnmarshaler
p.modelTypeToSpec[typ] = spec
p.modelNameToSpec[options.Name] = spec
collection := &Collection{
spec: spec,
pool: p,
index: options.Index,
}
addCollection(collection)
return collection, nil
} | go | func (p *Pool) NewCollectionWithOptions(model Model, options CollectionOptions) (*Collection, error) {
typ := reflect.TypeOf(model)
// If options.Name is empty use the name of the concrete model type (without
// the package prefix).
if options.Name == "" {
options.Name = getDefaultModelSpecName(typ)
} else if strings.Contains(options.Name, ":") {
return nil, fmt.Errorf("zoom: CollectionOptions.Name cannot contain a colon. Got: %s", options.Name)
}
// Make sure the name and type have not been previously registered
switch {
case p.typeIsRegistered(typ):
return nil, fmt.Errorf("zoom: Error in NewCollection: The type %T has already been registered", model)
case p.nameIsRegistered(options.Name):
return nil, fmt.Errorf("zoom: Error in NewCollection: The name %s has already been registered", options.Name)
case !typeIsPointerToStruct(typ):
return nil, fmt.Errorf("zoom: NewCollection requires a pointer to a struct as an argument. Got type %T", model)
}
// Compile the spec for this model and store it in the maps
spec, err := compileModelSpec(typ)
if err != nil {
return nil, err
}
spec.name = options.Name
spec.fallback = options.FallbackMarshalerUnmarshaler
p.modelTypeToSpec[typ] = spec
p.modelNameToSpec[options.Name] = spec
collection := &Collection{
spec: spec,
pool: p,
index: options.Index,
}
addCollection(collection)
return collection, nil
} | [
"func",
"(",
"p",
"*",
"Pool",
")",
"NewCollectionWithOptions",
"(",
"model",
"Model",
",",
"options",
"CollectionOptions",
")",
"(",
"*",
"Collection",
",",
"error",
")",
"{",
"typ",
":=",
"reflect",
".",
"TypeOf",
"(",
"model",
")",
"\n",
"// If options.... | // NewCollectionWithOptions registers and returns a new collection of the given
// model type and with the provided options. | [
"NewCollectionWithOptions",
"registers",
"and",
"returns",
"a",
"new",
"collection",
"of",
"the",
"given",
"model",
"type",
"and",
"with",
"the",
"provided",
"options",
"."
] | 4cc9cdbf65ce1b2f60b11b765d3e6b3a5e7e8952 | https://github.com/albrow/zoom/blob/4cc9cdbf65ce1b2f60b11b765d3e6b3a5e7e8952/collection.go#L97-L134 |
17,681 | albrow/zoom | collection.go | addCollection | func addCollection(collection *Collection) {
for e := collections.Front(); e != nil; e = e.Next() {
otherCollection := e.Value.(*Collection)
if collection.spec.typ == otherCollection.spec.typ {
// The Collection was already added to the list. No need to do
// anything.
return
}
}
collections.PushFront(collection)
} | go | func addCollection(collection *Collection) {
for e := collections.Front(); e != nil; e = e.Next() {
otherCollection := e.Value.(*Collection)
if collection.spec.typ == otherCollection.spec.typ {
// The Collection was already added to the list. No need to do
// anything.
return
}
}
collections.PushFront(collection)
} | [
"func",
"addCollection",
"(",
"collection",
"*",
"Collection",
")",
"{",
"for",
"e",
":=",
"collections",
".",
"Front",
"(",
")",
";",
"e",
"!=",
"nil",
";",
"e",
"=",
"e",
".",
"Next",
"(",
")",
"{",
"otherCollection",
":=",
"e",
".",
"Value",
"."... | // addCollection adds the given spec to the list of collections iff it has not
// already been added. | [
"addCollection",
"adds",
"the",
"given",
"spec",
"to",
"the",
"list",
"of",
"collections",
"iff",
"it",
"has",
"not",
"already",
"been",
"added",
"."
] | 4cc9cdbf65ce1b2f60b11b765d3e6b3a5e7e8952 | https://github.com/albrow/zoom/blob/4cc9cdbf65ce1b2f60b11b765d3e6b3a5e7e8952/collection.go#L145-L155 |
17,682 | albrow/zoom | collection.go | getCollectionForModel | func getCollectionForModel(model Model) (*Collection, error) {
typ := reflect.TypeOf(model)
for e := collections.Front(); e != nil; e = e.Next() {
col := e.Value.(*Collection)
if col.spec.typ == typ {
return col, nil
}
}
return nil, fmt.Errorf("Could not find Collection for type %T", model)
} | go | func getCollectionForModel(model Model) (*Collection, error) {
typ := reflect.TypeOf(model)
for e := collections.Front(); e != nil; e = e.Next() {
col := e.Value.(*Collection)
if col.spec.typ == typ {
return col, nil
}
}
return nil, fmt.Errorf("Could not find Collection for type %T", model)
} | [
"func",
"getCollectionForModel",
"(",
"model",
"Model",
")",
"(",
"*",
"Collection",
",",
"error",
")",
"{",
"typ",
":=",
"reflect",
".",
"TypeOf",
"(",
"model",
")",
"\n",
"for",
"e",
":=",
"collections",
".",
"Front",
"(",
")",
";",
"e",
"!=",
"nil... | // getCollectionForModel returns the Collection corresponding to the type of
// model. | [
"getCollectionForModel",
"returns",
"the",
"Collection",
"corresponding",
"to",
"the",
"type",
"of",
"model",
"."
] | 4cc9cdbf65ce1b2f60b11b765d3e6b3a5e7e8952 | https://github.com/albrow/zoom/blob/4cc9cdbf65ce1b2f60b11b765d3e6b3a5e7e8952/collection.go#L159-L168 |
17,683 | albrow/zoom | collection.go | ModelKey | func (c *Collection) ModelKey(id string) string {
if id == "" {
return ""
}
// c.spec.modelKey(id) will only return an error if id was an empty string.
// Since we already ruled that out with the check above, we can safely ignore
// the error return value here.
key, _ := c.spec.modelKey(id)
return key
} | go | func (c *Collection) ModelKey(id string) string {
if id == "" {
return ""
}
// c.spec.modelKey(id) will only return an error if id was an empty string.
// Since we already ruled that out with the check above, we can safely ignore
// the error return value here.
key, _ := c.spec.modelKey(id)
return key
} | [
"func",
"(",
"c",
"*",
"Collection",
")",
"ModelKey",
"(",
"id",
"string",
")",
"string",
"{",
"if",
"id",
"==",
"\"",
"\"",
"{",
"return",
"\"",
"\"",
"\n",
"}",
"\n",
"// c.spec.modelKey(id) will only return an error if id was an empty string.",
"// Since we alr... | // ModelKey returns the key that identifies a hash in the database
// which contains all the fields of the model corresponding to the given
// id. If id is an empty string, it will return an empty string. | [
"ModelKey",
"returns",
"the",
"key",
"that",
"identifies",
"a",
"hash",
"in",
"the",
"database",
"which",
"contains",
"all",
"the",
"fields",
"of",
"the",
"model",
"corresponding",
"to",
"the",
"given",
"id",
".",
"If",
"id",
"is",
"an",
"empty",
"string",... | 4cc9cdbf65ce1b2f60b11b765d3e6b3a5e7e8952 | https://github.com/albrow/zoom/blob/4cc9cdbf65ce1b2f60b11b765d3e6b3a5e7e8952/collection.go#L183-L192 |
17,684 | albrow/zoom | collection.go | FieldIndexKey | func (c *Collection) FieldIndexKey(fieldName string) (string, error) {
return c.spec.fieldIndexKey(fieldName)
} | go | func (c *Collection) FieldIndexKey(fieldName string) (string, error) {
return c.spec.fieldIndexKey(fieldName)
} | [
"func",
"(",
"c",
"*",
"Collection",
")",
"FieldIndexKey",
"(",
"fieldName",
"string",
")",
"(",
"string",
",",
"error",
")",
"{",
"return",
"c",
".",
"spec",
".",
"fieldIndexKey",
"(",
"fieldName",
")",
"\n",
"}"
] | // FieldIndexKey returns the key for the sorted set used to index the field
// identified by fieldName. It returns an error if fieldName does not identify a
// field in the spec or if the field it identifies is not an indexed field. | [
"FieldIndexKey",
"returns",
"the",
"key",
"for",
"the",
"sorted",
"set",
"used",
"to",
"index",
"the",
"field",
"identified",
"by",
"fieldName",
".",
"It",
"returns",
"an",
"error",
"if",
"fieldName",
"does",
"not",
"identify",
"a",
"field",
"in",
"the",
"... | 4cc9cdbf65ce1b2f60b11b765d3e6b3a5e7e8952 | https://github.com/albrow/zoom/blob/4cc9cdbf65ce1b2f60b11b765d3e6b3a5e7e8952/collection.go#L203-L205 |
17,685 | albrow/zoom | collection.go | saveFieldIndexes | func (t *Transaction) saveFieldIndexes(mr *modelRef) {
t.saveFieldIndexesForFields(mr.spec.fieldNames(), mr)
} | go | func (t *Transaction) saveFieldIndexes(mr *modelRef) {
t.saveFieldIndexesForFields(mr.spec.fieldNames(), mr)
} | [
"func",
"(",
"t",
"*",
"Transaction",
")",
"saveFieldIndexes",
"(",
"mr",
"*",
"modelRef",
")",
"{",
"t",
".",
"saveFieldIndexesForFields",
"(",
"mr",
".",
"spec",
".",
"fieldNames",
"(",
")",
",",
"mr",
")",
"\n",
"}"
] | // saveFieldIndexes adds commands to the transaction for saving the indexes
// for all indexed fields. | [
"saveFieldIndexes",
"adds",
"commands",
"to",
"the",
"transaction",
"for",
"saving",
"the",
"indexes",
"for",
"all",
"indexed",
"fields",
"."
] | 4cc9cdbf65ce1b2f60b11b765d3e6b3a5e7e8952 | https://github.com/albrow/zoom/blob/4cc9cdbf65ce1b2f60b11b765d3e6b3a5e7e8952/collection.go#L296-L298 |
17,686 | albrow/zoom | collection.go | saveFieldIndexesForFields | func (t *Transaction) saveFieldIndexesForFields(fieldNames []string, mr *modelRef) {
for _, fs := range mr.spec.fields {
// Skip fields whose names do not appear in fieldNames.
if !stringSliceContains(fieldNames, fs.name) {
continue
}
switch fs.indexKind {
case noIndex:
continue
case numericIndex:
t.saveNumericIndex(mr, fs)
case booleanIndex:
t.saveBooleanIndex(mr, fs)
case stringIndex:
t.saveStringIndex(mr, fs)
}
}
} | go | func (t *Transaction) saveFieldIndexesForFields(fieldNames []string, mr *modelRef) {
for _, fs := range mr.spec.fields {
// Skip fields whose names do not appear in fieldNames.
if !stringSliceContains(fieldNames, fs.name) {
continue
}
switch fs.indexKind {
case noIndex:
continue
case numericIndex:
t.saveNumericIndex(mr, fs)
case booleanIndex:
t.saveBooleanIndex(mr, fs)
case stringIndex:
t.saveStringIndex(mr, fs)
}
}
} | [
"func",
"(",
"t",
"*",
"Transaction",
")",
"saveFieldIndexesForFields",
"(",
"fieldNames",
"[",
"]",
"string",
",",
"mr",
"*",
"modelRef",
")",
"{",
"for",
"_",
",",
"fs",
":=",
"range",
"mr",
".",
"spec",
".",
"fields",
"{",
"// Skip fields whose names do... | // saveFieldIndexesForFields works like saveFieldIndexes, but only saves the
// indexes for the given fieldNames. | [
"saveFieldIndexesForFields",
"works",
"like",
"saveFieldIndexes",
"but",
"only",
"saves",
"the",
"indexes",
"for",
"the",
"given",
"fieldNames",
"."
] | 4cc9cdbf65ce1b2f60b11b765d3e6b3a5e7e8952 | https://github.com/albrow/zoom/blob/4cc9cdbf65ce1b2f60b11b765d3e6b3a5e7e8952/collection.go#L302-L319 |
17,687 | albrow/zoom | collection.go | saveNumericIndex | func (t *Transaction) saveNumericIndex(mr *modelRef, fs *fieldSpec) {
fieldValue := mr.fieldValue(fs.name)
if fieldValue.Kind() == reflect.Ptr && fieldValue.IsNil() {
return
}
score := numericScore(fieldValue)
indexKey, err := mr.spec.fieldIndexKey(fs.name)
if err != nil {
t.setError(err)
}
t.Command("ZADD", redis.Args{indexKey, score, mr.model.ModelID()}, nil)
} | go | func (t *Transaction) saveNumericIndex(mr *modelRef, fs *fieldSpec) {
fieldValue := mr.fieldValue(fs.name)
if fieldValue.Kind() == reflect.Ptr && fieldValue.IsNil() {
return
}
score := numericScore(fieldValue)
indexKey, err := mr.spec.fieldIndexKey(fs.name)
if err != nil {
t.setError(err)
}
t.Command("ZADD", redis.Args{indexKey, score, mr.model.ModelID()}, nil)
} | [
"func",
"(",
"t",
"*",
"Transaction",
")",
"saveNumericIndex",
"(",
"mr",
"*",
"modelRef",
",",
"fs",
"*",
"fieldSpec",
")",
"{",
"fieldValue",
":=",
"mr",
".",
"fieldValue",
"(",
"fs",
".",
"name",
")",
"\n",
"if",
"fieldValue",
".",
"Kind",
"(",
")... | // saveNumericIndex adds commands to the transaction for saving a numeric
// index on the given field. | [
"saveNumericIndex",
"adds",
"commands",
"to",
"the",
"transaction",
"for",
"saving",
"a",
"numeric",
"index",
"on",
"the",
"given",
"field",
"."
] | 4cc9cdbf65ce1b2f60b11b765d3e6b3a5e7e8952 | https://github.com/albrow/zoom/blob/4cc9cdbf65ce1b2f60b11b765d3e6b3a5e7e8952/collection.go#L323-L334 |
17,688 | albrow/zoom | collection.go | SaveFields | func (c *Collection) SaveFields(fieldNames []string, model Model) error {
t := c.pool.NewTransaction()
t.SaveFields(c, fieldNames, model)
if err := t.Exec(); err != nil {
return err
}
return nil
} | go | func (c *Collection) SaveFields(fieldNames []string, model Model) error {
t := c.pool.NewTransaction()
t.SaveFields(c, fieldNames, model)
if err := t.Exec(); err != nil {
return err
}
return nil
} | [
"func",
"(",
"c",
"*",
"Collection",
")",
"SaveFields",
"(",
"fieldNames",
"[",
"]",
"string",
",",
"model",
"Model",
")",
"error",
"{",
"t",
":=",
"c",
".",
"pool",
".",
"NewTransaction",
"(",
")",
"\n",
"t",
".",
"SaveFields",
"(",
"c",
",",
"fie... | // SaveFields saves only the given fields of the model. SaveFields uses
// "last write wins" semantics. If another caller updates the the same fields
// concurrently, your updates may be overwritten. It will return an error if
// the type of model does not match the registered Collection, or if any of
// the given fieldNames are not found in the registered Collection. If
// SaveFields is called on a model that has not yet been saved, it will not
// return an error. Instead, only the given fields will be saved in the
// database. | [
"SaveFields",
"saves",
"only",
"the",
"given",
"fields",
"of",
"the",
"model",
".",
"SaveFields",
"uses",
"last",
"write",
"wins",
"semantics",
".",
"If",
"another",
"caller",
"updates",
"the",
"the",
"same",
"fields",
"concurrently",
"your",
"updates",
"may",... | 4cc9cdbf65ce1b2f60b11b765d3e6b3a5e7e8952 | https://github.com/albrow/zoom/blob/4cc9cdbf65ce1b2f60b11b765d3e6b3a5e7e8952/collection.go#L379-L386 |
17,689 | albrow/zoom | collection.go | SaveFields | func (t *Transaction) SaveFields(c *Collection, fieldNames []string, model Model) {
// Check the model type
if err := c.checkModelType(model); err != nil {
t.setError(fmt.Errorf("zoom: Error in SaveFields or Transaction.SaveFields: %s", err.Error()))
return
}
// Check the given field names
for _, fieldName := range fieldNames {
if !stringSliceContains(c.spec.fieldNames(), fieldName) {
t.setError(fmt.Errorf("zoom: Error in SaveFields or Transaction.SaveFields: Collection %s does not have field named %s", c.Name(), fieldName))
return
}
}
// Create a modelRef and start a transaction
mr := &modelRef{
collection: c,
model: model,
spec: c.spec,
}
// Update indexes
// This must happen first, because it relies on reading the old field values
// from the hash for string indexes (if any)
t.saveFieldIndexesForFields(fieldNames, mr)
// Get the main hash args.
hashArgs, err := mr.mainHashArgsForFields(fieldNames)
if err != nil {
t.setError(err)
}
//
if len(hashArgs) > 1 {
// Only save the main hash if there are any fields
// The first element in hashArgs is the model key,
// so there are fields if the length is greater than
// 1.
t.Command("HMSET", hashArgs, nil)
}
// Add the model id to the set of all models for this collection
if c.index {
t.Command("SADD", redis.Args{c.IndexKey(), model.ModelID()}, nil)
}
} | go | func (t *Transaction) SaveFields(c *Collection, fieldNames []string, model Model) {
// Check the model type
if err := c.checkModelType(model); err != nil {
t.setError(fmt.Errorf("zoom: Error in SaveFields or Transaction.SaveFields: %s", err.Error()))
return
}
// Check the given field names
for _, fieldName := range fieldNames {
if !stringSliceContains(c.spec.fieldNames(), fieldName) {
t.setError(fmt.Errorf("zoom: Error in SaveFields or Transaction.SaveFields: Collection %s does not have field named %s", c.Name(), fieldName))
return
}
}
// Create a modelRef and start a transaction
mr := &modelRef{
collection: c,
model: model,
spec: c.spec,
}
// Update indexes
// This must happen first, because it relies on reading the old field values
// from the hash for string indexes (if any)
t.saveFieldIndexesForFields(fieldNames, mr)
// Get the main hash args.
hashArgs, err := mr.mainHashArgsForFields(fieldNames)
if err != nil {
t.setError(err)
}
//
if len(hashArgs) > 1 {
// Only save the main hash if there are any fields
// The first element in hashArgs is the model key,
// so there are fields if the length is greater than
// 1.
t.Command("HMSET", hashArgs, nil)
}
// Add the model id to the set of all models for this collection
if c.index {
t.Command("SADD", redis.Args{c.IndexKey(), model.ModelID()}, nil)
}
} | [
"func",
"(",
"t",
"*",
"Transaction",
")",
"SaveFields",
"(",
"c",
"*",
"Collection",
",",
"fieldNames",
"[",
"]",
"string",
",",
"model",
"Model",
")",
"{",
"// Check the model type",
"if",
"err",
":=",
"c",
".",
"checkModelType",
"(",
"model",
")",
";"... | // SaveFields saves only the given fields of the model inside an existing
// transaction. SaveFields will set the err property of the transaction if the
// type of model does not match the registered Collection, or if any of the
// given fieldNames are not found in the model type. In either case, the
// transaction will return the error when you call Exec. SaveFields uses "last
// write wins" semantics. If another caller updates the the same fields
// concurrently, your updates may be overwritten. If SaveFields is called on a
// model that has not yet been saved, it will not return an error. Instead, only
// the given fields will be saved in the database. | [
"SaveFields",
"saves",
"only",
"the",
"given",
"fields",
"of",
"the",
"model",
"inside",
"an",
"existing",
"transaction",
".",
"SaveFields",
"will",
"set",
"the",
"err",
"property",
"of",
"the",
"transaction",
"if",
"the",
"type",
"of",
"model",
"does",
"not... | 4cc9cdbf65ce1b2f60b11b765d3e6b3a5e7e8952 | https://github.com/albrow/zoom/blob/4cc9cdbf65ce1b2f60b11b765d3e6b3a5e7e8952/collection.go#L397-L437 |
17,690 | albrow/zoom | collection.go | Find | func (t *Transaction) Find(c *Collection, id string, model Model) {
if c == nil {
t.setError(newNilCollectionError("Find"))
return
}
if err := c.checkModelType(model); err != nil {
t.setError(fmt.Errorf("zoom: Error in Find or Transaction.Find: %s", err.Error()))
return
}
model.SetModelID(id)
mr := &modelRef{
collection: c,
model: model,
spec: c.spec,
}
// Check if the model actually exists
t.Command("EXISTS", redis.Args{mr.key()}, newModelExistsHandler(c, id))
// Get the fields from the main hash for this model
args := redis.Args{mr.key()}
for _, fieldName := range mr.spec.fieldRedisNames() {
args = append(args, fieldName)
}
t.Command("HMGET", args, newScanModelRefHandler(mr.spec.fieldNames(), mr))
} | go | func (t *Transaction) Find(c *Collection, id string, model Model) {
if c == nil {
t.setError(newNilCollectionError("Find"))
return
}
if err := c.checkModelType(model); err != nil {
t.setError(fmt.Errorf("zoom: Error in Find or Transaction.Find: %s", err.Error()))
return
}
model.SetModelID(id)
mr := &modelRef{
collection: c,
model: model,
spec: c.spec,
}
// Check if the model actually exists
t.Command("EXISTS", redis.Args{mr.key()}, newModelExistsHandler(c, id))
// Get the fields from the main hash for this model
args := redis.Args{mr.key()}
for _, fieldName := range mr.spec.fieldRedisNames() {
args = append(args, fieldName)
}
t.Command("HMGET", args, newScanModelRefHandler(mr.spec.fieldNames(), mr))
} | [
"func",
"(",
"t",
"*",
"Transaction",
")",
"Find",
"(",
"c",
"*",
"Collection",
",",
"id",
"string",
",",
"model",
"Model",
")",
"{",
"if",
"c",
"==",
"nil",
"{",
"t",
".",
"setError",
"(",
"newNilCollectionError",
"(",
"\"",
"\"",
")",
")",
"\n",
... | // Find retrieves a model with the given id from redis and scans its values
// into model in an existing transaction. model should be a pointer to a struct
// of a registered type corresponding to the Collection. find will mutate the struct,
// filling in its fields and overwriting any previous values. Any errors encountered
// will be added to the transaction and returned as an error when the transaction is
// executed. | [
"Find",
"retrieves",
"a",
"model",
"with",
"the",
"given",
"id",
"from",
"redis",
"and",
"scans",
"its",
"values",
"into",
"model",
"in",
"an",
"existing",
"transaction",
".",
"model",
"should",
"be",
"a",
"pointer",
"to",
"a",
"struct",
"of",
"a",
"regi... | 4cc9cdbf65ce1b2f60b11b765d3e6b3a5e7e8952 | https://github.com/albrow/zoom/blob/4cc9cdbf65ce1b2f60b11b765d3e6b3a5e7e8952/collection.go#L460-L483 |
17,691 | albrow/zoom | collection.go | FindFields | func (t *Transaction) FindFields(c *Collection, id string, fieldNames []string, model Model) {
if err := c.checkModelType(model); err != nil {
t.setError(fmt.Errorf("zoom: Error in FindFields or Transaction.FindFields: %s", err.Error()))
return
}
// Set the model id and create a modelRef
model.SetModelID(id)
mr := &modelRef{
collection: c,
spec: c.spec,
model: model,
}
// Check the given field names and append the corresponding redis field names
// to args.
args := redis.Args{mr.key()}
for _, fieldName := range fieldNames {
if !stringSliceContains(c.spec.fieldNames(), fieldName) {
t.setError(fmt.Errorf("zoom: Error in FindFields or Transaction.FindFields: Collection %s does not have field named %s", c.Name(), fieldName))
return
}
// args is an array of arguments passed to the HMGET command. We want to
// use the redis names corresponding to each field name. The redis names
// may be customized via struct tags.
args = append(args, c.spec.fieldsByName[fieldName].redisName)
}
// Check if the model actually exists.
t.Command("EXISTS", redis.Args{mr.key()}, newModelExistsHandler(c, id))
// Get the fields from the main hash for this model
t.Command("HMGET", args, newScanModelRefHandler(fieldNames, mr))
} | go | func (t *Transaction) FindFields(c *Collection, id string, fieldNames []string, model Model) {
if err := c.checkModelType(model); err != nil {
t.setError(fmt.Errorf("zoom: Error in FindFields or Transaction.FindFields: %s", err.Error()))
return
}
// Set the model id and create a modelRef
model.SetModelID(id)
mr := &modelRef{
collection: c,
spec: c.spec,
model: model,
}
// Check the given field names and append the corresponding redis field names
// to args.
args := redis.Args{mr.key()}
for _, fieldName := range fieldNames {
if !stringSliceContains(c.spec.fieldNames(), fieldName) {
t.setError(fmt.Errorf("zoom: Error in FindFields or Transaction.FindFields: Collection %s does not have field named %s", c.Name(), fieldName))
return
}
// args is an array of arguments passed to the HMGET command. We want to
// use the redis names corresponding to each field name. The redis names
// may be customized via struct tags.
args = append(args, c.spec.fieldsByName[fieldName].redisName)
}
// Check if the model actually exists.
t.Command("EXISTS", redis.Args{mr.key()}, newModelExistsHandler(c, id))
// Get the fields from the main hash for this model
t.Command("HMGET", args, newScanModelRefHandler(fieldNames, mr))
} | [
"func",
"(",
"t",
"*",
"Transaction",
")",
"FindFields",
"(",
"c",
"*",
"Collection",
",",
"id",
"string",
",",
"fieldNames",
"[",
"]",
"string",
",",
"model",
"Model",
")",
"{",
"if",
"err",
":=",
"c",
".",
"checkModelType",
"(",
"model",
")",
";",
... | // FindFields is like Find but finds and sets only the specified fields. Any
// fields of the model which are not in the given fieldNames are not mutated.
// FindFields will return an error if any of the given fieldNames are not found
// in the model type. | [
"FindFields",
"is",
"like",
"Find",
"but",
"finds",
"and",
"sets",
"only",
"the",
"specified",
"fields",
".",
"Any",
"fields",
"of",
"the",
"model",
"which",
"are",
"not",
"in",
"the",
"given",
"fieldNames",
"are",
"not",
"mutated",
".",
"FindFields",
"wil... | 4cc9cdbf65ce1b2f60b11b765d3e6b3a5e7e8952 | https://github.com/albrow/zoom/blob/4cc9cdbf65ce1b2f60b11b765d3e6b3a5e7e8952/collection.go#L502-L531 |
17,692 | albrow/zoom | collection.go | Exists | func (c *Collection) Exists(id string) (bool, error) {
t := c.pool.NewTransaction()
exists := false
t.Exists(c, id, &exists)
if err := t.Exec(); err != nil {
return false, err
}
return exists, nil
} | go | func (c *Collection) Exists(id string) (bool, error) {
t := c.pool.NewTransaction()
exists := false
t.Exists(c, id, &exists)
if err := t.Exec(); err != nil {
return false, err
}
return exists, nil
} | [
"func",
"(",
"c",
"*",
"Collection",
")",
"Exists",
"(",
"id",
"string",
")",
"(",
"bool",
",",
"error",
")",
"{",
"t",
":=",
"c",
".",
"pool",
".",
"NewTransaction",
"(",
")",
"\n",
"exists",
":=",
"false",
"\n",
"t",
".",
"Exists",
"(",
"c",
... | // Exists returns true if the collection has a model with the given id. It
// returns an error if there was a problem connecting to the database. | [
"Exists",
"returns",
"true",
"if",
"the",
"collection",
"has",
"a",
"model",
"with",
"the",
"given",
"id",
".",
"It",
"returns",
"an",
"error",
"if",
"there",
"was",
"a",
"problem",
"connecting",
"to",
"the",
"database",
"."
] | 4cc9cdbf65ce1b2f60b11b765d3e6b3a5e7e8952 | https://github.com/albrow/zoom/blob/4cc9cdbf65ce1b2f60b11b765d3e6b3a5e7e8952/collection.go#L580-L588 |
17,693 | albrow/zoom | collection.go | Count | func (t *Transaction) Count(c *Collection, count *int) {
if c == nil {
t.setError(newNilCollectionError("Count"))
return
}
if !c.index {
t.setError(newUnindexedCollectionError("Count"))
return
}
t.Command("SCARD", redis.Args{c.IndexKey()}, NewScanIntHandler(count))
} | go | func (t *Transaction) Count(c *Collection, count *int) {
if c == nil {
t.setError(newNilCollectionError("Count"))
return
}
if !c.index {
t.setError(newUnindexedCollectionError("Count"))
return
}
t.Command("SCARD", redis.Args{c.IndexKey()}, NewScanIntHandler(count))
} | [
"func",
"(",
"t",
"*",
"Transaction",
")",
"Count",
"(",
"c",
"*",
"Collection",
",",
"count",
"*",
"int",
")",
"{",
"if",
"c",
"==",
"nil",
"{",
"t",
".",
"setError",
"(",
"newNilCollectionError",
"(",
"\"",
"\"",
")",
")",
"\n",
"return",
"\n",
... | // Count counts the number of models of the given type in the database in an existing
// transaction. It sets the value of count to the number of models. Any errors
// encountered will be added to the transaction and returned as an error when the
// transaction is executed. | [
"Count",
"counts",
"the",
"number",
"of",
"models",
"of",
"the",
"given",
"type",
"in",
"the",
"database",
"in",
"an",
"existing",
"transaction",
".",
"It",
"sets",
"the",
"value",
"of",
"count",
"to",
"the",
"number",
"of",
"models",
".",
"Any",
"errors... | 4cc9cdbf65ce1b2f60b11b765d3e6b3a5e7e8952 | https://github.com/albrow/zoom/blob/4cc9cdbf65ce1b2f60b11b765d3e6b3a5e7e8952/collection.go#L618-L628 |
17,694 | albrow/zoom | collection.go | Delete | func (c *Collection) Delete(id string) (bool, error) {
t := c.pool.NewTransaction()
deleted := false
t.Delete(c, id, &deleted)
if err := t.Exec(); err != nil {
return deleted, err
}
return deleted, nil
} | go | func (c *Collection) Delete(id string) (bool, error) {
t := c.pool.NewTransaction()
deleted := false
t.Delete(c, id, &deleted)
if err := t.Exec(); err != nil {
return deleted, err
}
return deleted, nil
} | [
"func",
"(",
"c",
"*",
"Collection",
")",
"Delete",
"(",
"id",
"string",
")",
"(",
"bool",
",",
"error",
")",
"{",
"t",
":=",
"c",
".",
"pool",
".",
"NewTransaction",
"(",
")",
"\n",
"deleted",
":=",
"false",
"\n",
"t",
".",
"Delete",
"(",
"c",
... | // Delete removes the model with the given type and id from the database. It will
// not return an error if the model corresponding to the given id was not
// found in the database. Instead, it will return a boolean representing whether
// or not the model was found and deleted, and will only return an error
// if there was a problem connecting to the database. | [
"Delete",
"removes",
"the",
"model",
"with",
"the",
"given",
"type",
"and",
"id",
"from",
"the",
"database",
".",
"It",
"will",
"not",
"return",
"an",
"error",
"if",
"the",
"model",
"corresponding",
"to",
"the",
"given",
"id",
"was",
"not",
"found",
"in"... | 4cc9cdbf65ce1b2f60b11b765d3e6b3a5e7e8952 | https://github.com/albrow/zoom/blob/4cc9cdbf65ce1b2f60b11b765d3e6b3a5e7e8952/collection.go#L635-L643 |
17,695 | albrow/zoom | collection.go | Delete | func (t *Transaction) Delete(c *Collection, id string, deleted *bool) {
if c == nil {
t.setError(newNilCollectionError("Delete"))
return
}
// Delete any field indexes
// This must happen first, because it relies on reading the old field values
// from the hash for string indexes (if any)
t.deleteFieldIndexes(c, id)
var handler ReplyHandler
if deleted == nil {
handler = nil
} else {
handler = NewScanBoolHandler(deleted)
}
// Delete the main hash
t.Command("DEL", redis.Args{c.Name() + ":" + id}, handler)
// Remvoe the id from the index of all models for the given type
t.Command("SREM", redis.Args{c.IndexKey(), id}, nil)
} | go | func (t *Transaction) Delete(c *Collection, id string, deleted *bool) {
if c == nil {
t.setError(newNilCollectionError("Delete"))
return
}
// Delete any field indexes
// This must happen first, because it relies on reading the old field values
// from the hash for string indexes (if any)
t.deleteFieldIndexes(c, id)
var handler ReplyHandler
if deleted == nil {
handler = nil
} else {
handler = NewScanBoolHandler(deleted)
}
// Delete the main hash
t.Command("DEL", redis.Args{c.Name() + ":" + id}, handler)
// Remvoe the id from the index of all models for the given type
t.Command("SREM", redis.Args{c.IndexKey(), id}, nil)
} | [
"func",
"(",
"t",
"*",
"Transaction",
")",
"Delete",
"(",
"c",
"*",
"Collection",
",",
"id",
"string",
",",
"deleted",
"*",
"bool",
")",
"{",
"if",
"c",
"==",
"nil",
"{",
"t",
".",
"setError",
"(",
"newNilCollectionError",
"(",
"\"",
"\"",
")",
")"... | // Delete removes a model with the given type and id in an existing transaction.
// deleted will be set to true iff the model was successfully deleted when the
// transaction is executed. If the no model with the given type and id existed,
// the value of deleted will be set to false. Any errors encountered will be
// added to the transaction and returned as an error when the transaction is
// executed. You may pass in nil for deleted if you do not care whether or not
// the model was deleted. | [
"Delete",
"removes",
"a",
"model",
"with",
"the",
"given",
"type",
"and",
"id",
"in",
"an",
"existing",
"transaction",
".",
"deleted",
"will",
"be",
"set",
"to",
"true",
"iff",
"the",
"model",
"was",
"successfully",
"deleted",
"when",
"the",
"transaction",
... | 4cc9cdbf65ce1b2f60b11b765d3e6b3a5e7e8952 | https://github.com/albrow/zoom/blob/4cc9cdbf65ce1b2f60b11b765d3e6b3a5e7e8952/collection.go#L652-L671 |
17,696 | albrow/zoom | collection.go | deleteFieldIndexes | func (t *Transaction) deleteFieldIndexes(c *Collection, id string) {
for _, fs := range c.spec.fields {
switch fs.indexKind {
case noIndex:
continue
case numericIndex, booleanIndex:
t.deleteNumericOrBooleanIndex(fs, c.spec, id)
case stringIndex:
// NOTE: this invokes a lua script which is defined in scripts/delete_string_index.lua
t.deleteStringIndex(c.Name(), id, fs.redisName)
}
}
} | go | func (t *Transaction) deleteFieldIndexes(c *Collection, id string) {
for _, fs := range c.spec.fields {
switch fs.indexKind {
case noIndex:
continue
case numericIndex, booleanIndex:
t.deleteNumericOrBooleanIndex(fs, c.spec, id)
case stringIndex:
// NOTE: this invokes a lua script which is defined in scripts/delete_string_index.lua
t.deleteStringIndex(c.Name(), id, fs.redisName)
}
}
} | [
"func",
"(",
"t",
"*",
"Transaction",
")",
"deleteFieldIndexes",
"(",
"c",
"*",
"Collection",
",",
"id",
"string",
")",
"{",
"for",
"_",
",",
"fs",
":=",
"range",
"c",
".",
"spec",
".",
"fields",
"{",
"switch",
"fs",
".",
"indexKind",
"{",
"case",
... | // deleteFieldIndexes adds commands to the transaction for deleting the field
// indexes for all indexed fields of the given model type. | [
"deleteFieldIndexes",
"adds",
"commands",
"to",
"the",
"transaction",
"for",
"deleting",
"the",
"field",
"indexes",
"for",
"all",
"indexed",
"fields",
"of",
"the",
"given",
"model",
"type",
"."
] | 4cc9cdbf65ce1b2f60b11b765d3e6b3a5e7e8952 | https://github.com/albrow/zoom/blob/4cc9cdbf65ce1b2f60b11b765d3e6b3a5e7e8952/collection.go#L675-L687 |
17,697 | albrow/zoom | collection.go | deleteNumericOrBooleanIndex | func (t *Transaction) deleteNumericOrBooleanIndex(fs *fieldSpec, ms *modelSpec, modelID string) {
indexKey, err := ms.fieldIndexKey(fs.name)
if err != nil {
t.setError(err)
}
t.Command("ZREM", redis.Args{indexKey, modelID}, nil)
} | go | func (t *Transaction) deleteNumericOrBooleanIndex(fs *fieldSpec, ms *modelSpec, modelID string) {
indexKey, err := ms.fieldIndexKey(fs.name)
if err != nil {
t.setError(err)
}
t.Command("ZREM", redis.Args{indexKey, modelID}, nil)
} | [
"func",
"(",
"t",
"*",
"Transaction",
")",
"deleteNumericOrBooleanIndex",
"(",
"fs",
"*",
"fieldSpec",
",",
"ms",
"*",
"modelSpec",
",",
"modelID",
"string",
")",
"{",
"indexKey",
",",
"err",
":=",
"ms",
".",
"fieldIndexKey",
"(",
"fs",
".",
"name",
")",... | // deleteNumericOrBooleanIndex removes the model from a numeric or boolean index for the given
// field. I.e. it removes the model id from a sorted set. | [
"deleteNumericOrBooleanIndex",
"removes",
"the",
"model",
"from",
"a",
"numeric",
"or",
"boolean",
"index",
"for",
"the",
"given",
"field",
".",
"I",
".",
"e",
".",
"it",
"removes",
"the",
"model",
"id",
"from",
"a",
"sorted",
"set",
"."
] | 4cc9cdbf65ce1b2f60b11b765d3e6b3a5e7e8952 | https://github.com/albrow/zoom/blob/4cc9cdbf65ce1b2f60b11b765d3e6b3a5e7e8952/collection.go#L691-L697 |
17,698 | albrow/zoom | collection.go | DeleteAll | func (t *Transaction) DeleteAll(c *Collection, count *int) {
if c == nil {
t.setError(newNilCollectionError("DeleteAll"))
return
}
if !c.index {
t.setError(newUnindexedCollectionError("DeleteAll"))
return
}
var handler ReplyHandler
if count == nil {
handler = nil
} else {
handler = NewScanIntHandler(count)
}
t.DeleteModelsBySetIDs(c.IndexKey(), c.Name(), handler)
} | go | func (t *Transaction) DeleteAll(c *Collection, count *int) {
if c == nil {
t.setError(newNilCollectionError("DeleteAll"))
return
}
if !c.index {
t.setError(newUnindexedCollectionError("DeleteAll"))
return
}
var handler ReplyHandler
if count == nil {
handler = nil
} else {
handler = NewScanIntHandler(count)
}
t.DeleteModelsBySetIDs(c.IndexKey(), c.Name(), handler)
} | [
"func",
"(",
"t",
"*",
"Transaction",
")",
"DeleteAll",
"(",
"c",
"*",
"Collection",
",",
"count",
"*",
"int",
")",
"{",
"if",
"c",
"==",
"nil",
"{",
"t",
".",
"setError",
"(",
"newNilCollectionError",
"(",
"\"",
"\"",
")",
")",
"\n",
"return",
"\n... | // DeleteAll delets all models for the given model type in an existing transaction.
// The value of count will be set to the number of models that were successfully deleted
// when the transaction is executed. Any errors encountered will be added to the transaction
// and returned as an error when the transaction is executed. You may pass in nil
// for count if you do not care about the number of models that were deleted. | [
"DeleteAll",
"delets",
"all",
"models",
"for",
"the",
"given",
"model",
"type",
"in",
"an",
"existing",
"transaction",
".",
"The",
"value",
"of",
"count",
"will",
"be",
"set",
"to",
"the",
"number",
"of",
"models",
"that",
"were",
"successfully",
"deleted",
... | 4cc9cdbf65ce1b2f60b11b765d3e6b3a5e7e8952 | https://github.com/albrow/zoom/blob/4cc9cdbf65ce1b2f60b11b765d3e6b3a5e7e8952/collection.go#L717-L733 |
17,699 | albrow/zoom | collection.go | checkModelType | func (c *Collection) checkModelType(model Model) error {
return c.spec.checkModelType(model)
} | go | func (c *Collection) checkModelType(model Model) error {
return c.spec.checkModelType(model)
} | [
"func",
"(",
"c",
"*",
"Collection",
")",
"checkModelType",
"(",
"model",
"Model",
")",
"error",
"{",
"return",
"c",
".",
"spec",
".",
"checkModelType",
"(",
"model",
")",
"\n",
"}"
] | // checkModelType returns an error iff model is not of the registered type that
// corresponds to c. | [
"checkModelType",
"returns",
"an",
"error",
"iff",
"model",
"is",
"not",
"of",
"the",
"registered",
"type",
"that",
"corresponds",
"to",
"c",
"."
] | 4cc9cdbf65ce1b2f60b11b765d3e6b3a5e7e8952 | https://github.com/albrow/zoom/blob/4cc9cdbf65ce1b2f60b11b765d3e6b3a5e7e8952/collection.go#L737-L739 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.