id int32 0 167k | repo stringlengths 5 54 | path stringlengths 4 155 | func_name stringlengths 1 118 | original_string stringlengths 52 85.5k | language stringclasses 1
value | code stringlengths 52 85.5k | code_tokens list | docstring stringlengths 6 2.61k | docstring_tokens list | sha stringlengths 40 40 | url stringlengths 85 252 |
|---|---|---|---|---|---|---|---|---|---|---|---|
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",
"... | // 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",
"(",
")",
"\... | // 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... | // 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",
... | // 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",
"{",... | // 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",
"(",
"... | // 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",
"(",
"... | // 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",
"(",
"... | // 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",
"(",
... | // 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.",
... | // 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.",... | // 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",
... | // 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 ... | // 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",
"."... | // 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... | // 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",
"!=",
... | // 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",
"[... | // 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",
... | // 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",... | // 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",
")",
... | // 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",
"... | // 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",
... | // 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",
")... | // 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",
",",
... | // 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",
"=... | // 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... | 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",
"... | // 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",... | 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",
")",
"\... | // 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",
":="... | // 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",
"(",
"... | // 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",... | // 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",
"ColumnTypeInteg... | // 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",
"... | // 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",
... | // 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",
"... | // 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"... | // 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",
"{",
"switc... | // 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",
".... | // 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",... | // 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",
"(",
... | // 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",... | // 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",
"!=",
"... | // 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",
"create... | 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 an... | // 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",
"(",
... | // 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... | // 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",
"=="... | // 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",
".",
"De... | 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",
"{",
"... | // 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",
... | 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",
".",
"Value... | // 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",
"... | // 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",
",",
"\"",
"\"",
")",
"... | // 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",
"(",
")",
"}",
... | // 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",
"...",
")",... | // 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",
"...",
")",
"... | // 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",
"(",
"\"",
"\"",... | // 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",
"(... | // 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 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",
"(",
"b... | // 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",
".... | // 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",
".",... | 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",
"*",
"ti... | // 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",
"."... | // 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",
".",
"... | // 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 colum... | // 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",
"(",
"fie... | // 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"... | // 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",
... | // 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",
"{",
... | // 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",
"(",
"[",
"]",
... | // 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",
... | // 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",
"{",
... | // 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",
... | // 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",
... | 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",
")... | // 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... | // 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",
"... | 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",
")... | // 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",... | 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",... | // 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",
".",... | // 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",
".",... | // 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",
".... | // 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",
... | // 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"... | // 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",
"(",
"s... | // 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 community queries yet
The top public SQL queries from the community will appear here once available.