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
sequence | docstring
stringlengths 6
2.61k
| docstring_tokens
sequence | sha
stringlengths 40
40
| url
stringlengths 85
252
|
---|---|---|---|---|---|---|---|---|---|---|---|
2,200 | yosssi/gmq | mqtt/client/client.go | clean | func (cli *Client) clean() {
// Clean the Network Connection.
cli.conn = nil
// Clean the Session if the Clean Session is true.
if cli.sess != nil && cli.sess.cleanSession {
cli.sess = nil
}
} | go | func (cli *Client) clean() {
// Clean the Network Connection.
cli.conn = nil
// Clean the Session if the Clean Session is true.
if cli.sess != nil && cli.sess.cleanSession {
cli.sess = nil
}
} | [
"func",
"(",
"cli",
"*",
"Client",
")",
"clean",
"(",
")",
"{",
"// Clean the Network Connection.",
"cli",
".",
"conn",
"=",
"nil",
"\n\n",
"// Clean the Session if the Clean Session is true.",
"if",
"cli",
".",
"sess",
"!=",
"nil",
"&&",
"cli",
".",
"sess",
".",
"cleanSession",
"{",
"cli",
".",
"sess",
"=",
"nil",
"\n",
"}",
"\n",
"}"
] | // clean cleans the Network Connection and the Session if necessary. | [
"clean",
"cleans",
"the",
"Network",
"Connection",
"and",
"the",
"Session",
"if",
"necessary",
"."
] | b221999646da8ea48ff0796c2b0191aa510d062e | https://github.com/yosssi/gmq/blob/b221999646da8ea48ff0796c2b0191aa510d062e/mqtt/client/client.go#L475-L483 |
2,201 | yosssi/gmq | mqtt/client/client.go | waitPacket | func (cli *Client) waitPacket(packetc <-chan struct{}, timeout time.Duration, errTimeout error) {
defer cli.conn.wg.Done()
var timeoutc <-chan time.Time
if timeout > 0 {
timeoutc = time.After(timeout * time.Second)
}
select {
case <-packetc:
case <-timeoutc:
// Handle the timeout error.
cli.handleErrorAndDisconn(errTimeout)
}
} | go | func (cli *Client) waitPacket(packetc <-chan struct{}, timeout time.Duration, errTimeout error) {
defer cli.conn.wg.Done()
var timeoutc <-chan time.Time
if timeout > 0 {
timeoutc = time.After(timeout * time.Second)
}
select {
case <-packetc:
case <-timeoutc:
// Handle the timeout error.
cli.handleErrorAndDisconn(errTimeout)
}
} | [
"func",
"(",
"cli",
"*",
"Client",
")",
"waitPacket",
"(",
"packetc",
"<-",
"chan",
"struct",
"{",
"}",
",",
"timeout",
"time",
".",
"Duration",
",",
"errTimeout",
"error",
")",
"{",
"defer",
"cli",
".",
"conn",
".",
"wg",
".",
"Done",
"(",
")",
"\n\n",
"var",
"timeoutc",
"<-",
"chan",
"time",
".",
"Time",
"\n\n",
"if",
"timeout",
">",
"0",
"{",
"timeoutc",
"=",
"time",
".",
"After",
"(",
"timeout",
"*",
"time",
".",
"Second",
")",
"\n",
"}",
"\n\n",
"select",
"{",
"case",
"<-",
"packetc",
":",
"case",
"<-",
"timeoutc",
":",
"// Handle the timeout error.",
"cli",
".",
"handleErrorAndDisconn",
"(",
"errTimeout",
")",
"\n",
"}",
"\n",
"}"
] | // waitPacket waits for receiving the Packet. | [
"waitPacket",
"waits",
"for",
"receiving",
"the",
"Packet",
"."
] | b221999646da8ea48ff0796c2b0191aa510d062e | https://github.com/yosssi/gmq/blob/b221999646da8ea48ff0796c2b0191aa510d062e/mqtt/client/client.go#L486-L501 |
2,202 | yosssi/gmq | mqtt/client/client.go | receivePackets | func (cli *Client) receivePackets() {
defer func() {
// Close the channel which handles a signal which
// notifies the arrival of the CONNACK Packet.
close(cli.conn.connack)
cli.conn.wg.Done()
}()
for {
// Receive a Packet from the Server.
p, err := cli.receive()
if err != nil {
// Handle the error and disconnect
// the Network Connection.
cli.handleErrorAndDisconn(err)
// End the goroutine.
return
}
// Handle the Packet.
if err := cli.handlePacket(p); err != nil {
// Handle the error and disconnect
// the Network Connection.
cli.handleErrorAndDisconn(err)
// End the goroutine.
return
}
}
} | go | func (cli *Client) receivePackets() {
defer func() {
// Close the channel which handles a signal which
// notifies the arrival of the CONNACK Packet.
close(cli.conn.connack)
cli.conn.wg.Done()
}()
for {
// Receive a Packet from the Server.
p, err := cli.receive()
if err != nil {
// Handle the error and disconnect
// the Network Connection.
cli.handleErrorAndDisconn(err)
// End the goroutine.
return
}
// Handle the Packet.
if err := cli.handlePacket(p); err != nil {
// Handle the error and disconnect
// the Network Connection.
cli.handleErrorAndDisconn(err)
// End the goroutine.
return
}
}
} | [
"func",
"(",
"cli",
"*",
"Client",
")",
"receivePackets",
"(",
")",
"{",
"defer",
"func",
"(",
")",
"{",
"// Close the channel which handles a signal which",
"// notifies the arrival of the CONNACK Packet.",
"close",
"(",
"cli",
".",
"conn",
".",
"connack",
")",
"\n\n",
"cli",
".",
"conn",
".",
"wg",
".",
"Done",
"(",
")",
"\n",
"}",
"(",
")",
"\n\n",
"for",
"{",
"// Receive a Packet from the Server.",
"p",
",",
"err",
":=",
"cli",
".",
"receive",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"// Handle the error and disconnect",
"// the Network Connection.",
"cli",
".",
"handleErrorAndDisconn",
"(",
"err",
")",
"\n\n",
"// End the goroutine.",
"return",
"\n",
"}",
"\n\n",
"// Handle the Packet.",
"if",
"err",
":=",
"cli",
".",
"handlePacket",
"(",
"p",
")",
";",
"err",
"!=",
"nil",
"{",
"// Handle the error and disconnect",
"// the Network Connection.",
"cli",
".",
"handleErrorAndDisconn",
"(",
"err",
")",
"\n\n",
"// End the goroutine.",
"return",
"\n",
"}",
"\n",
"}",
"\n",
"}"
] | // receivePackets receives Packets from the Server. | [
"receivePackets",
"receives",
"Packets",
"from",
"the",
"Server",
"."
] | b221999646da8ea48ff0796c2b0191aa510d062e | https://github.com/yosssi/gmq/blob/b221999646da8ea48ff0796c2b0191aa510d062e/mqtt/client/client.go#L504-L535 |
2,203 | yosssi/gmq | mqtt/client/client.go | handlePacket | func (cli *Client) handlePacket(p packet.Packet) error {
// Get the MQTT Control Packet type.
ptype, err := p.Type()
if err != nil {
return err
}
switch ptype {
case packet.TypeCONNACK:
cli.handleCONNACK()
return nil
case packet.TypePUBLISH:
return cli.handlePUBLISH(p)
case packet.TypePUBACK:
return cli.handlePUBACK(p)
case packet.TypePUBREC:
return cli.handlePUBREC(p)
case packet.TypePUBREL:
return cli.handlePUBREL(p)
case packet.TypePUBCOMP:
return cli.handlePUBCOMP(p)
case packet.TypeSUBACK:
return cli.handleSUBACK(p)
case packet.TypeUNSUBACK:
return cli.handleUNSUBACK(p)
case packet.TypePINGRESP:
return cli.handlePINGRESP()
default:
return packet.ErrInvalidPacketType
}
} | go | func (cli *Client) handlePacket(p packet.Packet) error {
// Get the MQTT Control Packet type.
ptype, err := p.Type()
if err != nil {
return err
}
switch ptype {
case packet.TypeCONNACK:
cli.handleCONNACK()
return nil
case packet.TypePUBLISH:
return cli.handlePUBLISH(p)
case packet.TypePUBACK:
return cli.handlePUBACK(p)
case packet.TypePUBREC:
return cli.handlePUBREC(p)
case packet.TypePUBREL:
return cli.handlePUBREL(p)
case packet.TypePUBCOMP:
return cli.handlePUBCOMP(p)
case packet.TypeSUBACK:
return cli.handleSUBACK(p)
case packet.TypeUNSUBACK:
return cli.handleUNSUBACK(p)
case packet.TypePINGRESP:
return cli.handlePINGRESP()
default:
return packet.ErrInvalidPacketType
}
} | [
"func",
"(",
"cli",
"*",
"Client",
")",
"handlePacket",
"(",
"p",
"packet",
".",
"Packet",
")",
"error",
"{",
"// Get the MQTT Control Packet type.",
"ptype",
",",
"err",
":=",
"p",
".",
"Type",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"switch",
"ptype",
"{",
"case",
"packet",
".",
"TypeCONNACK",
":",
"cli",
".",
"handleCONNACK",
"(",
")",
"\n",
"return",
"nil",
"\n",
"case",
"packet",
".",
"TypePUBLISH",
":",
"return",
"cli",
".",
"handlePUBLISH",
"(",
"p",
")",
"\n",
"case",
"packet",
".",
"TypePUBACK",
":",
"return",
"cli",
".",
"handlePUBACK",
"(",
"p",
")",
"\n",
"case",
"packet",
".",
"TypePUBREC",
":",
"return",
"cli",
".",
"handlePUBREC",
"(",
"p",
")",
"\n",
"case",
"packet",
".",
"TypePUBREL",
":",
"return",
"cli",
".",
"handlePUBREL",
"(",
"p",
")",
"\n",
"case",
"packet",
".",
"TypePUBCOMP",
":",
"return",
"cli",
".",
"handlePUBCOMP",
"(",
"p",
")",
"\n",
"case",
"packet",
".",
"TypeSUBACK",
":",
"return",
"cli",
".",
"handleSUBACK",
"(",
"p",
")",
"\n",
"case",
"packet",
".",
"TypeUNSUBACK",
":",
"return",
"cli",
".",
"handleUNSUBACK",
"(",
"p",
")",
"\n",
"case",
"packet",
".",
"TypePINGRESP",
":",
"return",
"cli",
".",
"handlePINGRESP",
"(",
")",
"\n",
"default",
":",
"return",
"packet",
".",
"ErrInvalidPacketType",
"\n",
"}",
"\n",
"}"
] | // handlePacket handles the Packet. | [
"handlePacket",
"handles",
"the",
"Packet",
"."
] | b221999646da8ea48ff0796c2b0191aa510d062e | https://github.com/yosssi/gmq/blob/b221999646da8ea48ff0796c2b0191aa510d062e/mqtt/client/client.go#L538-L568 |
2,204 | yosssi/gmq | mqtt/client/client.go | handlePUBLISH | func (cli *Client) handlePUBLISH(p packet.Packet) error {
// Get the PUBLISH Packet.
publish := p.(*packet.PUBLISH)
switch publish.QoS {
case mqtt.QoS0:
// Lock for reading.
cli.muConn.RLock()
// Unlock.
defer cli.muConn.RUnlock()
// Handle the Application Message.
cli.handleMessage(publish.TopicName, publish.Message)
return nil
case mqtt.QoS1:
// Lock for reading.
cli.muConn.RLock()
// Unlock.
defer cli.muConn.RUnlock()
// Handle the Application Message.
cli.handleMessage(publish.TopicName, publish.Message)
// Create a PUBACK Packet.
puback, err := packet.NewPUBACK(&packet.PUBACKOptions{
PacketID: publish.PacketID,
})
if err != nil {
return err
}
// Send the Packet to the Server.
cli.conn.send <- puback
return nil
default:
// Lock for update.
cli.muSess.Lock()
// Unlock.
defer cli.muSess.Unlock()
// Validate the Packet Identifier.
if _, exist := cli.sess.receivingPackets[publish.PacketID]; exist {
return packet.ErrInvalidPacketID
}
// Set the Packet to the Session.
cli.sess.receivingPackets[publish.PacketID] = p
// Create a PUBREC Packet.
pubrec, err := packet.NewPUBREC(&packet.PUBRECOptions{
PacketID: publish.PacketID,
})
if err != nil {
return err
}
// Send the Packet to the Server.
cli.conn.send <- pubrec
return nil
}
} | go | func (cli *Client) handlePUBLISH(p packet.Packet) error {
// Get the PUBLISH Packet.
publish := p.(*packet.PUBLISH)
switch publish.QoS {
case mqtt.QoS0:
// Lock for reading.
cli.muConn.RLock()
// Unlock.
defer cli.muConn.RUnlock()
// Handle the Application Message.
cli.handleMessage(publish.TopicName, publish.Message)
return nil
case mqtt.QoS1:
// Lock for reading.
cli.muConn.RLock()
// Unlock.
defer cli.muConn.RUnlock()
// Handle the Application Message.
cli.handleMessage(publish.TopicName, publish.Message)
// Create a PUBACK Packet.
puback, err := packet.NewPUBACK(&packet.PUBACKOptions{
PacketID: publish.PacketID,
})
if err != nil {
return err
}
// Send the Packet to the Server.
cli.conn.send <- puback
return nil
default:
// Lock for update.
cli.muSess.Lock()
// Unlock.
defer cli.muSess.Unlock()
// Validate the Packet Identifier.
if _, exist := cli.sess.receivingPackets[publish.PacketID]; exist {
return packet.ErrInvalidPacketID
}
// Set the Packet to the Session.
cli.sess.receivingPackets[publish.PacketID] = p
// Create a PUBREC Packet.
pubrec, err := packet.NewPUBREC(&packet.PUBRECOptions{
PacketID: publish.PacketID,
})
if err != nil {
return err
}
// Send the Packet to the Server.
cli.conn.send <- pubrec
return nil
}
} | [
"func",
"(",
"cli",
"*",
"Client",
")",
"handlePUBLISH",
"(",
"p",
"packet",
".",
"Packet",
")",
"error",
"{",
"// Get the PUBLISH Packet.",
"publish",
":=",
"p",
".",
"(",
"*",
"packet",
".",
"PUBLISH",
")",
"\n\n",
"switch",
"publish",
".",
"QoS",
"{",
"case",
"mqtt",
".",
"QoS0",
":",
"// Lock for reading.",
"cli",
".",
"muConn",
".",
"RLock",
"(",
")",
"\n\n",
"// Unlock.",
"defer",
"cli",
".",
"muConn",
".",
"RUnlock",
"(",
")",
"\n\n",
"// Handle the Application Message.",
"cli",
".",
"handleMessage",
"(",
"publish",
".",
"TopicName",
",",
"publish",
".",
"Message",
")",
"\n\n",
"return",
"nil",
"\n",
"case",
"mqtt",
".",
"QoS1",
":",
"// Lock for reading.",
"cli",
".",
"muConn",
".",
"RLock",
"(",
")",
"\n\n",
"// Unlock.",
"defer",
"cli",
".",
"muConn",
".",
"RUnlock",
"(",
")",
"\n\n",
"// Handle the Application Message.",
"cli",
".",
"handleMessage",
"(",
"publish",
".",
"TopicName",
",",
"publish",
".",
"Message",
")",
"\n\n",
"// Create a PUBACK Packet.",
"puback",
",",
"err",
":=",
"packet",
".",
"NewPUBACK",
"(",
"&",
"packet",
".",
"PUBACKOptions",
"{",
"PacketID",
":",
"publish",
".",
"PacketID",
",",
"}",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"// Send the Packet to the Server.",
"cli",
".",
"conn",
".",
"send",
"<-",
"puback",
"\n\n",
"return",
"nil",
"\n",
"default",
":",
"// Lock for update.",
"cli",
".",
"muSess",
".",
"Lock",
"(",
")",
"\n\n",
"// Unlock.",
"defer",
"cli",
".",
"muSess",
".",
"Unlock",
"(",
")",
"\n\n",
"// Validate the Packet Identifier.",
"if",
"_",
",",
"exist",
":=",
"cli",
".",
"sess",
".",
"receivingPackets",
"[",
"publish",
".",
"PacketID",
"]",
";",
"exist",
"{",
"return",
"packet",
".",
"ErrInvalidPacketID",
"\n",
"}",
"\n\n",
"// Set the Packet to the Session.",
"cli",
".",
"sess",
".",
"receivingPackets",
"[",
"publish",
".",
"PacketID",
"]",
"=",
"p",
"\n\n",
"// Create a PUBREC Packet.",
"pubrec",
",",
"err",
":=",
"packet",
".",
"NewPUBREC",
"(",
"&",
"packet",
".",
"PUBRECOptions",
"{",
"PacketID",
":",
"publish",
".",
"PacketID",
",",
"}",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"// Send the Packet to the Server.",
"cli",
".",
"conn",
".",
"send",
"<-",
"pubrec",
"\n\n",
"return",
"nil",
"\n",
"}",
"\n",
"}"
] | // handlePUBLISH handles the PUBLISH Packet. | [
"handlePUBLISH",
"handles",
"the",
"PUBLISH",
"Packet",
"."
] | b221999646da8ea48ff0796c2b0191aa510d062e | https://github.com/yosssi/gmq/blob/b221999646da8ea48ff0796c2b0191aa510d062e/mqtt/client/client.go#L580-L646 |
2,205 | yosssi/gmq | mqtt/client/client.go | handlePUBACK | func (cli *Client) handlePUBACK(p packet.Packet) error {
// Lock for update.
cli.muSess.Lock()
// Unlock.
defer cli.muSess.Unlock()
// Extract the Packet Identifier of the Packet.
id := p.(*packet.PUBACK).PacketID
// Validate the Packet Identifier.
if err := cli.validatePacketID(cli.sess.sendingPackets, id, packet.TypePUBLISH); err != nil {
return err
}
// Delete the PUBLISH Packet from the Session.
delete(cli.sess.sendingPackets, id)
return nil
} | go | func (cli *Client) handlePUBACK(p packet.Packet) error {
// Lock for update.
cli.muSess.Lock()
// Unlock.
defer cli.muSess.Unlock()
// Extract the Packet Identifier of the Packet.
id := p.(*packet.PUBACK).PacketID
// Validate the Packet Identifier.
if err := cli.validatePacketID(cli.sess.sendingPackets, id, packet.TypePUBLISH); err != nil {
return err
}
// Delete the PUBLISH Packet from the Session.
delete(cli.sess.sendingPackets, id)
return nil
} | [
"func",
"(",
"cli",
"*",
"Client",
")",
"handlePUBACK",
"(",
"p",
"packet",
".",
"Packet",
")",
"error",
"{",
"// Lock for update.",
"cli",
".",
"muSess",
".",
"Lock",
"(",
")",
"\n\n",
"// Unlock.",
"defer",
"cli",
".",
"muSess",
".",
"Unlock",
"(",
")",
"\n\n",
"// Extract the Packet Identifier of the Packet.",
"id",
":=",
"p",
".",
"(",
"*",
"packet",
".",
"PUBACK",
")",
".",
"PacketID",
"\n\n",
"// Validate the Packet Identifier.",
"if",
"err",
":=",
"cli",
".",
"validatePacketID",
"(",
"cli",
".",
"sess",
".",
"sendingPackets",
",",
"id",
",",
"packet",
".",
"TypePUBLISH",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"// Delete the PUBLISH Packet from the Session.",
"delete",
"(",
"cli",
".",
"sess",
".",
"sendingPackets",
",",
"id",
")",
"\n\n",
"return",
"nil",
"\n",
"}"
] | // handlePUBACK handles the PUBACK Packet. | [
"handlePUBACK",
"handles",
"the",
"PUBACK",
"Packet",
"."
] | b221999646da8ea48ff0796c2b0191aa510d062e | https://github.com/yosssi/gmq/blob/b221999646da8ea48ff0796c2b0191aa510d062e/mqtt/client/client.go#L649-L668 |
2,206 | yosssi/gmq | mqtt/client/client.go | handlePUBREC | func (cli *Client) handlePUBREC(p packet.Packet) error {
// Lock for update.
cli.muSess.Lock()
// Unlock.
defer cli.muSess.Unlock()
// Extract the Packet Identifier of the Packet.
id := p.(*packet.PUBREC).PacketID
// Validate the Packet Identifier.
if err := cli.validatePacketID(cli.sess.sendingPackets, id, packet.TypePUBLISH); err != nil {
return err
}
// Create a PUBREL Packet.
pubrel, err := packet.NewPUBREL(&packet.PUBRELOptions{
PacketID: id,
})
if err != nil {
return err
}
// Set the PUBREL Packet to the Session.
cli.sess.sendingPackets[id] = pubrel
// Send the Packet to the Server.
cli.conn.send <- pubrel
return nil
} | go | func (cli *Client) handlePUBREC(p packet.Packet) error {
// Lock for update.
cli.muSess.Lock()
// Unlock.
defer cli.muSess.Unlock()
// Extract the Packet Identifier of the Packet.
id := p.(*packet.PUBREC).PacketID
// Validate the Packet Identifier.
if err := cli.validatePacketID(cli.sess.sendingPackets, id, packet.TypePUBLISH); err != nil {
return err
}
// Create a PUBREL Packet.
pubrel, err := packet.NewPUBREL(&packet.PUBRELOptions{
PacketID: id,
})
if err != nil {
return err
}
// Set the PUBREL Packet to the Session.
cli.sess.sendingPackets[id] = pubrel
// Send the Packet to the Server.
cli.conn.send <- pubrel
return nil
} | [
"func",
"(",
"cli",
"*",
"Client",
")",
"handlePUBREC",
"(",
"p",
"packet",
".",
"Packet",
")",
"error",
"{",
"// Lock for update.",
"cli",
".",
"muSess",
".",
"Lock",
"(",
")",
"\n\n",
"// Unlock.",
"defer",
"cli",
".",
"muSess",
".",
"Unlock",
"(",
")",
"\n\n",
"// Extract the Packet Identifier of the Packet.",
"id",
":=",
"p",
".",
"(",
"*",
"packet",
".",
"PUBREC",
")",
".",
"PacketID",
"\n\n",
"// Validate the Packet Identifier.",
"if",
"err",
":=",
"cli",
".",
"validatePacketID",
"(",
"cli",
".",
"sess",
".",
"sendingPackets",
",",
"id",
",",
"packet",
".",
"TypePUBLISH",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"// Create a PUBREL Packet.",
"pubrel",
",",
"err",
":=",
"packet",
".",
"NewPUBREL",
"(",
"&",
"packet",
".",
"PUBRELOptions",
"{",
"PacketID",
":",
"id",
",",
"}",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"// Set the PUBREL Packet to the Session.",
"cli",
".",
"sess",
".",
"sendingPackets",
"[",
"id",
"]",
"=",
"pubrel",
"\n\n",
"// Send the Packet to the Server.",
"cli",
".",
"conn",
".",
"send",
"<-",
"pubrel",
"\n\n",
"return",
"nil",
"\n",
"}"
] | // handlePUBREC handles the PUBREC Packet. | [
"handlePUBREC",
"handles",
"the",
"PUBREC",
"Packet",
"."
] | b221999646da8ea48ff0796c2b0191aa510d062e | https://github.com/yosssi/gmq/blob/b221999646da8ea48ff0796c2b0191aa510d062e/mqtt/client/client.go#L671-L701 |
2,207 | yosssi/gmq | mqtt/client/client.go | handlePUBREL | func (cli *Client) handlePUBREL(p packet.Packet) error {
// Lock for update.
cli.muSess.Lock()
// Unlock.
defer cli.muSess.Unlock()
// Extract the Packet Identifier of the Packet.
id := p.(*packet.PUBREL).PacketID
// Validate the Packet Identifier.
if err := cli.validatePacketID(cli.sess.receivingPackets, id, packet.TypePUBLISH); err != nil {
return err
}
// Get the Packet from the Session.
publish := cli.sess.receivingPackets[id].(*packet.PUBLISH)
// Lock for reading.
cli.muConn.RLock()
// Handle the Application Message.
cli.handleMessage(publish.TopicName, publish.Message)
// Unlock.
cli.muConn.RUnlock()
// Delete the Packet from the Session
delete(cli.sess.receivingPackets, id)
// Create a PUBCOMP Packet.
pubcomp, err := packet.NewPUBCOMP(&packet.PUBCOMPOptions{
PacketID: id,
})
if err != nil {
return err
}
// Send the Packet to the Server.
cli.conn.send <- pubcomp
return nil
} | go | func (cli *Client) handlePUBREL(p packet.Packet) error {
// Lock for update.
cli.muSess.Lock()
// Unlock.
defer cli.muSess.Unlock()
// Extract the Packet Identifier of the Packet.
id := p.(*packet.PUBREL).PacketID
// Validate the Packet Identifier.
if err := cli.validatePacketID(cli.sess.receivingPackets, id, packet.TypePUBLISH); err != nil {
return err
}
// Get the Packet from the Session.
publish := cli.sess.receivingPackets[id].(*packet.PUBLISH)
// Lock for reading.
cli.muConn.RLock()
// Handle the Application Message.
cli.handleMessage(publish.TopicName, publish.Message)
// Unlock.
cli.muConn.RUnlock()
// Delete the Packet from the Session
delete(cli.sess.receivingPackets, id)
// Create a PUBCOMP Packet.
pubcomp, err := packet.NewPUBCOMP(&packet.PUBCOMPOptions{
PacketID: id,
})
if err != nil {
return err
}
// Send the Packet to the Server.
cli.conn.send <- pubcomp
return nil
} | [
"func",
"(",
"cli",
"*",
"Client",
")",
"handlePUBREL",
"(",
"p",
"packet",
".",
"Packet",
")",
"error",
"{",
"// Lock for update.",
"cli",
".",
"muSess",
".",
"Lock",
"(",
")",
"\n\n",
"// Unlock.",
"defer",
"cli",
".",
"muSess",
".",
"Unlock",
"(",
")",
"\n\n",
"// Extract the Packet Identifier of the Packet.",
"id",
":=",
"p",
".",
"(",
"*",
"packet",
".",
"PUBREL",
")",
".",
"PacketID",
"\n\n",
"// Validate the Packet Identifier.",
"if",
"err",
":=",
"cli",
".",
"validatePacketID",
"(",
"cli",
".",
"sess",
".",
"receivingPackets",
",",
"id",
",",
"packet",
".",
"TypePUBLISH",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"// Get the Packet from the Session.",
"publish",
":=",
"cli",
".",
"sess",
".",
"receivingPackets",
"[",
"id",
"]",
".",
"(",
"*",
"packet",
".",
"PUBLISH",
")",
"\n\n",
"// Lock for reading.",
"cli",
".",
"muConn",
".",
"RLock",
"(",
")",
"\n\n",
"// Handle the Application Message.",
"cli",
".",
"handleMessage",
"(",
"publish",
".",
"TopicName",
",",
"publish",
".",
"Message",
")",
"\n\n",
"// Unlock.",
"cli",
".",
"muConn",
".",
"RUnlock",
"(",
")",
"\n\n",
"// Delete the Packet from the Session",
"delete",
"(",
"cli",
".",
"sess",
".",
"receivingPackets",
",",
"id",
")",
"\n\n",
"// Create a PUBCOMP Packet.",
"pubcomp",
",",
"err",
":=",
"packet",
".",
"NewPUBCOMP",
"(",
"&",
"packet",
".",
"PUBCOMPOptions",
"{",
"PacketID",
":",
"id",
",",
"}",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"// Send the Packet to the Server.",
"cli",
".",
"conn",
".",
"send",
"<-",
"pubcomp",
"\n\n",
"return",
"nil",
"\n",
"}"
] | // handlePUBREL handles the PUBREL Packet. | [
"handlePUBREL",
"handles",
"the",
"PUBREL",
"Packet",
"."
] | b221999646da8ea48ff0796c2b0191aa510d062e | https://github.com/yosssi/gmq/blob/b221999646da8ea48ff0796c2b0191aa510d062e/mqtt/client/client.go#L704-L746 |
2,208 | yosssi/gmq | mqtt/client/client.go | handlePUBCOMP | func (cli *Client) handlePUBCOMP(p packet.Packet) error {
// Lock for update.
cli.muSess.Lock()
// Unlock.
defer cli.muSess.Unlock()
// Extract the Packet Identifier of the Packet.
id := p.(*packet.PUBCOMP).PacketID
// Validate the Packet Identifier.
if err := cli.validatePacketID(cli.sess.sendingPackets, id, packet.TypePUBREL); err != nil {
return err
}
// Delete the PUBREL Packet from the Session.
delete(cli.sess.sendingPackets, id)
return nil
} | go | func (cli *Client) handlePUBCOMP(p packet.Packet) error {
// Lock for update.
cli.muSess.Lock()
// Unlock.
defer cli.muSess.Unlock()
// Extract the Packet Identifier of the Packet.
id := p.(*packet.PUBCOMP).PacketID
// Validate the Packet Identifier.
if err := cli.validatePacketID(cli.sess.sendingPackets, id, packet.TypePUBREL); err != nil {
return err
}
// Delete the PUBREL Packet from the Session.
delete(cli.sess.sendingPackets, id)
return nil
} | [
"func",
"(",
"cli",
"*",
"Client",
")",
"handlePUBCOMP",
"(",
"p",
"packet",
".",
"Packet",
")",
"error",
"{",
"// Lock for update.",
"cli",
".",
"muSess",
".",
"Lock",
"(",
")",
"\n\n",
"// Unlock.",
"defer",
"cli",
".",
"muSess",
".",
"Unlock",
"(",
")",
"\n\n",
"// Extract the Packet Identifier of the Packet.",
"id",
":=",
"p",
".",
"(",
"*",
"packet",
".",
"PUBCOMP",
")",
".",
"PacketID",
"\n\n",
"// Validate the Packet Identifier.",
"if",
"err",
":=",
"cli",
".",
"validatePacketID",
"(",
"cli",
".",
"sess",
".",
"sendingPackets",
",",
"id",
",",
"packet",
".",
"TypePUBREL",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"// Delete the PUBREL Packet from the Session.",
"delete",
"(",
"cli",
".",
"sess",
".",
"sendingPackets",
",",
"id",
")",
"\n\n",
"return",
"nil",
"\n",
"}"
] | // handlePUBCOMP handles the PUBCOMP Packet. | [
"handlePUBCOMP",
"handles",
"the",
"PUBCOMP",
"Packet",
"."
] | b221999646da8ea48ff0796c2b0191aa510d062e | https://github.com/yosssi/gmq/blob/b221999646da8ea48ff0796c2b0191aa510d062e/mqtt/client/client.go#L749-L768 |
2,209 | yosssi/gmq | mqtt/client/client.go | handleSUBACK | func (cli *Client) handleSUBACK(p packet.Packet) error {
// Lock for update.
cli.muConn.Lock()
cli.muSess.Lock()
// Unlock.
defer cli.muConn.Unlock()
defer cli.muSess.Unlock()
// Extract the Packet Identifier of the Packet.
id := p.(*packet.SUBACK).PacketID
// Validate the Packet Identifier.
if err := cli.validatePacketID(cli.sess.sendingPackets, id, packet.TypeSUBSCRIBE); err != nil {
return err
}
// Get the subscription requests of the SUBSCRIBE Packet.
subreqs := cli.sess.sendingPackets[id].(*packet.SUBSCRIBE).SubReqs
// Delete the SUBSCRIBE Packet from the Session.
delete(cli.sess.sendingPackets, id)
// Get the Return Codes of the SUBACK Packet.
returnCodes := p.(*packet.SUBACK).ReturnCodes
// Check the lengths of the Return Codes.
if len(returnCodes) != len(subreqs) {
return ErrInvalidSUBACK
}
// Set the subscriptions to the Network Connection.
for i, code := range returnCodes {
// Skip if the Return Code is failure.
if code == packet.SUBACKRetFailure {
continue
}
// Get the Topic Filter.
topicFilter := string(subreqs[i].TopicFilter)
// Move the subscription information from
// unackSubs to ackedSubs.
cli.conn.ackedSubs[topicFilter] = cli.conn.unackSubs[topicFilter]
delete(cli.conn.unackSubs, topicFilter)
}
return nil
} | go | func (cli *Client) handleSUBACK(p packet.Packet) error {
// Lock for update.
cli.muConn.Lock()
cli.muSess.Lock()
// Unlock.
defer cli.muConn.Unlock()
defer cli.muSess.Unlock()
// Extract the Packet Identifier of the Packet.
id := p.(*packet.SUBACK).PacketID
// Validate the Packet Identifier.
if err := cli.validatePacketID(cli.sess.sendingPackets, id, packet.TypeSUBSCRIBE); err != nil {
return err
}
// Get the subscription requests of the SUBSCRIBE Packet.
subreqs := cli.sess.sendingPackets[id].(*packet.SUBSCRIBE).SubReqs
// Delete the SUBSCRIBE Packet from the Session.
delete(cli.sess.sendingPackets, id)
// Get the Return Codes of the SUBACK Packet.
returnCodes := p.(*packet.SUBACK).ReturnCodes
// Check the lengths of the Return Codes.
if len(returnCodes) != len(subreqs) {
return ErrInvalidSUBACK
}
// Set the subscriptions to the Network Connection.
for i, code := range returnCodes {
// Skip if the Return Code is failure.
if code == packet.SUBACKRetFailure {
continue
}
// Get the Topic Filter.
topicFilter := string(subreqs[i].TopicFilter)
// Move the subscription information from
// unackSubs to ackedSubs.
cli.conn.ackedSubs[topicFilter] = cli.conn.unackSubs[topicFilter]
delete(cli.conn.unackSubs, topicFilter)
}
return nil
} | [
"func",
"(",
"cli",
"*",
"Client",
")",
"handleSUBACK",
"(",
"p",
"packet",
".",
"Packet",
")",
"error",
"{",
"// Lock for update.",
"cli",
".",
"muConn",
".",
"Lock",
"(",
")",
"\n",
"cli",
".",
"muSess",
".",
"Lock",
"(",
")",
"\n\n",
"// Unlock.",
"defer",
"cli",
".",
"muConn",
".",
"Unlock",
"(",
")",
"\n",
"defer",
"cli",
".",
"muSess",
".",
"Unlock",
"(",
")",
"\n\n",
"// Extract the Packet Identifier of the Packet.",
"id",
":=",
"p",
".",
"(",
"*",
"packet",
".",
"SUBACK",
")",
".",
"PacketID",
"\n\n",
"// Validate the Packet Identifier.",
"if",
"err",
":=",
"cli",
".",
"validatePacketID",
"(",
"cli",
".",
"sess",
".",
"sendingPackets",
",",
"id",
",",
"packet",
".",
"TypeSUBSCRIBE",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"// Get the subscription requests of the SUBSCRIBE Packet.",
"subreqs",
":=",
"cli",
".",
"sess",
".",
"sendingPackets",
"[",
"id",
"]",
".",
"(",
"*",
"packet",
".",
"SUBSCRIBE",
")",
".",
"SubReqs",
"\n\n",
"// Delete the SUBSCRIBE Packet from the Session.",
"delete",
"(",
"cli",
".",
"sess",
".",
"sendingPackets",
",",
"id",
")",
"\n\n",
"// Get the Return Codes of the SUBACK Packet.",
"returnCodes",
":=",
"p",
".",
"(",
"*",
"packet",
".",
"SUBACK",
")",
".",
"ReturnCodes",
"\n\n",
"// Check the lengths of the Return Codes.",
"if",
"len",
"(",
"returnCodes",
")",
"!=",
"len",
"(",
"subreqs",
")",
"{",
"return",
"ErrInvalidSUBACK",
"\n",
"}",
"\n\n",
"// Set the subscriptions to the Network Connection.",
"for",
"i",
",",
"code",
":=",
"range",
"returnCodes",
"{",
"// Skip if the Return Code is failure.",
"if",
"code",
"==",
"packet",
".",
"SUBACKRetFailure",
"{",
"continue",
"\n",
"}",
"\n\n",
"// Get the Topic Filter.",
"topicFilter",
":=",
"string",
"(",
"subreqs",
"[",
"i",
"]",
".",
"TopicFilter",
")",
"\n\n",
"// Move the subscription information from",
"// unackSubs to ackedSubs.",
"cli",
".",
"conn",
".",
"ackedSubs",
"[",
"topicFilter",
"]",
"=",
"cli",
".",
"conn",
".",
"unackSubs",
"[",
"topicFilter",
"]",
"\n",
"delete",
"(",
"cli",
".",
"conn",
".",
"unackSubs",
",",
"topicFilter",
")",
"\n",
"}",
"\n\n",
"return",
"nil",
"\n",
"}"
] | // handleSUBACK handles the SUBACK Packet. | [
"handleSUBACK",
"handles",
"the",
"SUBACK",
"Packet",
"."
] | b221999646da8ea48ff0796c2b0191aa510d062e | https://github.com/yosssi/gmq/blob/b221999646da8ea48ff0796c2b0191aa510d062e/mqtt/client/client.go#L771-L819 |
2,210 | yosssi/gmq | mqtt/client/client.go | handleUNSUBACK | func (cli *Client) handleUNSUBACK(p packet.Packet) error {
// Lock for update.
cli.muConn.Lock()
cli.muSess.Lock()
// Unlock.
defer cli.muConn.Unlock()
defer cli.muSess.Unlock()
// Extract the Packet Identifier of the Packet.
id := p.(*packet.UNSUBACK).PacketID
// Validate the Packet Identifier.
if err := cli.validatePacketID(cli.sess.sendingPackets, id, packet.TypeUNSUBSCRIBE); err != nil {
return err
}
// Get the Topic Filters of the UNSUBSCRIBE Packet.
topicFilters := cli.sess.sendingPackets[id].(*packet.UNSUBSCRIBE).TopicFilters
// Delete the UNSUBSCRIBE Packet from the Session.
delete(cli.sess.sendingPackets, id)
// Delete the Topic Filters from the Network Connection.
for _, topicFilter := range topicFilters {
delete(cli.conn.ackedSubs, string(topicFilter))
}
return nil
} | go | func (cli *Client) handleUNSUBACK(p packet.Packet) error {
// Lock for update.
cli.muConn.Lock()
cli.muSess.Lock()
// Unlock.
defer cli.muConn.Unlock()
defer cli.muSess.Unlock()
// Extract the Packet Identifier of the Packet.
id := p.(*packet.UNSUBACK).PacketID
// Validate the Packet Identifier.
if err := cli.validatePacketID(cli.sess.sendingPackets, id, packet.TypeUNSUBSCRIBE); err != nil {
return err
}
// Get the Topic Filters of the UNSUBSCRIBE Packet.
topicFilters := cli.sess.sendingPackets[id].(*packet.UNSUBSCRIBE).TopicFilters
// Delete the UNSUBSCRIBE Packet from the Session.
delete(cli.sess.sendingPackets, id)
// Delete the Topic Filters from the Network Connection.
for _, topicFilter := range topicFilters {
delete(cli.conn.ackedSubs, string(topicFilter))
}
return nil
} | [
"func",
"(",
"cli",
"*",
"Client",
")",
"handleUNSUBACK",
"(",
"p",
"packet",
".",
"Packet",
")",
"error",
"{",
"// Lock for update.",
"cli",
".",
"muConn",
".",
"Lock",
"(",
")",
"\n",
"cli",
".",
"muSess",
".",
"Lock",
"(",
")",
"\n\n",
"// Unlock.",
"defer",
"cli",
".",
"muConn",
".",
"Unlock",
"(",
")",
"\n",
"defer",
"cli",
".",
"muSess",
".",
"Unlock",
"(",
")",
"\n\n",
"// Extract the Packet Identifier of the Packet.",
"id",
":=",
"p",
".",
"(",
"*",
"packet",
".",
"UNSUBACK",
")",
".",
"PacketID",
"\n\n",
"// Validate the Packet Identifier.",
"if",
"err",
":=",
"cli",
".",
"validatePacketID",
"(",
"cli",
".",
"sess",
".",
"sendingPackets",
",",
"id",
",",
"packet",
".",
"TypeUNSUBSCRIBE",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"// Get the Topic Filters of the UNSUBSCRIBE Packet.",
"topicFilters",
":=",
"cli",
".",
"sess",
".",
"sendingPackets",
"[",
"id",
"]",
".",
"(",
"*",
"packet",
".",
"UNSUBSCRIBE",
")",
".",
"TopicFilters",
"\n\n",
"// Delete the UNSUBSCRIBE Packet from the Session.",
"delete",
"(",
"cli",
".",
"sess",
".",
"sendingPackets",
",",
"id",
")",
"\n\n",
"// Delete the Topic Filters from the Network Connection.",
"for",
"_",
",",
"topicFilter",
":=",
"range",
"topicFilters",
"{",
"delete",
"(",
"cli",
".",
"conn",
".",
"ackedSubs",
",",
"string",
"(",
"topicFilter",
")",
")",
"\n",
"}",
"\n\n",
"return",
"nil",
"\n",
"}"
] | // handleUNSUBACK handles the UNSUBACK Packet. | [
"handleUNSUBACK",
"handles",
"the",
"UNSUBACK",
"Packet",
"."
] | b221999646da8ea48ff0796c2b0191aa510d062e | https://github.com/yosssi/gmq/blob/b221999646da8ea48ff0796c2b0191aa510d062e/mqtt/client/client.go#L822-L851 |
2,211 | yosssi/gmq | mqtt/client/client.go | handlePINGRESP | func (cli *Client) handlePINGRESP() error {
// Lock for reading and updating pingrespcs.
cli.conn.muPINGRESPs.Lock()
// Check the length of pingrespcs.
if len(cli.conn.pingresps) == 0 {
// Unlock.
cli.conn.muPINGRESPs.Unlock()
// Return an error if there is no channel in pingrespcs.
return ErrInvalidPINGRESP
}
// Get the first channel in pingrespcs.
pingrespc := cli.conn.pingresps[0]
// Remove the first channel from pingrespcs.
cli.conn.pingresps = cli.conn.pingresps[1:]
// Unlock.
cli.conn.muPINGRESPs.Unlock()
// Notify the arrival of the PINGRESP Packet if possible.
select {
case pingrespc <- struct{}{}:
default:
}
return nil
} | go | func (cli *Client) handlePINGRESP() error {
// Lock for reading and updating pingrespcs.
cli.conn.muPINGRESPs.Lock()
// Check the length of pingrespcs.
if len(cli.conn.pingresps) == 0 {
// Unlock.
cli.conn.muPINGRESPs.Unlock()
// Return an error if there is no channel in pingrespcs.
return ErrInvalidPINGRESP
}
// Get the first channel in pingrespcs.
pingrespc := cli.conn.pingresps[0]
// Remove the first channel from pingrespcs.
cli.conn.pingresps = cli.conn.pingresps[1:]
// Unlock.
cli.conn.muPINGRESPs.Unlock()
// Notify the arrival of the PINGRESP Packet if possible.
select {
case pingrespc <- struct{}{}:
default:
}
return nil
} | [
"func",
"(",
"cli",
"*",
"Client",
")",
"handlePINGRESP",
"(",
")",
"error",
"{",
"// Lock for reading and updating pingrespcs.",
"cli",
".",
"conn",
".",
"muPINGRESPs",
".",
"Lock",
"(",
")",
"\n\n",
"// Check the length of pingrespcs.",
"if",
"len",
"(",
"cli",
".",
"conn",
".",
"pingresps",
")",
"==",
"0",
"{",
"// Unlock.",
"cli",
".",
"conn",
".",
"muPINGRESPs",
".",
"Unlock",
"(",
")",
"\n\n",
"// Return an error if there is no channel in pingrespcs.",
"return",
"ErrInvalidPINGRESP",
"\n",
"}",
"\n\n",
"// Get the first channel in pingrespcs.",
"pingrespc",
":=",
"cli",
".",
"conn",
".",
"pingresps",
"[",
"0",
"]",
"\n\n",
"// Remove the first channel from pingrespcs.",
"cli",
".",
"conn",
".",
"pingresps",
"=",
"cli",
".",
"conn",
".",
"pingresps",
"[",
"1",
":",
"]",
"\n\n",
"// Unlock.",
"cli",
".",
"conn",
".",
"muPINGRESPs",
".",
"Unlock",
"(",
")",
"\n\n",
"// Notify the arrival of the PINGRESP Packet if possible.",
"select",
"{",
"case",
"pingrespc",
"<-",
"struct",
"{",
"}",
"{",
"}",
":",
"default",
":",
"}",
"\n\n",
"return",
"nil",
"\n",
"}"
] | // handlePINGRESP handles the PINGRESP Packet. | [
"handlePINGRESP",
"handles",
"the",
"PINGRESP",
"Packet",
"."
] | b221999646da8ea48ff0796c2b0191aa510d062e | https://github.com/yosssi/gmq/blob/b221999646da8ea48ff0796c2b0191aa510d062e/mqtt/client/client.go#L854-L883 |
2,212 | yosssi/gmq | mqtt/client/client.go | handleErrorAndDisconn | func (cli *Client) handleErrorAndDisconn(err error) {
// Lock for reading.
cli.muConn.RLock()
// Ignore the error and end the process
// if the Network Connection has already
// been disconnected.
if cli.conn == nil || cli.conn.disconnected {
// Unlock.
cli.muConn.RUnlock()
return
}
// Unlock.
cli.muConn.RUnlock()
// Handle the error.
if cli.errorHandler != nil {
cli.errorHandler(err)
}
// Send a disconnect signal to the goroutine
// via the channel if possible.
select {
case cli.disconnc <- struct{}{}:
default:
}
} | go | func (cli *Client) handleErrorAndDisconn(err error) {
// Lock for reading.
cli.muConn.RLock()
// Ignore the error and end the process
// if the Network Connection has already
// been disconnected.
if cli.conn == nil || cli.conn.disconnected {
// Unlock.
cli.muConn.RUnlock()
return
}
// Unlock.
cli.muConn.RUnlock()
// Handle the error.
if cli.errorHandler != nil {
cli.errorHandler(err)
}
// Send a disconnect signal to the goroutine
// via the channel if possible.
select {
case cli.disconnc <- struct{}{}:
default:
}
} | [
"func",
"(",
"cli",
"*",
"Client",
")",
"handleErrorAndDisconn",
"(",
"err",
"error",
")",
"{",
"// Lock for reading.",
"cli",
".",
"muConn",
".",
"RLock",
"(",
")",
"\n\n",
"// Ignore the error and end the process",
"// if the Network Connection has already",
"// been disconnected.",
"if",
"cli",
".",
"conn",
"==",
"nil",
"||",
"cli",
".",
"conn",
".",
"disconnected",
"{",
"// Unlock.",
"cli",
".",
"muConn",
".",
"RUnlock",
"(",
")",
"\n\n",
"return",
"\n",
"}",
"\n\n",
"// Unlock.",
"cli",
".",
"muConn",
".",
"RUnlock",
"(",
")",
"\n\n",
"// Handle the error.",
"if",
"cli",
".",
"errorHandler",
"!=",
"nil",
"{",
"cli",
".",
"errorHandler",
"(",
"err",
")",
"\n",
"}",
"\n\n",
"// Send a disconnect signal to the goroutine",
"// via the channel if possible.",
"select",
"{",
"case",
"cli",
".",
"disconnc",
"<-",
"struct",
"{",
"}",
"{",
"}",
":",
"default",
":",
"}",
"\n",
"}"
] | // handleError handles the error and disconnects
// the Network Connection. | [
"handleError",
"handles",
"the",
"error",
"and",
"disconnects",
"the",
"Network",
"Connection",
"."
] | b221999646da8ea48ff0796c2b0191aa510d062e | https://github.com/yosssi/gmq/blob/b221999646da8ea48ff0796c2b0191aa510d062e/mqtt/client/client.go#L887-L915 |
2,213 | yosssi/gmq | mqtt/client/client.go | sendPackets | func (cli *Client) sendPackets(keepAlive time.Duration, pingrespTimeout time.Duration) {
defer func() {
// Lock for reading and updating pingrespcs.
cli.conn.muPINGRESPs.Lock()
// Close the channels which handle a signal which
// notifies the arrival of the PINGREQ Packet.
for _, pingresp := range cli.conn.pingresps {
close(pingresp)
}
// Initialize pingrespcs
cli.conn.pingresps = make([]chan struct{}, 0)
// Unlock.
cli.conn.muPINGRESPs.Unlock()
cli.conn.wg.Done()
}()
for {
var keepAlivec <-chan time.Time
if keepAlive > 0 {
keepAlivec = time.After(keepAlive * time.Second)
}
select {
case p := <-cli.conn.send:
// Lock for sending the Packet.
cli.muConn.RLock()
// Send the Packet to the Server.
err := cli.send(p)
// Unlock.
cli.muConn.RUnlock()
if err != nil {
// Handle the error and disconnect the Network Connection.
cli.handleErrorAndDisconn(err)
// End this function.
return
}
case <-keepAlivec:
// Lock for appending the channel to pingrespcs.
cli.conn.muPINGRESPs.Lock()
// Create a channel which handles the signal to notify the arrival of
// the PINGRESP Packet.
pingresp := make(chan struct{}, 1)
// Append the channel to pingrespcs.
cli.conn.pingresps = append(cli.conn.pingresps, pingresp)
// Launch a goroutine which waits for receiving the PINGRESP Packet.
cli.conn.wg.Add(1)
go cli.waitPacket(pingresp, pingrespTimeout, ErrPINGRESPTimeout)
// Unlock.
cli.conn.muPINGRESPs.Unlock()
// Lock for sending the Packet.
cli.muConn.RLock()
// Send a PINGREQ Packet to the Server.
err := cli.send(packet.NewPINGREQ())
// Unlock.
cli.muConn.RUnlock()
if err != nil {
// Handle the error and disconnect the Network Connection.
cli.handleErrorAndDisconn(err)
// End this function.
return
}
case <-cli.conn.sendEnd:
// End this function.
return
}
}
} | go | func (cli *Client) sendPackets(keepAlive time.Duration, pingrespTimeout time.Duration) {
defer func() {
// Lock for reading and updating pingrespcs.
cli.conn.muPINGRESPs.Lock()
// Close the channels which handle a signal which
// notifies the arrival of the PINGREQ Packet.
for _, pingresp := range cli.conn.pingresps {
close(pingresp)
}
// Initialize pingrespcs
cli.conn.pingresps = make([]chan struct{}, 0)
// Unlock.
cli.conn.muPINGRESPs.Unlock()
cli.conn.wg.Done()
}()
for {
var keepAlivec <-chan time.Time
if keepAlive > 0 {
keepAlivec = time.After(keepAlive * time.Second)
}
select {
case p := <-cli.conn.send:
// Lock for sending the Packet.
cli.muConn.RLock()
// Send the Packet to the Server.
err := cli.send(p)
// Unlock.
cli.muConn.RUnlock()
if err != nil {
// Handle the error and disconnect the Network Connection.
cli.handleErrorAndDisconn(err)
// End this function.
return
}
case <-keepAlivec:
// Lock for appending the channel to pingrespcs.
cli.conn.muPINGRESPs.Lock()
// Create a channel which handles the signal to notify the arrival of
// the PINGRESP Packet.
pingresp := make(chan struct{}, 1)
// Append the channel to pingrespcs.
cli.conn.pingresps = append(cli.conn.pingresps, pingresp)
// Launch a goroutine which waits for receiving the PINGRESP Packet.
cli.conn.wg.Add(1)
go cli.waitPacket(pingresp, pingrespTimeout, ErrPINGRESPTimeout)
// Unlock.
cli.conn.muPINGRESPs.Unlock()
// Lock for sending the Packet.
cli.muConn.RLock()
// Send a PINGREQ Packet to the Server.
err := cli.send(packet.NewPINGREQ())
// Unlock.
cli.muConn.RUnlock()
if err != nil {
// Handle the error and disconnect the Network Connection.
cli.handleErrorAndDisconn(err)
// End this function.
return
}
case <-cli.conn.sendEnd:
// End this function.
return
}
}
} | [
"func",
"(",
"cli",
"*",
"Client",
")",
"sendPackets",
"(",
"keepAlive",
"time",
".",
"Duration",
",",
"pingrespTimeout",
"time",
".",
"Duration",
")",
"{",
"defer",
"func",
"(",
")",
"{",
"// Lock for reading and updating pingrespcs.",
"cli",
".",
"conn",
".",
"muPINGRESPs",
".",
"Lock",
"(",
")",
"\n\n",
"// Close the channels which handle a signal which",
"// notifies the arrival of the PINGREQ Packet.",
"for",
"_",
",",
"pingresp",
":=",
"range",
"cli",
".",
"conn",
".",
"pingresps",
"{",
"close",
"(",
"pingresp",
")",
"\n",
"}",
"\n\n",
"// Initialize pingrespcs",
"cli",
".",
"conn",
".",
"pingresps",
"=",
"make",
"(",
"[",
"]",
"chan",
"struct",
"{",
"}",
",",
"0",
")",
"\n\n",
"// Unlock.",
"cli",
".",
"conn",
".",
"muPINGRESPs",
".",
"Unlock",
"(",
")",
"\n\n",
"cli",
".",
"conn",
".",
"wg",
".",
"Done",
"(",
")",
"\n",
"}",
"(",
")",
"\n\n",
"for",
"{",
"var",
"keepAlivec",
"<-",
"chan",
"time",
".",
"Time",
"\n\n",
"if",
"keepAlive",
">",
"0",
"{",
"keepAlivec",
"=",
"time",
".",
"After",
"(",
"keepAlive",
"*",
"time",
".",
"Second",
")",
"\n",
"}",
"\n\n",
"select",
"{",
"case",
"p",
":=",
"<-",
"cli",
".",
"conn",
".",
"send",
":",
"// Lock for sending the Packet.",
"cli",
".",
"muConn",
".",
"RLock",
"(",
")",
"\n\n",
"// Send the Packet to the Server.",
"err",
":=",
"cli",
".",
"send",
"(",
"p",
")",
"\n\n",
"// Unlock.",
"cli",
".",
"muConn",
".",
"RUnlock",
"(",
")",
"\n\n",
"if",
"err",
"!=",
"nil",
"{",
"// Handle the error and disconnect the Network Connection.",
"cli",
".",
"handleErrorAndDisconn",
"(",
"err",
")",
"\n\n",
"// End this function.",
"return",
"\n",
"}",
"\n",
"case",
"<-",
"keepAlivec",
":",
"// Lock for appending the channel to pingrespcs.",
"cli",
".",
"conn",
".",
"muPINGRESPs",
".",
"Lock",
"(",
")",
"\n\n",
"// Create a channel which handles the signal to notify the arrival of",
"// the PINGRESP Packet.",
"pingresp",
":=",
"make",
"(",
"chan",
"struct",
"{",
"}",
",",
"1",
")",
"\n\n",
"// Append the channel to pingrespcs.",
"cli",
".",
"conn",
".",
"pingresps",
"=",
"append",
"(",
"cli",
".",
"conn",
".",
"pingresps",
",",
"pingresp",
")",
"\n\n",
"// Launch a goroutine which waits for receiving the PINGRESP Packet.",
"cli",
".",
"conn",
".",
"wg",
".",
"Add",
"(",
"1",
")",
"\n",
"go",
"cli",
".",
"waitPacket",
"(",
"pingresp",
",",
"pingrespTimeout",
",",
"ErrPINGRESPTimeout",
")",
"\n\n",
"// Unlock.",
"cli",
".",
"conn",
".",
"muPINGRESPs",
".",
"Unlock",
"(",
")",
"\n\n",
"// Lock for sending the Packet.",
"cli",
".",
"muConn",
".",
"RLock",
"(",
")",
"\n\n",
"// Send a PINGREQ Packet to the Server.",
"err",
":=",
"cli",
".",
"send",
"(",
"packet",
".",
"NewPINGREQ",
"(",
")",
")",
"\n\n",
"// Unlock.",
"cli",
".",
"muConn",
".",
"RUnlock",
"(",
")",
"\n\n",
"if",
"err",
"!=",
"nil",
"{",
"// Handle the error and disconnect the Network Connection.",
"cli",
".",
"handleErrorAndDisconn",
"(",
"err",
")",
"\n\n",
"// End this function.",
"return",
"\n",
"}",
"\n",
"case",
"<-",
"cli",
".",
"conn",
".",
"sendEnd",
":",
"// End this function.",
"return",
"\n",
"}",
"\n",
"}",
"\n",
"}"
] | // sendPackets sends Packets to the Server. | [
"sendPackets",
"sends",
"Packets",
"to",
"the",
"Server",
"."
] | b221999646da8ea48ff0796c2b0191aa510d062e | https://github.com/yosssi/gmq/blob/b221999646da8ea48ff0796c2b0191aa510d062e/mqtt/client/client.go#L918-L1002 |
2,214 | yosssi/gmq | mqtt/client/client.go | generatePacketID | func (cli *Client) generatePacketID() (uint16, error) {
// Define a Packet Identifier.
id := minPacketID
for {
// Find a Packet Identifier which does not used.
if _, exist := cli.sess.sendingPackets[id]; !exist {
// Return the Packet Identifier.
return id, nil
}
if id == maxPacketID {
break
}
id++
}
// Return an error if available ids are not found.
return 0, ErrPacketIDExhaused
} | go | func (cli *Client) generatePacketID() (uint16, error) {
// Define a Packet Identifier.
id := minPacketID
for {
// Find a Packet Identifier which does not used.
if _, exist := cli.sess.sendingPackets[id]; !exist {
// Return the Packet Identifier.
return id, nil
}
if id == maxPacketID {
break
}
id++
}
// Return an error if available ids are not found.
return 0, ErrPacketIDExhaused
} | [
"func",
"(",
"cli",
"*",
"Client",
")",
"generatePacketID",
"(",
")",
"(",
"uint16",
",",
"error",
")",
"{",
"// Define a Packet Identifier.",
"id",
":=",
"minPacketID",
"\n\n",
"for",
"{",
"// Find a Packet Identifier which does not used.",
"if",
"_",
",",
"exist",
":=",
"cli",
".",
"sess",
".",
"sendingPackets",
"[",
"id",
"]",
";",
"!",
"exist",
"{",
"// Return the Packet Identifier.",
"return",
"id",
",",
"nil",
"\n",
"}",
"\n\n",
"if",
"id",
"==",
"maxPacketID",
"{",
"break",
"\n",
"}",
"\n\n",
"id",
"++",
"\n",
"}",
"\n\n",
"// Return an error if available ids are not found.",
"return",
"0",
",",
"ErrPacketIDExhaused",
"\n",
"}"
] | // generatePacketID generates and returns a Packet Identifier. | [
"generatePacketID",
"generates",
"and",
"returns",
"a",
"Packet",
"Identifier",
"."
] | b221999646da8ea48ff0796c2b0191aa510d062e | https://github.com/yosssi/gmq/blob/b221999646da8ea48ff0796c2b0191aa510d062e/mqtt/client/client.go#L1005-L1025 |
2,215 | yosssi/gmq | mqtt/client/client.go | newPUBLISHPacket | func (cli *Client) newPUBLISHPacket(opts *PublishOptions) (packet.Packet, error) {
// Define a Packet Identifier.
var packetID uint16
if opts.QoS != mqtt.QoS0 {
// Lock for reading and updating the Session.
cli.muSess.Lock()
defer cli.muSess.Unlock()
// Define an error.
var err error
// Generate a Packet Identifer.
if packetID, err = cli.generatePacketID(); err != nil {
return nil, err
}
}
// Create a PUBLISH Packet.
p, err := packet.NewPUBLISH(&packet.PUBLISHOptions{
QoS: opts.QoS,
Retain: opts.Retain,
TopicName: opts.TopicName,
PacketID: packetID,
Message: opts.Message,
})
if err != nil {
return nil, err
}
if opts.QoS != mqtt.QoS0 {
// Set the Packet to the Session.
cli.sess.sendingPackets[packetID] = p
}
// Return the Packet.
return p, nil
} | go | func (cli *Client) newPUBLISHPacket(opts *PublishOptions) (packet.Packet, error) {
// Define a Packet Identifier.
var packetID uint16
if opts.QoS != mqtt.QoS0 {
// Lock for reading and updating the Session.
cli.muSess.Lock()
defer cli.muSess.Unlock()
// Define an error.
var err error
// Generate a Packet Identifer.
if packetID, err = cli.generatePacketID(); err != nil {
return nil, err
}
}
// Create a PUBLISH Packet.
p, err := packet.NewPUBLISH(&packet.PUBLISHOptions{
QoS: opts.QoS,
Retain: opts.Retain,
TopicName: opts.TopicName,
PacketID: packetID,
Message: opts.Message,
})
if err != nil {
return nil, err
}
if opts.QoS != mqtt.QoS0 {
// Set the Packet to the Session.
cli.sess.sendingPackets[packetID] = p
}
// Return the Packet.
return p, nil
} | [
"func",
"(",
"cli",
"*",
"Client",
")",
"newPUBLISHPacket",
"(",
"opts",
"*",
"PublishOptions",
")",
"(",
"packet",
".",
"Packet",
",",
"error",
")",
"{",
"// Define a Packet Identifier.",
"var",
"packetID",
"uint16",
"\n\n",
"if",
"opts",
".",
"QoS",
"!=",
"mqtt",
".",
"QoS0",
"{",
"// Lock for reading and updating the Session.",
"cli",
".",
"muSess",
".",
"Lock",
"(",
")",
"\n\n",
"defer",
"cli",
".",
"muSess",
".",
"Unlock",
"(",
")",
"\n\n",
"// Define an error.",
"var",
"err",
"error",
"\n\n",
"// Generate a Packet Identifer.",
"if",
"packetID",
",",
"err",
"=",
"cli",
".",
"generatePacketID",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"}",
"\n\n",
"// Create a PUBLISH Packet.",
"p",
",",
"err",
":=",
"packet",
".",
"NewPUBLISH",
"(",
"&",
"packet",
".",
"PUBLISHOptions",
"{",
"QoS",
":",
"opts",
".",
"QoS",
",",
"Retain",
":",
"opts",
".",
"Retain",
",",
"TopicName",
":",
"opts",
".",
"TopicName",
",",
"PacketID",
":",
"packetID",
",",
"Message",
":",
"opts",
".",
"Message",
",",
"}",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"if",
"opts",
".",
"QoS",
"!=",
"mqtt",
".",
"QoS0",
"{",
"// Set the Packet to the Session.",
"cli",
".",
"sess",
".",
"sendingPackets",
"[",
"packetID",
"]",
"=",
"p",
"\n",
"}",
"\n\n",
"// Return the Packet.",
"return",
"p",
",",
"nil",
"\n",
"}"
] | // newPUBLISHPacket creates and returns a PUBLISH Packet. | [
"newPUBLISHPacket",
"creates",
"and",
"returns",
"a",
"PUBLISH",
"Packet",
"."
] | b221999646da8ea48ff0796c2b0191aa510d062e | https://github.com/yosssi/gmq/blob/b221999646da8ea48ff0796c2b0191aa510d062e/mqtt/client/client.go#L1028-L1066 |
2,216 | yosssi/gmq | mqtt/client/client.go | validatePacketID | func (cli *Client) validatePacketID(packets map[uint16]packet.Packet, id uint16, ptype byte) error {
// Extract the Packet.
p, exist := packets[id]
if !exist {
// Return an error if there is no Packet which has the Packet Identifier
// specified by the parameter.
return packet.ErrInvalidPacketID
}
// Extract the MQTT Control Packet type of the Packet.
t, err := p.Type()
if err != nil {
return err
}
if t != ptype {
// Return an error if the Packet's MQTT Control Packet type does not
// equal to one specified by the parameter.
return packet.ErrInvalidPacketID
}
return nil
} | go | func (cli *Client) validatePacketID(packets map[uint16]packet.Packet, id uint16, ptype byte) error {
// Extract the Packet.
p, exist := packets[id]
if !exist {
// Return an error if there is no Packet which has the Packet Identifier
// specified by the parameter.
return packet.ErrInvalidPacketID
}
// Extract the MQTT Control Packet type of the Packet.
t, err := p.Type()
if err != nil {
return err
}
if t != ptype {
// Return an error if the Packet's MQTT Control Packet type does not
// equal to one specified by the parameter.
return packet.ErrInvalidPacketID
}
return nil
} | [
"func",
"(",
"cli",
"*",
"Client",
")",
"validatePacketID",
"(",
"packets",
"map",
"[",
"uint16",
"]",
"packet",
".",
"Packet",
",",
"id",
"uint16",
",",
"ptype",
"byte",
")",
"error",
"{",
"// Extract the Packet.",
"p",
",",
"exist",
":=",
"packets",
"[",
"id",
"]",
"\n\n",
"if",
"!",
"exist",
"{",
"// Return an error if there is no Packet which has the Packet Identifier",
"// specified by the parameter.",
"return",
"packet",
".",
"ErrInvalidPacketID",
"\n",
"}",
"\n\n",
"// Extract the MQTT Control Packet type of the Packet.",
"t",
",",
"err",
":=",
"p",
".",
"Type",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"if",
"t",
"!=",
"ptype",
"{",
"// Return an error if the Packet's MQTT Control Packet type does not",
"// equal to one specified by the parameter.",
"return",
"packet",
".",
"ErrInvalidPacketID",
"\n",
"}",
"\n\n",
"return",
"nil",
"\n",
"}"
] | // validateSendingPacketID checks if the Packet which has
// the Packet Identifier and the MQTT Control Packet type
// specified by the parameters exists in the Session's
// sendingPackets. | [
"validateSendingPacketID",
"checks",
"if",
"the",
"Packet",
"which",
"has",
"the",
"Packet",
"Identifier",
"and",
"the",
"MQTT",
"Control",
"Packet",
"type",
"specified",
"by",
"the",
"parameters",
"exists",
"in",
"the",
"Session",
"s",
"sendingPackets",
"."
] | b221999646da8ea48ff0796c2b0191aa510d062e | https://github.com/yosssi/gmq/blob/b221999646da8ea48ff0796c2b0191aa510d062e/mqtt/client/client.go#L1072-L1095 |
2,217 | yosssi/gmq | mqtt/client/client.go | handleMessage | func (cli *Client) handleMessage(topicName, message []byte) {
// Get the string of the Topic Name.
topicNameStr := string(topicName)
for topicFilter, handler := range cli.conn.ackedSubs {
if handler == nil || !match(topicNameStr, topicFilter) {
continue
}
// Execute the handler.
go handler(topicName, message)
}
} | go | func (cli *Client) handleMessage(topicName, message []byte) {
// Get the string of the Topic Name.
topicNameStr := string(topicName)
for topicFilter, handler := range cli.conn.ackedSubs {
if handler == nil || !match(topicNameStr, topicFilter) {
continue
}
// Execute the handler.
go handler(topicName, message)
}
} | [
"func",
"(",
"cli",
"*",
"Client",
")",
"handleMessage",
"(",
"topicName",
",",
"message",
"[",
"]",
"byte",
")",
"{",
"// Get the string of the Topic Name.",
"topicNameStr",
":=",
"string",
"(",
"topicName",
")",
"\n\n",
"for",
"topicFilter",
",",
"handler",
":=",
"range",
"cli",
".",
"conn",
".",
"ackedSubs",
"{",
"if",
"handler",
"==",
"nil",
"||",
"!",
"match",
"(",
"topicNameStr",
",",
"topicFilter",
")",
"{",
"continue",
"\n",
"}",
"\n\n",
"// Execute the handler.",
"go",
"handler",
"(",
"topicName",
",",
"message",
")",
"\n",
"}",
"\n",
"}"
] | // handleMessage handles the Application Message. | [
"handleMessage",
"handles",
"the",
"Application",
"Message",
"."
] | b221999646da8ea48ff0796c2b0191aa510d062e | https://github.com/yosssi/gmq/blob/b221999646da8ea48ff0796c2b0191aa510d062e/mqtt/client/client.go#L1098-L1110 |
2,218 | yosssi/gmq | mqtt/client/client.go | New | func New(opts *Options) *Client {
// Initialize the options.
if opts == nil {
opts = &Options{}
}
// Create a Client.
cli := &Client{
disconnc: make(chan struct{}, 1),
disconnEndc: make(chan struct{}),
errorHandler: opts.ErrorHandler,
}
// Launch a goroutine which disconnects the Network Connection.
cli.wg.Add(1)
go func() {
defer func() {
cli.wg.Done()
}()
for {
select {
case <-cli.disconnc:
if err := cli.Disconnect(); err != nil {
if cli.errorHandler != nil {
cli.errorHandler(err)
}
}
case <-cli.disconnEndc:
// End the goroutine.
return
}
}
}()
// Return the Client.
return cli
} | go | func New(opts *Options) *Client {
// Initialize the options.
if opts == nil {
opts = &Options{}
}
// Create a Client.
cli := &Client{
disconnc: make(chan struct{}, 1),
disconnEndc: make(chan struct{}),
errorHandler: opts.ErrorHandler,
}
// Launch a goroutine which disconnects the Network Connection.
cli.wg.Add(1)
go func() {
defer func() {
cli.wg.Done()
}()
for {
select {
case <-cli.disconnc:
if err := cli.Disconnect(); err != nil {
if cli.errorHandler != nil {
cli.errorHandler(err)
}
}
case <-cli.disconnEndc:
// End the goroutine.
return
}
}
}()
// Return the Client.
return cli
} | [
"func",
"New",
"(",
"opts",
"*",
"Options",
")",
"*",
"Client",
"{",
"// Initialize the options.",
"if",
"opts",
"==",
"nil",
"{",
"opts",
"=",
"&",
"Options",
"{",
"}",
"\n",
"}",
"\n",
"// Create a Client.",
"cli",
":=",
"&",
"Client",
"{",
"disconnc",
":",
"make",
"(",
"chan",
"struct",
"{",
"}",
",",
"1",
")",
",",
"disconnEndc",
":",
"make",
"(",
"chan",
"struct",
"{",
"}",
")",
",",
"errorHandler",
":",
"opts",
".",
"ErrorHandler",
",",
"}",
"\n\n",
"// Launch a goroutine which disconnects the Network Connection.",
"cli",
".",
"wg",
".",
"Add",
"(",
"1",
")",
"\n",
"go",
"func",
"(",
")",
"{",
"defer",
"func",
"(",
")",
"{",
"cli",
".",
"wg",
".",
"Done",
"(",
")",
"\n",
"}",
"(",
")",
"\n\n",
"for",
"{",
"select",
"{",
"case",
"<-",
"cli",
".",
"disconnc",
":",
"if",
"err",
":=",
"cli",
".",
"Disconnect",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"if",
"cli",
".",
"errorHandler",
"!=",
"nil",
"{",
"cli",
".",
"errorHandler",
"(",
"err",
")",
"\n",
"}",
"\n",
"}",
"\n",
"case",
"<-",
"cli",
".",
"disconnEndc",
":",
"// End the goroutine.",
"return",
"\n",
"}",
"\n",
"}",
"\n\n",
"}",
"(",
")",
"\n\n",
"// Return the Client.",
"return",
"cli",
"\n",
"}"
] | // New creates and returns a Client. | [
"New",
"creates",
"and",
"returns",
"a",
"Client",
"."
] | b221999646da8ea48ff0796c2b0191aa510d062e | https://github.com/yosssi/gmq/blob/b221999646da8ea48ff0796c2b0191aa510d062e/mqtt/client/client.go#L1113-L1150 |
2,219 | yosssi/gmq | mqtt/client/client.go | match | func match(topicName, topicFilter string) bool {
// Tokenize the Topic Name.
nameTokens := strings.Split(topicName, "/")
nameTokensLen := len(nameTokens)
// Tolenize the Topic Filter.
filterTokens := strings.Split(topicFilter, "/")
for i, t := range filterTokens {
switch t {
case "#":
return i != 0 || !strings.HasPrefix(nameTokens[0], "$")
case "+":
if i == 0 && strings.HasPrefix(nameTokens[0], "$") {
return false
}
if nameTokensLen <= i {
return false
}
default:
if nameTokensLen <= i || t != nameTokens[i] {
return false
}
}
}
return len(filterTokens) == nameTokensLen
} | go | func match(topicName, topicFilter string) bool {
// Tokenize the Topic Name.
nameTokens := strings.Split(topicName, "/")
nameTokensLen := len(nameTokens)
// Tolenize the Topic Filter.
filterTokens := strings.Split(topicFilter, "/")
for i, t := range filterTokens {
switch t {
case "#":
return i != 0 || !strings.HasPrefix(nameTokens[0], "$")
case "+":
if i == 0 && strings.HasPrefix(nameTokens[0], "$") {
return false
}
if nameTokensLen <= i {
return false
}
default:
if nameTokensLen <= i || t != nameTokens[i] {
return false
}
}
}
return len(filterTokens) == nameTokensLen
} | [
"func",
"match",
"(",
"topicName",
",",
"topicFilter",
"string",
")",
"bool",
"{",
"// Tokenize the Topic Name.",
"nameTokens",
":=",
"strings",
".",
"Split",
"(",
"topicName",
",",
"\"",
"\"",
")",
"\n",
"nameTokensLen",
":=",
"len",
"(",
"nameTokens",
")",
"\n\n",
"// Tolenize the Topic Filter.",
"filterTokens",
":=",
"strings",
".",
"Split",
"(",
"topicFilter",
",",
"\"",
"\"",
")",
"\n\n",
"for",
"i",
",",
"t",
":=",
"range",
"filterTokens",
"{",
"switch",
"t",
"{",
"case",
"\"",
"\"",
":",
"return",
"i",
"!=",
"0",
"||",
"!",
"strings",
".",
"HasPrefix",
"(",
"nameTokens",
"[",
"0",
"]",
",",
"\"",
"\"",
")",
"\n",
"case",
"\"",
"\"",
":",
"if",
"i",
"==",
"0",
"&&",
"strings",
".",
"HasPrefix",
"(",
"nameTokens",
"[",
"0",
"]",
",",
"\"",
"\"",
")",
"{",
"return",
"false",
"\n",
"}",
"\n\n",
"if",
"nameTokensLen",
"<=",
"i",
"{",
"return",
"false",
"\n",
"}",
"\n",
"default",
":",
"if",
"nameTokensLen",
"<=",
"i",
"||",
"t",
"!=",
"nameTokens",
"[",
"i",
"]",
"{",
"return",
"false",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n\n",
"return",
"len",
"(",
"filterTokens",
")",
"==",
"nameTokensLen",
"\n",
"}"
] | // match checks if the Topic Name matches the Topic Filter. | [
"match",
"checks",
"if",
"the",
"Topic",
"Name",
"matches",
"the",
"Topic",
"Filter",
"."
] | b221999646da8ea48ff0796c2b0191aa510d062e | https://github.com/yosssi/gmq/blob/b221999646da8ea48ff0796c2b0191aa510d062e/mqtt/client/client.go#L1153-L1181 |
2,220 | yosssi/gmq | cmd/gmq-cli/command_unsub.go | newCommandUnsub | func newCommandUnsub(args []string, cli *client.Client) (command, error) {
// Create a flag set.
var flg flag.FlagSet
// Define the flags.
topicFilter := flg.String("t", "", "Topic Filter")
// Parse the flag.
if err := flg.Parse(args); err != nil {
return nil, errCmdArgsParse
}
// Create an unsub command.
cmd := &commandUnsub{
cli: cli,
unsubscribeOpts: &client.UnsubscribeOptions{
TopicFilters: [][]byte{
[]byte(*topicFilter),
},
},
}
// Return the command.
return cmd, nil
} | go | func newCommandUnsub(args []string, cli *client.Client) (command, error) {
// Create a flag set.
var flg flag.FlagSet
// Define the flags.
topicFilter := flg.String("t", "", "Topic Filter")
// Parse the flag.
if err := flg.Parse(args); err != nil {
return nil, errCmdArgsParse
}
// Create an unsub command.
cmd := &commandUnsub{
cli: cli,
unsubscribeOpts: &client.UnsubscribeOptions{
TopicFilters: [][]byte{
[]byte(*topicFilter),
},
},
}
// Return the command.
return cmd, nil
} | [
"func",
"newCommandUnsub",
"(",
"args",
"[",
"]",
"string",
",",
"cli",
"*",
"client",
".",
"Client",
")",
"(",
"command",
",",
"error",
")",
"{",
"// Create a flag set.",
"var",
"flg",
"flag",
".",
"FlagSet",
"\n\n",
"// Define the flags.",
"topicFilter",
":=",
"flg",
".",
"String",
"(",
"\"",
"\"",
",",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\n\n",
"// Parse the flag.",
"if",
"err",
":=",
"flg",
".",
"Parse",
"(",
"args",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"errCmdArgsParse",
"\n",
"}",
"\n\n",
"// Create an unsub command.",
"cmd",
":=",
"&",
"commandUnsub",
"{",
"cli",
":",
"cli",
",",
"unsubscribeOpts",
":",
"&",
"client",
".",
"UnsubscribeOptions",
"{",
"TopicFilters",
":",
"[",
"]",
"[",
"]",
"byte",
"{",
"[",
"]",
"byte",
"(",
"*",
"topicFilter",
")",
",",
"}",
",",
"}",
",",
"}",
"\n\n",
"// Return the command.",
"return",
"cmd",
",",
"nil",
"\n",
"}"
] | // newCommandUnsub creates and returns an unsub command. | [
"newCommandUnsub",
"creates",
"and",
"returns",
"an",
"unsub",
"command",
"."
] | b221999646da8ea48ff0796c2b0191aa510d062e | https://github.com/yosssi/gmq/blob/b221999646da8ea48ff0796c2b0191aa510d062e/cmd/gmq-cli/command_unsub.go#L24-L48 |
2,221 | yosssi/gmq | mqtt/packet/base.go | WriteTo | func (b *base) WriteTo(w io.Writer) (int64, error) {
// Create a byte buffer.
var bf bytes.Buffer
// Write the Packet data to the buffer.
bf.Write(b.fixedHeader)
bf.Write(b.variableHeader)
bf.Write(b.payload)
// Write the buffered data to the writer.
n, err := w.Write(bf.Bytes())
// Return the result.
return int64(n), err
} | go | func (b *base) WriteTo(w io.Writer) (int64, error) {
// Create a byte buffer.
var bf bytes.Buffer
// Write the Packet data to the buffer.
bf.Write(b.fixedHeader)
bf.Write(b.variableHeader)
bf.Write(b.payload)
// Write the buffered data to the writer.
n, err := w.Write(bf.Bytes())
// Return the result.
return int64(n), err
} | [
"func",
"(",
"b",
"*",
"base",
")",
"WriteTo",
"(",
"w",
"io",
".",
"Writer",
")",
"(",
"int64",
",",
"error",
")",
"{",
"// Create a byte buffer.",
"var",
"bf",
"bytes",
".",
"Buffer",
"\n\n",
"// Write the Packet data to the buffer.",
"bf",
".",
"Write",
"(",
"b",
".",
"fixedHeader",
")",
"\n",
"bf",
".",
"Write",
"(",
"b",
".",
"variableHeader",
")",
"\n",
"bf",
".",
"Write",
"(",
"b",
".",
"payload",
")",
"\n\n",
"// Write the buffered data to the writer.",
"n",
",",
"err",
":=",
"w",
".",
"Write",
"(",
"bf",
".",
"Bytes",
"(",
")",
")",
"\n\n",
"// Return the result.",
"return",
"int64",
"(",
"n",
")",
",",
"err",
"\n",
"}"
] | // WriteTo writes the Packet data to the writer. | [
"WriteTo",
"writes",
"the",
"Packet",
"data",
"to",
"the",
"writer",
"."
] | b221999646da8ea48ff0796c2b0191aa510d062e | https://github.com/yosssi/gmq/blob/b221999646da8ea48ff0796c2b0191aa510d062e/mqtt/packet/base.go#L20-L34 |
2,222 | yosssi/gmq | mqtt/packet/base.go | appendRemainingLength | func (b *base) appendRemainingLength() {
// Calculate and encode the Remaining Length.
rl := encodeLength(uint32(len(b.variableHeader) + len(b.payload)))
// Append the Remaining Length to the fixed header.
b.fixedHeader = appendRemainingLength(b.fixedHeader, rl)
} | go | func (b *base) appendRemainingLength() {
// Calculate and encode the Remaining Length.
rl := encodeLength(uint32(len(b.variableHeader) + len(b.payload)))
// Append the Remaining Length to the fixed header.
b.fixedHeader = appendRemainingLength(b.fixedHeader, rl)
} | [
"func",
"(",
"b",
"*",
"base",
")",
"appendRemainingLength",
"(",
")",
"{",
"// Calculate and encode the Remaining Length.",
"rl",
":=",
"encodeLength",
"(",
"uint32",
"(",
"len",
"(",
"b",
".",
"variableHeader",
")",
"+",
"len",
"(",
"b",
".",
"payload",
")",
")",
")",
"\n\n",
"// Append the Remaining Length to the fixed header.",
"b",
".",
"fixedHeader",
"=",
"appendRemainingLength",
"(",
"b",
".",
"fixedHeader",
",",
"rl",
")",
"\n",
"}"
] | // appendRemainingLength appends the Remaining Length
// to the fixed header. | [
"appendRemainingLength",
"appends",
"the",
"Remaining",
"Length",
"to",
"the",
"fixed",
"header",
"."
] | b221999646da8ea48ff0796c2b0191aa510d062e | https://github.com/yosssi/gmq/blob/b221999646da8ea48ff0796c2b0191aa510d062e/mqtt/packet/base.go#L44-L50 |
2,223 | yosssi/gmq | mqtt/packet/base.go | appendRemainingLength | func appendRemainingLength(b []byte, rl uint32) []byte {
// Append the Remaining Length to the slice.
switch {
case rl&0xFF000000 > 0:
b = append(b, byte((rl&0xFF000000)>>24))
fallthrough
case rl&0x00FF0000 > 0:
b = append(b, byte((rl&0x00FF0000)>>16))
fallthrough
case rl&0x0000FF00 > 0:
b = append(b, byte((rl&0x0000FF00)>>8))
fallthrough
default:
b = append(b, byte(rl&0x000000FF))
}
// Return the slice.
return b
} | go | func appendRemainingLength(b []byte, rl uint32) []byte {
// Append the Remaining Length to the slice.
switch {
case rl&0xFF000000 > 0:
b = append(b, byte((rl&0xFF000000)>>24))
fallthrough
case rl&0x00FF0000 > 0:
b = append(b, byte((rl&0x00FF0000)>>16))
fallthrough
case rl&0x0000FF00 > 0:
b = append(b, byte((rl&0x0000FF00)>>8))
fallthrough
default:
b = append(b, byte(rl&0x000000FF))
}
// Return the slice.
return b
} | [
"func",
"appendRemainingLength",
"(",
"b",
"[",
"]",
"byte",
",",
"rl",
"uint32",
")",
"[",
"]",
"byte",
"{",
"// Append the Remaining Length to the slice.",
"switch",
"{",
"case",
"rl",
"&",
"0xFF000000",
">",
"0",
":",
"b",
"=",
"append",
"(",
"b",
",",
"byte",
"(",
"(",
"rl",
"&",
"0xFF000000",
")",
">>",
"24",
")",
")",
"\n",
"fallthrough",
"\n",
"case",
"rl",
"&",
"0x00FF0000",
">",
"0",
":",
"b",
"=",
"append",
"(",
"b",
",",
"byte",
"(",
"(",
"rl",
"&",
"0x00FF0000",
")",
">>",
"16",
")",
")",
"\n",
"fallthrough",
"\n",
"case",
"rl",
"&",
"0x0000FF00",
">",
"0",
":",
"b",
"=",
"append",
"(",
"b",
",",
"byte",
"(",
"(",
"rl",
"&",
"0x0000FF00",
")",
">>",
"8",
")",
")",
"\n",
"fallthrough",
"\n",
"default",
":",
"b",
"=",
"append",
"(",
"b",
",",
"byte",
"(",
"rl",
"&",
"0x000000FF",
")",
")",
"\n",
"}",
"\n\n",
"// Return the slice.",
"return",
"b",
"\n",
"}"
] | // appendRemainingLength appends the Remaining Length
// to the slice and returns it. | [
"appendRemainingLength",
"appends",
"the",
"Remaining",
"Length",
"to",
"the",
"slice",
"and",
"returns",
"it",
"."
] | b221999646da8ea48ff0796c2b0191aa510d062e | https://github.com/yosssi/gmq/blob/b221999646da8ea48ff0796c2b0191aa510d062e/mqtt/packet/base.go#L54-L72 |
2,224 | ogier/pflag | flag.go | PrintDefaults | func (f *FlagSet) PrintDefaults() {
f.VisitAll(func(flag *Flag) {
s := ""
if len(flag.Shorthand) > 0 {
s = fmt.Sprintf(" -%s, --%s", flag.Shorthand, flag.Name)
} else {
s = fmt.Sprintf(" --%s", flag.Name)
}
name, usage := UnquoteUsage(flag)
if len(name) > 0 {
s += " " + name
}
s += "\n \t"
s += usage
if !isZeroValue(flag.DefValue) {
if _, ok := flag.Value.(*stringValue); ok {
// put quotes on the value
s += fmt.Sprintf(" (default %q)", flag.DefValue)
} else {
s += fmt.Sprintf(" (default %v)", flag.DefValue)
}
}
fmt.Fprint(f.out(), s, "\n")
})
} | go | func (f *FlagSet) PrintDefaults() {
f.VisitAll(func(flag *Flag) {
s := ""
if len(flag.Shorthand) > 0 {
s = fmt.Sprintf(" -%s, --%s", flag.Shorthand, flag.Name)
} else {
s = fmt.Sprintf(" --%s", flag.Name)
}
name, usage := UnquoteUsage(flag)
if len(name) > 0 {
s += " " + name
}
s += "\n \t"
s += usage
if !isZeroValue(flag.DefValue) {
if _, ok := flag.Value.(*stringValue); ok {
// put quotes on the value
s += fmt.Sprintf(" (default %q)", flag.DefValue)
} else {
s += fmt.Sprintf(" (default %v)", flag.DefValue)
}
}
fmt.Fprint(f.out(), s, "\n")
})
} | [
"func",
"(",
"f",
"*",
"FlagSet",
")",
"PrintDefaults",
"(",
")",
"{",
"f",
".",
"VisitAll",
"(",
"func",
"(",
"flag",
"*",
"Flag",
")",
"{",
"s",
":=",
"\"",
"\"",
"\n",
"if",
"len",
"(",
"flag",
".",
"Shorthand",
")",
">",
"0",
"{",
"s",
"=",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"flag",
".",
"Shorthand",
",",
"flag",
".",
"Name",
")",
"\n",
"}",
"else",
"{",
"s",
"=",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"flag",
".",
"Name",
")",
"\n",
"}",
"\n\n",
"name",
",",
"usage",
":=",
"UnquoteUsage",
"(",
"flag",
")",
"\n",
"if",
"len",
"(",
"name",
")",
">",
"0",
"{",
"s",
"+=",
"\"",
"\"",
"+",
"name",
"\n",
"}",
"\n\n",
"s",
"+=",
"\"",
"\\n",
"\\t",
"\"",
"\n",
"s",
"+=",
"usage",
"\n",
"if",
"!",
"isZeroValue",
"(",
"flag",
".",
"DefValue",
")",
"{",
"if",
"_",
",",
"ok",
":=",
"flag",
".",
"Value",
".",
"(",
"*",
"stringValue",
")",
";",
"ok",
"{",
"// put quotes on the value",
"s",
"+=",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"flag",
".",
"DefValue",
")",
"\n",
"}",
"else",
"{",
"s",
"+=",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"flag",
".",
"DefValue",
")",
"\n",
"}",
"\n",
"}",
"\n",
"fmt",
".",
"Fprint",
"(",
"f",
".",
"out",
"(",
")",
",",
"s",
",",
"\"",
"\\n",
"\"",
")",
"\n",
"}",
")",
"\n",
"}"
] | // PrintDefaults prints to standard error the default values of all
// defined command-line flags in the set. See the documentation for
// the global function PrintDefaults for more information. | [
"PrintDefaults",
"prints",
"to",
"standard",
"error",
"the",
"default",
"values",
"of",
"all",
"defined",
"command",
"-",
"line",
"flags",
"in",
"the",
"set",
".",
"See",
"the",
"documentation",
"for",
"the",
"global",
"function",
"PrintDefaults",
"for",
"more",
"information",
"."
] | 45c278ab3607870051a2ea9040bb85fcb8557481 | https://github.com/ogier/pflag/blob/45c278ab3607870051a2ea9040bb85fcb8557481/flag.go#L296-L322 |
2,225 | ogier/pflag | ip.go | IP | func (f *FlagSet) IP(name string, value net.IP, usage string) *net.IP {
p := new(net.IP)
f.IPVarP(p, name, "", value, usage)
return p
} | go | func (f *FlagSet) IP(name string, value net.IP, usage string) *net.IP {
p := new(net.IP)
f.IPVarP(p, name, "", value, usage)
return p
} | [
"func",
"(",
"f",
"*",
"FlagSet",
")",
"IP",
"(",
"name",
"string",
",",
"value",
"net",
".",
"IP",
",",
"usage",
"string",
")",
"*",
"net",
".",
"IP",
"{",
"p",
":=",
"new",
"(",
"net",
".",
"IP",
")",
"\n",
"f",
".",
"IPVarP",
"(",
"p",
",",
"name",
",",
"\"",
"\"",
",",
"value",
",",
"usage",
")",
"\n",
"return",
"p",
"\n",
"}"
] | // IP defines an net.IP flag with specified name, default value, and usage string.
// The return value is the address of an net.IP variable that stores the value of the flag. | [
"IP",
"defines",
"an",
"net",
".",
"IP",
"flag",
"with",
"specified",
"name",
"default",
"value",
"and",
"usage",
"string",
".",
"The",
"return",
"value",
"is",
"the",
"address",
"of",
"an",
"net",
".",
"IP",
"variable",
"that",
"stores",
"the",
"value",
"of",
"the",
"flag",
"."
] | 45c278ab3607870051a2ea9040bb85fcb8557481 | https://github.com/ogier/pflag/blob/45c278ab3607870051a2ea9040bb85fcb8557481/ip.go#L53-L57 |
2,226 | ogier/pflag | ip.go | IPP | func IPP(name, shorthand string, value net.IP, usage string) *net.IP {
return CommandLine.IPP(name, shorthand, value, usage)
} | go | func IPP(name, shorthand string, value net.IP, usage string) *net.IP {
return CommandLine.IPP(name, shorthand, value, usage)
} | [
"func",
"IPP",
"(",
"name",
",",
"shorthand",
"string",
",",
"value",
"net",
".",
"IP",
",",
"usage",
"string",
")",
"*",
"net",
".",
"IP",
"{",
"return",
"CommandLine",
".",
"IPP",
"(",
"name",
",",
"shorthand",
",",
"value",
",",
"usage",
")",
"\n",
"}"
] | // Like IP, but accepts a shorthand letter that can be used after a single dash. | [
"Like",
"IP",
"but",
"accepts",
"a",
"shorthand",
"letter",
"that",
"can",
"be",
"used",
"after",
"a",
"single",
"dash",
"."
] | 45c278ab3607870051a2ea9040bb85fcb8557481 | https://github.com/ogier/pflag/blob/45c278ab3607870051a2ea9040bb85fcb8557481/ip.go#L73-L75 |
2,227 | tucnak/climax | context.go | Is | func (c *Context) Is(flagName string) bool {
if _, ok := c.NonVariable[flagName]; ok {
return true
}
if _, ok := c.Variable[flagName]; ok {
return true
}
return false
} | go | func (c *Context) Is(flagName string) bool {
if _, ok := c.NonVariable[flagName]; ok {
return true
}
if _, ok := c.Variable[flagName]; ok {
return true
}
return false
} | [
"func",
"(",
"c",
"*",
"Context",
")",
"Is",
"(",
"flagName",
"string",
")",
"bool",
"{",
"if",
"_",
",",
"ok",
":=",
"c",
".",
"NonVariable",
"[",
"flagName",
"]",
";",
"ok",
"{",
"return",
"true",
"\n",
"}",
"\n\n",
"if",
"_",
",",
"ok",
":=",
"c",
".",
"Variable",
"[",
"flagName",
"]",
";",
"ok",
"{",
"return",
"true",
"\n",
"}",
"\n\n",
"return",
"false",
"\n",
"}"
] | // Is returns true if a flag with corresponding name is defined. | [
"Is",
"returns",
"true",
"if",
"a",
"flag",
"with",
"corresponding",
"name",
"is",
"defined",
"."
] | da4c02f3b1f8ee2c27bb2a8910fe692900d8fc26 | https://github.com/tucnak/climax/blob/da4c02f3b1f8ee2c27bb2a8910fe692900d8fc26/context.go#L33-L43 |
2,228 | tucnak/climax | application.go | AddGroup | func (a *Application) AddGroup(name string) string {
a.Groups = append(a.Groups, Group{Name: name})
return name
} | go | func (a *Application) AddGroup(name string) string {
a.Groups = append(a.Groups, Group{Name: name})
return name
} | [
"func",
"(",
"a",
"*",
"Application",
")",
"AddGroup",
"(",
"name",
"string",
")",
"string",
"{",
"a",
".",
"Groups",
"=",
"append",
"(",
"a",
".",
"Groups",
",",
"Group",
"{",
"Name",
":",
"name",
"}",
")",
"\n",
"return",
"name",
"\n",
"}"
] | // AddGroup adds a new empty, named group.
//
// Pass the returned group name to Command's Group member
// to make the command part of the group. | [
"AddGroup",
"adds",
"a",
"new",
"empty",
"named",
"group",
".",
"Pass",
"the",
"returned",
"group",
"name",
"to",
"Command",
"s",
"Group",
"member",
"to",
"make",
"the",
"command",
"part",
"of",
"the",
"group",
"."
] | da4c02f3b1f8ee2c27bb2a8910fe692900d8fc26 | https://github.com/tucnak/climax/blob/da4c02f3b1f8ee2c27bb2a8910fe692900d8fc26/application.go#L101-L104 |
2,229 | tucnak/climax | application.go | AddCommand | func (a *Application) AddCommand(command Command) {
a.Commands = append(a.Commands, command)
newCmd := &a.Commands[len(a.Commands)-1]
if newCmd.Group != "" {
group := a.groupByName(newCmd.Group)
if group == nil {
panic("group doesn't exist")
}
group.Commands = append(group.Commands, newCmd)
} else {
a.ungroupedCmdsCount++
}
} | go | func (a *Application) AddCommand(command Command) {
a.Commands = append(a.Commands, command)
newCmd := &a.Commands[len(a.Commands)-1]
if newCmd.Group != "" {
group := a.groupByName(newCmd.Group)
if group == nil {
panic("group doesn't exist")
}
group.Commands = append(group.Commands, newCmd)
} else {
a.ungroupedCmdsCount++
}
} | [
"func",
"(",
"a",
"*",
"Application",
")",
"AddCommand",
"(",
"command",
"Command",
")",
"{",
"a",
".",
"Commands",
"=",
"append",
"(",
"a",
".",
"Commands",
",",
"command",
")",
"\n\n",
"newCmd",
":=",
"&",
"a",
".",
"Commands",
"[",
"len",
"(",
"a",
".",
"Commands",
")",
"-",
"1",
"]",
"\n",
"if",
"newCmd",
".",
"Group",
"!=",
"\"",
"\"",
"{",
"group",
":=",
"a",
".",
"groupByName",
"(",
"newCmd",
".",
"Group",
")",
"\n",
"if",
"group",
"==",
"nil",
"{",
"panic",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"group",
".",
"Commands",
"=",
"append",
"(",
"group",
".",
"Commands",
",",
"newCmd",
")",
"\n",
"}",
"else",
"{",
"a",
".",
"ungroupedCmdsCount",
"++",
"\n",
"}",
"\n",
"}"
] | // AddCommand does literally what its name says. | [
"AddCommand",
"does",
"literally",
"what",
"its",
"name",
"says",
"."
] | da4c02f3b1f8ee2c27bb2a8910fe692900d8fc26 | https://github.com/tucnak/climax/blob/da4c02f3b1f8ee2c27bb2a8910fe692900d8fc26/application.go#L107-L121 |
2,230 | tucnak/climax | application.go | AddTopic | func (a *Application) AddTopic(topic Topic) {
a.Topics = append(a.Topics, topic)
} | go | func (a *Application) AddTopic(topic Topic) {
a.Topics = append(a.Topics, topic)
} | [
"func",
"(",
"a",
"*",
"Application",
")",
"AddTopic",
"(",
"topic",
"Topic",
")",
"{",
"a",
".",
"Topics",
"=",
"append",
"(",
"a",
".",
"Topics",
",",
"topic",
")",
"\n",
"}"
] | // AddTopic does literally what its name says. | [
"AddTopic",
"does",
"literally",
"what",
"its",
"name",
"says",
"."
] | da4c02f3b1f8ee2c27bb2a8910fe692900d8fc26 | https://github.com/tucnak/climax/blob/da4c02f3b1f8ee2c27bb2a8910fe692900d8fc26/application.go#L124-L126 |
2,231 | tucnak/climax | command.go | AddFlag | func (c *Command) AddFlag(newFlag Flag) {
c.Flags = append(c.Flags, newFlag)
} | go | func (c *Command) AddFlag(newFlag Flag) {
c.Flags = append(c.Flags, newFlag)
} | [
"func",
"(",
"c",
"*",
"Command",
")",
"AddFlag",
"(",
"newFlag",
"Flag",
")",
"{",
"c",
".",
"Flags",
"=",
"append",
"(",
"c",
".",
"Flags",
",",
"newFlag",
")",
"\n",
"}"
] | // AddFlag does literally what its name says. | [
"AddFlag",
"does",
"literally",
"what",
"its",
"name",
"says",
"."
] | da4c02f3b1f8ee2c27bb2a8910fe692900d8fc26 | https://github.com/tucnak/climax/blob/da4c02f3b1f8ee2c27bb2a8910fe692900d8fc26/command.go#L57-L59 |
2,232 | tucnak/climax | command.go | AddExample | func (c *Command) AddExample(newExample Example) {
c.Examples = append(c.Examples, newExample)
} | go | func (c *Command) AddExample(newExample Example) {
c.Examples = append(c.Examples, newExample)
} | [
"func",
"(",
"c",
"*",
"Command",
")",
"AddExample",
"(",
"newExample",
"Example",
")",
"{",
"c",
".",
"Examples",
"=",
"append",
"(",
"c",
".",
"Examples",
",",
"newExample",
")",
"\n",
"}"
] | // AddExample does exactly what its name says. | [
"AddExample",
"does",
"exactly",
"what",
"its",
"name",
"says",
"."
] | da4c02f3b1f8ee2c27bb2a8910fe692900d8fc26 | https://github.com/tucnak/climax/blob/da4c02f3b1f8ee2c27bb2a8910fe692900d8fc26/command.go#L62-L64 |
2,233 | schemalex/schemalex | tokens_gen.go | NewToken | func NewToken(t TokenType, v string) *Token {
return &Token{Type: t, Value: v}
} | go | func NewToken(t TokenType, v string) *Token {
return &Token{Type: t, Value: v}
} | [
"func",
"NewToken",
"(",
"t",
"TokenType",
",",
"v",
"string",
")",
"*",
"Token",
"{",
"return",
"&",
"Token",
"{",
"Type",
":",
"t",
",",
"Value",
":",
"v",
"}",
"\n",
"}"
] | // NewToken creates a new token of type `t`, with value `v` | [
"NewToken",
"creates",
"a",
"new",
"token",
"of",
"type",
"t",
"with",
"value",
"v"
] | 082f7dd92f9145e57574d872d4718fe5145d9c12 | https://github.com/schemalex/schemalex/blob/082f7dd92f9145e57574d872d4718fe5145d9c12/tokens_gen.go#L19-L21 |
2,234 | schemalex/schemalex | model/statement.go | Lookup | func (s Stmts) Lookup(id string) (Stmt, bool) {
for _, stmt := range s {
if stmt.ID() == id {
return stmt, true
}
}
return nil, false
} | go | func (s Stmts) Lookup(id string) (Stmt, bool) {
for _, stmt := range s {
if stmt.ID() == id {
return stmt, true
}
}
return nil, false
} | [
"func",
"(",
"s",
"Stmts",
")",
"Lookup",
"(",
"id",
"string",
")",
"(",
"Stmt",
",",
"bool",
")",
"{",
"for",
"_",
",",
"stmt",
":=",
"range",
"s",
"{",
"if",
"stmt",
".",
"ID",
"(",
")",
"==",
"id",
"{",
"return",
"stmt",
",",
"true",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"nil",
",",
"false",
"\n",
"}"
] | // Lookup looks for a statement with the given ID | [
"Lookup",
"looks",
"for",
"a",
"statement",
"with",
"the",
"given",
"ID"
] | 082f7dd92f9145e57574d872d4718fe5145d9c12 | https://github.com/schemalex/schemalex/blob/082f7dd92f9145e57574d872d4718fe5145d9c12/model/statement.go#L4-L11 |
2,235 | schemalex/schemalex | model/columns_gen.go | SynonymType | func (c ColumnType) SynonymType() ColumnType {
switch c {
case ColumnTypeBool:
return ColumnTypeTinyInt
case ColumnTypeBoolean:
return ColumnTypeTinyInt
case ColumnTypeInteger:
return ColumnTypeInt
case ColumnTypeNumeric:
return ColumnTypeDecimal
case ColumnTypeReal:
return ColumnTypeDouble
}
return c
} | go | func (c ColumnType) SynonymType() ColumnType {
switch c {
case ColumnTypeBool:
return ColumnTypeTinyInt
case ColumnTypeBoolean:
return ColumnTypeTinyInt
case ColumnTypeInteger:
return ColumnTypeInt
case ColumnTypeNumeric:
return ColumnTypeDecimal
case ColumnTypeReal:
return ColumnTypeDouble
}
return c
} | [
"func",
"(",
"c",
"ColumnType",
")",
"SynonymType",
"(",
")",
"ColumnType",
"{",
"switch",
"c",
"{",
"case",
"ColumnTypeBool",
":",
"return",
"ColumnTypeTinyInt",
"\n",
"case",
"ColumnTypeBoolean",
":",
"return",
"ColumnTypeTinyInt",
"\n",
"case",
"ColumnTypeInteger",
":",
"return",
"ColumnTypeInt",
"\n",
"case",
"ColumnTypeNumeric",
":",
"return",
"ColumnTypeDecimal",
"\n",
"case",
"ColumnTypeReal",
":",
"return",
"ColumnTypeDouble",
"\n",
"}",
"\n",
"return",
"c",
"\n",
"}"
] | // SynonymType returns synonym for a given type.
// If the type does not have a synonym then this method returns the receiver itself | [
"SynonymType",
"returns",
"synonym",
"for",
"a",
"given",
"type",
".",
"If",
"the",
"type",
"does",
"not",
"have",
"a",
"synonym",
"then",
"this",
"method",
"returns",
"the",
"receiver",
"itself"
] | 082f7dd92f9145e57574d872d4718fe5145d9c12 | https://github.com/schemalex/schemalex/blob/082f7dd92f9145e57574d872d4718fe5145d9c12/model/columns_gen.go#L126-L140 |
2,236 | schemalex/schemalex | model/index.go | NewIndex | func NewIndex(kind IndexKind, table string) Index {
return &index{
kind: kind,
table: table,
}
} | go | func NewIndex(kind IndexKind, table string) Index {
return &index{
kind: kind,
table: table,
}
} | [
"func",
"NewIndex",
"(",
"kind",
"IndexKind",
",",
"table",
"string",
")",
"Index",
"{",
"return",
"&",
"index",
"{",
"kind",
":",
"kind",
",",
"table",
":",
"table",
",",
"}",
"\n",
"}"
] | // NewIndex creates a new index with the given index kind. | [
"NewIndex",
"creates",
"a",
"new",
"index",
"with",
"the",
"given",
"index",
"kind",
"."
] | 082f7dd92f9145e57574d872d4718fe5145d9c12 | https://github.com/schemalex/schemalex/blob/082f7dd92f9145e57574d872d4718fe5145d9c12/model/index.go#L9-L14 |
2,237 | schemalex/schemalex | errors.go | Error | func (e parseError) Error() string {
var buf bytes.Buffer
buf.WriteString("parse error: ")
buf.WriteString(e.message)
if f := e.file; len(f) > 0 {
buf.WriteString(" in file ")
buf.WriteString(f)
}
buf.WriteString(" at line ")
buf.WriteString(strconv.Itoa(e.line))
buf.WriteString(" column ")
buf.WriteString(strconv.Itoa(e.col))
if e.eof {
buf.WriteString(" (at EOF)")
}
buf.WriteString("\n ")
buf.WriteString(e.context)
return buf.String()
} | go | func (e parseError) Error() string {
var buf bytes.Buffer
buf.WriteString("parse error: ")
buf.WriteString(e.message)
if f := e.file; len(f) > 0 {
buf.WriteString(" in file ")
buf.WriteString(f)
}
buf.WriteString(" at line ")
buf.WriteString(strconv.Itoa(e.line))
buf.WriteString(" column ")
buf.WriteString(strconv.Itoa(e.col))
if e.eof {
buf.WriteString(" (at EOF)")
}
buf.WriteString("\n ")
buf.WriteString(e.context)
return buf.String()
} | [
"func",
"(",
"e",
"parseError",
")",
"Error",
"(",
")",
"string",
"{",
"var",
"buf",
"bytes",
".",
"Buffer",
"\n",
"buf",
".",
"WriteString",
"(",
"\"",
"\"",
")",
"\n",
"buf",
".",
"WriteString",
"(",
"e",
".",
"message",
")",
"\n",
"if",
"f",
":=",
"e",
".",
"file",
";",
"len",
"(",
"f",
")",
">",
"0",
"{",
"buf",
".",
"WriteString",
"(",
"\"",
"\"",
")",
"\n",
"buf",
".",
"WriteString",
"(",
"f",
")",
"\n",
"}",
"\n",
"buf",
".",
"WriteString",
"(",
"\"",
"\"",
")",
"\n",
"buf",
".",
"WriteString",
"(",
"strconv",
".",
"Itoa",
"(",
"e",
".",
"line",
")",
")",
"\n",
"buf",
".",
"WriteString",
"(",
"\"",
"\"",
")",
"\n",
"buf",
".",
"WriteString",
"(",
"strconv",
".",
"Itoa",
"(",
"e",
".",
"col",
")",
")",
"\n",
"if",
"e",
".",
"eof",
"{",
"buf",
".",
"WriteString",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"buf",
".",
"WriteString",
"(",
"\"",
"\\n",
"\"",
")",
"\n",
"buf",
".",
"WriteString",
"(",
"e",
".",
"context",
")",
"\n",
"return",
"buf",
".",
"String",
"(",
")",
"\n",
"}"
] | // Error returns the formatted string representation of this parse error. | [
"Error",
"returns",
"the",
"formatted",
"string",
"representation",
"of",
"this",
"parse",
"error",
"."
] | 082f7dd92f9145e57574d872d4718fe5145d9c12 | https://github.com/schemalex/schemalex/blob/082f7dd92f9145e57574d872d4718fe5145d9c12/errors.go#L49-L67 |
2,238 | schemalex/schemalex | source.go | NewLocalGitSource | func NewLocalGitSource(gitDir, file, commitish string) SchemaSource {
return &localGitSource{
dir: gitDir,
file: file,
commitish: commitish,
}
} | go | func NewLocalGitSource(gitDir, file, commitish string) SchemaSource {
return &localGitSource{
dir: gitDir,
file: file,
commitish: commitish,
}
} | [
"func",
"NewLocalGitSource",
"(",
"gitDir",
",",
"file",
",",
"commitish",
"string",
")",
"SchemaSource",
"{",
"return",
"&",
"localGitSource",
"{",
"dir",
":",
"gitDir",
",",
"file",
":",
"file",
",",
"commitish",
":",
"commitish",
",",
"}",
"\n",
"}"
] | // NewLocalGitSource creates a SchemaSource whose contents are derived from
// the given file at the given commit ID in a git repository. | [
"NewLocalGitSource",
"creates",
"a",
"SchemaSource",
"whose",
"contents",
"are",
"derived",
"from",
"the",
"given",
"file",
"at",
"the",
"given",
"commit",
"ID",
"in",
"a",
"git",
"repository",
"."
] | 082f7dd92f9145e57574d872d4718fe5145d9c12 | https://github.com/schemalex/schemalex/blob/082f7dd92f9145e57574d872d4718fe5145d9c12/source.go#L110-L116 |
2,239 | schemalex/schemalex | model/table.go | NewTable | func NewTable(name string) Table {
return &table{
name: name,
columnNameToIndex: make(map[string]int),
}
} | go | func NewTable(name string) Table {
return &table{
name: name,
columnNameToIndex: make(map[string]int),
}
} | [
"func",
"NewTable",
"(",
"name",
"string",
")",
"Table",
"{",
"return",
"&",
"table",
"{",
"name",
":",
"name",
",",
"columnNameToIndex",
":",
"make",
"(",
"map",
"[",
"string",
"]",
"int",
")",
",",
"}",
"\n",
"}"
] | // NewTable create a new table with the given name | [
"NewTable",
"create",
"a",
"new",
"table",
"with",
"the",
"given",
"name"
] | 082f7dd92f9145e57574d872d4718fe5145d9c12 | https://github.com/schemalex/schemalex/blob/082f7dd92f9145e57574d872d4718fe5145d9c12/model/table.go#L4-L9 |
2,240 | schemalex/schemalex | model/table.go | NewTableOption | func NewTableOption(k, v string, q bool) TableOption {
return &tableopt{
key: k,
value: v,
needQuotes: q,
}
} | go | func NewTableOption(k, v string, q bool) TableOption {
return &tableopt{
key: k,
value: v,
needQuotes: q,
}
} | [
"func",
"NewTableOption",
"(",
"k",
",",
"v",
"string",
",",
"q",
"bool",
")",
"TableOption",
"{",
"return",
"&",
"tableopt",
"{",
"key",
":",
"k",
",",
"value",
":",
"v",
",",
"needQuotes",
":",
"q",
",",
"}",
"\n",
"}"
] | // NewTableOption creates a new table option with the given name, value, and a flag indicating if quoting is necessary | [
"NewTableOption",
"creates",
"a",
"new",
"table",
"option",
"with",
"the",
"given",
"name",
"value",
"and",
"a",
"flag",
"indicating",
"if",
"quoting",
"is",
"necessary"
] | 082f7dd92f9145e57574d872d4718fe5145d9c12 | https://github.com/schemalex/schemalex/blob/082f7dd92f9145e57574d872d4718fe5145d9c12/model/table.go#L257-L263 |
2,241 | schemalex/schemalex | parser.go | ParseFile | func (p *Parser) ParseFile(fn string) (model.Stmts, error) {
src, err := ioutil.ReadFile(fn)
if err != nil {
return nil, errors.Wrapf(err, `failed to open file %s`, fn)
}
stmts, err := p.Parse(src)
if err != nil {
if pe, ok := err.(*parseError); ok {
pe.file = fn
}
return nil, err
}
return stmts, nil
} | go | func (p *Parser) ParseFile(fn string) (model.Stmts, error) {
src, err := ioutil.ReadFile(fn)
if err != nil {
return nil, errors.Wrapf(err, `failed to open file %s`, fn)
}
stmts, err := p.Parse(src)
if err != nil {
if pe, ok := err.(*parseError); ok {
pe.file = fn
}
return nil, err
}
return stmts, nil
} | [
"func",
"(",
"p",
"*",
"Parser",
")",
"ParseFile",
"(",
"fn",
"string",
")",
"(",
"model",
".",
"Stmts",
",",
"error",
")",
"{",
"src",
",",
"err",
":=",
"ioutil",
".",
"ReadFile",
"(",
"fn",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"errors",
".",
"Wrapf",
"(",
"err",
",",
"`failed to open file %s`",
",",
"fn",
")",
"\n",
"}",
"\n\n",
"stmts",
",",
"err",
":=",
"p",
".",
"Parse",
"(",
"src",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"if",
"pe",
",",
"ok",
":=",
"err",
".",
"(",
"*",
"parseError",
")",
";",
"ok",
"{",
"pe",
".",
"file",
"=",
"fn",
"\n",
"}",
"\n",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"return",
"stmts",
",",
"nil",
"\n",
"}"
] | // ParseFile parses a file containing SQL statements and creates
// a mode.Stmts structure.
// See Parse for details. | [
"ParseFile",
"parses",
"a",
"file",
"containing",
"SQL",
"statements",
"and",
"creates",
"a",
"mode",
".",
"Stmts",
"structure",
".",
"See",
"Parse",
"for",
"details",
"."
] | 082f7dd92f9145e57574d872d4718fe5145d9c12 | https://github.com/schemalex/schemalex/blob/082f7dd92f9145e57574d872d4718fe5145d9c12/parser.go#L119-L133 |
2,242 | schemalex/schemalex | parser.go | ParseString | func (p *Parser) ParseString(src string) (model.Stmts, error) {
return p.Parse([]byte(src))
} | go | func (p *Parser) ParseString(src string) (model.Stmts, error) {
return p.Parse([]byte(src))
} | [
"func",
"(",
"p",
"*",
"Parser",
")",
"ParseString",
"(",
"src",
"string",
")",
"(",
"model",
".",
"Stmts",
",",
"error",
")",
"{",
"return",
"p",
".",
"Parse",
"(",
"[",
"]",
"byte",
"(",
"src",
")",
")",
"\n",
"}"
] | // ParseString parses a string containing SQL statements and creates
// a mode.Stmts structure.
// See Parse for details. | [
"ParseString",
"parses",
"a",
"string",
"containing",
"SQL",
"statements",
"and",
"creates",
"a",
"mode",
".",
"Stmts",
"structure",
".",
"See",
"Parse",
"for",
"details",
"."
] | 082f7dd92f9145e57574d872d4718fe5145d9c12 | https://github.com/schemalex/schemalex/blob/082f7dd92f9145e57574d872d4718fe5145d9c12/parser.go#L138-L140 |
2,243 | schemalex/schemalex | parser.go | Parse | func (p *Parser) Parse(src []byte) (model.Stmts, error) {
cctx, cancel := context.WithCancel(context.TODO())
defer cancel()
ctx := newParseCtx(cctx)
ctx.input = src
ctx.lexsrc = lex(cctx, src)
var stmts model.Stmts
LOOP:
for {
ctx.skipWhiteSpaces()
switch t := ctx.peek(); t.Type {
case CREATE:
stmt, err := p.parseCreate(ctx)
if err != nil {
if errors.IsIgnorable(err) {
// this is ignorable.
continue
}
if pe, ok := err.(ParseError); ok {
return nil, pe
}
return nil, errors.Wrap(err, `failed to parse create`)
}
stmts = append(stmts, stmt)
case COMMENT_IDENT:
ctx.advance()
case DROP, SET, USE:
// We don't do anything about these
S1:
for {
switch t := ctx.peek(); t.Type {
case SEMICOLON:
ctx.advance()
fallthrough
case EOF:
break S1
default:
ctx.advance()
}
}
case SEMICOLON:
// you could have statements where it's just empty, followed by a
// semicolon. These are just empty lines, so we just skip and go
// process the next statement
ctx.advance()
continue
case EOF:
ctx.advance()
break LOOP
default:
return nil, newParseError(ctx, t, "expected CREATE, COMMENT_IDENT, SEMICOLON or EOF")
}
}
return stmts, nil
} | go | func (p *Parser) Parse(src []byte) (model.Stmts, error) {
cctx, cancel := context.WithCancel(context.TODO())
defer cancel()
ctx := newParseCtx(cctx)
ctx.input = src
ctx.lexsrc = lex(cctx, src)
var stmts model.Stmts
LOOP:
for {
ctx.skipWhiteSpaces()
switch t := ctx.peek(); t.Type {
case CREATE:
stmt, err := p.parseCreate(ctx)
if err != nil {
if errors.IsIgnorable(err) {
// this is ignorable.
continue
}
if pe, ok := err.(ParseError); ok {
return nil, pe
}
return nil, errors.Wrap(err, `failed to parse create`)
}
stmts = append(stmts, stmt)
case COMMENT_IDENT:
ctx.advance()
case DROP, SET, USE:
// We don't do anything about these
S1:
for {
switch t := ctx.peek(); t.Type {
case SEMICOLON:
ctx.advance()
fallthrough
case EOF:
break S1
default:
ctx.advance()
}
}
case SEMICOLON:
// you could have statements where it's just empty, followed by a
// semicolon. These are just empty lines, so we just skip and go
// process the next statement
ctx.advance()
continue
case EOF:
ctx.advance()
break LOOP
default:
return nil, newParseError(ctx, t, "expected CREATE, COMMENT_IDENT, SEMICOLON or EOF")
}
}
return stmts, nil
} | [
"func",
"(",
"p",
"*",
"Parser",
")",
"Parse",
"(",
"src",
"[",
"]",
"byte",
")",
"(",
"model",
".",
"Stmts",
",",
"error",
")",
"{",
"cctx",
",",
"cancel",
":=",
"context",
".",
"WithCancel",
"(",
"context",
".",
"TODO",
"(",
")",
")",
"\n",
"defer",
"cancel",
"(",
")",
"\n\n",
"ctx",
":=",
"newParseCtx",
"(",
"cctx",
")",
"\n",
"ctx",
".",
"input",
"=",
"src",
"\n",
"ctx",
".",
"lexsrc",
"=",
"lex",
"(",
"cctx",
",",
"src",
")",
"\n\n",
"var",
"stmts",
"model",
".",
"Stmts",
"\n",
"LOOP",
":",
"for",
"{",
"ctx",
".",
"skipWhiteSpaces",
"(",
")",
"\n",
"switch",
"t",
":=",
"ctx",
".",
"peek",
"(",
")",
";",
"t",
".",
"Type",
"{",
"case",
"CREATE",
":",
"stmt",
",",
"err",
":=",
"p",
".",
"parseCreate",
"(",
"ctx",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"if",
"errors",
".",
"IsIgnorable",
"(",
"err",
")",
"{",
"// this is ignorable.",
"continue",
"\n",
"}",
"\n",
"if",
"pe",
",",
"ok",
":=",
"err",
".",
"(",
"ParseError",
")",
";",
"ok",
"{",
"return",
"nil",
",",
"pe",
"\n",
"}",
"\n",
"return",
"nil",
",",
"errors",
".",
"Wrap",
"(",
"err",
",",
"`failed to parse create`",
")",
"\n",
"}",
"\n",
"stmts",
"=",
"append",
"(",
"stmts",
",",
"stmt",
")",
"\n",
"case",
"COMMENT_IDENT",
":",
"ctx",
".",
"advance",
"(",
")",
"\n",
"case",
"DROP",
",",
"SET",
",",
"USE",
":",
"// We don't do anything about these",
"S1",
":",
"for",
"{",
"switch",
"t",
":=",
"ctx",
".",
"peek",
"(",
")",
";",
"t",
".",
"Type",
"{",
"case",
"SEMICOLON",
":",
"ctx",
".",
"advance",
"(",
")",
"\n",
"fallthrough",
"\n",
"case",
"EOF",
":",
"break",
"S1",
"\n",
"default",
":",
"ctx",
".",
"advance",
"(",
")",
"\n",
"}",
"\n",
"}",
"\n",
"case",
"SEMICOLON",
":",
"// you could have statements where it's just empty, followed by a",
"// semicolon. These are just empty lines, so we just skip and go",
"// process the next statement",
"ctx",
".",
"advance",
"(",
")",
"\n",
"continue",
"\n",
"case",
"EOF",
":",
"ctx",
".",
"advance",
"(",
")",
"\n",
"break",
"LOOP",
"\n",
"default",
":",
"return",
"nil",
",",
"newParseError",
"(",
"ctx",
",",
"t",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"}",
"\n\n",
"return",
"stmts",
",",
"nil",
"\n",
"}"
] | // Parse parses the given set of SQL statements and creates a
// model.Stmts structure.
// If it encounters errors while parsing, the returned error will be a
// ParseError type. | [
"Parse",
"parses",
"the",
"given",
"set",
"of",
"SQL",
"statements",
"and",
"creates",
"a",
"model",
".",
"Stmts",
"structure",
".",
"If",
"it",
"encounters",
"errors",
"while",
"parsing",
"the",
"returned",
"error",
"will",
"be",
"a",
"ParseError",
"type",
"."
] | 082f7dd92f9145e57574d872d4718fe5145d9c12 | https://github.com/schemalex/schemalex/blob/082f7dd92f9145e57574d872d4718fe5145d9c12/parser.go#L146-L203 |
2,244 | schemalex/schemalex | diff/diff.go | Statements | func Statements(dst io.Writer, from, to model.Stmts, options ...Option) error {
var txn bool
for _, o := range options {
switch o.Name() {
case optkeyTransaction:
txn = o.Value().(bool)
}
}
ctx := newDiffCtx(from, to)
var procs = []func(*diffCtx, io.Writer) (int64, error){
dropTables,
createTables,
alterTables,
}
var buf bytes.Buffer
if txn {
buf.WriteString("\nBEGIN;\n\nSET FOREIGN_KEY_CHECKS = 0;")
}
for _, p := range procs {
var pbuf bytes.Buffer
n, err := p(ctx, &pbuf)
if err != nil {
return errors.Wrap(err, `failed to produce diff`)
}
if txn && n > 0 || !txn && buf.Len() > 0 && n > 0 {
buf.WriteString("\n\n")
}
pbuf.WriteTo(&buf)
}
if txn {
buf.WriteString("\n\nSET FOREIGN_KEY_CHECKS = 1;\n\nCOMMIT;")
}
if _, err := buf.WriteTo(dst); err != nil {
return errors.Wrap(err, `failed to write diff`)
}
return nil
} | go | func Statements(dst io.Writer, from, to model.Stmts, options ...Option) error {
var txn bool
for _, o := range options {
switch o.Name() {
case optkeyTransaction:
txn = o.Value().(bool)
}
}
ctx := newDiffCtx(from, to)
var procs = []func(*diffCtx, io.Writer) (int64, error){
dropTables,
createTables,
alterTables,
}
var buf bytes.Buffer
if txn {
buf.WriteString("\nBEGIN;\n\nSET FOREIGN_KEY_CHECKS = 0;")
}
for _, p := range procs {
var pbuf bytes.Buffer
n, err := p(ctx, &pbuf)
if err != nil {
return errors.Wrap(err, `failed to produce diff`)
}
if txn && n > 0 || !txn && buf.Len() > 0 && n > 0 {
buf.WriteString("\n\n")
}
pbuf.WriteTo(&buf)
}
if txn {
buf.WriteString("\n\nSET FOREIGN_KEY_CHECKS = 1;\n\nCOMMIT;")
}
if _, err := buf.WriteTo(dst); err != nil {
return errors.Wrap(err, `failed to write diff`)
}
return nil
} | [
"func",
"Statements",
"(",
"dst",
"io",
".",
"Writer",
",",
"from",
",",
"to",
"model",
".",
"Stmts",
",",
"options",
"...",
"Option",
")",
"error",
"{",
"var",
"txn",
"bool",
"\n",
"for",
"_",
",",
"o",
":=",
"range",
"options",
"{",
"switch",
"o",
".",
"Name",
"(",
")",
"{",
"case",
"optkeyTransaction",
":",
"txn",
"=",
"o",
".",
"Value",
"(",
")",
".",
"(",
"bool",
")",
"\n",
"}",
"\n",
"}",
"\n\n",
"ctx",
":=",
"newDiffCtx",
"(",
"from",
",",
"to",
")",
"\n\n",
"var",
"procs",
"=",
"[",
"]",
"func",
"(",
"*",
"diffCtx",
",",
"io",
".",
"Writer",
")",
"(",
"int64",
",",
"error",
")",
"{",
"dropTables",
",",
"createTables",
",",
"alterTables",
",",
"}",
"\n\n",
"var",
"buf",
"bytes",
".",
"Buffer",
"\n",
"if",
"txn",
"{",
"buf",
".",
"WriteString",
"(",
"\"",
"\\n",
"\\n",
"\\n",
"\"",
")",
"\n",
"}",
"\n\n",
"for",
"_",
",",
"p",
":=",
"range",
"procs",
"{",
"var",
"pbuf",
"bytes",
".",
"Buffer",
"\n",
"n",
",",
"err",
":=",
"p",
"(",
"ctx",
",",
"&",
"pbuf",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Wrap",
"(",
"err",
",",
"`failed to produce diff`",
")",
"\n",
"}",
"\n",
"if",
"txn",
"&&",
"n",
">",
"0",
"||",
"!",
"txn",
"&&",
"buf",
".",
"Len",
"(",
")",
">",
"0",
"&&",
"n",
">",
"0",
"{",
"buf",
".",
"WriteString",
"(",
"\"",
"\\n",
"\\n",
"\"",
")",
"\n",
"}",
"\n",
"pbuf",
".",
"WriteTo",
"(",
"&",
"buf",
")",
"\n",
"}",
"\n",
"if",
"txn",
"{",
"buf",
".",
"WriteString",
"(",
"\"",
"\\n",
"\\n",
"\\n",
"\\n",
"\"",
")",
"\n",
"}",
"\n\n",
"if",
"_",
",",
"err",
":=",
"buf",
".",
"WriteTo",
"(",
"dst",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Wrap",
"(",
"err",
",",
"`failed to write diff`",
")",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] | // Statements compares two model.Stmts and generates a series
// of statements to migrate from the old one to the new one,
// writing the result to `dst` | [
"Statements",
"compares",
"two",
"model",
".",
"Stmts",
"and",
"generates",
"a",
"series",
"of",
"statements",
"to",
"migrate",
"from",
"the",
"old",
"one",
"to",
"the",
"new",
"one",
"writing",
"the",
"result",
"to",
"dst"
] | 082f7dd92f9145e57574d872d4718fe5145d9c12 | https://github.com/schemalex/schemalex/blob/082f7dd92f9145e57574d872d4718fe5145d9c12/diff/diff.go#L50-L91 |
2,245 | schemalex/schemalex | diff/diff.go | Strings | func Strings(dst io.Writer, from, to string, options ...Option) error {
var p *schemalex.Parser
for _, o := range options {
switch o.Name() {
case optkeyParser:
p = o.Value().(*schemalex.Parser)
}
}
if p == nil {
p = schemalex.New()
}
stmts1, err := p.ParseString(from)
if err != nil {
return errors.Wrapf(err, `failed to parse "from" %s`, from)
}
stmts2, err := p.ParseString(to)
if err != nil {
return errors.Wrapf(err, `failed to parse "to" %s`, to)
}
return Statements(dst, stmts1, stmts2, options...)
} | go | func Strings(dst io.Writer, from, to string, options ...Option) error {
var p *schemalex.Parser
for _, o := range options {
switch o.Name() {
case optkeyParser:
p = o.Value().(*schemalex.Parser)
}
}
if p == nil {
p = schemalex.New()
}
stmts1, err := p.ParseString(from)
if err != nil {
return errors.Wrapf(err, `failed to parse "from" %s`, from)
}
stmts2, err := p.ParseString(to)
if err != nil {
return errors.Wrapf(err, `failed to parse "to" %s`, to)
}
return Statements(dst, stmts1, stmts2, options...)
} | [
"func",
"Strings",
"(",
"dst",
"io",
".",
"Writer",
",",
"from",
",",
"to",
"string",
",",
"options",
"...",
"Option",
")",
"error",
"{",
"var",
"p",
"*",
"schemalex",
".",
"Parser",
"\n",
"for",
"_",
",",
"o",
":=",
"range",
"options",
"{",
"switch",
"o",
".",
"Name",
"(",
")",
"{",
"case",
"optkeyParser",
":",
"p",
"=",
"o",
".",
"Value",
"(",
")",
".",
"(",
"*",
"schemalex",
".",
"Parser",
")",
"\n",
"}",
"\n",
"}",
"\n",
"if",
"p",
"==",
"nil",
"{",
"p",
"=",
"schemalex",
".",
"New",
"(",
")",
"\n",
"}",
"\n\n",
"stmts1",
",",
"err",
":=",
"p",
".",
"ParseString",
"(",
"from",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Wrapf",
"(",
"err",
",",
"`failed to parse \"from\" %s`",
",",
"from",
")",
"\n",
"}",
"\n\n",
"stmts2",
",",
"err",
":=",
"p",
".",
"ParseString",
"(",
"to",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Wrapf",
"(",
"err",
",",
"`failed to parse \"to\" %s`",
",",
"to",
")",
"\n",
"}",
"\n\n",
"return",
"Statements",
"(",
"dst",
",",
"stmts1",
",",
"stmts2",
",",
"options",
"...",
")",
"\n",
"}"
] | // Strings compares two strings and generates a series
// of statements to migrate from the old one to the new one,
// writing the result to `dst` | [
"Strings",
"compares",
"two",
"strings",
"and",
"generates",
"a",
"series",
"of",
"statements",
"to",
"migrate",
"from",
"the",
"old",
"one",
"to",
"the",
"new",
"one",
"writing",
"the",
"result",
"to",
"dst"
] | 082f7dd92f9145e57574d872d4718fe5145d9c12 | https://github.com/schemalex/schemalex/blob/082f7dd92f9145e57574d872d4718fe5145d9c12/diff/diff.go#L96-L119 |
2,246 | schemalex/schemalex | diff/diff.go | Files | func Files(dst io.Writer, from, to string, options ...Option) error {
return Sources(dst, schemalex.NewLocalFileSource(from), schemalex.NewLocalFileSource(to), options...)
} | go | func Files(dst io.Writer, from, to string, options ...Option) error {
return Sources(dst, schemalex.NewLocalFileSource(from), schemalex.NewLocalFileSource(to), options...)
} | [
"func",
"Files",
"(",
"dst",
"io",
".",
"Writer",
",",
"from",
",",
"to",
"string",
",",
"options",
"...",
"Option",
")",
"error",
"{",
"return",
"Sources",
"(",
"dst",
",",
"schemalex",
".",
"NewLocalFileSource",
"(",
"from",
")",
",",
"schemalex",
".",
"NewLocalFileSource",
"(",
"to",
")",
",",
"options",
"...",
")",
"\n",
"}"
] | // Files compares contents of two files and generates a series
// of statements to migrate from the old one to the new one,
// writing the result to `dst` | [
"Files",
"compares",
"contents",
"of",
"two",
"files",
"and",
"generates",
"a",
"series",
"of",
"statements",
"to",
"migrate",
"from",
"the",
"old",
"one",
"to",
"the",
"new",
"one",
"writing",
"the",
"result",
"to",
"dst"
] | 082f7dd92f9145e57574d872d4718fe5145d9c12 | https://github.com/schemalex/schemalex/blob/082f7dd92f9145e57574d872d4718fe5145d9c12/diff/diff.go#L124-L126 |
2,247 | schemalex/schemalex | diff/diff.go | Sources | func Sources(dst io.Writer, from, to schemalex.SchemaSource, options ...Option) error {
var buf bytes.Buffer
if err := from.WriteSchema(&buf); err != nil {
return errors.Wrapf(err, `failed to retrieve schema from "from" source %s`, from)
}
fromStr := buf.String()
buf.Reset()
if err := to.WriteSchema(&buf); err != nil {
return errors.Wrapf(err, `failed to retrieve schema from "to" source %s`, to)
}
return Strings(dst, fromStr, buf.String(), options...)
} | go | func Sources(dst io.Writer, from, to schemalex.SchemaSource, options ...Option) error {
var buf bytes.Buffer
if err := from.WriteSchema(&buf); err != nil {
return errors.Wrapf(err, `failed to retrieve schema from "from" source %s`, from)
}
fromStr := buf.String()
buf.Reset()
if err := to.WriteSchema(&buf); err != nil {
return errors.Wrapf(err, `failed to retrieve schema from "to" source %s`, to)
}
return Strings(dst, fromStr, buf.String(), options...)
} | [
"func",
"Sources",
"(",
"dst",
"io",
".",
"Writer",
",",
"from",
",",
"to",
"schemalex",
".",
"SchemaSource",
",",
"options",
"...",
"Option",
")",
"error",
"{",
"var",
"buf",
"bytes",
".",
"Buffer",
"\n",
"if",
"err",
":=",
"from",
".",
"WriteSchema",
"(",
"&",
"buf",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Wrapf",
"(",
"err",
",",
"`failed to retrieve schema from \"from\" source %s`",
",",
"from",
")",
"\n",
"}",
"\n",
"fromStr",
":=",
"buf",
".",
"String",
"(",
")",
"\n",
"buf",
".",
"Reset",
"(",
")",
"\n\n",
"if",
"err",
":=",
"to",
".",
"WriteSchema",
"(",
"&",
"buf",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Wrapf",
"(",
"err",
",",
"`failed to retrieve schema from \"to\" source %s`",
",",
"to",
")",
"\n",
"}",
"\n",
"return",
"Strings",
"(",
"dst",
",",
"fromStr",
",",
"buf",
".",
"String",
"(",
")",
",",
"options",
"...",
")",
"\n",
"}"
] | // Files compares contents from two sources and generates a series
// of statements to migrate from the old one to the new one,
// writing the result to `dst` | [
"Files",
"compares",
"contents",
"from",
"two",
"sources",
"and",
"generates",
"a",
"series",
"of",
"statements",
"to",
"migrate",
"from",
"the",
"old",
"one",
"to",
"the",
"new",
"one",
"writing",
"the",
"result",
"to",
"dst"
] | 082f7dd92f9145e57574d872d4718fe5145d9c12 | https://github.com/schemalex/schemalex/blob/082f7dd92f9145e57574d872d4718fe5145d9c12/diff/diff.go#L131-L143 |
2,248 | mitchellh/copystructure | copystructure.go | lock | func (w *walker) lock(v reflect.Value) {
if !w.useLocks {
return
}
if !v.IsValid() || !v.CanInterface() {
return
}
type rlocker interface {
RLocker() sync.Locker
}
var locker sync.Locker
// We can't call Interface() on a value directly, since that requires
// a copy. This is OK, since the pointer to a value which is a sync.Locker
// is also a sync.Locker.
if v.Kind() == reflect.Ptr {
switch l := v.Interface().(type) {
case rlocker:
// don't lock a mutex directly
if _, ok := l.(*sync.RWMutex); !ok {
locker = l.RLocker()
}
case sync.Locker:
locker = l
}
} else if v.CanAddr() {
switch l := v.Addr().Interface().(type) {
case rlocker:
// don't lock a mutex directly
if _, ok := l.(*sync.RWMutex); !ok {
locker = l.RLocker()
}
case sync.Locker:
locker = l
}
}
// still no callable locker
if locker == nil {
return
}
// don't lock a mutex directly
switch locker.(type) {
case *sync.Mutex, *sync.RWMutex:
return
}
locker.Lock()
w.locks[w.depth] = locker
} | go | func (w *walker) lock(v reflect.Value) {
if !w.useLocks {
return
}
if !v.IsValid() || !v.CanInterface() {
return
}
type rlocker interface {
RLocker() sync.Locker
}
var locker sync.Locker
// We can't call Interface() on a value directly, since that requires
// a copy. This is OK, since the pointer to a value which is a sync.Locker
// is also a sync.Locker.
if v.Kind() == reflect.Ptr {
switch l := v.Interface().(type) {
case rlocker:
// don't lock a mutex directly
if _, ok := l.(*sync.RWMutex); !ok {
locker = l.RLocker()
}
case sync.Locker:
locker = l
}
} else if v.CanAddr() {
switch l := v.Addr().Interface().(type) {
case rlocker:
// don't lock a mutex directly
if _, ok := l.(*sync.RWMutex); !ok {
locker = l.RLocker()
}
case sync.Locker:
locker = l
}
}
// still no callable locker
if locker == nil {
return
}
// don't lock a mutex directly
switch locker.(type) {
case *sync.Mutex, *sync.RWMutex:
return
}
locker.Lock()
w.locks[w.depth] = locker
} | [
"func",
"(",
"w",
"*",
"walker",
")",
"lock",
"(",
"v",
"reflect",
".",
"Value",
")",
"{",
"if",
"!",
"w",
".",
"useLocks",
"{",
"return",
"\n",
"}",
"\n\n",
"if",
"!",
"v",
".",
"IsValid",
"(",
")",
"||",
"!",
"v",
".",
"CanInterface",
"(",
")",
"{",
"return",
"\n",
"}",
"\n\n",
"type",
"rlocker",
"interface",
"{",
"RLocker",
"(",
")",
"sync",
".",
"Locker",
"\n",
"}",
"\n\n",
"var",
"locker",
"sync",
".",
"Locker",
"\n\n",
"// We can't call Interface() on a value directly, since that requires",
"// a copy. This is OK, since the pointer to a value which is a sync.Locker",
"// is also a sync.Locker.",
"if",
"v",
".",
"Kind",
"(",
")",
"==",
"reflect",
".",
"Ptr",
"{",
"switch",
"l",
":=",
"v",
".",
"Interface",
"(",
")",
".",
"(",
"type",
")",
"{",
"case",
"rlocker",
":",
"// don't lock a mutex directly",
"if",
"_",
",",
"ok",
":=",
"l",
".",
"(",
"*",
"sync",
".",
"RWMutex",
")",
";",
"!",
"ok",
"{",
"locker",
"=",
"l",
".",
"RLocker",
"(",
")",
"\n",
"}",
"\n",
"case",
"sync",
".",
"Locker",
":",
"locker",
"=",
"l",
"\n",
"}",
"\n",
"}",
"else",
"if",
"v",
".",
"CanAddr",
"(",
")",
"{",
"switch",
"l",
":=",
"v",
".",
"Addr",
"(",
")",
".",
"Interface",
"(",
")",
".",
"(",
"type",
")",
"{",
"case",
"rlocker",
":",
"// don't lock a mutex directly",
"if",
"_",
",",
"ok",
":=",
"l",
".",
"(",
"*",
"sync",
".",
"RWMutex",
")",
";",
"!",
"ok",
"{",
"locker",
"=",
"l",
".",
"RLocker",
"(",
")",
"\n",
"}",
"\n",
"case",
"sync",
".",
"Locker",
":",
"locker",
"=",
"l",
"\n",
"}",
"\n",
"}",
"\n\n",
"// still no callable locker",
"if",
"locker",
"==",
"nil",
"{",
"return",
"\n",
"}",
"\n\n",
"// don't lock a mutex directly",
"switch",
"locker",
".",
"(",
"type",
")",
"{",
"case",
"*",
"sync",
".",
"Mutex",
",",
"*",
"sync",
".",
"RWMutex",
":",
"return",
"\n",
"}",
"\n\n",
"locker",
".",
"Lock",
"(",
")",
"\n",
"w",
".",
"locks",
"[",
"w",
".",
"depth",
"]",
"=",
"locker",
"\n",
"}"
] | // if this value is a Locker, lock it and add it to the locks slice | [
"if",
"this",
"value",
"is",
"a",
"Locker",
"lock",
"it",
"and",
"add",
"it",
"to",
"the",
"locks",
"slice"
] | 9a1b6f44e8da0e0e374624fb0a825a231b00c537 | https://github.com/mitchellh/copystructure/blob/9a1b6f44e8da0e0e374624fb0a825a231b00c537/copystructure.go#L484-L537 |
2,249 | natefinch/npipe | npipe_windows.go | DialTimeout | func DialTimeout(address string, timeout time.Duration) (*PipeConn, error) {
deadline := time.Now().Add(timeout)
now := time.Now()
for now.Before(deadline) {
millis := uint32(deadline.Sub(now) / time.Millisecond)
conn, err := dial(address, millis)
if err == nil {
return conn, nil
}
if err == error_sem_timeout {
// This is WaitNamedPipe's timeout error, so we know we're done
return nil, PipeError{fmt.Sprintf(
"Timed out waiting for pipe '%s' to come available", address), true}
}
if isPipeNotReady(err) {
left := deadline.Sub(time.Now())
retry := 100 * time.Millisecond
if left > retry {
<-time.After(retry)
} else {
<-time.After(left - time.Millisecond)
}
now = time.Now()
continue
}
return nil, err
}
return nil, PipeError{fmt.Sprintf(
"Timed out waiting for pipe '%s' to come available", address), true}
} | go | func DialTimeout(address string, timeout time.Duration) (*PipeConn, error) {
deadline := time.Now().Add(timeout)
now := time.Now()
for now.Before(deadline) {
millis := uint32(deadline.Sub(now) / time.Millisecond)
conn, err := dial(address, millis)
if err == nil {
return conn, nil
}
if err == error_sem_timeout {
// This is WaitNamedPipe's timeout error, so we know we're done
return nil, PipeError{fmt.Sprintf(
"Timed out waiting for pipe '%s' to come available", address), true}
}
if isPipeNotReady(err) {
left := deadline.Sub(time.Now())
retry := 100 * time.Millisecond
if left > retry {
<-time.After(retry)
} else {
<-time.After(left - time.Millisecond)
}
now = time.Now()
continue
}
return nil, err
}
return nil, PipeError{fmt.Sprintf(
"Timed out waiting for pipe '%s' to come available", address), true}
} | [
"func",
"DialTimeout",
"(",
"address",
"string",
",",
"timeout",
"time",
".",
"Duration",
")",
"(",
"*",
"PipeConn",
",",
"error",
")",
"{",
"deadline",
":=",
"time",
".",
"Now",
"(",
")",
".",
"Add",
"(",
"timeout",
")",
"\n\n",
"now",
":=",
"time",
".",
"Now",
"(",
")",
"\n",
"for",
"now",
".",
"Before",
"(",
"deadline",
")",
"{",
"millis",
":=",
"uint32",
"(",
"deadline",
".",
"Sub",
"(",
"now",
")",
"/",
"time",
".",
"Millisecond",
")",
"\n",
"conn",
",",
"err",
":=",
"dial",
"(",
"address",
",",
"millis",
")",
"\n",
"if",
"err",
"==",
"nil",
"{",
"return",
"conn",
",",
"nil",
"\n",
"}",
"\n",
"if",
"err",
"==",
"error_sem_timeout",
"{",
"// This is WaitNamedPipe's timeout error, so we know we're done",
"return",
"nil",
",",
"PipeError",
"{",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"address",
")",
",",
"true",
"}",
"\n",
"}",
"\n",
"if",
"isPipeNotReady",
"(",
"err",
")",
"{",
"left",
":=",
"deadline",
".",
"Sub",
"(",
"time",
".",
"Now",
"(",
")",
")",
"\n",
"retry",
":=",
"100",
"*",
"time",
".",
"Millisecond",
"\n",
"if",
"left",
">",
"retry",
"{",
"<-",
"time",
".",
"After",
"(",
"retry",
")",
"\n",
"}",
"else",
"{",
"<-",
"time",
".",
"After",
"(",
"left",
"-",
"time",
".",
"Millisecond",
")",
"\n",
"}",
"\n",
"now",
"=",
"time",
".",
"Now",
"(",
")",
"\n",
"continue",
"\n",
"}",
"\n",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"return",
"nil",
",",
"PipeError",
"{",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"address",
")",
",",
"true",
"}",
"\n",
"}"
] | // DialTimeout acts like Dial, but will time out after the duration of timeout | [
"DialTimeout",
"acts",
"like",
"Dial",
"but",
"will",
"time",
"out",
"after",
"the",
"duration",
"of",
"timeout"
] | c1b8fa8bdccecb0b8db834ee0b92fdbcfa606dd6 | https://github.com/natefinch/npipe/blob/c1b8fa8bdccecb0b8db834ee0b92fdbcfa606dd6/npipe_windows.go#L126-L156 |
2,250 | natefinch/npipe | npipe_windows.go | dial | func dial(address string, timeout uint32) (*PipeConn, error) {
name, err := syscall.UTF16PtrFromString(string(address))
if err != nil {
return nil, err
}
// If at least one instance of the pipe has been created, this function
// will wait timeout milliseconds for it to become available.
// It will return immediately regardless of timeout, if no instances
// of the named pipe have been created yet.
// If this returns with no error, there is a pipe available.
if err := waitNamedPipe(name, timeout); err != nil {
if err == error_bad_pathname {
// badly formatted pipe name
return nil, badAddr(address)
}
return nil, err
}
pathp, err := syscall.UTF16PtrFromString(address)
if err != nil {
return nil, err
}
handle, err := syscall.CreateFile(pathp, syscall.GENERIC_READ|syscall.GENERIC_WRITE,
uint32(syscall.FILE_SHARE_READ|syscall.FILE_SHARE_WRITE), nil, syscall.OPEN_EXISTING,
syscall.FILE_FLAG_OVERLAPPED, 0)
if err != nil {
return nil, err
}
return &PipeConn{handle: handle, addr: PipeAddr(address)}, nil
} | go | func dial(address string, timeout uint32) (*PipeConn, error) {
name, err := syscall.UTF16PtrFromString(string(address))
if err != nil {
return nil, err
}
// If at least one instance of the pipe has been created, this function
// will wait timeout milliseconds for it to become available.
// It will return immediately regardless of timeout, if no instances
// of the named pipe have been created yet.
// If this returns with no error, there is a pipe available.
if err := waitNamedPipe(name, timeout); err != nil {
if err == error_bad_pathname {
// badly formatted pipe name
return nil, badAddr(address)
}
return nil, err
}
pathp, err := syscall.UTF16PtrFromString(address)
if err != nil {
return nil, err
}
handle, err := syscall.CreateFile(pathp, syscall.GENERIC_READ|syscall.GENERIC_WRITE,
uint32(syscall.FILE_SHARE_READ|syscall.FILE_SHARE_WRITE), nil, syscall.OPEN_EXISTING,
syscall.FILE_FLAG_OVERLAPPED, 0)
if err != nil {
return nil, err
}
return &PipeConn{handle: handle, addr: PipeAddr(address)}, nil
} | [
"func",
"dial",
"(",
"address",
"string",
",",
"timeout",
"uint32",
")",
"(",
"*",
"PipeConn",
",",
"error",
")",
"{",
"name",
",",
"err",
":=",
"syscall",
".",
"UTF16PtrFromString",
"(",
"string",
"(",
"address",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"// If at least one instance of the pipe has been created, this function",
"// will wait timeout milliseconds for it to become available.",
"// It will return immediately regardless of timeout, if no instances",
"// of the named pipe have been created yet.",
"// If this returns with no error, there is a pipe available.",
"if",
"err",
":=",
"waitNamedPipe",
"(",
"name",
",",
"timeout",
")",
";",
"err",
"!=",
"nil",
"{",
"if",
"err",
"==",
"error_bad_pathname",
"{",
"// badly formatted pipe name",
"return",
"nil",
",",
"badAddr",
"(",
"address",
")",
"\n",
"}",
"\n",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"pathp",
",",
"err",
":=",
"syscall",
".",
"UTF16PtrFromString",
"(",
"address",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"handle",
",",
"err",
":=",
"syscall",
".",
"CreateFile",
"(",
"pathp",
",",
"syscall",
".",
"GENERIC_READ",
"|",
"syscall",
".",
"GENERIC_WRITE",
",",
"uint32",
"(",
"syscall",
".",
"FILE_SHARE_READ",
"|",
"syscall",
".",
"FILE_SHARE_WRITE",
")",
",",
"nil",
",",
"syscall",
".",
"OPEN_EXISTING",
",",
"syscall",
".",
"FILE_FLAG_OVERLAPPED",
",",
"0",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"return",
"&",
"PipeConn",
"{",
"handle",
":",
"handle",
",",
"addr",
":",
"PipeAddr",
"(",
"address",
")",
"}",
",",
"nil",
"\n",
"}"
] | // dial is a helper to initiate a connection to a named pipe that has been started by a server.
// The timeout is only enforced if the pipe server has already created the pipe, otherwise
// this function will return immediately. | [
"dial",
"is",
"a",
"helper",
"to",
"initiate",
"a",
"connection",
"to",
"a",
"named",
"pipe",
"that",
"has",
"been",
"started",
"by",
"a",
"server",
".",
"The",
"timeout",
"is",
"only",
"enforced",
"if",
"the",
"pipe",
"server",
"has",
"already",
"created",
"the",
"pipe",
"otherwise",
"this",
"function",
"will",
"return",
"immediately",
"."
] | c1b8fa8bdccecb0b8db834ee0b92fdbcfa606dd6 | https://github.com/natefinch/npipe/blob/c1b8fa8bdccecb0b8db834ee0b92fdbcfa606dd6/npipe_windows.go#L194-L222 |
2,251 | natefinch/npipe | npipe_windows.go | Accept | func (l *PipeListener) Accept() (net.Conn, error) {
c, err := l.AcceptPipe()
for err == error_no_data {
// Ignore clients that connect and immediately disconnect.
c, err = l.AcceptPipe()
}
if err != nil {
return nil, err
}
return c, nil
} | go | func (l *PipeListener) Accept() (net.Conn, error) {
c, err := l.AcceptPipe()
for err == error_no_data {
// Ignore clients that connect and immediately disconnect.
c, err = l.AcceptPipe()
}
if err != nil {
return nil, err
}
return c, nil
} | [
"func",
"(",
"l",
"*",
"PipeListener",
")",
"Accept",
"(",
")",
"(",
"net",
".",
"Conn",
",",
"error",
")",
"{",
"c",
",",
"err",
":=",
"l",
".",
"AcceptPipe",
"(",
")",
"\n",
"for",
"err",
"==",
"error_no_data",
"{",
"// Ignore clients that connect and immediately disconnect.",
"c",
",",
"err",
"=",
"l",
".",
"AcceptPipe",
"(",
")",
"\n",
"}",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"return",
"c",
",",
"nil",
"\n",
"}"
] | // Accept implements the Accept method in the net.Listener interface; it
// waits for the next call and returns a generic net.Conn. | [
"Accept",
"implements",
"the",
"Accept",
"method",
"in",
"the",
"net",
".",
"Listener",
"interface",
";",
"it",
"waits",
"for",
"the",
"next",
"call",
"and",
"returns",
"a",
"generic",
"net",
".",
"Conn",
"."
] | c1b8fa8bdccecb0b8db834ee0b92fdbcfa606dd6 | https://github.com/natefinch/npipe/blob/c1b8fa8bdccecb0b8db834ee0b92fdbcfa606dd6/npipe_windows.go#L262-L272 |
2,252 | natefinch/npipe | npipe_windows.go | AcceptPipe | func (l *PipeListener) AcceptPipe() (*PipeConn, error) {
if l == nil {
return nil, syscall.EINVAL
}
l.mu.Lock()
defer l.mu.Unlock()
if l.addr == "" || l.closed {
return nil, syscall.EINVAL
}
// the first time we call accept, the handle will have been created by the Listen
// call. This is to prevent race conditions where the client thinks the server
// isn't listening because it hasn't actually called create yet. After the first time, we'll
// have to create a new handle each time
handle := l.handle
if handle == 0 {
var err error
handle, err = createPipe(string(l.addr), false)
if err != nil {
return nil, err
}
} else {
l.handle = 0
}
overlapped, err := newOverlapped()
if err != nil {
return nil, err
}
defer syscall.CloseHandle(overlapped.HEvent)
err = connectNamedPipe(handle, overlapped)
if err == nil || err == error_pipe_connected {
return &PipeConn{handle: handle, addr: l.addr}, nil
}
if err == error_io_incomplete || err == syscall.ERROR_IO_PENDING {
l.acceptOverlapped = overlapped
l.acceptHandle = handle
// unlock here so close can function correctly while we wait (we'll
// get relocked via the defer below, before the original defer
// unlock happens.)
l.mu.Unlock()
defer func() {
l.mu.Lock()
l.acceptOverlapped = nil
l.acceptHandle = 0
// unlock is via defer above.
}()
_, err = waitForCompletion(handle, overlapped)
}
if err == syscall.ERROR_OPERATION_ABORTED {
// Return error compatible to net.Listener.Accept() in case the
// listener was closed.
return nil, ErrClosed
}
if err != nil {
return nil, err
}
return &PipeConn{handle: handle, addr: l.addr}, nil
} | go | func (l *PipeListener) AcceptPipe() (*PipeConn, error) {
if l == nil {
return nil, syscall.EINVAL
}
l.mu.Lock()
defer l.mu.Unlock()
if l.addr == "" || l.closed {
return nil, syscall.EINVAL
}
// the first time we call accept, the handle will have been created by the Listen
// call. This is to prevent race conditions where the client thinks the server
// isn't listening because it hasn't actually called create yet. After the first time, we'll
// have to create a new handle each time
handle := l.handle
if handle == 0 {
var err error
handle, err = createPipe(string(l.addr), false)
if err != nil {
return nil, err
}
} else {
l.handle = 0
}
overlapped, err := newOverlapped()
if err != nil {
return nil, err
}
defer syscall.CloseHandle(overlapped.HEvent)
err = connectNamedPipe(handle, overlapped)
if err == nil || err == error_pipe_connected {
return &PipeConn{handle: handle, addr: l.addr}, nil
}
if err == error_io_incomplete || err == syscall.ERROR_IO_PENDING {
l.acceptOverlapped = overlapped
l.acceptHandle = handle
// unlock here so close can function correctly while we wait (we'll
// get relocked via the defer below, before the original defer
// unlock happens.)
l.mu.Unlock()
defer func() {
l.mu.Lock()
l.acceptOverlapped = nil
l.acceptHandle = 0
// unlock is via defer above.
}()
_, err = waitForCompletion(handle, overlapped)
}
if err == syscall.ERROR_OPERATION_ABORTED {
// Return error compatible to net.Listener.Accept() in case the
// listener was closed.
return nil, ErrClosed
}
if err != nil {
return nil, err
}
return &PipeConn{handle: handle, addr: l.addr}, nil
} | [
"func",
"(",
"l",
"*",
"PipeListener",
")",
"AcceptPipe",
"(",
")",
"(",
"*",
"PipeConn",
",",
"error",
")",
"{",
"if",
"l",
"==",
"nil",
"{",
"return",
"nil",
",",
"syscall",
".",
"EINVAL",
"\n",
"}",
"\n\n",
"l",
".",
"mu",
".",
"Lock",
"(",
")",
"\n",
"defer",
"l",
".",
"mu",
".",
"Unlock",
"(",
")",
"\n\n",
"if",
"l",
".",
"addr",
"==",
"\"",
"\"",
"||",
"l",
".",
"closed",
"{",
"return",
"nil",
",",
"syscall",
".",
"EINVAL",
"\n",
"}",
"\n\n",
"// the first time we call accept, the handle will have been created by the Listen",
"// call. This is to prevent race conditions where the client thinks the server",
"// isn't listening because it hasn't actually called create yet. After the first time, we'll",
"// have to create a new handle each time",
"handle",
":=",
"l",
".",
"handle",
"\n",
"if",
"handle",
"==",
"0",
"{",
"var",
"err",
"error",
"\n",
"handle",
",",
"err",
"=",
"createPipe",
"(",
"string",
"(",
"l",
".",
"addr",
")",
",",
"false",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"}",
"else",
"{",
"l",
".",
"handle",
"=",
"0",
"\n",
"}",
"\n\n",
"overlapped",
",",
"err",
":=",
"newOverlapped",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"defer",
"syscall",
".",
"CloseHandle",
"(",
"overlapped",
".",
"HEvent",
")",
"\n",
"err",
"=",
"connectNamedPipe",
"(",
"handle",
",",
"overlapped",
")",
"\n",
"if",
"err",
"==",
"nil",
"||",
"err",
"==",
"error_pipe_connected",
"{",
"return",
"&",
"PipeConn",
"{",
"handle",
":",
"handle",
",",
"addr",
":",
"l",
".",
"addr",
"}",
",",
"nil",
"\n",
"}",
"\n\n",
"if",
"err",
"==",
"error_io_incomplete",
"||",
"err",
"==",
"syscall",
".",
"ERROR_IO_PENDING",
"{",
"l",
".",
"acceptOverlapped",
"=",
"overlapped",
"\n",
"l",
".",
"acceptHandle",
"=",
"handle",
"\n",
"// unlock here so close can function correctly while we wait (we'll",
"// get relocked via the defer below, before the original defer",
"// unlock happens.)",
"l",
".",
"mu",
".",
"Unlock",
"(",
")",
"\n",
"defer",
"func",
"(",
")",
"{",
"l",
".",
"mu",
".",
"Lock",
"(",
")",
"\n",
"l",
".",
"acceptOverlapped",
"=",
"nil",
"\n",
"l",
".",
"acceptHandle",
"=",
"0",
"\n",
"// unlock is via defer above.",
"}",
"(",
")",
"\n",
"_",
",",
"err",
"=",
"waitForCompletion",
"(",
"handle",
",",
"overlapped",
")",
"\n",
"}",
"\n",
"if",
"err",
"==",
"syscall",
".",
"ERROR_OPERATION_ABORTED",
"{",
"// Return error compatible to net.Listener.Accept() in case the",
"// listener was closed.",
"return",
"nil",
",",
"ErrClosed",
"\n",
"}",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"return",
"&",
"PipeConn",
"{",
"handle",
":",
"handle",
",",
"addr",
":",
"l",
".",
"addr",
"}",
",",
"nil",
"\n",
"}"
] | // AcceptPipe accepts the next incoming call and returns the new connection.
// It might return an error if a client connected and immediately cancelled
// the connection. | [
"AcceptPipe",
"accepts",
"the",
"next",
"incoming",
"call",
"and",
"returns",
"the",
"new",
"connection",
".",
"It",
"might",
"return",
"an",
"error",
"if",
"a",
"client",
"connected",
"and",
"immediately",
"cancelled",
"the",
"connection",
"."
] | c1b8fa8bdccecb0b8db834ee0b92fdbcfa606dd6 | https://github.com/natefinch/npipe/blob/c1b8fa8bdccecb0b8db834ee0b92fdbcfa606dd6/npipe_windows.go#L277-L338 |
2,253 | natefinch/npipe | npipe_windows.go | Close | func (l *PipeListener) Close() error {
l.mu.Lock()
defer l.mu.Unlock()
if l.closed {
return nil
}
l.closed = true
if l.handle != 0 {
err := disconnectNamedPipe(l.handle)
if err != nil {
return err
}
err = syscall.CloseHandle(l.handle)
if err != nil {
return err
}
l.handle = 0
}
if l.acceptOverlapped != nil && l.acceptHandle != 0 {
// Cancel the pending IO. This call does not block, so it is safe
// to hold onto the mutex above.
if err := cancelIoEx(l.acceptHandle, l.acceptOverlapped); err != nil {
return err
}
err := syscall.CloseHandle(l.acceptOverlapped.HEvent)
if err != nil {
return err
}
l.acceptOverlapped.HEvent = 0
err = syscall.CloseHandle(l.acceptHandle)
if err != nil {
return err
}
l.acceptHandle = 0
}
return nil
} | go | func (l *PipeListener) Close() error {
l.mu.Lock()
defer l.mu.Unlock()
if l.closed {
return nil
}
l.closed = true
if l.handle != 0 {
err := disconnectNamedPipe(l.handle)
if err != nil {
return err
}
err = syscall.CloseHandle(l.handle)
if err != nil {
return err
}
l.handle = 0
}
if l.acceptOverlapped != nil && l.acceptHandle != 0 {
// Cancel the pending IO. This call does not block, so it is safe
// to hold onto the mutex above.
if err := cancelIoEx(l.acceptHandle, l.acceptOverlapped); err != nil {
return err
}
err := syscall.CloseHandle(l.acceptOverlapped.HEvent)
if err != nil {
return err
}
l.acceptOverlapped.HEvent = 0
err = syscall.CloseHandle(l.acceptHandle)
if err != nil {
return err
}
l.acceptHandle = 0
}
return nil
} | [
"func",
"(",
"l",
"*",
"PipeListener",
")",
"Close",
"(",
")",
"error",
"{",
"l",
".",
"mu",
".",
"Lock",
"(",
")",
"\n",
"defer",
"l",
".",
"mu",
".",
"Unlock",
"(",
")",
"\n\n",
"if",
"l",
".",
"closed",
"{",
"return",
"nil",
"\n",
"}",
"\n",
"l",
".",
"closed",
"=",
"true",
"\n",
"if",
"l",
".",
"handle",
"!=",
"0",
"{",
"err",
":=",
"disconnectNamedPipe",
"(",
"l",
".",
"handle",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"err",
"=",
"syscall",
".",
"CloseHandle",
"(",
"l",
".",
"handle",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"l",
".",
"handle",
"=",
"0",
"\n",
"}",
"\n",
"if",
"l",
".",
"acceptOverlapped",
"!=",
"nil",
"&&",
"l",
".",
"acceptHandle",
"!=",
"0",
"{",
"// Cancel the pending IO. This call does not block, so it is safe",
"// to hold onto the mutex above.",
"if",
"err",
":=",
"cancelIoEx",
"(",
"l",
".",
"acceptHandle",
",",
"l",
".",
"acceptOverlapped",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"err",
":=",
"syscall",
".",
"CloseHandle",
"(",
"l",
".",
"acceptOverlapped",
".",
"HEvent",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"l",
".",
"acceptOverlapped",
".",
"HEvent",
"=",
"0",
"\n",
"err",
"=",
"syscall",
".",
"CloseHandle",
"(",
"l",
".",
"acceptHandle",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"l",
".",
"acceptHandle",
"=",
"0",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] | // Close stops listening on the address.
// Already Accepted connections are not closed. | [
"Close",
"stops",
"listening",
"on",
"the",
"address",
".",
"Already",
"Accepted",
"connections",
"are",
"not",
"closed",
"."
] | c1b8fa8bdccecb0b8db834ee0b92fdbcfa606dd6 | https://github.com/natefinch/npipe/blob/c1b8fa8bdccecb0b8db834ee0b92fdbcfa606dd6/npipe_windows.go#L342-L379 |
2,254 | natefinch/npipe | npipe_windows.go | completeRequest | func (c *PipeConn) completeRequest(data iodata, deadline *time.Time, overlapped *syscall.Overlapped) (int, error) {
if data.err == error_io_incomplete || data.err == syscall.ERROR_IO_PENDING {
var timer <-chan time.Time
if deadline != nil {
if timeDiff := deadline.Sub(time.Now()); timeDiff > 0 {
timer = time.After(timeDiff)
}
}
done := make(chan iodata)
go func() {
n, err := waitForCompletion(c.handle, overlapped)
done <- iodata{n, err}
}()
select {
case data = <-done:
case <-timer:
syscall.CancelIoEx(c.handle, overlapped)
data = iodata{0, timeout(c.addr.String())}
}
}
// Windows will produce ERROR_BROKEN_PIPE upon closing
// a handle on the other end of a connection. Go RPC
// expects an io.EOF error in this case.
if data.err == syscall.ERROR_BROKEN_PIPE {
data.err = io.EOF
}
return int(data.n), data.err
} | go | func (c *PipeConn) completeRequest(data iodata, deadline *time.Time, overlapped *syscall.Overlapped) (int, error) {
if data.err == error_io_incomplete || data.err == syscall.ERROR_IO_PENDING {
var timer <-chan time.Time
if deadline != nil {
if timeDiff := deadline.Sub(time.Now()); timeDiff > 0 {
timer = time.After(timeDiff)
}
}
done := make(chan iodata)
go func() {
n, err := waitForCompletion(c.handle, overlapped)
done <- iodata{n, err}
}()
select {
case data = <-done:
case <-timer:
syscall.CancelIoEx(c.handle, overlapped)
data = iodata{0, timeout(c.addr.String())}
}
}
// Windows will produce ERROR_BROKEN_PIPE upon closing
// a handle on the other end of a connection. Go RPC
// expects an io.EOF error in this case.
if data.err == syscall.ERROR_BROKEN_PIPE {
data.err = io.EOF
}
return int(data.n), data.err
} | [
"func",
"(",
"c",
"*",
"PipeConn",
")",
"completeRequest",
"(",
"data",
"iodata",
",",
"deadline",
"*",
"time",
".",
"Time",
",",
"overlapped",
"*",
"syscall",
".",
"Overlapped",
")",
"(",
"int",
",",
"error",
")",
"{",
"if",
"data",
".",
"err",
"==",
"error_io_incomplete",
"||",
"data",
".",
"err",
"==",
"syscall",
".",
"ERROR_IO_PENDING",
"{",
"var",
"timer",
"<-",
"chan",
"time",
".",
"Time",
"\n",
"if",
"deadline",
"!=",
"nil",
"{",
"if",
"timeDiff",
":=",
"deadline",
".",
"Sub",
"(",
"time",
".",
"Now",
"(",
")",
")",
";",
"timeDiff",
">",
"0",
"{",
"timer",
"=",
"time",
".",
"After",
"(",
"timeDiff",
")",
"\n",
"}",
"\n",
"}",
"\n",
"done",
":=",
"make",
"(",
"chan",
"iodata",
")",
"\n",
"go",
"func",
"(",
")",
"{",
"n",
",",
"err",
":=",
"waitForCompletion",
"(",
"c",
".",
"handle",
",",
"overlapped",
")",
"\n",
"done",
"<-",
"iodata",
"{",
"n",
",",
"err",
"}",
"\n",
"}",
"(",
")",
"\n",
"select",
"{",
"case",
"data",
"=",
"<-",
"done",
":",
"case",
"<-",
"timer",
":",
"syscall",
".",
"CancelIoEx",
"(",
"c",
".",
"handle",
",",
"overlapped",
")",
"\n",
"data",
"=",
"iodata",
"{",
"0",
",",
"timeout",
"(",
"c",
".",
"addr",
".",
"String",
"(",
")",
")",
"}",
"\n",
"}",
"\n",
"}",
"\n",
"// Windows will produce ERROR_BROKEN_PIPE upon closing",
"// a handle on the other end of a connection. Go RPC",
"// expects an io.EOF error in this case.",
"if",
"data",
".",
"err",
"==",
"syscall",
".",
"ERROR_BROKEN_PIPE",
"{",
"data",
".",
"err",
"=",
"io",
".",
"EOF",
"\n",
"}",
"\n",
"return",
"int",
"(",
"data",
".",
"n",
")",
",",
"data",
".",
"err",
"\n",
"}"
] | // completeRequest looks at iodata to see if a request is pending. If so, it waits for it to either complete or to
// abort due to hitting the specified deadline. Deadline may be set to nil to wait forever. If no request is pending,
// the content of iodata is returned. | [
"completeRequest",
"looks",
"at",
"iodata",
"to",
"see",
"if",
"a",
"request",
"is",
"pending",
".",
"If",
"so",
"it",
"waits",
"for",
"it",
"to",
"either",
"complete",
"or",
"to",
"abort",
"due",
"to",
"hitting",
"the",
"specified",
"deadline",
".",
"Deadline",
"may",
"be",
"set",
"to",
"nil",
"to",
"wait",
"forever",
".",
"If",
"no",
"request",
"is",
"pending",
"the",
"content",
"of",
"iodata",
"is",
"returned",
"."
] | c1b8fa8bdccecb0b8db834ee0b92fdbcfa606dd6 | https://github.com/natefinch/npipe/blob/c1b8fa8bdccecb0b8db834ee0b92fdbcfa606dd6/npipe_windows.go#L402-L429 |
2,255 | natefinch/npipe | npipe_windows.go | createPipe | func createPipe(address string, first bool) (syscall.Handle, error) {
n, err := syscall.UTF16PtrFromString(address)
if err != nil {
return 0, err
}
mode := uint32(pipe_access_duplex | syscall.FILE_FLAG_OVERLAPPED)
if first {
mode |= file_flag_first_pipe_instance
}
return createNamedPipe(n,
mode,
pipe_type_byte,
pipe_unlimited_instances,
512, 512, 0, nil)
} | go | func createPipe(address string, first bool) (syscall.Handle, error) {
n, err := syscall.UTF16PtrFromString(address)
if err != nil {
return 0, err
}
mode := uint32(pipe_access_duplex | syscall.FILE_FLAG_OVERLAPPED)
if first {
mode |= file_flag_first_pipe_instance
}
return createNamedPipe(n,
mode,
pipe_type_byte,
pipe_unlimited_instances,
512, 512, 0, nil)
} | [
"func",
"createPipe",
"(",
"address",
"string",
",",
"first",
"bool",
")",
"(",
"syscall",
".",
"Handle",
",",
"error",
")",
"{",
"n",
",",
"err",
":=",
"syscall",
".",
"UTF16PtrFromString",
"(",
"address",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"0",
",",
"err",
"\n",
"}",
"\n",
"mode",
":=",
"uint32",
"(",
"pipe_access_duplex",
"|",
"syscall",
".",
"FILE_FLAG_OVERLAPPED",
")",
"\n",
"if",
"first",
"{",
"mode",
"|=",
"file_flag_first_pipe_instance",
"\n",
"}",
"\n",
"return",
"createNamedPipe",
"(",
"n",
",",
"mode",
",",
"pipe_type_byte",
",",
"pipe_unlimited_instances",
",",
"512",
",",
"512",
",",
"0",
",",
"nil",
")",
"\n",
"}"
] | // createPipe is a helper function to make sure we always create pipes
// with the same arguments, since subsequent calls to create pipe need
// to use the same arguments as the first one. If first is set, fail
// if the pipe already exists. | [
"createPipe",
"is",
"a",
"helper",
"function",
"to",
"make",
"sure",
"we",
"always",
"create",
"pipes",
"with",
"the",
"same",
"arguments",
"since",
"subsequent",
"calls",
"to",
"create",
"pipe",
"need",
"to",
"use",
"the",
"same",
"arguments",
"as",
"the",
"first",
"one",
".",
"If",
"first",
"is",
"set",
"fail",
"if",
"the",
"pipe",
"already",
"exists",
"."
] | c1b8fa8bdccecb0b8db834ee0b92fdbcfa606dd6 | https://github.com/natefinch/npipe/blob/c1b8fa8bdccecb0b8db834ee0b92fdbcfa606dd6/npipe_windows.go#L510-L524 |
2,256 | alecthomas/repr | repr.go | Hide | func Hide(ts ...interface{}) Option {
return func(o *Printer) {
for _, t := range ts {
rt := reflect.Indirect(reflect.ValueOf(t)).Type()
o.exclude[rt] = true
}
}
} | go | func Hide(ts ...interface{}) Option {
return func(o *Printer) {
for _, t := range ts {
rt := reflect.Indirect(reflect.ValueOf(t)).Type()
o.exclude[rt] = true
}
}
} | [
"func",
"Hide",
"(",
"ts",
"...",
"interface",
"{",
"}",
")",
"Option",
"{",
"return",
"func",
"(",
"o",
"*",
"Printer",
")",
"{",
"for",
"_",
",",
"t",
":=",
"range",
"ts",
"{",
"rt",
":=",
"reflect",
".",
"Indirect",
"(",
"reflect",
".",
"ValueOf",
"(",
"t",
")",
")",
".",
"Type",
"(",
")",
"\n",
"o",
".",
"exclude",
"[",
"rt",
"]",
"=",
"true",
"\n",
"}",
"\n",
"}",
"\n",
"}"
] | // Hide excludes the given types from representation, instead just printing the name of the type. | [
"Hide",
"excludes",
"the",
"given",
"types",
"from",
"representation",
"instead",
"just",
"printing",
"the",
"name",
"of",
"the",
"type",
"."
] | d37bc2a10ba1a7951e19dd5dc10f7d59b142d8d7 | https://github.com/alecthomas/repr/blob/d37bc2a10ba1a7951e19dd5dc10f7d59b142d8d7/repr.go#L68-L75 |
2,257 | alecthomas/repr | repr.go | New | func New(w io.Writer, options ...Option) *Printer {
p := &Printer{
w: w,
indent: " ",
omitEmpty: true,
exclude: map[reflect.Type]bool{},
}
for _, option := range options {
option(p)
}
return p
} | go | func New(w io.Writer, options ...Option) *Printer {
p := &Printer{
w: w,
indent: " ",
omitEmpty: true,
exclude: map[reflect.Type]bool{},
}
for _, option := range options {
option(p)
}
return p
} | [
"func",
"New",
"(",
"w",
"io",
".",
"Writer",
",",
"options",
"...",
"Option",
")",
"*",
"Printer",
"{",
"p",
":=",
"&",
"Printer",
"{",
"w",
":",
"w",
",",
"indent",
":",
"\"",
"\"",
",",
"omitEmpty",
":",
"true",
",",
"exclude",
":",
"map",
"[",
"reflect",
".",
"Type",
"]",
"bool",
"{",
"}",
",",
"}",
"\n",
"for",
"_",
",",
"option",
":=",
"range",
"options",
"{",
"option",
"(",
"p",
")",
"\n",
"}",
"\n",
"return",
"p",
"\n",
"}"
] | // New creates a new Printer on w with the given Options. | [
"New",
"creates",
"a",
"new",
"Printer",
"on",
"w",
"with",
"the",
"given",
"Options",
"."
] | d37bc2a10ba1a7951e19dd5dc10f7d59b142d8d7 | https://github.com/alecthomas/repr/blob/d37bc2a10ba1a7951e19dd5dc10f7d59b142d8d7/repr.go#L91-L102 |
2,258 | alecthomas/repr | repr.go | Print | func (p *Printer) Print(vs ...interface{}) {
for i, v := range vs {
if i > 0 {
fmt.Fprint(p.w, " ")
}
p.reprValue(map[reflect.Value]bool{}, reflect.ValueOf(v), "")
}
} | go | func (p *Printer) Print(vs ...interface{}) {
for i, v := range vs {
if i > 0 {
fmt.Fprint(p.w, " ")
}
p.reprValue(map[reflect.Value]bool{}, reflect.ValueOf(v), "")
}
} | [
"func",
"(",
"p",
"*",
"Printer",
")",
"Print",
"(",
"vs",
"...",
"interface",
"{",
"}",
")",
"{",
"for",
"i",
",",
"v",
":=",
"range",
"vs",
"{",
"if",
"i",
">",
"0",
"{",
"fmt",
".",
"Fprint",
"(",
"p",
".",
"w",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"p",
".",
"reprValue",
"(",
"map",
"[",
"reflect",
".",
"Value",
"]",
"bool",
"{",
"}",
",",
"reflect",
".",
"ValueOf",
"(",
"v",
")",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"}"
] | // Print the values. | [
"Print",
"the",
"values",
"."
] | d37bc2a10ba1a7951e19dd5dc10f7d59b142d8d7 | https://github.com/alecthomas/repr/blob/d37bc2a10ba1a7951e19dd5dc10f7d59b142d8d7/repr.go#L119-L126 |
2,259 | alecthomas/repr | repr.go | String | func String(v interface{}, options ...Option) string {
w := bytes.NewBuffer(nil)
options = append([]Option{NoIndent()}, options...)
p := New(w, options...)
p.Print(v)
return w.String()
} | go | func String(v interface{}, options ...Option) string {
w := bytes.NewBuffer(nil)
options = append([]Option{NoIndent()}, options...)
p := New(w, options...)
p.Print(v)
return w.String()
} | [
"func",
"String",
"(",
"v",
"interface",
"{",
"}",
",",
"options",
"...",
"Option",
")",
"string",
"{",
"w",
":=",
"bytes",
".",
"NewBuffer",
"(",
"nil",
")",
"\n",
"options",
"=",
"append",
"(",
"[",
"]",
"Option",
"{",
"NoIndent",
"(",
")",
"}",
",",
"options",
"...",
")",
"\n",
"p",
":=",
"New",
"(",
"w",
",",
"options",
"...",
")",
"\n",
"p",
".",
"Print",
"(",
"v",
")",
"\n",
"return",
"w",
".",
"String",
"(",
")",
"\n",
"}"
] | // String returns a string representing v. | [
"String",
"returns",
"a",
"string",
"representing",
"v",
"."
] | d37bc2a10ba1a7951e19dd5dc10f7d59b142d8d7 | https://github.com/alecthomas/repr/blob/d37bc2a10ba1a7951e19dd5dc10f7d59b142d8d7/repr.go#L278-L284 |
2,260 | alecthomas/repr | repr.go | Println | func Println(vs ...interface{}) {
args, options := extractOptions(vs...)
New(os.Stdout, options...).Println(args...)
} | go | func Println(vs ...interface{}) {
args, options := extractOptions(vs...)
New(os.Stdout, options...).Println(args...)
} | [
"func",
"Println",
"(",
"vs",
"...",
"interface",
"{",
"}",
")",
"{",
"args",
",",
"options",
":=",
"extractOptions",
"(",
"vs",
"...",
")",
"\n",
"New",
"(",
"os",
".",
"Stdout",
",",
"options",
"...",
")",
".",
"Println",
"(",
"args",
"...",
")",
"\n",
"}"
] | // Println prints v to os.Stdout, one per line. | [
"Println",
"prints",
"v",
"to",
"os",
".",
"Stdout",
"one",
"per",
"line",
"."
] | d37bc2a10ba1a7951e19dd5dc10f7d59b142d8d7 | https://github.com/alecthomas/repr/blob/d37bc2a10ba1a7951e19dd5dc10f7d59b142d8d7/repr.go#L298-L301 |
2,261 | alecthomas/repr | repr.go | Print | func Print(vs ...interface{}) {
args, options := extractOptions(vs...)
New(os.Stdout, options...).Print(args...)
} | go | func Print(vs ...interface{}) {
args, options := extractOptions(vs...)
New(os.Stdout, options...).Print(args...)
} | [
"func",
"Print",
"(",
"vs",
"...",
"interface",
"{",
"}",
")",
"{",
"args",
",",
"options",
":=",
"extractOptions",
"(",
"vs",
"...",
")",
"\n",
"New",
"(",
"os",
".",
"Stdout",
",",
"options",
"...",
")",
".",
"Print",
"(",
"args",
"...",
")",
"\n",
"}"
] | // Print writes a representation of v to os.Stdout, separated by spaces. | [
"Print",
"writes",
"a",
"representation",
"of",
"v",
"to",
"os",
".",
"Stdout",
"separated",
"by",
"spaces",
"."
] | d37bc2a10ba1a7951e19dd5dc10f7d59b142d8d7 | https://github.com/alecthomas/repr/blob/d37bc2a10ba1a7951e19dd5dc10f7d59b142d8d7/repr.go#L304-L307 |
2,262 | MarinX/keylogger | keylogger.go | New | func New(devPath string) (*KeyLogger, error) {
k := &KeyLogger{}
if !k.IsRoot() {
return nil, errors.New("Must be run as root")
}
fd, err := os.Open(devPath)
k.fd = fd
return k, err
} | go | func New(devPath string) (*KeyLogger, error) {
k := &KeyLogger{}
if !k.IsRoot() {
return nil, errors.New("Must be run as root")
}
fd, err := os.Open(devPath)
k.fd = fd
return k, err
} | [
"func",
"New",
"(",
"devPath",
"string",
")",
"(",
"*",
"KeyLogger",
",",
"error",
")",
"{",
"k",
":=",
"&",
"KeyLogger",
"{",
"}",
"\n",
"if",
"!",
"k",
".",
"IsRoot",
"(",
")",
"{",
"return",
"nil",
",",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"fd",
",",
"err",
":=",
"os",
".",
"Open",
"(",
"devPath",
")",
"\n",
"k",
".",
"fd",
"=",
"fd",
"\n",
"return",
"k",
",",
"err",
"\n",
"}"
] | // New creates a new keylogger for a device path | [
"New",
"creates",
"a",
"new",
"keylogger",
"for",
"a",
"device",
"path"
] | bf368a5eb23f3fa9da2311cb6812ce0a2be9c53e | https://github.com/MarinX/keylogger/blob/bf368a5eb23f3fa9da2311cb6812ce0a2be9c53e/keylogger.go#L22-L30 |
2,263 | MarinX/keylogger | keylogger.go | FindKeyboardDevice | func FindKeyboardDevice() string {
path := "/sys/class/input/event%d/device/name"
resolved := "/dev/input/event%d"
for i := 0; i < 255; i++ {
buff, err := ioutil.ReadFile(fmt.Sprintf(path, i))
if err != nil {
logrus.Error(err)
}
if strings.Contains(strings.ToLower(string(buff)), "keyboard") {
return fmt.Sprintf(resolved, i)
}
}
return ""
} | go | func FindKeyboardDevice() string {
path := "/sys/class/input/event%d/device/name"
resolved := "/dev/input/event%d"
for i := 0; i < 255; i++ {
buff, err := ioutil.ReadFile(fmt.Sprintf(path, i))
if err != nil {
logrus.Error(err)
}
if strings.Contains(strings.ToLower(string(buff)), "keyboard") {
return fmt.Sprintf(resolved, i)
}
}
return ""
} | [
"func",
"FindKeyboardDevice",
"(",
")",
"string",
"{",
"path",
":=",
"\"",
"\"",
"\n",
"resolved",
":=",
"\"",
"\"",
"\n\n",
"for",
"i",
":=",
"0",
";",
"i",
"<",
"255",
";",
"i",
"++",
"{",
"buff",
",",
"err",
":=",
"ioutil",
".",
"ReadFile",
"(",
"fmt",
".",
"Sprintf",
"(",
"path",
",",
"i",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"logrus",
".",
"Error",
"(",
"err",
")",
"\n",
"}",
"\n",
"if",
"strings",
".",
"Contains",
"(",
"strings",
".",
"ToLower",
"(",
"string",
"(",
"buff",
")",
")",
",",
"\"",
"\"",
")",
"{",
"return",
"fmt",
".",
"Sprintf",
"(",
"resolved",
",",
"i",
")",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"\"",
"\"",
"\n",
"}"
] | // FindKeyboardDevice by going through each device registered on OS
// Mostly it will contain keyword - keyboard
// Returns the file path which contains events | [
"FindKeyboardDevice",
"by",
"going",
"through",
"each",
"device",
"registered",
"on",
"OS",
"Mostly",
"it",
"will",
"contain",
"keyword",
"-",
"keyboard",
"Returns",
"the",
"file",
"path",
"which",
"contains",
"events"
] | bf368a5eb23f3fa9da2311cb6812ce0a2be9c53e | https://github.com/MarinX/keylogger/blob/bf368a5eb23f3fa9da2311cb6812ce0a2be9c53e/keylogger.go#L35-L49 |
2,264 | MarinX/keylogger | keylogger.go | Read | func (k *KeyLogger) Read() chan InputEvent {
event := make(chan InputEvent)
go func(event chan InputEvent) {
for {
e, err := k.read()
if err != nil {
logrus.Error(err)
close(event)
break
}
if e != nil {
event <- *e
}
}
}(event)
return event
} | go | func (k *KeyLogger) Read() chan InputEvent {
event := make(chan InputEvent)
go func(event chan InputEvent) {
for {
e, err := k.read()
if err != nil {
logrus.Error(err)
close(event)
break
}
if e != nil {
event <- *e
}
}
}(event)
return event
} | [
"func",
"(",
"k",
"*",
"KeyLogger",
")",
"Read",
"(",
")",
"chan",
"InputEvent",
"{",
"event",
":=",
"make",
"(",
"chan",
"InputEvent",
")",
"\n",
"go",
"func",
"(",
"event",
"chan",
"InputEvent",
")",
"{",
"for",
"{",
"e",
",",
"err",
":=",
"k",
".",
"read",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"logrus",
".",
"Error",
"(",
"err",
")",
"\n",
"close",
"(",
"event",
")",
"\n",
"break",
"\n",
"}",
"\n\n",
"if",
"e",
"!=",
"nil",
"{",
"event",
"<-",
"*",
"e",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"(",
"event",
")",
"\n",
"return",
"event",
"\n",
"}"
] | // Read from file descriptor
// Blocking call, returns channel
// Make sure to close channel when finish | [
"Read",
"from",
"file",
"descriptor",
"Blocking",
"call",
"returns",
"channel",
"Make",
"sure",
"to",
"close",
"channel",
"when",
"finish"
] | bf368a5eb23f3fa9da2311cb6812ce0a2be9c53e | https://github.com/MarinX/keylogger/blob/bf368a5eb23f3fa9da2311cb6812ce0a2be9c53e/keylogger.go#L59-L76 |
2,265 | MarinX/keylogger | keylogger.go | read | func (k *KeyLogger) read() (*InputEvent, error) {
buffer := make([]byte, eventsize)
n, err := k.fd.Read(buffer)
if err != nil {
return nil, err
}
// no input, dont send error
if n <= 0 {
return nil, nil
}
return k.eventFromBuffer(buffer)
} | go | func (k *KeyLogger) read() (*InputEvent, error) {
buffer := make([]byte, eventsize)
n, err := k.fd.Read(buffer)
if err != nil {
return nil, err
}
// no input, dont send error
if n <= 0 {
return nil, nil
}
return k.eventFromBuffer(buffer)
} | [
"func",
"(",
"k",
"*",
"KeyLogger",
")",
"read",
"(",
")",
"(",
"*",
"InputEvent",
",",
"error",
")",
"{",
"buffer",
":=",
"make",
"(",
"[",
"]",
"byte",
",",
"eventsize",
")",
"\n",
"n",
",",
"err",
":=",
"k",
".",
"fd",
".",
"Read",
"(",
"buffer",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"// no input, dont send error",
"if",
"n",
"<=",
"0",
"{",
"return",
"nil",
",",
"nil",
"\n",
"}",
"\n",
"return",
"k",
".",
"eventFromBuffer",
"(",
"buffer",
")",
"\n",
"}"
] | // read from file description and parse binary into go struct | [
"read",
"from",
"file",
"description",
"and",
"parse",
"binary",
"into",
"go",
"struct"
] | bf368a5eb23f3fa9da2311cb6812ce0a2be9c53e | https://github.com/MarinX/keylogger/blob/bf368a5eb23f3fa9da2311cb6812ce0a2be9c53e/keylogger.go#L79-L90 |
2,266 | MarinX/keylogger | keylogger.go | eventFromBuffer | func (k *KeyLogger) eventFromBuffer(buffer []byte) (*InputEvent, error) {
event := &InputEvent{}
err := binary.Read(bytes.NewBuffer(buffer), binary.LittleEndian, event)
return event, err
} | go | func (k *KeyLogger) eventFromBuffer(buffer []byte) (*InputEvent, error) {
event := &InputEvent{}
err := binary.Read(bytes.NewBuffer(buffer), binary.LittleEndian, event)
return event, err
} | [
"func",
"(",
"k",
"*",
"KeyLogger",
")",
"eventFromBuffer",
"(",
"buffer",
"[",
"]",
"byte",
")",
"(",
"*",
"InputEvent",
",",
"error",
")",
"{",
"event",
":=",
"&",
"InputEvent",
"{",
"}",
"\n",
"err",
":=",
"binary",
".",
"Read",
"(",
"bytes",
".",
"NewBuffer",
"(",
"buffer",
")",
",",
"binary",
".",
"LittleEndian",
",",
"event",
")",
"\n",
"return",
"event",
",",
"err",
"\n",
"}"
] | // eventFromBuffer parser bytes into InputEvent struct | [
"eventFromBuffer",
"parser",
"bytes",
"into",
"InputEvent",
"struct"
] | bf368a5eb23f3fa9da2311cb6812ce0a2be9c53e | https://github.com/MarinX/keylogger/blob/bf368a5eb23f3fa9da2311cb6812ce0a2be9c53e/keylogger.go#L93-L97 |
2,267 | MarinX/keylogger | keylogger.go | Close | func (k *KeyLogger) Close() error {
if k.fd == nil {
return nil
}
return k.fd.Close()
} | go | func (k *KeyLogger) Close() error {
if k.fd == nil {
return nil
}
return k.fd.Close()
} | [
"func",
"(",
"k",
"*",
"KeyLogger",
")",
"Close",
"(",
")",
"error",
"{",
"if",
"k",
".",
"fd",
"==",
"nil",
"{",
"return",
"nil",
"\n",
"}",
"\n",
"return",
"k",
".",
"fd",
".",
"Close",
"(",
")",
"\n",
"}"
] | // Close file descriptor | [
"Close",
"file",
"descriptor"
] | bf368a5eb23f3fa9da2311cb6812ce0a2be9c53e | https://github.com/MarinX/keylogger/blob/bf368a5eb23f3fa9da2311cb6812ce0a2be9c53e/keylogger.go#L100-L105 |
2,268 | russross/meddler | meddler.go | Register | func Register(name string, m Meddler) {
if name == "pk" {
panic("meddler.Register: pk cannot be used as a meddler name")
}
registry[name] = m
} | go | func Register(name string, m Meddler) {
if name == "pk" {
panic("meddler.Register: pk cannot be used as a meddler name")
}
registry[name] = m
} | [
"func",
"Register",
"(",
"name",
"string",
",",
"m",
"Meddler",
")",
"{",
"if",
"name",
"==",
"\"",
"\"",
"{",
"panic",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"registry",
"[",
"name",
"]",
"=",
"m",
"\n",
"}"
] | // Register sets up a meddler type. Meddlers get a chance to meddle with the
// data being loaded or saved when a field is annotated with the name of the meddler.
// The registry is global. | [
"Register",
"sets",
"up",
"a",
"meddler",
"type",
".",
"Meddlers",
"get",
"a",
"chance",
"to",
"meddle",
"with",
"the",
"data",
"being",
"loaded",
"or",
"saved",
"when",
"a",
"field",
"is",
"annotated",
"with",
"the",
"name",
"of",
"the",
"meddler",
".",
"The",
"registry",
"is",
"global",
"."
] | 87a225081a7cb35c4f5f8d0977a79105e5287115 | https://github.com/russross/meddler/blob/87a225081a7cb35c4f5f8d0977a79105e5287115/meddler.go#L35-L40 |
2,269 | russross/meddler | meddler.go | PreRead | func (elt TimeMeddler) PreRead(fieldAddr interface{}) (scanTarget interface{}, err error) {
switch tgt := fieldAddr.(type) {
case *time.Time:
if elt.ZeroIsNull {
return &tgt, nil
}
return fieldAddr, nil
case **time.Time:
if elt.ZeroIsNull {
return nil, fmt.Errorf("meddler.TimeMeddler cannot be used on a *time.Time field, only time.Time")
}
return fieldAddr, nil
default:
return nil, fmt.Errorf("meddler.TimeMeddler.PreRead: unknown struct field type: %T", fieldAddr)
}
} | go | func (elt TimeMeddler) PreRead(fieldAddr interface{}) (scanTarget interface{}, err error) {
switch tgt := fieldAddr.(type) {
case *time.Time:
if elt.ZeroIsNull {
return &tgt, nil
}
return fieldAddr, nil
case **time.Time:
if elt.ZeroIsNull {
return nil, fmt.Errorf("meddler.TimeMeddler cannot be used on a *time.Time field, only time.Time")
}
return fieldAddr, nil
default:
return nil, fmt.Errorf("meddler.TimeMeddler.PreRead: unknown struct field type: %T", fieldAddr)
}
} | [
"func",
"(",
"elt",
"TimeMeddler",
")",
"PreRead",
"(",
"fieldAddr",
"interface",
"{",
"}",
")",
"(",
"scanTarget",
"interface",
"{",
"}",
",",
"err",
"error",
")",
"{",
"switch",
"tgt",
":=",
"fieldAddr",
".",
"(",
"type",
")",
"{",
"case",
"*",
"time",
".",
"Time",
":",
"if",
"elt",
".",
"ZeroIsNull",
"{",
"return",
"&",
"tgt",
",",
"nil",
"\n",
"}",
"\n",
"return",
"fieldAddr",
",",
"nil",
"\n",
"case",
"*",
"*",
"time",
".",
"Time",
":",
"if",
"elt",
".",
"ZeroIsNull",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"return",
"fieldAddr",
",",
"nil",
"\n",
"default",
":",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"fieldAddr",
")",
"\n",
"}",
"\n",
"}"
] | // PreRead is called before a Scan operation for fields that have a TimeMeddler | [
"PreRead",
"is",
"called",
"before",
"a",
"Scan",
"operation",
"for",
"fields",
"that",
"have",
"a",
"TimeMeddler"
] | 87a225081a7cb35c4f5f8d0977a79105e5287115 | https://github.com/russross/meddler/blob/87a225081a7cb35c4f5f8d0977a79105e5287115/meddler.go#L84-L99 |
2,270 | russross/meddler | meddler.go | PostRead | func (elt TimeMeddler) PostRead(fieldAddr, scanTarget interface{}) error {
switch tgt := fieldAddr.(type) {
case *time.Time:
if elt.ZeroIsNull {
src := scanTarget.(**time.Time)
if *src == nil {
*tgt = time.Time{}
} else if elt.Local {
*tgt = (*src).Local()
} else {
*tgt = (*src).UTC()
}
return nil
}
src := scanTarget.(*time.Time)
if elt.Local {
*tgt = src.Local()
} else {
*tgt = src.UTC()
}
return nil
case **time.Time:
if elt.ZeroIsNull {
return fmt.Errorf("meddler TimeMeddler cannot be used on a *time.Time field, only time.Time")
}
src := scanTarget.(**time.Time)
if *src == nil {
*tgt = nil
} else if elt.Local {
**src = (*src).Local()
*tgt = *src
} else {
**src = (*src).UTC()
*tgt = *src
}
return nil
default:
return fmt.Errorf("meddler.TimeMeddler.PostRead: unknown struct field type: %T", fieldAddr)
}
} | go | func (elt TimeMeddler) PostRead(fieldAddr, scanTarget interface{}) error {
switch tgt := fieldAddr.(type) {
case *time.Time:
if elt.ZeroIsNull {
src := scanTarget.(**time.Time)
if *src == nil {
*tgt = time.Time{}
} else if elt.Local {
*tgt = (*src).Local()
} else {
*tgt = (*src).UTC()
}
return nil
}
src := scanTarget.(*time.Time)
if elt.Local {
*tgt = src.Local()
} else {
*tgt = src.UTC()
}
return nil
case **time.Time:
if elt.ZeroIsNull {
return fmt.Errorf("meddler TimeMeddler cannot be used on a *time.Time field, only time.Time")
}
src := scanTarget.(**time.Time)
if *src == nil {
*tgt = nil
} else if elt.Local {
**src = (*src).Local()
*tgt = *src
} else {
**src = (*src).UTC()
*tgt = *src
}
return nil
default:
return fmt.Errorf("meddler.TimeMeddler.PostRead: unknown struct field type: %T", fieldAddr)
}
} | [
"func",
"(",
"elt",
"TimeMeddler",
")",
"PostRead",
"(",
"fieldAddr",
",",
"scanTarget",
"interface",
"{",
"}",
")",
"error",
"{",
"switch",
"tgt",
":=",
"fieldAddr",
".",
"(",
"type",
")",
"{",
"case",
"*",
"time",
".",
"Time",
":",
"if",
"elt",
".",
"ZeroIsNull",
"{",
"src",
":=",
"scanTarget",
".",
"(",
"*",
"*",
"time",
".",
"Time",
")",
"\n",
"if",
"*",
"src",
"==",
"nil",
"{",
"*",
"tgt",
"=",
"time",
".",
"Time",
"{",
"}",
"\n",
"}",
"else",
"if",
"elt",
".",
"Local",
"{",
"*",
"tgt",
"=",
"(",
"*",
"src",
")",
".",
"Local",
"(",
")",
"\n",
"}",
"else",
"{",
"*",
"tgt",
"=",
"(",
"*",
"src",
")",
".",
"UTC",
"(",
")",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}",
"\n\n",
"src",
":=",
"scanTarget",
".",
"(",
"*",
"time",
".",
"Time",
")",
"\n",
"if",
"elt",
".",
"Local",
"{",
"*",
"tgt",
"=",
"src",
".",
"Local",
"(",
")",
"\n",
"}",
"else",
"{",
"*",
"tgt",
"=",
"src",
".",
"UTC",
"(",
")",
"\n",
"}",
"\n\n",
"return",
"nil",
"\n\n",
"case",
"*",
"*",
"time",
".",
"Time",
":",
"if",
"elt",
".",
"ZeroIsNull",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"src",
":=",
"scanTarget",
".",
"(",
"*",
"*",
"time",
".",
"Time",
")",
"\n",
"if",
"*",
"src",
"==",
"nil",
"{",
"*",
"tgt",
"=",
"nil",
"\n",
"}",
"else",
"if",
"elt",
".",
"Local",
"{",
"*",
"*",
"src",
"=",
"(",
"*",
"src",
")",
".",
"Local",
"(",
")",
"\n",
"*",
"tgt",
"=",
"*",
"src",
"\n",
"}",
"else",
"{",
"*",
"*",
"src",
"=",
"(",
"*",
"src",
")",
".",
"UTC",
"(",
")",
"\n",
"*",
"tgt",
"=",
"*",
"src",
"\n",
"}",
"\n\n",
"return",
"nil",
"\n\n",
"default",
":",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"fieldAddr",
")",
"\n",
"}",
"\n",
"}"
] | // PostRead is called after a Scan operation for fields that have a TimeMeddler | [
"PostRead",
"is",
"called",
"after",
"a",
"Scan",
"operation",
"for",
"fields",
"that",
"have",
"a",
"TimeMeddler"
] | 87a225081a7cb35c4f5f8d0977a79105e5287115 | https://github.com/russross/meddler/blob/87a225081a7cb35c4f5f8d0977a79105e5287115/meddler.go#L102-L146 |
2,271 | russross/meddler | meddler.go | PreWrite | func (elt TimeMeddler) PreWrite(field interface{}) (saveValue interface{}, err error) {
switch tgt := field.(type) {
case time.Time:
if elt.ZeroIsNull && tgt.IsZero() {
return nil, nil
}
return tgt.UTC(), nil
case *time.Time:
if tgt == nil || elt.ZeroIsNull && tgt.IsZero() {
return nil, nil
}
return tgt.UTC(), nil
default:
return nil, fmt.Errorf("meddler.TimeMeddler.PreWrite: unknown struct field type: %T", field)
}
} | go | func (elt TimeMeddler) PreWrite(field interface{}) (saveValue interface{}, err error) {
switch tgt := field.(type) {
case time.Time:
if elt.ZeroIsNull && tgt.IsZero() {
return nil, nil
}
return tgt.UTC(), nil
case *time.Time:
if tgt == nil || elt.ZeroIsNull && tgt.IsZero() {
return nil, nil
}
return tgt.UTC(), nil
default:
return nil, fmt.Errorf("meddler.TimeMeddler.PreWrite: unknown struct field type: %T", field)
}
} | [
"func",
"(",
"elt",
"TimeMeddler",
")",
"PreWrite",
"(",
"field",
"interface",
"{",
"}",
")",
"(",
"saveValue",
"interface",
"{",
"}",
",",
"err",
"error",
")",
"{",
"switch",
"tgt",
":=",
"field",
".",
"(",
"type",
")",
"{",
"case",
"time",
".",
"Time",
":",
"if",
"elt",
".",
"ZeroIsNull",
"&&",
"tgt",
".",
"IsZero",
"(",
")",
"{",
"return",
"nil",
",",
"nil",
"\n",
"}",
"\n",
"return",
"tgt",
".",
"UTC",
"(",
")",
",",
"nil",
"\n\n",
"case",
"*",
"time",
".",
"Time",
":",
"if",
"tgt",
"==",
"nil",
"||",
"elt",
".",
"ZeroIsNull",
"&&",
"tgt",
".",
"IsZero",
"(",
")",
"{",
"return",
"nil",
",",
"nil",
"\n",
"}",
"\n",
"return",
"tgt",
".",
"UTC",
"(",
")",
",",
"nil",
"\n\n",
"default",
":",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"field",
")",
"\n",
"}",
"\n",
"}"
] | // PreWrite is called before an Insert or Update operation for fields that have a TimeMeddler | [
"PreWrite",
"is",
"called",
"before",
"an",
"Insert",
"or",
"Update",
"operation",
"for",
"fields",
"that",
"have",
"a",
"TimeMeddler"
] | 87a225081a7cb35c4f5f8d0977a79105e5287115 | https://github.com/russross/meddler/blob/87a225081a7cb35c4f5f8d0977a79105e5287115/meddler.go#L149-L166 |
2,272 | russross/meddler | meddler.go | PreRead | func (elt ZeroIsNullMeddler) PreRead(fieldAddr interface{}) (scanTarget interface{}, err error) {
// create a pointer to this element
// the database driver will set it to nil if the column value is null
return reflect.New(reflect.TypeOf(fieldAddr)).Interface(), nil
} | go | func (elt ZeroIsNullMeddler) PreRead(fieldAddr interface{}) (scanTarget interface{}, err error) {
// create a pointer to this element
// the database driver will set it to nil if the column value is null
return reflect.New(reflect.TypeOf(fieldAddr)).Interface(), nil
} | [
"func",
"(",
"elt",
"ZeroIsNullMeddler",
")",
"PreRead",
"(",
"fieldAddr",
"interface",
"{",
"}",
")",
"(",
"scanTarget",
"interface",
"{",
"}",
",",
"err",
"error",
")",
"{",
"// create a pointer to this element",
"// the database driver will set it to nil if the column value is null",
"return",
"reflect",
".",
"New",
"(",
"reflect",
".",
"TypeOf",
"(",
"fieldAddr",
")",
")",
".",
"Interface",
"(",
")",
",",
"nil",
"\n",
"}"
] | // PreRead is called before a Scan operation for fields that have the ZeroIsNullMeddler | [
"PreRead",
"is",
"called",
"before",
"a",
"Scan",
"operation",
"for",
"fields",
"that",
"have",
"the",
"ZeroIsNullMeddler"
] | 87a225081a7cb35c4f5f8d0977a79105e5287115 | https://github.com/russross/meddler/blob/87a225081a7cb35c4f5f8d0977a79105e5287115/meddler.go#L173-L177 |
2,273 | russross/meddler | meddler.go | PostRead | func (elt ZeroIsNullMeddler) PostRead(fieldAddr, scanTarget interface{}) error {
sv := reflect.ValueOf(scanTarget)
fv := reflect.ValueOf(fieldAddr)
if sv.Elem().IsNil() {
// null column, so set target to be zero value
fv.Elem().Set(reflect.Zero(fv.Elem().Type()))
} else {
// copy the value that scan found
fv.Elem().Set(sv.Elem().Elem())
}
return nil
} | go | func (elt ZeroIsNullMeddler) PostRead(fieldAddr, scanTarget interface{}) error {
sv := reflect.ValueOf(scanTarget)
fv := reflect.ValueOf(fieldAddr)
if sv.Elem().IsNil() {
// null column, so set target to be zero value
fv.Elem().Set(reflect.Zero(fv.Elem().Type()))
} else {
// copy the value that scan found
fv.Elem().Set(sv.Elem().Elem())
}
return nil
} | [
"func",
"(",
"elt",
"ZeroIsNullMeddler",
")",
"PostRead",
"(",
"fieldAddr",
",",
"scanTarget",
"interface",
"{",
"}",
")",
"error",
"{",
"sv",
":=",
"reflect",
".",
"ValueOf",
"(",
"scanTarget",
")",
"\n",
"fv",
":=",
"reflect",
".",
"ValueOf",
"(",
"fieldAddr",
")",
"\n",
"if",
"sv",
".",
"Elem",
"(",
")",
".",
"IsNil",
"(",
")",
"{",
"// null column, so set target to be zero value",
"fv",
".",
"Elem",
"(",
")",
".",
"Set",
"(",
"reflect",
".",
"Zero",
"(",
"fv",
".",
"Elem",
"(",
")",
".",
"Type",
"(",
")",
")",
")",
"\n",
"}",
"else",
"{",
"// copy the value that scan found",
"fv",
".",
"Elem",
"(",
")",
".",
"Set",
"(",
"sv",
".",
"Elem",
"(",
")",
".",
"Elem",
"(",
")",
")",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] | // PostRead is called after a Scan operation for fields that have the ZeroIsNullMeddler | [
"PostRead",
"is",
"called",
"after",
"a",
"Scan",
"operation",
"for",
"fields",
"that",
"have",
"the",
"ZeroIsNullMeddler"
] | 87a225081a7cb35c4f5f8d0977a79105e5287115 | https://github.com/russross/meddler/blob/87a225081a7cb35c4f5f8d0977a79105e5287115/meddler.go#L180-L191 |
2,274 | russross/meddler | meddler.go | PreWrite | func (elt ZeroIsNullMeddler) PreWrite(field interface{}) (saveValue interface{}, err error) {
val := reflect.ValueOf(field)
switch val.Kind() {
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
if val.Int() == 0 {
return nil, nil
}
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
if val.Uint() == 0 {
return nil, nil
}
case reflect.Float32, reflect.Float64:
if val.Float() == 0 {
return nil, nil
}
case reflect.Complex64, reflect.Complex128:
if val.Complex() == 0 {
return nil, nil
}
case reflect.String:
if val.String() == "" {
return nil, nil
}
case reflect.Bool:
if !val.Bool() {
return nil, nil
}
default:
return nil, fmt.Errorf("ZeroIsNullMeddler.PreWrite: unknown struct field type: %T", field)
}
return field, nil
} | go | func (elt ZeroIsNullMeddler) PreWrite(field interface{}) (saveValue interface{}, err error) {
val := reflect.ValueOf(field)
switch val.Kind() {
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
if val.Int() == 0 {
return nil, nil
}
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
if val.Uint() == 0 {
return nil, nil
}
case reflect.Float32, reflect.Float64:
if val.Float() == 0 {
return nil, nil
}
case reflect.Complex64, reflect.Complex128:
if val.Complex() == 0 {
return nil, nil
}
case reflect.String:
if val.String() == "" {
return nil, nil
}
case reflect.Bool:
if !val.Bool() {
return nil, nil
}
default:
return nil, fmt.Errorf("ZeroIsNullMeddler.PreWrite: unknown struct field type: %T", field)
}
return field, nil
} | [
"func",
"(",
"elt",
"ZeroIsNullMeddler",
")",
"PreWrite",
"(",
"field",
"interface",
"{",
"}",
")",
"(",
"saveValue",
"interface",
"{",
"}",
",",
"err",
"error",
")",
"{",
"val",
":=",
"reflect",
".",
"ValueOf",
"(",
"field",
")",
"\n",
"switch",
"val",
".",
"Kind",
"(",
")",
"{",
"case",
"reflect",
".",
"Int",
",",
"reflect",
".",
"Int8",
",",
"reflect",
".",
"Int16",
",",
"reflect",
".",
"Int32",
",",
"reflect",
".",
"Int64",
":",
"if",
"val",
".",
"Int",
"(",
")",
"==",
"0",
"{",
"return",
"nil",
",",
"nil",
"\n",
"}",
"\n",
"case",
"reflect",
".",
"Uint",
",",
"reflect",
".",
"Uint8",
",",
"reflect",
".",
"Uint16",
",",
"reflect",
".",
"Uint32",
",",
"reflect",
".",
"Uint64",
":",
"if",
"val",
".",
"Uint",
"(",
")",
"==",
"0",
"{",
"return",
"nil",
",",
"nil",
"\n",
"}",
"\n",
"case",
"reflect",
".",
"Float32",
",",
"reflect",
".",
"Float64",
":",
"if",
"val",
".",
"Float",
"(",
")",
"==",
"0",
"{",
"return",
"nil",
",",
"nil",
"\n",
"}",
"\n",
"case",
"reflect",
".",
"Complex64",
",",
"reflect",
".",
"Complex128",
":",
"if",
"val",
".",
"Complex",
"(",
")",
"==",
"0",
"{",
"return",
"nil",
",",
"nil",
"\n",
"}",
"\n",
"case",
"reflect",
".",
"String",
":",
"if",
"val",
".",
"String",
"(",
")",
"==",
"\"",
"\"",
"{",
"return",
"nil",
",",
"nil",
"\n",
"}",
"\n",
"case",
"reflect",
".",
"Bool",
":",
"if",
"!",
"val",
".",
"Bool",
"(",
")",
"{",
"return",
"nil",
",",
"nil",
"\n",
"}",
"\n",
"default",
":",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"field",
")",
"\n",
"}",
"\n\n",
"return",
"field",
",",
"nil",
"\n",
"}"
] | // PreWrite is called before an Insert or Update operation for fields that have the ZeroIsNullMeddler | [
"PreWrite",
"is",
"called",
"before",
"an",
"Insert",
"or",
"Update",
"operation",
"for",
"fields",
"that",
"have",
"the",
"ZeroIsNullMeddler"
] | 87a225081a7cb35c4f5f8d0977a79105e5287115 | https://github.com/russross/meddler/blob/87a225081a7cb35c4f5f8d0977a79105e5287115/meddler.go#L194-L226 |
2,275 | russross/meddler | meddler.go | PostRead | func (zip JSONMeddler) PostRead(fieldAddr, scanTarget interface{}) error {
ptr := scanTarget.(*[]byte)
if ptr == nil {
return fmt.Errorf("JSONMeddler.PostRead: nil pointer")
}
raw := *ptr
if zip {
// un-gzip and decode json
gzipReader, err := gzip.NewReader(bytes.NewReader(raw))
if err != nil {
return fmt.Errorf("Error creating gzip Reader: %v", err)
}
defer gzipReader.Close()
jsonDecoder := json.NewDecoder(gzipReader)
if err := jsonDecoder.Decode(fieldAddr); err != nil {
return fmt.Errorf("JSON decoder/gzip error: %v", err)
}
if err := gzipReader.Close(); err != nil {
return fmt.Errorf("Closing gzip reader: %v", err)
}
return nil
}
// decode json
jsonDecoder := json.NewDecoder(bytes.NewReader(raw))
if err := jsonDecoder.Decode(fieldAddr); err != nil {
return fmt.Errorf("JSON decode error: %v", err)
}
return nil
} | go | func (zip JSONMeddler) PostRead(fieldAddr, scanTarget interface{}) error {
ptr := scanTarget.(*[]byte)
if ptr == nil {
return fmt.Errorf("JSONMeddler.PostRead: nil pointer")
}
raw := *ptr
if zip {
// un-gzip and decode json
gzipReader, err := gzip.NewReader(bytes.NewReader(raw))
if err != nil {
return fmt.Errorf("Error creating gzip Reader: %v", err)
}
defer gzipReader.Close()
jsonDecoder := json.NewDecoder(gzipReader)
if err := jsonDecoder.Decode(fieldAddr); err != nil {
return fmt.Errorf("JSON decoder/gzip error: %v", err)
}
if err := gzipReader.Close(); err != nil {
return fmt.Errorf("Closing gzip reader: %v", err)
}
return nil
}
// decode json
jsonDecoder := json.NewDecoder(bytes.NewReader(raw))
if err := jsonDecoder.Decode(fieldAddr); err != nil {
return fmt.Errorf("JSON decode error: %v", err)
}
return nil
} | [
"func",
"(",
"zip",
"JSONMeddler",
")",
"PostRead",
"(",
"fieldAddr",
",",
"scanTarget",
"interface",
"{",
"}",
")",
"error",
"{",
"ptr",
":=",
"scanTarget",
".",
"(",
"*",
"[",
"]",
"byte",
")",
"\n",
"if",
"ptr",
"==",
"nil",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"raw",
":=",
"*",
"ptr",
"\n\n",
"if",
"zip",
"{",
"// un-gzip and decode json",
"gzipReader",
",",
"err",
":=",
"gzip",
".",
"NewReader",
"(",
"bytes",
".",
"NewReader",
"(",
"raw",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n",
"defer",
"gzipReader",
".",
"Close",
"(",
")",
"\n",
"jsonDecoder",
":=",
"json",
".",
"NewDecoder",
"(",
"gzipReader",
")",
"\n",
"if",
"err",
":=",
"jsonDecoder",
".",
"Decode",
"(",
"fieldAddr",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n",
"if",
"err",
":=",
"gzipReader",
".",
"Close",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n\n",
"return",
"nil",
"\n",
"}",
"\n\n",
"// decode json",
"jsonDecoder",
":=",
"json",
".",
"NewDecoder",
"(",
"bytes",
".",
"NewReader",
"(",
"raw",
")",
")",
"\n",
"if",
"err",
":=",
"jsonDecoder",
".",
"Decode",
"(",
"fieldAddr",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n\n",
"return",
"nil",
"\n",
"}"
] | // PostRead is called after a Scan operation for fields that have the JSONMeddler | [
"PostRead",
"is",
"called",
"after",
"a",
"Scan",
"operation",
"for",
"fields",
"that",
"have",
"the",
"JSONMeddler"
] | 87a225081a7cb35c4f5f8d0977a79105e5287115 | https://github.com/russross/meddler/blob/87a225081a7cb35c4f5f8d0977a79105e5287115/meddler.go#L238-L270 |
2,276 | russross/meddler | meddler.go | PreWrite | func (zip JSONMeddler) PreWrite(field interface{}) (saveValue interface{}, err error) {
buffer := new(bytes.Buffer)
if zip {
// json encode and gzip
gzipWriter := gzip.NewWriter(buffer)
defer gzipWriter.Close()
jsonEncoder := json.NewEncoder(gzipWriter)
if err := jsonEncoder.Encode(field); err != nil {
return nil, fmt.Errorf("JSON encoding/gzip error: %v", err)
}
if err := gzipWriter.Close(); err != nil {
return nil, fmt.Errorf("Closing gzip writer: %v", err)
}
return buffer.Bytes(), nil
}
// json encode
jsonEncoder := json.NewEncoder(buffer)
if err := jsonEncoder.Encode(field); err != nil {
return nil, fmt.Errorf("JSON encoding error: %v", err)
}
return buffer.Bytes(), nil
} | go | func (zip JSONMeddler) PreWrite(field interface{}) (saveValue interface{}, err error) {
buffer := new(bytes.Buffer)
if zip {
// json encode and gzip
gzipWriter := gzip.NewWriter(buffer)
defer gzipWriter.Close()
jsonEncoder := json.NewEncoder(gzipWriter)
if err := jsonEncoder.Encode(field); err != nil {
return nil, fmt.Errorf("JSON encoding/gzip error: %v", err)
}
if err := gzipWriter.Close(); err != nil {
return nil, fmt.Errorf("Closing gzip writer: %v", err)
}
return buffer.Bytes(), nil
}
// json encode
jsonEncoder := json.NewEncoder(buffer)
if err := jsonEncoder.Encode(field); err != nil {
return nil, fmt.Errorf("JSON encoding error: %v", err)
}
return buffer.Bytes(), nil
} | [
"func",
"(",
"zip",
"JSONMeddler",
")",
"PreWrite",
"(",
"field",
"interface",
"{",
"}",
")",
"(",
"saveValue",
"interface",
"{",
"}",
",",
"err",
"error",
")",
"{",
"buffer",
":=",
"new",
"(",
"bytes",
".",
"Buffer",
")",
"\n\n",
"if",
"zip",
"{",
"// json encode and gzip",
"gzipWriter",
":=",
"gzip",
".",
"NewWriter",
"(",
"buffer",
")",
"\n",
"defer",
"gzipWriter",
".",
"Close",
"(",
")",
"\n",
"jsonEncoder",
":=",
"json",
".",
"NewEncoder",
"(",
"gzipWriter",
")",
"\n",
"if",
"err",
":=",
"jsonEncoder",
".",
"Encode",
"(",
"field",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n",
"if",
"err",
":=",
"gzipWriter",
".",
"Close",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n\n",
"return",
"buffer",
".",
"Bytes",
"(",
")",
",",
"nil",
"\n",
"}",
"\n\n",
"// json encode",
"jsonEncoder",
":=",
"json",
".",
"NewEncoder",
"(",
"buffer",
")",
"\n",
"if",
"err",
":=",
"jsonEncoder",
".",
"Encode",
"(",
"field",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n",
"return",
"buffer",
".",
"Bytes",
"(",
")",
",",
"nil",
"\n",
"}"
] | // PreWrite is called before an Insert or Update operation for fields that have the JSONMeddler | [
"PreWrite",
"is",
"called",
"before",
"an",
"Insert",
"or",
"Update",
"operation",
"for",
"fields",
"that",
"have",
"the",
"JSONMeddler"
] | 87a225081a7cb35c4f5f8d0977a79105e5287115 | https://github.com/russross/meddler/blob/87a225081a7cb35c4f5f8d0977a79105e5287115/meddler.go#L273-L297 |
2,277 | russross/meddler | meddler.go | PreRead | func (zip GobMeddler) PreRead(fieldAddr interface{}) (scanTarget interface{}, err error) {
// give a pointer to a byte buffer to grab the raw data
return new([]byte), nil
} | go | func (zip GobMeddler) PreRead(fieldAddr interface{}) (scanTarget interface{}, err error) {
// give a pointer to a byte buffer to grab the raw data
return new([]byte), nil
} | [
"func",
"(",
"zip",
"GobMeddler",
")",
"PreRead",
"(",
"fieldAddr",
"interface",
"{",
"}",
")",
"(",
"scanTarget",
"interface",
"{",
"}",
",",
"err",
"error",
")",
"{",
"// give a pointer to a byte buffer to grab the raw data",
"return",
"new",
"(",
"[",
"]",
"byte",
")",
",",
"nil",
"\n",
"}"
] | // PreRead is called before a Scan operation for fields that have the GobMeddler | [
"PreRead",
"is",
"called",
"before",
"a",
"Scan",
"operation",
"for",
"fields",
"that",
"have",
"the",
"GobMeddler"
] | 87a225081a7cb35c4f5f8d0977a79105e5287115 | https://github.com/russross/meddler/blob/87a225081a7cb35c4f5f8d0977a79105e5287115/meddler.go#L303-L306 |
2,278 | russross/meddler | meddler.go | PostRead | func (zip GobMeddler) PostRead(fieldAddr, scanTarget interface{}) error {
ptr := scanTarget.(*[]byte)
if ptr == nil {
return fmt.Errorf("GobMeddler.PostRead: nil pointer")
}
raw := *ptr
if zip {
// un-gzip and decode gob
gzipReader, err := gzip.NewReader(bytes.NewReader(raw))
if err != nil {
return fmt.Errorf("Error creating gzip Reader: %v", err)
}
defer gzipReader.Close()
gobDecoder := gob.NewDecoder(gzipReader)
if err := gobDecoder.Decode(fieldAddr); err != nil {
return fmt.Errorf("Gob decoder/gzip error: %v", err)
}
if err := gzipReader.Close(); err != nil {
return fmt.Errorf("Closing gzip reader: %v", err)
}
return nil
}
// decode gob
gobDecoder := gob.NewDecoder(bytes.NewReader(raw))
if err := gobDecoder.Decode(fieldAddr); err != nil {
return fmt.Errorf("Gob decode error: %v", err)
}
return nil
} | go | func (zip GobMeddler) PostRead(fieldAddr, scanTarget interface{}) error {
ptr := scanTarget.(*[]byte)
if ptr == nil {
return fmt.Errorf("GobMeddler.PostRead: nil pointer")
}
raw := *ptr
if zip {
// un-gzip and decode gob
gzipReader, err := gzip.NewReader(bytes.NewReader(raw))
if err != nil {
return fmt.Errorf("Error creating gzip Reader: %v", err)
}
defer gzipReader.Close()
gobDecoder := gob.NewDecoder(gzipReader)
if err := gobDecoder.Decode(fieldAddr); err != nil {
return fmt.Errorf("Gob decoder/gzip error: %v", err)
}
if err := gzipReader.Close(); err != nil {
return fmt.Errorf("Closing gzip reader: %v", err)
}
return nil
}
// decode gob
gobDecoder := gob.NewDecoder(bytes.NewReader(raw))
if err := gobDecoder.Decode(fieldAddr); err != nil {
return fmt.Errorf("Gob decode error: %v", err)
}
return nil
} | [
"func",
"(",
"zip",
"GobMeddler",
")",
"PostRead",
"(",
"fieldAddr",
",",
"scanTarget",
"interface",
"{",
"}",
")",
"error",
"{",
"ptr",
":=",
"scanTarget",
".",
"(",
"*",
"[",
"]",
"byte",
")",
"\n",
"if",
"ptr",
"==",
"nil",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"raw",
":=",
"*",
"ptr",
"\n\n",
"if",
"zip",
"{",
"// un-gzip and decode gob",
"gzipReader",
",",
"err",
":=",
"gzip",
".",
"NewReader",
"(",
"bytes",
".",
"NewReader",
"(",
"raw",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n",
"defer",
"gzipReader",
".",
"Close",
"(",
")",
"\n",
"gobDecoder",
":=",
"gob",
".",
"NewDecoder",
"(",
"gzipReader",
")",
"\n",
"if",
"err",
":=",
"gobDecoder",
".",
"Decode",
"(",
"fieldAddr",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n",
"if",
"err",
":=",
"gzipReader",
".",
"Close",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n\n",
"return",
"nil",
"\n",
"}",
"\n\n",
"// decode gob",
"gobDecoder",
":=",
"gob",
".",
"NewDecoder",
"(",
"bytes",
".",
"NewReader",
"(",
"raw",
")",
")",
"\n",
"if",
"err",
":=",
"gobDecoder",
".",
"Decode",
"(",
"fieldAddr",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n\n",
"return",
"nil",
"\n",
"}"
] | // PostRead is called after a Scan operation for fields that have the GobMeddler | [
"PostRead",
"is",
"called",
"after",
"a",
"Scan",
"operation",
"for",
"fields",
"that",
"have",
"the",
"GobMeddler"
] | 87a225081a7cb35c4f5f8d0977a79105e5287115 | https://github.com/russross/meddler/blob/87a225081a7cb35c4f5f8d0977a79105e5287115/meddler.go#L309-L341 |
2,279 | russross/meddler | meddler.go | PreWrite | func (zip GobMeddler) PreWrite(field interface{}) (saveValue interface{}, err error) {
buffer := new(bytes.Buffer)
if zip {
// gob encode and gzip
gzipWriter := gzip.NewWriter(buffer)
defer gzipWriter.Close()
gobEncoder := gob.NewEncoder(gzipWriter)
if err := gobEncoder.Encode(field); err != nil {
return nil, fmt.Errorf("Gob encoding/gzip error: %v", err)
}
if err := gzipWriter.Close(); err != nil {
return nil, fmt.Errorf("Closing gzip writer: %v", err)
}
return buffer.Bytes(), nil
}
// gob encode
gobEncoder := gob.NewEncoder(buffer)
if err := gobEncoder.Encode(field); err != nil {
return nil, fmt.Errorf("Gob encoding error: %v", err)
}
return buffer.Bytes(), nil
} | go | func (zip GobMeddler) PreWrite(field interface{}) (saveValue interface{}, err error) {
buffer := new(bytes.Buffer)
if zip {
// gob encode and gzip
gzipWriter := gzip.NewWriter(buffer)
defer gzipWriter.Close()
gobEncoder := gob.NewEncoder(gzipWriter)
if err := gobEncoder.Encode(field); err != nil {
return nil, fmt.Errorf("Gob encoding/gzip error: %v", err)
}
if err := gzipWriter.Close(); err != nil {
return nil, fmt.Errorf("Closing gzip writer: %v", err)
}
return buffer.Bytes(), nil
}
// gob encode
gobEncoder := gob.NewEncoder(buffer)
if err := gobEncoder.Encode(field); err != nil {
return nil, fmt.Errorf("Gob encoding error: %v", err)
}
return buffer.Bytes(), nil
} | [
"func",
"(",
"zip",
"GobMeddler",
")",
"PreWrite",
"(",
"field",
"interface",
"{",
"}",
")",
"(",
"saveValue",
"interface",
"{",
"}",
",",
"err",
"error",
")",
"{",
"buffer",
":=",
"new",
"(",
"bytes",
".",
"Buffer",
")",
"\n\n",
"if",
"zip",
"{",
"// gob encode and gzip",
"gzipWriter",
":=",
"gzip",
".",
"NewWriter",
"(",
"buffer",
")",
"\n",
"defer",
"gzipWriter",
".",
"Close",
"(",
")",
"\n",
"gobEncoder",
":=",
"gob",
".",
"NewEncoder",
"(",
"gzipWriter",
")",
"\n",
"if",
"err",
":=",
"gobEncoder",
".",
"Encode",
"(",
"field",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n",
"if",
"err",
":=",
"gzipWriter",
".",
"Close",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n\n",
"return",
"buffer",
".",
"Bytes",
"(",
")",
",",
"nil",
"\n",
"}",
"\n\n",
"// gob encode",
"gobEncoder",
":=",
"gob",
".",
"NewEncoder",
"(",
"buffer",
")",
"\n",
"if",
"err",
":=",
"gobEncoder",
".",
"Encode",
"(",
"field",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n",
"return",
"buffer",
".",
"Bytes",
"(",
")",
",",
"nil",
"\n",
"}"
] | // PreWrite is called before an Insert or Update operation for fields that have the GobMeddler | [
"PreWrite",
"is",
"called",
"before",
"an",
"Insert",
"or",
"Update",
"operation",
"for",
"fields",
"that",
"have",
"the",
"GobMeddler"
] | 87a225081a7cb35c4f5f8d0977a79105e5287115 | https://github.com/russross/meddler/blob/87a225081a7cb35c4f5f8d0977a79105e5287115/meddler.go#L344-L368 |
2,280 | russross/meddler | loadsave.go | DriverErr | func DriverErr(err error) (error, bool) {
if dbe, ok := err.(*dbErr); ok {
return dbe.err, true
}
return err, false
} | go | func DriverErr(err error) (error, bool) {
if dbe, ok := err.(*dbErr); ok {
return dbe.err, true
}
return err, false
} | [
"func",
"DriverErr",
"(",
"err",
"error",
")",
"(",
"error",
",",
"bool",
")",
"{",
"if",
"dbe",
",",
"ok",
":=",
"err",
".",
"(",
"*",
"dbErr",
")",
";",
"ok",
"{",
"return",
"dbe",
".",
"err",
",",
"true",
"\n",
"}",
"\n",
"return",
"err",
",",
"false",
"\n",
"}"
] | // DriverErr returns the original error as returned by the database driver
// if the error comes from the driver, with the second value set to true.
// Otherwise, it returns err itself with false as second value. | [
"DriverErr",
"returns",
"the",
"original",
"error",
"as",
"returned",
"by",
"the",
"database",
"driver",
"if",
"the",
"error",
"comes",
"from",
"the",
"driver",
"with",
"the",
"second",
"value",
"set",
"to",
"true",
".",
"Otherwise",
"it",
"returns",
"err",
"itself",
"with",
"false",
"as",
"second",
"value",
"."
] | 87a225081a7cb35c4f5f8d0977a79105e5287115 | https://github.com/russross/meddler/blob/87a225081a7cb35c4f5f8d0977a79105e5287115/loadsave.go#L21-L26 |
2,281 | russross/meddler | loadsave.go | Load | func (d *Database) Load(db DB, table string, dst interface{}, pk int64) error {
columns, err := d.ColumnsQuoted(dst, true)
if err != nil {
return err
}
// make sure we have a primary key field
pkName, _, err := d.PrimaryKey(dst)
if err != nil {
return err
}
if pkName == "" {
return fmt.Errorf("meddler.Load: no primary key field found")
}
// run the query
q := fmt.Sprintf("SELECT %s FROM %s WHERE %s = %s", columns, d.quoted(table), d.quoted(pkName), d.Placeholder)
rows, err := db.Query(q, pk)
if err != nil {
return &dbErr{msg: "meddler.Load: DB error in Query", err: err}
}
// scan the row
return d.ScanRow(rows, dst)
} | go | func (d *Database) Load(db DB, table string, dst interface{}, pk int64) error {
columns, err := d.ColumnsQuoted(dst, true)
if err != nil {
return err
}
// make sure we have a primary key field
pkName, _, err := d.PrimaryKey(dst)
if err != nil {
return err
}
if pkName == "" {
return fmt.Errorf("meddler.Load: no primary key field found")
}
// run the query
q := fmt.Sprintf("SELECT %s FROM %s WHERE %s = %s", columns, d.quoted(table), d.quoted(pkName), d.Placeholder)
rows, err := db.Query(q, pk)
if err != nil {
return &dbErr{msg: "meddler.Load: DB error in Query", err: err}
}
// scan the row
return d.ScanRow(rows, dst)
} | [
"func",
"(",
"d",
"*",
"Database",
")",
"Load",
"(",
"db",
"DB",
",",
"table",
"string",
",",
"dst",
"interface",
"{",
"}",
",",
"pk",
"int64",
")",
"error",
"{",
"columns",
",",
"err",
":=",
"d",
".",
"ColumnsQuoted",
"(",
"dst",
",",
"true",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"// make sure we have a primary key field",
"pkName",
",",
"_",
",",
"err",
":=",
"d",
".",
"PrimaryKey",
"(",
"dst",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"if",
"pkName",
"==",
"\"",
"\"",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"// run the query",
"q",
":=",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"columns",
",",
"d",
".",
"quoted",
"(",
"table",
")",
",",
"d",
".",
"quoted",
"(",
"pkName",
")",
",",
"d",
".",
"Placeholder",
")",
"\n\n",
"rows",
",",
"err",
":=",
"db",
".",
"Query",
"(",
"q",
",",
"pk",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"&",
"dbErr",
"{",
"msg",
":",
"\"",
"\"",
",",
"err",
":",
"err",
"}",
"\n",
"}",
"\n\n",
"// scan the row",
"return",
"d",
".",
"ScanRow",
"(",
"rows",
",",
"dst",
")",
"\n",
"}"
] | // Load loads a record using a query for the primary key field.
// Returns sql.ErrNoRows if not found. | [
"Load",
"loads",
"a",
"record",
"using",
"a",
"query",
"for",
"the",
"primary",
"key",
"field",
".",
"Returns",
"sql",
".",
"ErrNoRows",
"if",
"not",
"found",
"."
] | 87a225081a7cb35c4f5f8d0977a79105e5287115 | https://github.com/russross/meddler/blob/87a225081a7cb35c4f5f8d0977a79105e5287115/loadsave.go#L37-L62 |
2,282 | russross/meddler | loadsave.go | Load | func Load(db DB, table string, dst interface{}, pk int64) error {
return Default.Load(db, table, dst, pk)
} | go | func Load(db DB, table string, dst interface{}, pk int64) error {
return Default.Load(db, table, dst, pk)
} | [
"func",
"Load",
"(",
"db",
"DB",
",",
"table",
"string",
",",
"dst",
"interface",
"{",
"}",
",",
"pk",
"int64",
")",
"error",
"{",
"return",
"Default",
".",
"Load",
"(",
"db",
",",
"table",
",",
"dst",
",",
"pk",
")",
"\n",
"}"
] | // Load using the Default Database type | [
"Load",
"using",
"the",
"Default",
"Database",
"type"
] | 87a225081a7cb35c4f5f8d0977a79105e5287115 | https://github.com/russross/meddler/blob/87a225081a7cb35c4f5f8d0977a79105e5287115/loadsave.go#L65-L67 |
2,283 | russross/meddler | loadsave.go | Insert | func (d *Database) Insert(db DB, table string, src interface{}) error {
pkName, pkValue, err := d.PrimaryKey(src)
if err != nil {
return err
}
if pkName != "" && pkValue != 0 {
return fmt.Errorf("meddler.Insert: primary key must be zero")
}
// gather the query parts
namesPart, err := d.ColumnsQuoted(src, false)
if err != nil {
return err
}
valuesPart, err := d.PlaceholdersString(src, false)
if err != nil {
return err
}
values, err := d.Values(src, false)
if err != nil {
return err
}
// run the query
q := fmt.Sprintf("INSERT INTO %s (%s) VALUES (%s)", d.quoted(table), namesPart, valuesPart)
if d.UseReturningToGetID && pkName != "" {
q += " RETURNING " + d.quoted(pkName)
var newPk int64
err := db.QueryRow(q, values...).Scan(&newPk)
if err != nil {
return &dbErr{msg: "meddler.Insert: DB error in QueryRow", err: err}
}
if err = d.SetPrimaryKey(src, newPk); err != nil {
return fmt.Errorf("meddler.Insert: Error saving updated pk: %v", err)
}
} else if pkName != "" {
result, err := db.Exec(q, values...)
if err != nil {
return &dbErr{msg: "meddler.Insert: DB error in Exec", err: err}
}
// save the new primary key
newPk, err := result.LastInsertId()
if err != nil {
return &dbErr{msg: "meddler.Insert: DB error getting new primary key value", err: err}
}
if err = d.SetPrimaryKey(src, newPk); err != nil {
return fmt.Errorf("meddler.Insert: Error saving updated pk: %v", err)
}
} else {
// no primary key, so no need to lookup new value
_, err := db.Exec(q, values...)
if err != nil {
return &dbErr{msg: "meddler.Insert: DB error in Exec", err: err}
}
}
return nil
} | go | func (d *Database) Insert(db DB, table string, src interface{}) error {
pkName, pkValue, err := d.PrimaryKey(src)
if err != nil {
return err
}
if pkName != "" && pkValue != 0 {
return fmt.Errorf("meddler.Insert: primary key must be zero")
}
// gather the query parts
namesPart, err := d.ColumnsQuoted(src, false)
if err != nil {
return err
}
valuesPart, err := d.PlaceholdersString(src, false)
if err != nil {
return err
}
values, err := d.Values(src, false)
if err != nil {
return err
}
// run the query
q := fmt.Sprintf("INSERT INTO %s (%s) VALUES (%s)", d.quoted(table), namesPart, valuesPart)
if d.UseReturningToGetID && pkName != "" {
q += " RETURNING " + d.quoted(pkName)
var newPk int64
err := db.QueryRow(q, values...).Scan(&newPk)
if err != nil {
return &dbErr{msg: "meddler.Insert: DB error in QueryRow", err: err}
}
if err = d.SetPrimaryKey(src, newPk); err != nil {
return fmt.Errorf("meddler.Insert: Error saving updated pk: %v", err)
}
} else if pkName != "" {
result, err := db.Exec(q, values...)
if err != nil {
return &dbErr{msg: "meddler.Insert: DB error in Exec", err: err}
}
// save the new primary key
newPk, err := result.LastInsertId()
if err != nil {
return &dbErr{msg: "meddler.Insert: DB error getting new primary key value", err: err}
}
if err = d.SetPrimaryKey(src, newPk); err != nil {
return fmt.Errorf("meddler.Insert: Error saving updated pk: %v", err)
}
} else {
// no primary key, so no need to lookup new value
_, err := db.Exec(q, values...)
if err != nil {
return &dbErr{msg: "meddler.Insert: DB error in Exec", err: err}
}
}
return nil
} | [
"func",
"(",
"d",
"*",
"Database",
")",
"Insert",
"(",
"db",
"DB",
",",
"table",
"string",
",",
"src",
"interface",
"{",
"}",
")",
"error",
"{",
"pkName",
",",
"pkValue",
",",
"err",
":=",
"d",
".",
"PrimaryKey",
"(",
"src",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"if",
"pkName",
"!=",
"\"",
"\"",
"&&",
"pkValue",
"!=",
"0",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"// gather the query parts",
"namesPart",
",",
"err",
":=",
"d",
".",
"ColumnsQuoted",
"(",
"src",
",",
"false",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"valuesPart",
",",
"err",
":=",
"d",
".",
"PlaceholdersString",
"(",
"src",
",",
"false",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"values",
",",
"err",
":=",
"d",
".",
"Values",
"(",
"src",
",",
"false",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"// run the query",
"q",
":=",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"d",
".",
"quoted",
"(",
"table",
")",
",",
"namesPart",
",",
"valuesPart",
")",
"\n",
"if",
"d",
".",
"UseReturningToGetID",
"&&",
"pkName",
"!=",
"\"",
"\"",
"{",
"q",
"+=",
"\"",
"\"",
"+",
"d",
".",
"quoted",
"(",
"pkName",
")",
"\n",
"var",
"newPk",
"int64",
"\n",
"err",
":=",
"db",
".",
"QueryRow",
"(",
"q",
",",
"values",
"...",
")",
".",
"Scan",
"(",
"&",
"newPk",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"&",
"dbErr",
"{",
"msg",
":",
"\"",
"\"",
",",
"err",
":",
"err",
"}",
"\n",
"}",
"\n",
"if",
"err",
"=",
"d",
".",
"SetPrimaryKey",
"(",
"src",
",",
"newPk",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n",
"}",
"else",
"if",
"pkName",
"!=",
"\"",
"\"",
"{",
"result",
",",
"err",
":=",
"db",
".",
"Exec",
"(",
"q",
",",
"values",
"...",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"&",
"dbErr",
"{",
"msg",
":",
"\"",
"\"",
",",
"err",
":",
"err",
"}",
"\n",
"}",
"\n\n",
"// save the new primary key",
"newPk",
",",
"err",
":=",
"result",
".",
"LastInsertId",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"&",
"dbErr",
"{",
"msg",
":",
"\"",
"\"",
",",
"err",
":",
"err",
"}",
"\n",
"}",
"\n",
"if",
"err",
"=",
"d",
".",
"SetPrimaryKey",
"(",
"src",
",",
"newPk",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n",
"}",
"else",
"{",
"// no primary key, so no need to lookup new value",
"_",
",",
"err",
":=",
"db",
".",
"Exec",
"(",
"q",
",",
"values",
"...",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"&",
"dbErr",
"{",
"msg",
":",
"\"",
"\"",
",",
"err",
":",
"err",
"}",
"\n",
"}",
"\n",
"}",
"\n\n",
"return",
"nil",
"\n",
"}"
] | // Insert performs an INSERT query for the given record.
// If the record has a primary key flagged, it must be zero, and it
// will be set to the newly-allocated primary key value from the database
// as returned by LastInsertId. | [
"Insert",
"performs",
"an",
"INSERT",
"query",
"for",
"the",
"given",
"record",
".",
"If",
"the",
"record",
"has",
"a",
"primary",
"key",
"flagged",
"it",
"must",
"be",
"zero",
"and",
"it",
"will",
"be",
"set",
"to",
"the",
"newly",
"-",
"allocated",
"primary",
"key",
"value",
"from",
"the",
"database",
"as",
"returned",
"by",
"LastInsertId",
"."
] | 87a225081a7cb35c4f5f8d0977a79105e5287115 | https://github.com/russross/meddler/blob/87a225081a7cb35c4f5f8d0977a79105e5287115/loadsave.go#L73-L131 |
2,284 | russross/meddler | loadsave.go | Insert | func Insert(db DB, table string, src interface{}) error {
return Default.Insert(db, table, src)
} | go | func Insert(db DB, table string, src interface{}) error {
return Default.Insert(db, table, src)
} | [
"func",
"Insert",
"(",
"db",
"DB",
",",
"table",
"string",
",",
"src",
"interface",
"{",
"}",
")",
"error",
"{",
"return",
"Default",
".",
"Insert",
"(",
"db",
",",
"table",
",",
"src",
")",
"\n",
"}"
] | // Insert using the Default Database type | [
"Insert",
"using",
"the",
"Default",
"Database",
"type"
] | 87a225081a7cb35c4f5f8d0977a79105e5287115 | https://github.com/russross/meddler/blob/87a225081a7cb35c4f5f8d0977a79105e5287115/loadsave.go#L134-L136 |
2,285 | russross/meddler | loadsave.go | Update | func (d *Database) Update(db DB, table string, src interface{}) error {
// gather the query parts
names, err := d.Columns(src, false)
if err != nil {
return err
}
placeholders, err := d.Placeholders(src, false)
if err != nil {
return err
}
values, err := d.Values(src, false)
if err != nil {
return err
}
// form the column=placeholder pairs
var pairs []string
for i := 0; i < len(names) && i < len(placeholders); i++ {
pair := fmt.Sprintf("%s=%s", d.quoted(names[i]), placeholders[i])
pairs = append(pairs, pair)
}
pkName, pkValue, err := d.PrimaryKey(src)
if err != nil {
return err
}
if pkName == "" {
return fmt.Errorf("meddler.Update: no primary key field")
}
if pkValue < 1 {
return fmt.Errorf("meddler.Update: primary key must be an integer > 0")
}
ph := d.placeholder(len(placeholders) + 1)
// run the query
q := fmt.Sprintf("UPDATE %s SET %s WHERE %s=%s", d.quoted(table),
strings.Join(pairs, ","),
d.quoted(pkName), ph)
values = append(values, pkValue)
if _, err := db.Exec(q, values...); err != nil {
return &dbErr{msg: "meddler.Update: DB error in Exec", err: err}
}
return nil
} | go | func (d *Database) Update(db DB, table string, src interface{}) error {
// gather the query parts
names, err := d.Columns(src, false)
if err != nil {
return err
}
placeholders, err := d.Placeholders(src, false)
if err != nil {
return err
}
values, err := d.Values(src, false)
if err != nil {
return err
}
// form the column=placeholder pairs
var pairs []string
for i := 0; i < len(names) && i < len(placeholders); i++ {
pair := fmt.Sprintf("%s=%s", d.quoted(names[i]), placeholders[i])
pairs = append(pairs, pair)
}
pkName, pkValue, err := d.PrimaryKey(src)
if err != nil {
return err
}
if pkName == "" {
return fmt.Errorf("meddler.Update: no primary key field")
}
if pkValue < 1 {
return fmt.Errorf("meddler.Update: primary key must be an integer > 0")
}
ph := d.placeholder(len(placeholders) + 1)
// run the query
q := fmt.Sprintf("UPDATE %s SET %s WHERE %s=%s", d.quoted(table),
strings.Join(pairs, ","),
d.quoted(pkName), ph)
values = append(values, pkValue)
if _, err := db.Exec(q, values...); err != nil {
return &dbErr{msg: "meddler.Update: DB error in Exec", err: err}
}
return nil
} | [
"func",
"(",
"d",
"*",
"Database",
")",
"Update",
"(",
"db",
"DB",
",",
"table",
"string",
",",
"src",
"interface",
"{",
"}",
")",
"error",
"{",
"// gather the query parts",
"names",
",",
"err",
":=",
"d",
".",
"Columns",
"(",
"src",
",",
"false",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"placeholders",
",",
"err",
":=",
"d",
".",
"Placeholders",
"(",
"src",
",",
"false",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"values",
",",
"err",
":=",
"d",
".",
"Values",
"(",
"src",
",",
"false",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"// form the column=placeholder pairs",
"var",
"pairs",
"[",
"]",
"string",
"\n",
"for",
"i",
":=",
"0",
";",
"i",
"<",
"len",
"(",
"names",
")",
"&&",
"i",
"<",
"len",
"(",
"placeholders",
")",
";",
"i",
"++",
"{",
"pair",
":=",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"d",
".",
"quoted",
"(",
"names",
"[",
"i",
"]",
")",
",",
"placeholders",
"[",
"i",
"]",
")",
"\n",
"pairs",
"=",
"append",
"(",
"pairs",
",",
"pair",
")",
"\n",
"}",
"\n\n",
"pkName",
",",
"pkValue",
",",
"err",
":=",
"d",
".",
"PrimaryKey",
"(",
"src",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"if",
"pkName",
"==",
"\"",
"\"",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"if",
"pkValue",
"<",
"1",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"ph",
":=",
"d",
".",
"placeholder",
"(",
"len",
"(",
"placeholders",
")",
"+",
"1",
")",
"\n\n",
"// run the query",
"q",
":=",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"d",
".",
"quoted",
"(",
"table",
")",
",",
"strings",
".",
"Join",
"(",
"pairs",
",",
"\"",
"\"",
")",
",",
"d",
".",
"quoted",
"(",
"pkName",
")",
",",
"ph",
")",
"\n",
"values",
"=",
"append",
"(",
"values",
",",
"pkValue",
")",
"\n\n",
"if",
"_",
",",
"err",
":=",
"db",
".",
"Exec",
"(",
"q",
",",
"values",
"...",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"&",
"dbErr",
"{",
"msg",
":",
"\"",
"\"",
",",
"err",
":",
"err",
"}",
"\n",
"}",
"\n\n",
"return",
"nil",
"\n",
"}"
] | // Update performs and UPDATE query for the given record.
// The record must have an integer primary key field that is non-zero,
// and it will be used to select the database row that gets updated. | [
"Update",
"performs",
"and",
"UPDATE",
"query",
"for",
"the",
"given",
"record",
".",
"The",
"record",
"must",
"have",
"an",
"integer",
"primary",
"key",
"field",
"that",
"is",
"non",
"-",
"zero",
"and",
"it",
"will",
"be",
"used",
"to",
"select",
"the",
"database",
"row",
"that",
"gets",
"updated",
"."
] | 87a225081a7cb35c4f5f8d0977a79105e5287115 | https://github.com/russross/meddler/blob/87a225081a7cb35c4f5f8d0977a79105e5287115/loadsave.go#L141-L186 |
2,286 | russross/meddler | loadsave.go | Update | func Update(db DB, table string, src interface{}) error {
return Default.Update(db, table, src)
} | go | func Update(db DB, table string, src interface{}) error {
return Default.Update(db, table, src)
} | [
"func",
"Update",
"(",
"db",
"DB",
",",
"table",
"string",
",",
"src",
"interface",
"{",
"}",
")",
"error",
"{",
"return",
"Default",
".",
"Update",
"(",
"db",
",",
"table",
",",
"src",
")",
"\n",
"}"
] | // Update using the Default Database type | [
"Update",
"using",
"the",
"Default",
"Database",
"type"
] | 87a225081a7cb35c4f5f8d0977a79105e5287115 | https://github.com/russross/meddler/blob/87a225081a7cb35c4f5f8d0977a79105e5287115/loadsave.go#L189-L191 |
2,287 | russross/meddler | loadsave.go | Save | func (d *Database) Save(db DB, table string, src interface{}) error {
pkName, pkValue, err := d.PrimaryKey(src)
if err != nil {
return err
}
if pkName != "" && pkValue != 0 {
return d.Update(db, table, src)
}
return d.Insert(db, table, src)
} | go | func (d *Database) Save(db DB, table string, src interface{}) error {
pkName, pkValue, err := d.PrimaryKey(src)
if err != nil {
return err
}
if pkName != "" && pkValue != 0 {
return d.Update(db, table, src)
}
return d.Insert(db, table, src)
} | [
"func",
"(",
"d",
"*",
"Database",
")",
"Save",
"(",
"db",
"DB",
",",
"table",
"string",
",",
"src",
"interface",
"{",
"}",
")",
"error",
"{",
"pkName",
",",
"pkValue",
",",
"err",
":=",
"d",
".",
"PrimaryKey",
"(",
"src",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"if",
"pkName",
"!=",
"\"",
"\"",
"&&",
"pkValue",
"!=",
"0",
"{",
"return",
"d",
".",
"Update",
"(",
"db",
",",
"table",
",",
"src",
")",
"\n",
"}",
"\n\n",
"return",
"d",
".",
"Insert",
"(",
"db",
",",
"table",
",",
"src",
")",
"\n",
"}"
] | // Save performs an INSERT or an UPDATE, depending on whether or not
// a primary keys exists and is non-zero. | [
"Save",
"performs",
"an",
"INSERT",
"or",
"an",
"UPDATE",
"depending",
"on",
"whether",
"or",
"not",
"a",
"primary",
"keys",
"exists",
"and",
"is",
"non",
"-",
"zero",
"."
] | 87a225081a7cb35c4f5f8d0977a79105e5287115 | https://github.com/russross/meddler/blob/87a225081a7cb35c4f5f8d0977a79105e5287115/loadsave.go#L195-L205 |
2,288 | russross/meddler | loadsave.go | Save | func Save(db DB, table string, src interface{}) error {
return Default.Save(db, table, src)
} | go | func Save(db DB, table string, src interface{}) error {
return Default.Save(db, table, src)
} | [
"func",
"Save",
"(",
"db",
"DB",
",",
"table",
"string",
",",
"src",
"interface",
"{",
"}",
")",
"error",
"{",
"return",
"Default",
".",
"Save",
"(",
"db",
",",
"table",
",",
"src",
")",
"\n",
"}"
] | // Save using the Default Database type | [
"Save",
"using",
"the",
"Default",
"Database",
"type"
] | 87a225081a7cb35c4f5f8d0977a79105e5287115 | https://github.com/russross/meddler/blob/87a225081a7cb35c4f5f8d0977a79105e5287115/loadsave.go#L208-L210 |
2,289 | russross/meddler | loadsave.go | QueryRow | func (d *Database) QueryRow(db DB, dst interface{}, query string, args ...interface{}) error {
// perform the query
rows, err := db.Query(query, args...)
if err != nil {
return err
}
// gather the result
return d.ScanRow(rows, dst)
} | go | func (d *Database) QueryRow(db DB, dst interface{}, query string, args ...interface{}) error {
// perform the query
rows, err := db.Query(query, args...)
if err != nil {
return err
}
// gather the result
return d.ScanRow(rows, dst)
} | [
"func",
"(",
"d",
"*",
"Database",
")",
"QueryRow",
"(",
"db",
"DB",
",",
"dst",
"interface",
"{",
"}",
",",
"query",
"string",
",",
"args",
"...",
"interface",
"{",
"}",
")",
"error",
"{",
"// perform the query",
"rows",
",",
"err",
":=",
"db",
".",
"Query",
"(",
"query",
",",
"args",
"...",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"// gather the result",
"return",
"d",
".",
"ScanRow",
"(",
"rows",
",",
"dst",
")",
"\n",
"}"
] | // QueryRow performs the given query with the given arguments, scanning a
// single row of results into dst. Returns sql.ErrNoRows if there was no
// result row. | [
"QueryRow",
"performs",
"the",
"given",
"query",
"with",
"the",
"given",
"arguments",
"scanning",
"a",
"single",
"row",
"of",
"results",
"into",
"dst",
".",
"Returns",
"sql",
".",
"ErrNoRows",
"if",
"there",
"was",
"no",
"result",
"row",
"."
] | 87a225081a7cb35c4f5f8d0977a79105e5287115 | https://github.com/russross/meddler/blob/87a225081a7cb35c4f5f8d0977a79105e5287115/loadsave.go#L215-L224 |
2,290 | russross/meddler | loadsave.go | QueryAll | func (d *Database) QueryAll(db DB, dst interface{}, query string, args ...interface{}) error {
// perform the query
rows, err := db.Query(query, args...)
if err != nil {
return err
}
// gather the results
return d.ScanAll(rows, dst)
} | go | func (d *Database) QueryAll(db DB, dst interface{}, query string, args ...interface{}) error {
// perform the query
rows, err := db.Query(query, args...)
if err != nil {
return err
}
// gather the results
return d.ScanAll(rows, dst)
} | [
"func",
"(",
"d",
"*",
"Database",
")",
"QueryAll",
"(",
"db",
"DB",
",",
"dst",
"interface",
"{",
"}",
",",
"query",
"string",
",",
"args",
"...",
"interface",
"{",
"}",
")",
"error",
"{",
"// perform the query",
"rows",
",",
"err",
":=",
"db",
".",
"Query",
"(",
"query",
",",
"args",
"...",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"// gather the results",
"return",
"d",
".",
"ScanAll",
"(",
"rows",
",",
"dst",
")",
"\n",
"}"
] | // QueryAll performs the given query with the given arguments, scanning
// all results rows into dst. | [
"QueryAll",
"performs",
"the",
"given",
"query",
"with",
"the",
"given",
"arguments",
"scanning",
"all",
"results",
"rows",
"into",
"dst",
"."
] | 87a225081a7cb35c4f5f8d0977a79105e5287115 | https://github.com/russross/meddler/blob/87a225081a7cb35c4f5f8d0977a79105e5287115/loadsave.go#L233-L242 |
2,291 | russross/meddler | loadsave.go | QueryAll | func QueryAll(db DB, dst interface{}, query string, args ...interface{}) error {
return Default.QueryAll(db, dst, query, args...)
} | go | func QueryAll(db DB, dst interface{}, query string, args ...interface{}) error {
return Default.QueryAll(db, dst, query, args...)
} | [
"func",
"QueryAll",
"(",
"db",
"DB",
",",
"dst",
"interface",
"{",
"}",
",",
"query",
"string",
",",
"args",
"...",
"interface",
"{",
"}",
")",
"error",
"{",
"return",
"Default",
".",
"QueryAll",
"(",
"db",
",",
"dst",
",",
"query",
",",
"args",
"...",
")",
"\n",
"}"
] | // QueryAll using the Default Database type | [
"QueryAll",
"using",
"the",
"Default",
"Database",
"type"
] | 87a225081a7cb35c4f5f8d0977a79105e5287115 | https://github.com/russross/meddler/blob/87a225081a7cb35c4f5f8d0977a79105e5287115/loadsave.go#L245-L247 |
2,292 | russross/meddler | scan.go | Columns | func (d *Database) Columns(src interface{}, includePk bool) ([]string, error) {
data, err := getFields(reflect.TypeOf(src))
if err != nil {
return nil, err
}
var names []string
for _, elt := range data.columns {
if !includePk && elt == data.pk {
continue
}
names = append(names, elt)
}
return names, nil
} | go | func (d *Database) Columns(src interface{}, includePk bool) ([]string, error) {
data, err := getFields(reflect.TypeOf(src))
if err != nil {
return nil, err
}
var names []string
for _, elt := range data.columns {
if !includePk && elt == data.pk {
continue
}
names = append(names, elt)
}
return names, nil
} | [
"func",
"(",
"d",
"*",
"Database",
")",
"Columns",
"(",
"src",
"interface",
"{",
"}",
",",
"includePk",
"bool",
")",
"(",
"[",
"]",
"string",
",",
"error",
")",
"{",
"data",
",",
"err",
":=",
"getFields",
"(",
"reflect",
".",
"TypeOf",
"(",
"src",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"var",
"names",
"[",
"]",
"string",
"\n",
"for",
"_",
",",
"elt",
":=",
"range",
"data",
".",
"columns",
"{",
"if",
"!",
"includePk",
"&&",
"elt",
"==",
"data",
".",
"pk",
"{",
"continue",
"\n",
"}",
"\n",
"names",
"=",
"append",
"(",
"names",
",",
"elt",
")",
"\n",
"}",
"\n\n",
"return",
"names",
",",
"nil",
"\n",
"}"
] | // Columns returns a list of column names for its input struct. | [
"Columns",
"returns",
"a",
"list",
"of",
"column",
"names",
"for",
"its",
"input",
"struct",
"."
] | 87a225081a7cb35c4f5f8d0977a79105e5287115 | https://github.com/russross/meddler/blob/87a225081a7cb35c4f5f8d0977a79105e5287115/scan.go#L170-L185 |
2,293 | russross/meddler | scan.go | Columns | func Columns(src interface{}, includePk bool) ([]string, error) {
return Default.Columns(src, includePk)
} | go | func Columns(src interface{}, includePk bool) ([]string, error) {
return Default.Columns(src, includePk)
} | [
"func",
"Columns",
"(",
"src",
"interface",
"{",
"}",
",",
"includePk",
"bool",
")",
"(",
"[",
"]",
"string",
",",
"error",
")",
"{",
"return",
"Default",
".",
"Columns",
"(",
"src",
",",
"includePk",
")",
"\n",
"}"
] | // Columns using the Default Database type | [
"Columns",
"using",
"the",
"Default",
"Database",
"type"
] | 87a225081a7cb35c4f5f8d0977a79105e5287115 | https://github.com/russross/meddler/blob/87a225081a7cb35c4f5f8d0977a79105e5287115/scan.go#L188-L190 |
2,294 | russross/meddler | scan.go | ColumnsQuoted | func ColumnsQuoted(src interface{}, includePk bool) (string, error) {
return Default.ColumnsQuoted(src, includePk)
} | go | func ColumnsQuoted(src interface{}, includePk bool) (string, error) {
return Default.ColumnsQuoted(src, includePk)
} | [
"func",
"ColumnsQuoted",
"(",
"src",
"interface",
"{",
"}",
",",
"includePk",
"bool",
")",
"(",
"string",
",",
"error",
")",
"{",
"return",
"Default",
".",
"ColumnsQuoted",
"(",
"src",
",",
"includePk",
")",
"\n",
"}"
] | // ColumnsQuoted using the Default Database type | [
"ColumnsQuoted",
"using",
"the",
"Default",
"Database",
"type"
] | 87a225081a7cb35c4f5f8d0977a79105e5287115 | https://github.com/russross/meddler/blob/87a225081a7cb35c4f5f8d0977a79105e5287115/scan.go#L210-L212 |
2,295 | russross/meddler | scan.go | PrimaryKey | func (d *Database) PrimaryKey(src interface{}) (name string, pk int64, err error) {
data, err := getFields(reflect.TypeOf(src))
if err != nil {
return "", 0, err
}
if data.pk == "" {
return "", 0, nil
}
name = data.pk
field := reflect.ValueOf(src).Elem().Field(data.fields[name].index)
switch field.Type().Kind() {
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
pk = field.Int()
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
pk = int64(field.Uint())
default:
return "", 0, fmt.Errorf("meddler found field %s which is marked as the primary key, but is not an integer type", name)
}
return name, pk, nil
} | go | func (d *Database) PrimaryKey(src interface{}) (name string, pk int64, err error) {
data, err := getFields(reflect.TypeOf(src))
if err != nil {
return "", 0, err
}
if data.pk == "" {
return "", 0, nil
}
name = data.pk
field := reflect.ValueOf(src).Elem().Field(data.fields[name].index)
switch field.Type().Kind() {
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
pk = field.Int()
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
pk = int64(field.Uint())
default:
return "", 0, fmt.Errorf("meddler found field %s which is marked as the primary key, but is not an integer type", name)
}
return name, pk, nil
} | [
"func",
"(",
"d",
"*",
"Database",
")",
"PrimaryKey",
"(",
"src",
"interface",
"{",
"}",
")",
"(",
"name",
"string",
",",
"pk",
"int64",
",",
"err",
"error",
")",
"{",
"data",
",",
"err",
":=",
"getFields",
"(",
"reflect",
".",
"TypeOf",
"(",
"src",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\"",
"\"",
",",
"0",
",",
"err",
"\n",
"}",
"\n\n",
"if",
"data",
".",
"pk",
"==",
"\"",
"\"",
"{",
"return",
"\"",
"\"",
",",
"0",
",",
"nil",
"\n",
"}",
"\n\n",
"name",
"=",
"data",
".",
"pk",
"\n",
"field",
":=",
"reflect",
".",
"ValueOf",
"(",
"src",
")",
".",
"Elem",
"(",
")",
".",
"Field",
"(",
"data",
".",
"fields",
"[",
"name",
"]",
".",
"index",
")",
"\n",
"switch",
"field",
".",
"Type",
"(",
")",
".",
"Kind",
"(",
")",
"{",
"case",
"reflect",
".",
"Int",
",",
"reflect",
".",
"Int8",
",",
"reflect",
".",
"Int16",
",",
"reflect",
".",
"Int32",
",",
"reflect",
".",
"Int64",
":",
"pk",
"=",
"field",
".",
"Int",
"(",
")",
"\n",
"case",
"reflect",
".",
"Uint",
",",
"reflect",
".",
"Uint8",
",",
"reflect",
".",
"Uint16",
",",
"reflect",
".",
"Uint32",
",",
"reflect",
".",
"Uint64",
":",
"pk",
"=",
"int64",
"(",
"field",
".",
"Uint",
"(",
")",
")",
"\n",
"default",
":",
"return",
"\"",
"\"",
",",
"0",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"name",
")",
"\n",
"}",
"\n\n",
"return",
"name",
",",
"pk",
",",
"nil",
"\n",
"}"
] | // PrimaryKey returns the name and value of the primary key field. The name
// is the empty string if there is not primary key field marked. | [
"PrimaryKey",
"returns",
"the",
"name",
"and",
"value",
"of",
"the",
"primary",
"key",
"field",
".",
"The",
"name",
"is",
"the",
"empty",
"string",
"if",
"there",
"is",
"not",
"primary",
"key",
"field",
"marked",
"."
] | 87a225081a7cb35c4f5f8d0977a79105e5287115 | https://github.com/russross/meddler/blob/87a225081a7cb35c4f5f8d0977a79105e5287115/scan.go#L216-L238 |
2,296 | russross/meddler | scan.go | PrimaryKey | func PrimaryKey(src interface{}) (name string, pk int64, err error) {
return Default.PrimaryKey(src)
} | go | func PrimaryKey(src interface{}) (name string, pk int64, err error) {
return Default.PrimaryKey(src)
} | [
"func",
"PrimaryKey",
"(",
"src",
"interface",
"{",
"}",
")",
"(",
"name",
"string",
",",
"pk",
"int64",
",",
"err",
"error",
")",
"{",
"return",
"Default",
".",
"PrimaryKey",
"(",
"src",
")",
"\n",
"}"
] | // PrimaryKey using the Default Database type | [
"PrimaryKey",
"using",
"the",
"Default",
"Database",
"type"
] | 87a225081a7cb35c4f5f8d0977a79105e5287115 | https://github.com/russross/meddler/blob/87a225081a7cb35c4f5f8d0977a79105e5287115/scan.go#L241-L243 |
2,297 | russross/meddler | scan.go | Placeholders | func (d *Database) Placeholders(src interface{}, includePk bool) ([]string, error) {
data, err := getFields(reflect.TypeOf(src))
if err != nil {
return nil, err
}
var placeholders []string
for _, name := range data.columns {
if !includePk && name == data.pk {
continue
}
ph := d.placeholder(len(placeholders) + 1)
placeholders = append(placeholders, ph)
}
return placeholders, nil
} | go | func (d *Database) Placeholders(src interface{}, includePk bool) ([]string, error) {
data, err := getFields(reflect.TypeOf(src))
if err != nil {
return nil, err
}
var placeholders []string
for _, name := range data.columns {
if !includePk && name == data.pk {
continue
}
ph := d.placeholder(len(placeholders) + 1)
placeholders = append(placeholders, ph)
}
return placeholders, nil
} | [
"func",
"(",
"d",
"*",
"Database",
")",
"Placeholders",
"(",
"src",
"interface",
"{",
"}",
",",
"includePk",
"bool",
")",
"(",
"[",
"]",
"string",
",",
"error",
")",
"{",
"data",
",",
"err",
":=",
"getFields",
"(",
"reflect",
".",
"TypeOf",
"(",
"src",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"var",
"placeholders",
"[",
"]",
"string",
"\n",
"for",
"_",
",",
"name",
":=",
"range",
"data",
".",
"columns",
"{",
"if",
"!",
"includePk",
"&&",
"name",
"==",
"data",
".",
"pk",
"{",
"continue",
"\n",
"}",
"\n",
"ph",
":=",
"d",
".",
"placeholder",
"(",
"len",
"(",
"placeholders",
")",
"+",
"1",
")",
"\n",
"placeholders",
"=",
"append",
"(",
"placeholders",
",",
"ph",
")",
"\n",
"}",
"\n\n",
"return",
"placeholders",
",",
"nil",
"\n",
"}"
] | // Placeholders returns a list of placeholders suitable for an INSERT or UPDATE query.
// If includePk is false, the primary key field is omitted. | [
"Placeholders",
"returns",
"a",
"list",
"of",
"placeholders",
"suitable",
"for",
"an",
"INSERT",
"or",
"UPDATE",
"query",
".",
"If",
"includePk",
"is",
"false",
"the",
"primary",
"key",
"field",
"is",
"omitted",
"."
] | 87a225081a7cb35c4f5f8d0977a79105e5287115 | https://github.com/russross/meddler/blob/87a225081a7cb35c4f5f8d0977a79105e5287115/scan.go#L331-L347 |
2,298 | russross/meddler | scan.go | Placeholders | func Placeholders(src interface{}, includePk bool) ([]string, error) {
return Default.Placeholders(src, includePk)
} | go | func Placeholders(src interface{}, includePk bool) ([]string, error) {
return Default.Placeholders(src, includePk)
} | [
"func",
"Placeholders",
"(",
"src",
"interface",
"{",
"}",
",",
"includePk",
"bool",
")",
"(",
"[",
"]",
"string",
",",
"error",
")",
"{",
"return",
"Default",
".",
"Placeholders",
"(",
"src",
",",
"includePk",
")",
"\n",
"}"
] | // Placeholders using the Default Database type | [
"Placeholders",
"using",
"the",
"Default",
"Database",
"type"
] | 87a225081a7cb35c4f5f8d0977a79105e5287115 | https://github.com/russross/meddler/blob/87a225081a7cb35c4f5f8d0977a79105e5287115/scan.go#L350-L352 |
2,299 | russross/meddler | scan.go | PlaceholdersString | func PlaceholdersString(src interface{}, includePk bool) (string, error) {
return Default.PlaceholdersString(src, includePk)
} | go | func PlaceholdersString(src interface{}, includePk bool) (string, error) {
return Default.PlaceholdersString(src, includePk)
} | [
"func",
"PlaceholdersString",
"(",
"src",
"interface",
"{",
"}",
",",
"includePk",
"bool",
")",
"(",
"string",
",",
"error",
")",
"{",
"return",
"Default",
".",
"PlaceholdersString",
"(",
"src",
",",
"includePk",
")",
"\n",
"}"
] | // PlaceholdersString using the Default Database type | [
"PlaceholdersString",
"using",
"the",
"Default",
"Database",
"type"
] | 87a225081a7cb35c4f5f8d0977a79105e5287115 | https://github.com/russross/meddler/blob/87a225081a7cb35c4f5f8d0977a79105e5287115/scan.go#L367-L369 |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.