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
sequencelengths
21
1.41k
docstring
stringlengths
6
2.61k
docstring_tokens
sequencelengths
3
215
sha
stringlengths
40
40
url
stringlengths
85
252
5,400
Pallinder/go-randomdata
random_data.go
Email
func Email() string { return strings.ToLower(FirstName(RandomGender)+LastName()) + StringNumberExt(1, "", 3) + "@" + randomFrom(jsonData.Domains) }
go
func Email() string { return strings.ToLower(FirstName(RandomGender)+LastName()) + StringNumberExt(1, "", 3) + "@" + randomFrom(jsonData.Domains) }
[ "func", "Email", "(", ")", "string", "{", "return", "strings", ".", "ToLower", "(", "FirstName", "(", "RandomGender", ")", "+", "LastName", "(", ")", ")", "+", "StringNumberExt", "(", "1", ",", "\"", "\"", ",", "3", ")", "+", "\"", "\"", "+", "randomFrom", "(", "jsonData", ".", "Domains", ")", "\n", "}" ]
// Email returns a random email
[ "Email", "returns", "a", "random", "email" ]
97a2356fcab20708fb8ae46cbbf69a5bc9feca63
https://github.com/Pallinder/go-randomdata/blob/97a2356fcab20708fb8ae46cbbf69a5bc9feca63/random_data.go#L136-L138
5,401
Pallinder/go-randomdata
random_data.go
Country
func Country(countryStyle int64) string { country := "" switch countryStyle { default: case FullCountry: country = randomFrom(jsonData.Countries) break case TwoCharCountry: country = randomFrom(jsonData.CountriesTwoChars) break case ThreeCharCountry: country = randomFrom(jsonData.CountriesThreeChars) break } return country }
go
func Country(countryStyle int64) string { country := "" switch countryStyle { default: case FullCountry: country = randomFrom(jsonData.Countries) break case TwoCharCountry: country = randomFrom(jsonData.CountriesTwoChars) break case ThreeCharCountry: country = randomFrom(jsonData.CountriesThreeChars) break } return country }
[ "func", "Country", "(", "countryStyle", "int64", ")", "string", "{", "country", ":=", "\"", "\"", "\n", "switch", "countryStyle", "{", "default", ":", "case", "FullCountry", ":", "country", "=", "randomFrom", "(", "jsonData", ".", "Countries", ")", "\n", "break", "\n\n", "case", "TwoCharCountry", ":", "country", "=", "randomFrom", "(", "jsonData", ".", "CountriesTwoChars", ")", "\n", "break", "\n\n", "case", "ThreeCharCountry", ":", "country", "=", "randomFrom", "(", "jsonData", ".", "CountriesThreeChars", ")", "\n", "break", "\n", "}", "\n", "return", "country", "\n", "}" ]
// Country returns a random country, countryStyle decides what kind of format the returned country will have
[ "Country", "returns", "a", "random", "country", "countryStyle", "decides", "what", "kind", "of", "format", "the", "returned", "country", "will", "have" ]
97a2356fcab20708fb8ae46cbbf69a5bc9feca63
https://github.com/Pallinder/go-randomdata/blob/97a2356fcab20708fb8ae46cbbf69a5bc9feca63/random_data.go#L141-L160
5,402
Pallinder/go-randomdata
random_data.go
State
func State(typeOfState int) string { if typeOfState == Small { return randomFrom(jsonData.StatesSmall) } return randomFrom(jsonData.States) }
go
func State(typeOfState int) string { if typeOfState == Small { return randomFrom(jsonData.StatesSmall) } return randomFrom(jsonData.States) }
[ "func", "State", "(", "typeOfState", "int", ")", "string", "{", "if", "typeOfState", "==", "Small", "{", "return", "randomFrom", "(", "jsonData", ".", "StatesSmall", ")", "\n", "}", "\n", "return", "randomFrom", "(", "jsonData", ".", "States", ")", "\n", "}" ]
// State returns a random american state
[ "State", "returns", "a", "random", "american", "state" ]
97a2356fcab20708fb8ae46cbbf69a5bc9feca63
https://github.com/Pallinder/go-randomdata/blob/97a2356fcab20708fb8ae46cbbf69a5bc9feca63/random_data.go#L185-L190
5,403
Pallinder/go-randomdata
random_data.go
Street
func Street() string { return fmt.Sprintf("%s %s", randomFrom(jsonData.People), randomFrom(jsonData.StreetTypes)) }
go
func Street() string { return fmt.Sprintf("%s %s", randomFrom(jsonData.People), randomFrom(jsonData.StreetTypes)) }
[ "func", "Street", "(", ")", "string", "{", "return", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "randomFrom", "(", "jsonData", ".", "People", ")", ",", "randomFrom", "(", "jsonData", ".", "StreetTypes", ")", ")", "\n", "}" ]
// Street returns a random fake street name
[ "Street", "returns", "a", "random", "fake", "street", "name" ]
97a2356fcab20708fb8ae46cbbf69a5bc9feca63
https://github.com/Pallinder/go-randomdata/blob/97a2356fcab20708fb8ae46cbbf69a5bc9feca63/random_data.go#L193-L195
5,404
Pallinder/go-randomdata
random_data.go
StreetForCountry
func StreetForCountry(countrycode string) string { switch countrycode { case "US": return Street() case "GB": return fmt.Sprintf("%s %s", randomFrom(jsonData.StreetNameGB), randomFrom(jsonData.StreetTypesGB)) } return "" }
go
func StreetForCountry(countrycode string) string { switch countrycode { case "US": return Street() case "GB": return fmt.Sprintf("%s %s", randomFrom(jsonData.StreetNameGB), randomFrom(jsonData.StreetTypesGB)) } return "" }
[ "func", "StreetForCountry", "(", "countrycode", "string", ")", "string", "{", "switch", "countrycode", "{", "case", "\"", "\"", ":", "return", "Street", "(", ")", "\n", "case", "\"", "\"", ":", "return", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "randomFrom", "(", "jsonData", ".", "StreetNameGB", ")", ",", "randomFrom", "(", "jsonData", ".", "StreetTypesGB", ")", ")", "\n", "}", "\n", "return", "\"", "\"", "\n", "}" ]
// StreetForCountry returns a random fake street name typical to the supplied country. // If the country is not supported it will return an empty string.
[ "StreetForCountry", "returns", "a", "random", "fake", "street", "name", "typical", "to", "the", "supplied", "country", ".", "If", "the", "country", "is", "not", "supported", "it", "will", "return", "an", "empty", "string", "." ]
97a2356fcab20708fb8ae46cbbf69a5bc9feca63
https://github.com/Pallinder/go-randomdata/blob/97a2356fcab20708fb8ae46cbbf69a5bc9feca63/random_data.go#L199-L207
5,405
Pallinder/go-randomdata
random_data.go
Address
func Address() string { return fmt.Sprintf("%d %s,\n%s, %s, %s", Number(100), Street(), City(), State(Small), PostalCode("US")) }
go
func Address() string { return fmt.Sprintf("%d %s,\n%s, %s, %s", Number(100), Street(), City(), State(Small), PostalCode("US")) }
[ "func", "Address", "(", ")", "string", "{", "return", "fmt", ".", "Sprintf", "(", "\"", "\\n", "\"", ",", "Number", "(", "100", ")", ",", "Street", "(", ")", ",", "City", "(", ")", ",", "State", "(", "Small", ")", ",", "PostalCode", "(", "\"", "\"", ")", ")", "\n", "}" ]
// Address returns an american style address
[ "Address", "returns", "an", "american", "style", "address" ]
97a2356fcab20708fb8ae46cbbf69a5bc9feca63
https://github.com/Pallinder/go-randomdata/blob/97a2356fcab20708fb8ae46cbbf69a5bc9feca63/random_data.go#L210-L212
5,406
Pallinder/go-randomdata
random_data.go
StringSample
func StringSample(stringList ...string) string { str := "" if len(stringList) > 0 { str = stringList[Number(0, len(stringList))] } return str }
go
func StringSample(stringList ...string) string { str := "" if len(stringList) > 0 { str = stringList[Number(0, len(stringList))] } return str }
[ "func", "StringSample", "(", "stringList", "...", "string", ")", "string", "{", "str", ":=", "\"", "\"", "\n", "if", "len", "(", "stringList", ")", ">", "0", "{", "str", "=", "stringList", "[", "Number", "(", "0", ",", "len", "(", "stringList", ")", ")", "]", "\n", "}", "\n", "return", "str", "\n", "}" ]
// StringSample returns a random string from a list of strings
[ "StringSample", "returns", "a", "random", "string", "from", "a", "list", "of", "strings" ]
97a2356fcab20708fb8ae46cbbf69a5bc9feca63
https://github.com/Pallinder/go-randomdata/blob/97a2356fcab20708fb8ae46cbbf69a5bc9feca63/random_data.go#L270-L276
5,407
Pallinder/go-randomdata
random_data.go
IpV4Address
func IpV4Address() string { blocks := []string{} for i := 0; i < 4; i++ { number := privateRand.Intn(255) blocks = append(blocks, strconv.Itoa(number)) } return strings.Join(blocks, ".") }
go
func IpV4Address() string { blocks := []string{} for i := 0; i < 4; i++ { number := privateRand.Intn(255) blocks = append(blocks, strconv.Itoa(number)) } return strings.Join(blocks, ".") }
[ "func", "IpV4Address", "(", ")", "string", "{", "blocks", ":=", "[", "]", "string", "{", "}", "\n", "for", "i", ":=", "0", ";", "i", "<", "4", ";", "i", "++", "{", "number", ":=", "privateRand", ".", "Intn", "(", "255", ")", "\n", "blocks", "=", "append", "(", "blocks", ",", "strconv", ".", "Itoa", "(", "number", ")", ")", "\n", "}", "\n\n", "return", "strings", ".", "Join", "(", "blocks", ",", "\"", "\"", ")", "\n", "}" ]
// IpV4Address returns a valid IPv4 address as string
[ "IpV4Address", "returns", "a", "valid", "IPv4", "address", "as", "string" ]
97a2356fcab20708fb8ae46cbbf69a5bc9feca63
https://github.com/Pallinder/go-randomdata/blob/97a2356fcab20708fb8ae46cbbf69a5bc9feca63/random_data.go#L311-L319
5,408
Pallinder/go-randomdata
random_data.go
IpV6Address
func IpV6Address() string { var ip net.IP for i := 0; i < net.IPv6len; i++ { number := uint8(privateRand.Intn(255)) ip = append(ip, number) } return ip.String() }
go
func IpV6Address() string { var ip net.IP for i := 0; i < net.IPv6len; i++ { number := uint8(privateRand.Intn(255)) ip = append(ip, number) } return ip.String() }
[ "func", "IpV6Address", "(", ")", "string", "{", "var", "ip", "net", ".", "IP", "\n", "for", "i", ":=", "0", ";", "i", "<", "net", ".", "IPv6len", ";", "i", "++", "{", "number", ":=", "uint8", "(", "privateRand", ".", "Intn", "(", "255", ")", ")", "\n", "ip", "=", "append", "(", "ip", ",", "number", ")", "\n", "}", "\n", "return", "ip", ".", "String", "(", ")", "\n", "}" ]
// IpV6Address returns a valid IPv6 address as net.IP
[ "IpV6Address", "returns", "a", "valid", "IPv6", "address", "as", "net", ".", "IP" ]
97a2356fcab20708fb8ae46cbbf69a5bc9feca63
https://github.com/Pallinder/go-randomdata/blob/97a2356fcab20708fb8ae46cbbf69a5bc9feca63/random_data.go#L322-L329
5,409
Pallinder/go-randomdata
random_data.go
MacAddress
func MacAddress() string { blocks := []string{} for i := 0; i < 6; i++ { number := fmt.Sprintf("%02x", privateRand.Intn(255)) blocks = append(blocks, number) } return strings.Join(blocks, ":") }
go
func MacAddress() string { blocks := []string{} for i := 0; i < 6; i++ { number := fmt.Sprintf("%02x", privateRand.Intn(255)) blocks = append(blocks, number) } return strings.Join(blocks, ":") }
[ "func", "MacAddress", "(", ")", "string", "{", "blocks", ":=", "[", "]", "string", "{", "}", "\n", "for", "i", ":=", "0", ";", "i", "<", "6", ";", "i", "++", "{", "number", ":=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "privateRand", ".", "Intn", "(", "255", ")", ")", "\n", "blocks", "=", "append", "(", "blocks", ",", "number", ")", "\n", "}", "\n\n", "return", "strings", ".", "Join", "(", "blocks", ",", "\"", "\"", ")", "\n", "}" ]
// MacAddress returns an mac address string
[ "MacAddress", "returns", "an", "mac", "address", "string" ]
97a2356fcab20708fb8ae46cbbf69a5bc9feca63
https://github.com/Pallinder/go-randomdata/blob/97a2356fcab20708fb8ae46cbbf69a5bc9feca63/random_data.go#L332-L340
5,410
Pallinder/go-randomdata
random_data.go
FullDate
func FullDate() string { timestamp := time.Now() year := timestamp.Year() month := Number(1, 13) maxDay := time.Date(year, time.Month(month+1), 0, 0, 0, 0, 0, time.UTC).Day() day := Number(1, maxDay+1) date := time.Date(year, time.Month(month), day, 0, 0, 0, 0, time.UTC) return date.Format(DateOutputLayout) }
go
func FullDate() string { timestamp := time.Now() year := timestamp.Year() month := Number(1, 13) maxDay := time.Date(year, time.Month(month+1), 0, 0, 0, 0, 0, time.UTC).Day() day := Number(1, maxDay+1) date := time.Date(year, time.Month(month), day, 0, 0, 0, 0, time.UTC) return date.Format(DateOutputLayout) }
[ "func", "FullDate", "(", ")", "string", "{", "timestamp", ":=", "time", ".", "Now", "(", ")", "\n", "year", ":=", "timestamp", ".", "Year", "(", ")", "\n", "month", ":=", "Number", "(", "1", ",", "13", ")", "\n", "maxDay", ":=", "time", ".", "Date", "(", "year", ",", "time", ".", "Month", "(", "month", "+", "1", ")", ",", "0", ",", "0", ",", "0", ",", "0", ",", "0", ",", "time", ".", "UTC", ")", ".", "Day", "(", ")", "\n", "day", ":=", "Number", "(", "1", ",", "maxDay", "+", "1", ")", "\n", "date", ":=", "time", ".", "Date", "(", "year", ",", "time", ".", "Month", "(", "month", ")", ",", "day", ",", "0", ",", "0", ",", "0", ",", "0", ",", "time", ".", "UTC", ")", "\n", "return", "date", ".", "Format", "(", "DateOutputLayout", ")", "\n", "}" ]
// FullDate returns full date
[ "FullDate", "returns", "full", "date" ]
97a2356fcab20708fb8ae46cbbf69a5bc9feca63
https://github.com/Pallinder/go-randomdata/blob/97a2356fcab20708fb8ae46cbbf69a5bc9feca63/random_data.go#L353-L361
5,411
paypal/gatt
device_linux.go
update
func (d *device) update() error { if d.advParam != nil { if err := d.hci.SendCmdWithAdvOff(d.advParam); err != nil { return err } d.advParam = nil } if d.scanResp != nil { if err := d.hci.SendCmdWithAdvOff(d.scanResp); err != nil { return err } d.scanResp = nil } if d.advData != nil { if err := d.hci.SendCmdWithAdvOff(d.advData); err != nil { return err } d.advData = nil } return nil }
go
func (d *device) update() error { if d.advParam != nil { if err := d.hci.SendCmdWithAdvOff(d.advParam); err != nil { return err } d.advParam = nil } if d.scanResp != nil { if err := d.hci.SendCmdWithAdvOff(d.scanResp); err != nil { return err } d.scanResp = nil } if d.advData != nil { if err := d.hci.SendCmdWithAdvOff(d.advData); err != nil { return err } d.advData = nil } return nil }
[ "func", "(", "d", "*", "device", ")", "update", "(", ")", "error", "{", "if", "d", ".", "advParam", "!=", "nil", "{", "if", "err", ":=", "d", ".", "hci", ".", "SendCmdWithAdvOff", "(", "d", ".", "advParam", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "d", ".", "advParam", "=", "nil", "\n", "}", "\n", "if", "d", ".", "scanResp", "!=", "nil", "{", "if", "err", ":=", "d", ".", "hci", ".", "SendCmdWithAdvOff", "(", "d", ".", "scanResp", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "d", ".", "scanResp", "=", "nil", "\n", "}", "\n", "if", "d", ".", "advData", "!=", "nil", "{", "if", "err", ":=", "d", ".", "hci", ".", "SendCmdWithAdvOff", "(", "d", ".", "advData", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "d", ".", "advData", "=", "nil", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// Flush pending advertising settings to the device.
[ "Flush", "pending", "advertising", "settings", "to", "the", "device", "." ]
4ae819d591cfc94c496c45deb55928469542beec
https://github.com/paypal/gatt/blob/4ae819d591cfc94c496c45deb55928469542beec/device_linux.go#L218-L238
5,412
paypal/gatt
option_linux.go
LnxDeviceID
func LnxDeviceID(n int, chk bool) Option { return func(d Device) error { d.(*device).devID = n d.(*device).chkLE = chk return nil } }
go
func LnxDeviceID(n int, chk bool) Option { return func(d Device) error { d.(*device).devID = n d.(*device).chkLE = chk return nil } }
[ "func", "LnxDeviceID", "(", "n", "int", ",", "chk", "bool", ")", "Option", "{", "return", "func", "(", "d", "Device", ")", "error", "{", "d", ".", "(", "*", "device", ")", ".", "devID", "=", "n", "\n", "d", ".", "(", "*", "device", ")", ".", "chkLE", "=", "chk", "\n", "return", "nil", "\n", "}", "\n", "}" ]
// LnxDeviceID specifies which HCI device to use. // If n is set to -1, all the available HCI devices will be probed. // If chk is set to true, LnxDeviceID checks the LE support in the feature list of the HCI device. // This is to filter devices that does not support LE. In case some LE driver that doesn't correctly // set the LE support in its feature list, user can turn off the check. // This option can only be used with NewDevice on Linux implementation.
[ "LnxDeviceID", "specifies", "which", "HCI", "device", "to", "use", ".", "If", "n", "is", "set", "to", "-", "1", "all", "the", "available", "HCI", "devices", "will", "be", "probed", ".", "If", "chk", "is", "set", "to", "true", "LnxDeviceID", "checks", "the", "LE", "support", "in", "the", "feature", "list", "of", "the", "HCI", "device", ".", "This", "is", "to", "filter", "devices", "that", "does", "not", "support", "LE", ".", "In", "case", "some", "LE", "driver", "that", "doesn", "t", "correctly", "set", "the", "LE", "support", "in", "its", "feature", "list", "user", "can", "turn", "off", "the", "check", ".", "This", "option", "can", "only", "be", "used", "with", "NewDevice", "on", "Linux", "implementation", "." ]
4ae819d591cfc94c496c45deb55928469542beec
https://github.com/paypal/gatt/blob/4ae819d591cfc94c496c45deb55928469542beec/option_linux.go#L16-L22
5,413
paypal/gatt
option_linux.go
LnxMaxConnections
func LnxMaxConnections(n int) Option { return func(d Device) error { d.(*device).maxConn = n return nil } }
go
func LnxMaxConnections(n int) Option { return func(d Device) error { d.(*device).maxConn = n return nil } }
[ "func", "LnxMaxConnections", "(", "n", "int", ")", "Option", "{", "return", "func", "(", "d", "Device", ")", "error", "{", "d", ".", "(", "*", "device", ")", ".", "maxConn", "=", "n", "\n", "return", "nil", "\n", "}", "\n", "}" ]
// LnxMaxConnections is an optional parameter. // If set, it overrides the default max connections supported. // This option can only be used with NewDevice on Linux implementation.
[ "LnxMaxConnections", "is", "an", "optional", "parameter", ".", "If", "set", "it", "overrides", "the", "default", "max", "connections", "supported", ".", "This", "option", "can", "only", "be", "used", "with", "NewDevice", "on", "Linux", "implementation", "." ]
4ae819d591cfc94c496c45deb55928469542beec
https://github.com/paypal/gatt/blob/4ae819d591cfc94c496c45deb55928469542beec/option_linux.go#L27-L32
5,414
paypal/gatt
option_linux.go
LnxSetAdvertisingEnable
func LnxSetAdvertisingEnable(en bool) Option { return func(d Device) error { dd := d.(*device) if dd == nil { return errors.New("device is not initialized") } if err := dd.update(); err != nil { return err } return dd.hci.SetAdvertiseEnable(en) } }
go
func LnxSetAdvertisingEnable(en bool) Option { return func(d Device) error { dd := d.(*device) if dd == nil { return errors.New("device is not initialized") } if err := dd.update(); err != nil { return err } return dd.hci.SetAdvertiseEnable(en) } }
[ "func", "LnxSetAdvertisingEnable", "(", "en", "bool", ")", "Option", "{", "return", "func", "(", "d", "Device", ")", "error", "{", "dd", ":=", "d", ".", "(", "*", "device", ")", "\n", "if", "dd", "==", "nil", "{", "return", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n", "if", "err", ":=", "dd", ".", "update", "(", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "return", "dd", ".", "hci", ".", "SetAdvertiseEnable", "(", "en", ")", "\n", "}", "\n", "}" ]
// LnxSetAdvertisingEnable sets the advertising data to the HCI device. // This option can be used with Option on Linux implementation.
[ "LnxSetAdvertisingEnable", "sets", "the", "advertising", "data", "to", "the", "HCI", "device", ".", "This", "option", "can", "be", "used", "with", "Option", "on", "Linux", "implementation", "." ]
4ae819d591cfc94c496c45deb55928469542beec
https://github.com/paypal/gatt/blob/4ae819d591cfc94c496c45deb55928469542beec/option_linux.go#L36-L47
5,415
paypal/gatt
option_linux.go
LnxSetAdvertisingData
func LnxSetAdvertisingData(c *cmd.LESetAdvertisingData) Option { return func(d Device) error { d.(*device).advData = c return nil } }
go
func LnxSetAdvertisingData(c *cmd.LESetAdvertisingData) Option { return func(d Device) error { d.(*device).advData = c return nil } }
[ "func", "LnxSetAdvertisingData", "(", "c", "*", "cmd", ".", "LESetAdvertisingData", ")", "Option", "{", "return", "func", "(", "d", "Device", ")", "error", "{", "d", ".", "(", "*", "device", ")", ".", "advData", "=", "c", "\n", "return", "nil", "\n", "}", "\n", "}" ]
// LnxSetAdvertisingData sets the advertising data to the HCI device. // This option can be used with NewDevice or Option on Linux implementation.
[ "LnxSetAdvertisingData", "sets", "the", "advertising", "data", "to", "the", "HCI", "device", ".", "This", "option", "can", "be", "used", "with", "NewDevice", "or", "Option", "on", "Linux", "implementation", "." ]
4ae819d591cfc94c496c45deb55928469542beec
https://github.com/paypal/gatt/blob/4ae819d591cfc94c496c45deb55928469542beec/option_linux.go#L51-L56
5,416
paypal/gatt
option_linux.go
LnxSetScanResponseData
func LnxSetScanResponseData(c *cmd.LESetScanResponseData) Option { return func(d Device) error { d.(*device).scanResp = c return nil } }
go
func LnxSetScanResponseData(c *cmd.LESetScanResponseData) Option { return func(d Device) error { d.(*device).scanResp = c return nil } }
[ "func", "LnxSetScanResponseData", "(", "c", "*", "cmd", ".", "LESetScanResponseData", ")", "Option", "{", "return", "func", "(", "d", "Device", ")", "error", "{", "d", ".", "(", "*", "device", ")", ".", "scanResp", "=", "c", "\n", "return", "nil", "\n", "}", "\n", "}" ]
// LnxSetScanResponseData sets the scan response data to the HXI device. // This option can be used with NewDevice or Option on Linux implementation.
[ "LnxSetScanResponseData", "sets", "the", "scan", "response", "data", "to", "the", "HXI", "device", ".", "This", "option", "can", "be", "used", "with", "NewDevice", "or", "Option", "on", "Linux", "implementation", "." ]
4ae819d591cfc94c496c45deb55928469542beec
https://github.com/paypal/gatt/blob/4ae819d591cfc94c496c45deb55928469542beec/option_linux.go#L60-L65
5,417
paypal/gatt
option_linux.go
LnxSetAdvertisingParameters
func LnxSetAdvertisingParameters(c *cmd.LESetAdvertisingParameters) Option { return func(d Device) error { d.(*device).advParam = c return nil } }
go
func LnxSetAdvertisingParameters(c *cmd.LESetAdvertisingParameters) Option { return func(d Device) error { d.(*device).advParam = c return nil } }
[ "func", "LnxSetAdvertisingParameters", "(", "c", "*", "cmd", ".", "LESetAdvertisingParameters", ")", "Option", "{", "return", "func", "(", "d", "Device", ")", "error", "{", "d", ".", "(", "*", "device", ")", ".", "advParam", "=", "c", "\n", "return", "nil", "\n", "}", "\n", "}" ]
// LnxSetAdvertisingParameters sets the advertising parameters to the HCI device. // This option can be used with NewDevice or Option on Linux implementation.
[ "LnxSetAdvertisingParameters", "sets", "the", "advertising", "parameters", "to", "the", "HCI", "device", ".", "This", "option", "can", "be", "used", "with", "NewDevice", "or", "Option", "on", "Linux", "implementation", "." ]
4ae819d591cfc94c496c45deb55928469542beec
https://github.com/paypal/gatt/blob/4ae819d591cfc94c496c45deb55928469542beec/option_linux.go#L69-L74
5,418
paypal/gatt
option_linux.go
LnxSendHCIRawCommand
func LnxSendHCIRawCommand(c cmd.CmdParam, rsp io.Writer) Option { return func(d Device) error { b, err := d.(*device).SendHCIRawCommand(c) if rsp == nil { return err } rsp.Write(b) return err } }
go
func LnxSendHCIRawCommand(c cmd.CmdParam, rsp io.Writer) Option { return func(d Device) error { b, err := d.(*device).SendHCIRawCommand(c) if rsp == nil { return err } rsp.Write(b) return err } }
[ "func", "LnxSendHCIRawCommand", "(", "c", "cmd", ".", "CmdParam", ",", "rsp", "io", ".", "Writer", ")", "Option", "{", "return", "func", "(", "d", "Device", ")", "error", "{", "b", ",", "err", ":=", "d", ".", "(", "*", "device", ")", ".", "SendHCIRawCommand", "(", "c", ")", "\n", "if", "rsp", "==", "nil", "{", "return", "err", "\n", "}", "\n", "rsp", ".", "Write", "(", "b", ")", "\n", "return", "err", "\n", "}", "\n", "}" ]
// LnxSendHCIRawCommand sends a raw command to the HCI device // This option can be used with NewDevice or Option on Linux implementation.
[ "LnxSendHCIRawCommand", "sends", "a", "raw", "command", "to", "the", "HCI", "device", "This", "option", "can", "be", "used", "with", "NewDevice", "or", "Option", "on", "Linux", "implementation", "." ]
4ae819d591cfc94c496c45deb55928469542beec
https://github.com/paypal/gatt/blob/4ae819d591cfc94c496c45deb55928469542beec/option_linux.go#L78-L87
5,419
paypal/gatt
option_darwin.go
MacDeviceRole
func MacDeviceRole(r int) Option { return func(d Device) error { d.(*device).role = r return nil } }
go
func MacDeviceRole(r int) Option { return func(d Device) error { d.(*device).role = r return nil } }
[ "func", "MacDeviceRole", "(", "r", "int", ")", "Option", "{", "return", "func", "(", "d", "Device", ")", "error", "{", "d", ".", "(", "*", "device", ")", ".", "role", "=", "r", "\n", "return", "nil", "\n", "}", "\n", "}" ]
// MacDeviceRole specify the XPC connection type to connect blued. // THis option can only be used with NewDevice on OS X implementation.
[ "MacDeviceRole", "specify", "the", "XPC", "connection", "type", "to", "connect", "blued", ".", "THis", "option", "can", "only", "be", "used", "with", "NewDevice", "on", "OS", "X", "implementation", "." ]
4ae819d591cfc94c496c45deb55928469542beec
https://github.com/paypal/gatt/blob/4ae819d591cfc94c496c45deb55928469542beec/option_darwin.go#L10-L15
5,420
paypal/gatt
linux/gioctl/ioctl.go
IoW
func IoW(t, nr, size uintptr) uintptr { return ioc(directionWrite, t, nr, size) }
go
func IoW(t, nr, size uintptr) uintptr { return ioc(directionWrite, t, nr, size) }
[ "func", "IoW", "(", "t", ",", "nr", ",", "size", "uintptr", ")", "uintptr", "{", "return", "ioc", "(", "directionWrite", ",", "t", ",", "nr", ",", "size", ")", "\n", "}" ]
// IoW used for an ioctl that writes data to the device driver.
[ "IoW", "used", "for", "an", "ioctl", "that", "writes", "data", "to", "the", "device", "driver", "." ]
4ae819d591cfc94c496c45deb55928469542beec
https://github.com/paypal/gatt/blob/4ae819d591cfc94c496c45deb55928469542beec/linux/gioctl/ioctl.go#L41-L43
5,421
paypal/gatt
linux/gioctl/ioctl.go
IoRW
func IoRW(t, nr, size uintptr) uintptr { return ioc(directionRead|directionWrite, t, nr, size) }
go
func IoRW(t, nr, size uintptr) uintptr { return ioc(directionRead|directionWrite, t, nr, size) }
[ "func", "IoRW", "(", "t", ",", "nr", ",", "size", "uintptr", ")", "uintptr", "{", "return", "ioc", "(", "directionRead", "|", "directionWrite", ",", "t", ",", "nr", ",", "size", ")", "\n", "}" ]
// IoRW a combination of IoR and IoW. That is, data is both written to the driver and then read back from the driver by the client.
[ "IoRW", "a", "combination", "of", "IoR", "and", "IoW", ".", "That", "is", "data", "is", "both", "written", "to", "the", "driver", "and", "then", "read", "back", "from", "the", "driver", "by", "the", "client", "." ]
4ae819d591cfc94c496c45deb55928469542beec
https://github.com/paypal/gatt/blob/4ae819d591cfc94c496c45deb55928469542beec/linux/gioctl/ioctl.go#L46-L48
5,422
paypal/gatt
common.go
NewCharacteristic
func NewCharacteristic(u UUID, s *Service, props Property, h uint16, vh uint16) *Characteristic { c := &Characteristic{ uuid: u, svc: s, props: props, h: h, vh: vh, } return c }
go
func NewCharacteristic(u UUID, s *Service, props Property, h uint16, vh uint16) *Characteristic { c := &Characteristic{ uuid: u, svc: s, props: props, h: h, vh: vh, } return c }
[ "func", "NewCharacteristic", "(", "u", "UUID", ",", "s", "*", "Service", ",", "props", "Property", ",", "h", "uint16", ",", "vh", "uint16", ")", "*", "Characteristic", "{", "c", ":=", "&", "Characteristic", "{", "uuid", ":", "u", ",", "svc", ":", "s", ",", "props", ":", "props", ",", "h", ":", "h", ",", "vh", ":", "vh", ",", "}", "\n\n", "return", "c", "\n", "}" ]
// NewCharacteristic creates and returns a Characteristic.
[ "NewCharacteristic", "creates", "and", "returns", "a", "Characteristic", "." ]
4ae819d591cfc94c496c45deb55928469542beec
https://github.com/paypal/gatt/blob/4ae819d591cfc94c496c45deb55928469542beec/common.go#L144-L154
5,423
paypal/gatt
common.go
NewDescriptor
func NewDescriptor(u UUID, h uint16, char *Characteristic) *Descriptor { cd := &Descriptor{ uuid: u, h: h, char: char, } return cd }
go
func NewDescriptor(u UUID, h uint16, char *Characteristic) *Descriptor { cd := &Descriptor{ uuid: u, h: h, char: char, } return cd }
[ "func", "NewDescriptor", "(", "u", "UUID", ",", "h", "uint16", ",", "char", "*", "Characteristic", ")", "*", "Descriptor", "{", "cd", ":=", "&", "Descriptor", "{", "uuid", ":", "u", ",", "h", ":", "h", ",", "char", ":", "char", ",", "}", "\n", "return", "cd", "\n", "}" ]
// NewDescriptor creates and returns a Descriptor.
[ "NewDescriptor", "creates", "and", "returns", "a", "Descriptor", "." ]
4ae819d591cfc94c496c45deb55928469542beec
https://github.com/paypal/gatt/blob/4ae819d591cfc94c496c45deb55928469542beec/common.go#L332-L339
5,424
paypal/gatt
xpc/xpc_darwin.go
xpcToGo
func xpcToGo(v C.xpc_object_t) interface{} { t := C.xpc_get_type(v) switch t { case C.TYPE_ARRAY: a := make(Array, C.int(C.xpc_array_get_count(v))) C.XpcArrayApply(unsafe.Pointer(&a), v) return a case C.TYPE_DATA: return C.GoBytes(C.xpc_data_get_bytes_ptr(v), C.int(C.xpc_data_get_length(v))) case C.TYPE_DICT: d := make(Dict) C.XpcDictApply(unsafe.Pointer(&d), v) return d case C.TYPE_INT64: return int64(C.xpc_int64_get_value(v)) case C.TYPE_STRING: return C.GoString(C.xpc_string_get_string_ptr(v)) case C.TYPE_UUID: a := [16]byte{} C.XpcUUIDGetBytes(unsafe.Pointer(&a), v) return UUID(a[:]) default: log.Fatalf("unexpected type %#v, value %#v", t, v) } return nil }
go
func xpcToGo(v C.xpc_object_t) interface{} { t := C.xpc_get_type(v) switch t { case C.TYPE_ARRAY: a := make(Array, C.int(C.xpc_array_get_count(v))) C.XpcArrayApply(unsafe.Pointer(&a), v) return a case C.TYPE_DATA: return C.GoBytes(C.xpc_data_get_bytes_ptr(v), C.int(C.xpc_data_get_length(v))) case C.TYPE_DICT: d := make(Dict) C.XpcDictApply(unsafe.Pointer(&d), v) return d case C.TYPE_INT64: return int64(C.xpc_int64_get_value(v)) case C.TYPE_STRING: return C.GoString(C.xpc_string_get_string_ptr(v)) case C.TYPE_UUID: a := [16]byte{} C.XpcUUIDGetBytes(unsafe.Pointer(&a), v) return UUID(a[:]) default: log.Fatalf("unexpected type %#v, value %#v", t, v) } return nil }
[ "func", "xpcToGo", "(", "v", "C", ".", "xpc_object_t", ")", "interface", "{", "}", "{", "t", ":=", "C", ".", "xpc_get_type", "(", "v", ")", "\n\n", "switch", "t", "{", "case", "C", ".", "TYPE_ARRAY", ":", "a", ":=", "make", "(", "Array", ",", "C", ".", "int", "(", "C", ".", "xpc_array_get_count", "(", "v", ")", ")", ")", "\n", "C", ".", "XpcArrayApply", "(", "unsafe", ".", "Pointer", "(", "&", "a", ")", ",", "v", ")", "\n", "return", "a", "\n\n", "case", "C", ".", "TYPE_DATA", ":", "return", "C", ".", "GoBytes", "(", "C", ".", "xpc_data_get_bytes_ptr", "(", "v", ")", ",", "C", ".", "int", "(", "C", ".", "xpc_data_get_length", "(", "v", ")", ")", ")", "\n\n", "case", "C", ".", "TYPE_DICT", ":", "d", ":=", "make", "(", "Dict", ")", "\n", "C", ".", "XpcDictApply", "(", "unsafe", ".", "Pointer", "(", "&", "d", ")", ",", "v", ")", "\n", "return", "d", "\n\n", "case", "C", ".", "TYPE_INT64", ":", "return", "int64", "(", "C", ".", "xpc_int64_get_value", "(", "v", ")", ")", "\n\n", "case", "C", ".", "TYPE_STRING", ":", "return", "C", ".", "GoString", "(", "C", ".", "xpc_string_get_string_ptr", "(", "v", ")", ")", "\n\n", "case", "C", ".", "TYPE_UUID", ":", "a", ":=", "[", "16", "]", "byte", "{", "}", "\n", "C", ".", "XpcUUIDGetBytes", "(", "unsafe", ".", "Pointer", "(", "&", "a", ")", ",", "v", ")", "\n", "return", "UUID", "(", "a", "[", ":", "]", ")", "\n\n", "default", ":", "log", ".", "Fatalf", "(", "\"", "\"", ",", "t", ",", "v", ")", "\n", "}", "\n\n", "return", "nil", "\n", "}" ]
// xpcToGo converts an xpc object to a go object // // note that not all the types are supported, but only the subset required for Blued
[ "xpcToGo", "converts", "an", "xpc", "object", "to", "a", "go", "object", "note", "that", "not", "all", "the", "types", "are", "supported", "but", "only", "the", "subset", "required", "for", "Blued" ]
4ae819d591cfc94c496c45deb55928469542beec
https://github.com/paypal/gatt/blob/4ae819d591cfc94c496c45deb55928469542beec/xpc/xpc_darwin.go#L286-L319
5,425
paypal/gatt
adv.go
unmarshall
func (a *Advertisement) unmarshall(b []byte) error { // Utility function for creating a list of uuids. uuidList := func(u []UUID, d []byte, w int) []UUID { for len(d) > 0 { u = append(u, UUID{d[:w]}) d = d[w:] } return u } for len(b) > 0 { if len(b) < 2 { return errors.New("invalid advertise data") } l, t := b[0], b[1] if len(b) < int(1+l) { return errors.New("invalid advertise data") } d := b[2 : 1+l] switch t { case typeFlags: // TODO: should we do anything about the discoverability here? case typeSomeUUID16: a.Services = uuidList(a.Services, d, 2) case typeAllUUID16: a.Services = uuidList(a.Services, d, 2) case typeSomeUUID32: a.Services = uuidList(a.Services, d, 4) case typeAllUUID32: a.Services = uuidList(a.Services, d, 4) case typeSomeUUID128: a.Services = uuidList(a.Services, d, 16) case typeAllUUID128: a.Services = uuidList(a.Services, d, 16) case typeShortName: a.LocalName = string(d) case typeCompleteName: a.LocalName = string(d) case typeTxPower: a.TxPowerLevel = int(d[0]) case typeServiceSol16: a.SolicitedService = uuidList(a.SolicitedService, d, 2) case typeServiceSol128: a.SolicitedService = uuidList(a.SolicitedService, d, 16) case typeServiceSol32: a.SolicitedService = uuidList(a.SolicitedService, d, 4) case typeManufacturerData: a.ManufacturerData = make([]byte, len(d)) copy(a.ManufacturerData, d) // case typeServiceData16, // case typeServiceData32, // case typeServiceData128: default: log.Printf("DATA: [ % X ]", d) } b = b[1+l:] } return nil }
go
func (a *Advertisement) unmarshall(b []byte) error { // Utility function for creating a list of uuids. uuidList := func(u []UUID, d []byte, w int) []UUID { for len(d) > 0 { u = append(u, UUID{d[:w]}) d = d[w:] } return u } for len(b) > 0 { if len(b) < 2 { return errors.New("invalid advertise data") } l, t := b[0], b[1] if len(b) < int(1+l) { return errors.New("invalid advertise data") } d := b[2 : 1+l] switch t { case typeFlags: // TODO: should we do anything about the discoverability here? case typeSomeUUID16: a.Services = uuidList(a.Services, d, 2) case typeAllUUID16: a.Services = uuidList(a.Services, d, 2) case typeSomeUUID32: a.Services = uuidList(a.Services, d, 4) case typeAllUUID32: a.Services = uuidList(a.Services, d, 4) case typeSomeUUID128: a.Services = uuidList(a.Services, d, 16) case typeAllUUID128: a.Services = uuidList(a.Services, d, 16) case typeShortName: a.LocalName = string(d) case typeCompleteName: a.LocalName = string(d) case typeTxPower: a.TxPowerLevel = int(d[0]) case typeServiceSol16: a.SolicitedService = uuidList(a.SolicitedService, d, 2) case typeServiceSol128: a.SolicitedService = uuidList(a.SolicitedService, d, 16) case typeServiceSol32: a.SolicitedService = uuidList(a.SolicitedService, d, 4) case typeManufacturerData: a.ManufacturerData = make([]byte, len(d)) copy(a.ManufacturerData, d) // case typeServiceData16, // case typeServiceData32, // case typeServiceData128: default: log.Printf("DATA: [ % X ]", d) } b = b[1+l:] } return nil }
[ "func", "(", "a", "*", "Advertisement", ")", "unmarshall", "(", "b", "[", "]", "byte", ")", "error", "{", "// Utility function for creating a list of uuids.", "uuidList", ":=", "func", "(", "u", "[", "]", "UUID", ",", "d", "[", "]", "byte", ",", "w", "int", ")", "[", "]", "UUID", "{", "for", "len", "(", "d", ")", ">", "0", "{", "u", "=", "append", "(", "u", ",", "UUID", "{", "d", "[", ":", "w", "]", "}", ")", "\n", "d", "=", "d", "[", "w", ":", "]", "\n", "}", "\n", "return", "u", "\n", "}", "\n\n", "for", "len", "(", "b", ")", ">", "0", "{", "if", "len", "(", "b", ")", "<", "2", "{", "return", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n", "l", ",", "t", ":=", "b", "[", "0", "]", ",", "b", "[", "1", "]", "\n", "if", "len", "(", "b", ")", "<", "int", "(", "1", "+", "l", ")", "{", "return", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n", "d", ":=", "b", "[", "2", ":", "1", "+", "l", "]", "\n", "switch", "t", "{", "case", "typeFlags", ":", "// TODO: should we do anything about the discoverability here?", "case", "typeSomeUUID16", ":", "a", ".", "Services", "=", "uuidList", "(", "a", ".", "Services", ",", "d", ",", "2", ")", "\n", "case", "typeAllUUID16", ":", "a", ".", "Services", "=", "uuidList", "(", "a", ".", "Services", ",", "d", ",", "2", ")", "\n", "case", "typeSomeUUID32", ":", "a", ".", "Services", "=", "uuidList", "(", "a", ".", "Services", ",", "d", ",", "4", ")", "\n", "case", "typeAllUUID32", ":", "a", ".", "Services", "=", "uuidList", "(", "a", ".", "Services", ",", "d", ",", "4", ")", "\n", "case", "typeSomeUUID128", ":", "a", ".", "Services", "=", "uuidList", "(", "a", ".", "Services", ",", "d", ",", "16", ")", "\n", "case", "typeAllUUID128", ":", "a", ".", "Services", "=", "uuidList", "(", "a", ".", "Services", ",", "d", ",", "16", ")", "\n", "case", "typeShortName", ":", "a", ".", "LocalName", "=", "string", "(", "d", ")", "\n", "case", "typeCompleteName", ":", "a", ".", "LocalName", "=", "string", "(", "d", ")", "\n", "case", "typeTxPower", ":", "a", ".", "TxPowerLevel", "=", "int", "(", "d", "[", "0", "]", ")", "\n", "case", "typeServiceSol16", ":", "a", ".", "SolicitedService", "=", "uuidList", "(", "a", ".", "SolicitedService", ",", "d", ",", "2", ")", "\n", "case", "typeServiceSol128", ":", "a", ".", "SolicitedService", "=", "uuidList", "(", "a", ".", "SolicitedService", ",", "d", ",", "16", ")", "\n", "case", "typeServiceSol32", ":", "a", ".", "SolicitedService", "=", "uuidList", "(", "a", ".", "SolicitedService", ",", "d", ",", "4", ")", "\n", "case", "typeManufacturerData", ":", "a", ".", "ManufacturerData", "=", "make", "(", "[", "]", "byte", ",", "len", "(", "d", ")", ")", "\n", "copy", "(", "a", ".", "ManufacturerData", ",", "d", ")", "\n", "// case typeServiceData16,", "// case typeServiceData32,", "// case typeServiceData128:", "default", ":", "log", ".", "Printf", "(", "\"", "\"", ",", "d", ")", "\n", "}", "\n", "b", "=", "b", "[", "1", "+", "l", ":", "]", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// This is only used in Linux port.
[ "This", "is", "only", "used", "in", "Linux", "port", "." ]
4ae819d591cfc94c496c45deb55928469542beec
https://github.com/paypal/gatt/blob/4ae819d591cfc94c496c45deb55928469542beec/adv.go#L80-L139
5,426
paypal/gatt
adv.go
Bytes
func (a *AdvPacket) Bytes() [31]byte { b := [31]byte{} copy(b[:], a.b) return b }
go
func (a *AdvPacket) Bytes() [31]byte { b := [31]byte{} copy(b[:], a.b) return b }
[ "func", "(", "a", "*", "AdvPacket", ")", "Bytes", "(", ")", "[", "31", "]", "byte", "{", "b", ":=", "[", "31", "]", "byte", "{", "}", "\n", "copy", "(", "b", "[", ":", "]", ",", "a", ".", "b", ")", "\n", "return", "b", "\n", "}" ]
// Bytes returns an 31-byte array, which contains up to 31 bytes of the packet.
[ "Bytes", "returns", "an", "31", "-", "byte", "array", "which", "contains", "up", "to", "31", "bytes", "of", "the", "packet", "." ]
4ae819d591cfc94c496c45deb55928469542beec
https://github.com/paypal/gatt/blob/4ae819d591cfc94c496c45deb55928469542beec/adv.go#L147-L151
5,427
paypal/gatt
adv.go
Len
func (a *AdvPacket) Len() int { if len(a.b) > 31 { return 31 } return len(a.b) }
go
func (a *AdvPacket) Len() int { if len(a.b) > 31 { return 31 } return len(a.b) }
[ "func", "(", "a", "*", "AdvPacket", ")", "Len", "(", ")", "int", "{", "if", "len", "(", "a", ".", "b", ")", ">", "31", "{", "return", "31", "\n", "}", "\n", "return", "len", "(", "a", ".", "b", ")", "\n", "}" ]
// Len returns the length of the packets with a maximum of 31.
[ "Len", "returns", "the", "length", "of", "the", "packets", "with", "a", "maximum", "of", "31", "." ]
4ae819d591cfc94c496c45deb55928469542beec
https://github.com/paypal/gatt/blob/4ae819d591cfc94c496c45deb55928469542beec/adv.go#L154-L159
5,428
paypal/gatt
adv.go
AppendFlags
func (a *AdvPacket) AppendFlags(f byte) *AdvPacket { return a.AppendField(typeFlags, []byte{f}) }
go
func (a *AdvPacket) AppendFlags(f byte) *AdvPacket { return a.AppendField(typeFlags, []byte{f}) }
[ "func", "(", "a", "*", "AdvPacket", ")", "AppendFlags", "(", "f", "byte", ")", "*", "AdvPacket", "{", "return", "a", ".", "AppendField", "(", "typeFlags", ",", "[", "]", "byte", "{", "f", "}", ")", "\n", "}" ]
// AppendFlags appends a flag field to the packet.
[ "AppendFlags", "appends", "a", "flag", "field", "to", "the", "packet", "." ]
4ae819d591cfc94c496c45deb55928469542beec
https://github.com/paypal/gatt/blob/4ae819d591cfc94c496c45deb55928469542beec/adv.go#L176-L178
5,429
paypal/gatt
adv.go
AppendName
func (a *AdvPacket) AppendName(n string) *AdvPacket { typ := byte(typeCompleteName) if len(a.b)+2+len(n) > MaxEIRPacketLength { typ = byte(typeShortName) } return a.AppendField(typ, []byte(n)) }
go
func (a *AdvPacket) AppendName(n string) *AdvPacket { typ := byte(typeCompleteName) if len(a.b)+2+len(n) > MaxEIRPacketLength { typ = byte(typeShortName) } return a.AppendField(typ, []byte(n)) }
[ "func", "(", "a", "*", "AdvPacket", ")", "AppendName", "(", "n", "string", ")", "*", "AdvPacket", "{", "typ", ":=", "byte", "(", "typeCompleteName", ")", "\n", "if", "len", "(", "a", ".", "b", ")", "+", "2", "+", "len", "(", "n", ")", ">", "MaxEIRPacketLength", "{", "typ", "=", "byte", "(", "typeShortName", ")", "\n", "}", "\n", "return", "a", ".", "AppendField", "(", "typ", ",", "[", "]", "byte", "(", "n", ")", ")", "\n", "}" ]
// AppendFlags appends a name field to the packet. // If the name fits in the space, it will be append as a complete name field, otherwise a short name field.
[ "AppendFlags", "appends", "a", "name", "field", "to", "the", "packet", ".", "If", "the", "name", "fits", "in", "the", "space", "it", "will", "be", "append", "as", "a", "complete", "name", "field", "otherwise", "a", "short", "name", "field", "." ]
4ae819d591cfc94c496c45deb55928469542beec
https://github.com/paypal/gatt/blob/4ae819d591cfc94c496c45deb55928469542beec/adv.go#L182-L188
5,430
paypal/gatt
adv.go
AppendManufacturerData
func (a *AdvPacket) AppendManufacturerData(id uint16, b []byte) *AdvPacket { d := append([]byte{uint8(id), uint8(id >> 8)}, b...) return a.AppendField(typeManufacturerData, d) }
go
func (a *AdvPacket) AppendManufacturerData(id uint16, b []byte) *AdvPacket { d := append([]byte{uint8(id), uint8(id >> 8)}, b...) return a.AppendField(typeManufacturerData, d) }
[ "func", "(", "a", "*", "AdvPacket", ")", "AppendManufacturerData", "(", "id", "uint16", ",", "b", "[", "]", "byte", ")", "*", "AdvPacket", "{", "d", ":=", "append", "(", "[", "]", "byte", "{", "uint8", "(", "id", ")", ",", "uint8", "(", "id", ">>", "8", ")", "}", ",", "b", "...", ")", "\n", "return", "a", ".", "AppendField", "(", "typeManufacturerData", ",", "d", ")", "\n", "}" ]
// AppendManufacturerData appends a manufacturer data field to the packet.
[ "AppendManufacturerData", "appends", "a", "manufacturer", "data", "field", "to", "the", "packet", "." ]
4ae819d591cfc94c496c45deb55928469542beec
https://github.com/paypal/gatt/blob/4ae819d591cfc94c496c45deb55928469542beec/adv.go#L191-L194
5,431
paypal/gatt
adv.go
AppendUUIDFit
func (a *AdvPacket) AppendUUIDFit(uu []UUID) bool { // Iterate all UUIDs to see if they fit in the packet or not. fit, l := true, len(a.b) for _, u := range uu { if u.Equal(attrGAPUUID) || u.Equal(attrGATTUUID) { continue } l += 2 + u.Len() if l > MaxEIRPacketLength { fit = false break } } // Append the UUIDs until they no longer fit. for _, u := range uu { if u.Equal(attrGAPUUID) || u.Equal(attrGATTUUID) { continue } if len(a.b)+2+u.Len() > MaxEIRPacketLength { break } switch l = u.Len(); { case l == 2 && fit: a.AppendField(typeAllUUID16, u.b) case l == 16 && fit: a.AppendField(typeAllUUID128, u.b) case l == 2 && !fit: a.AppendField(typeSomeUUID16, u.b) case l == 16 && !fit: a.AppendField(typeSomeUUID128, u.b) } } return fit }
go
func (a *AdvPacket) AppendUUIDFit(uu []UUID) bool { // Iterate all UUIDs to see if they fit in the packet or not. fit, l := true, len(a.b) for _, u := range uu { if u.Equal(attrGAPUUID) || u.Equal(attrGATTUUID) { continue } l += 2 + u.Len() if l > MaxEIRPacketLength { fit = false break } } // Append the UUIDs until they no longer fit. for _, u := range uu { if u.Equal(attrGAPUUID) || u.Equal(attrGATTUUID) { continue } if len(a.b)+2+u.Len() > MaxEIRPacketLength { break } switch l = u.Len(); { case l == 2 && fit: a.AppendField(typeAllUUID16, u.b) case l == 16 && fit: a.AppendField(typeAllUUID128, u.b) case l == 2 && !fit: a.AppendField(typeSomeUUID16, u.b) case l == 16 && !fit: a.AppendField(typeSomeUUID128, u.b) } } return fit }
[ "func", "(", "a", "*", "AdvPacket", ")", "AppendUUIDFit", "(", "uu", "[", "]", "UUID", ")", "bool", "{", "// Iterate all UUIDs to see if they fit in the packet or not.", "fit", ",", "l", ":=", "true", ",", "len", "(", "a", ".", "b", ")", "\n", "for", "_", ",", "u", ":=", "range", "uu", "{", "if", "u", ".", "Equal", "(", "attrGAPUUID", ")", "||", "u", ".", "Equal", "(", "attrGATTUUID", ")", "{", "continue", "\n", "}", "\n", "l", "+=", "2", "+", "u", ".", "Len", "(", ")", "\n", "if", "l", ">", "MaxEIRPacketLength", "{", "fit", "=", "false", "\n", "break", "\n", "}", "\n", "}", "\n\n", "// Append the UUIDs until they no longer fit.", "for", "_", ",", "u", ":=", "range", "uu", "{", "if", "u", ".", "Equal", "(", "attrGAPUUID", ")", "||", "u", ".", "Equal", "(", "attrGATTUUID", ")", "{", "continue", "\n", "}", "\n", "if", "len", "(", "a", ".", "b", ")", "+", "2", "+", "u", ".", "Len", "(", ")", ">", "MaxEIRPacketLength", "{", "break", "\n", "}", "\n", "switch", "l", "=", "u", ".", "Len", "(", ")", ";", "{", "case", "l", "==", "2", "&&", "fit", ":", "a", ".", "AppendField", "(", "typeAllUUID16", ",", "u", ".", "b", ")", "\n", "case", "l", "==", "16", "&&", "fit", ":", "a", ".", "AppendField", "(", "typeAllUUID128", ",", "u", ".", "b", ")", "\n", "case", "l", "==", "2", "&&", "!", "fit", ":", "a", ".", "AppendField", "(", "typeSomeUUID16", ",", "u", ".", "b", ")", "\n", "case", "l", "==", "16", "&&", "!", "fit", ":", "a", ".", "AppendField", "(", "typeSomeUUID128", ",", "u", ".", "b", ")", "\n", "}", "\n", "}", "\n", "return", "fit", "\n", "}" ]
// AppendUUIDFit appends a BLE advertised service UUID // packet field if it fits in the packet, and reports whether the UUID fit.
[ "AppendUUIDFit", "appends", "a", "BLE", "advertised", "service", "UUID", "packet", "field", "if", "it", "fits", "in", "the", "packet", "and", "reports", "whether", "the", "UUID", "fit", "." ]
4ae819d591cfc94c496c45deb55928469542beec
https://github.com/paypal/gatt/blob/4ae819d591cfc94c496c45deb55928469542beec/adv.go#L198-L232
5,432
paypal/gatt
linux/l2cap.go
Close
func (c *conn) Close() error { h := c.hci hh := c.attr h.connsmu.Lock() defer h.connsmu.Unlock() _, found := h.conns[hh] if !found { // log.Printf("l2conn: 0x%04x already disconnected", hh) return nil } if err, _ := h.c.Send(cmd.Disconnect{ConnectionHandle: hh, Reason: 0x13}); err != nil { return fmt.Errorf("l2conn: failed to disconnect, %s", err) } return nil }
go
func (c *conn) Close() error { h := c.hci hh := c.attr h.connsmu.Lock() defer h.connsmu.Unlock() _, found := h.conns[hh] if !found { // log.Printf("l2conn: 0x%04x already disconnected", hh) return nil } if err, _ := h.c.Send(cmd.Disconnect{ConnectionHandle: hh, Reason: 0x13}); err != nil { return fmt.Errorf("l2conn: failed to disconnect, %s", err) } return nil }
[ "func", "(", "c", "*", "conn", ")", "Close", "(", ")", "error", "{", "h", ":=", "c", ".", "hci", "\n", "hh", ":=", "c", ".", "attr", "\n", "h", ".", "connsmu", ".", "Lock", "(", ")", "\n", "defer", "h", ".", "connsmu", ".", "Unlock", "(", ")", "\n", "_", ",", "found", ":=", "h", ".", "conns", "[", "hh", "]", "\n", "if", "!", "found", "{", "// log.Printf(\"l2conn: 0x%04x already disconnected\", hh)", "return", "nil", "\n", "}", "\n", "if", "err", ",", "_", ":=", "h", ".", "c", ".", "Send", "(", "cmd", ".", "Disconnect", "{", "ConnectionHandle", ":", "hh", ",", "Reason", ":", "0x13", "}", ")", ";", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// Close disconnects the connection by sending HCI disconnect command to the device.
[ "Close", "disconnects", "the", "connection", "by", "sending", "HCI", "disconnect", "command", "to", "the", "device", "." ]
4ae819d591cfc94c496c45deb55928469542beec
https://github.com/paypal/gatt/blob/4ae819d591cfc94c496c45deb55928469542beec/linux/l2cap.go#L130-L144
5,433
paypal/gatt
linux/l2cap.go
handleSignal
func (c *conn) handleSignal(a *aclData) error { log.Printf("ignore l2cap signal:[ % X ]", a.b) // FIXME: handle LE signaling channel (CID: 5) return nil }
go
func (c *conn) handleSignal(a *aclData) error { log.Printf("ignore l2cap signal:[ % X ]", a.b) // FIXME: handle LE signaling channel (CID: 5) return nil }
[ "func", "(", "c", "*", "conn", ")", "handleSignal", "(", "a", "*", "aclData", ")", "error", "{", "log", ".", "Printf", "(", "\"", "\"", ",", "a", ".", "b", ")", "\n", "// FIXME: handle LE signaling channel (CID: 5)", "return", "nil", "\n", "}" ]
// Signal Packets // 0x00 Reserved Any // 0x01 Command reject 0x0001 and 0x0005 // 0x02 Connection request 0x0001 // 0x03 Connection response 0x0001 // 0x04 Configure request 0x0001 // 0x05 Configure response 0x0001 // 0x06 Disconnection request 0x0001 and 0x0005 // 0x07 Disconnection response 0x0001 and 0x0005 // 0x08 Echo request 0x0001 // 0x09 Echo response 0x0001 // 0x0A Information request 0x0001 // 0x0B Information response 0x0001 // 0x0C Create Channel request 0x0001 // 0x0D Create Channel response 0x0001 // 0x0E Move Channel request 0x0001 // 0x0F Move Channel response 0x0001 // 0x10 Move Channel Confirmation 0x0001 // 0x11 Move Channel Confirmation response 0x0001 // 0x12 Connection Parameter Update request 0x0005 // 0x13 Connection Parameter Update response 0x0005 // 0x14 LE Credit Based Connection request 0x0005 // 0x15 LE Credit Based Connection response 0x0005 // 0x16 LE Flow Control Credit 0x0005
[ "Signal", "Packets", "0x00", "Reserved", "Any", "0x01", "Command", "reject", "0x0001", "and", "0x0005", "0x02", "Connection", "request", "0x0001", "0x03", "Connection", "response", "0x0001", "0x04", "Configure", "request", "0x0001", "0x05", "Configure", "response", "0x0001", "0x06", "Disconnection", "request", "0x0001", "and", "0x0005", "0x07", "Disconnection", "response", "0x0001", "and", "0x0005", "0x08", "Echo", "request", "0x0001", "0x09", "Echo", "response", "0x0001", "0x0A", "Information", "request", "0x0001", "0x0B", "Information", "response", "0x0001", "0x0C", "Create", "Channel", "request", "0x0001", "0x0D", "Create", "Channel", "response", "0x0001", "0x0E", "Move", "Channel", "request", "0x0001", "0x0F", "Move", "Channel", "response", "0x0001", "0x10", "Move", "Channel", "Confirmation", "0x0001", "0x11", "Move", "Channel", "Confirmation", "response", "0x0001", "0x12", "Connection", "Parameter", "Update", "request", "0x0005", "0x13", "Connection", "Parameter", "Update", "response", "0x0005", "0x14", "LE", "Credit", "Based", "Connection", "request", "0x0005", "0x15", "LE", "Credit", "Based", "Connection", "response", "0x0005", "0x16", "LE", "Flow", "Control", "Credit", "0x0005" ]
4ae819d591cfc94c496c45deb55928469542beec
https://github.com/paypal/gatt/blob/4ae819d591cfc94c496c45deb55928469542beec/linux/l2cap.go#L170-L174
5,434
paypal/gatt
uuid.go
ParseUUID
func ParseUUID(s string) (UUID, error) { s = strings.Replace(s, "-", "", -1) b, err := hex.DecodeString(s) if err != nil { return UUID{}, err } if err := lenErr(len(b)); err != nil { return UUID{}, err } return UUID{reverse(b)}, nil }
go
func ParseUUID(s string) (UUID, error) { s = strings.Replace(s, "-", "", -1) b, err := hex.DecodeString(s) if err != nil { return UUID{}, err } if err := lenErr(len(b)); err != nil { return UUID{}, err } return UUID{reverse(b)}, nil }
[ "func", "ParseUUID", "(", "s", "string", ")", "(", "UUID", ",", "error", ")", "{", "s", "=", "strings", ".", "Replace", "(", "s", ",", "\"", "\"", ",", "\"", "\"", ",", "-", "1", ")", "\n", "b", ",", "err", ":=", "hex", ".", "DecodeString", "(", "s", ")", "\n", "if", "err", "!=", "nil", "{", "return", "UUID", "{", "}", ",", "err", "\n", "}", "\n", "if", "err", ":=", "lenErr", "(", "len", "(", "b", ")", ")", ";", "err", "!=", "nil", "{", "return", "UUID", "{", "}", ",", "err", "\n", "}", "\n", "return", "UUID", "{", "reverse", "(", "b", ")", "}", ",", "nil", "\n", "}" ]
// ParseUUID parses a standard-format UUID string, such // as "1800" or "34DA3AD1-7110-41A1-B1EF-4430F509CDE7".
[ "ParseUUID", "parses", "a", "standard", "-", "format", "UUID", "string", "such", "as", "1800", "or", "34DA3AD1", "-", "7110", "-", "41A1", "-", "B1EF", "-", "4430F509CDE7", "." ]
4ae819d591cfc94c496c45deb55928469542beec
https://github.com/paypal/gatt/blob/4ae819d591cfc94c496c45deb55928469542beec/uuid.go#L27-L37
5,435
paypal/gatt
uuid.go
MustParseUUID
func MustParseUUID(s string) UUID { u, err := ParseUUID(s) if err != nil { panic(err) } return u }
go
func MustParseUUID(s string) UUID { u, err := ParseUUID(s) if err != nil { panic(err) } return u }
[ "func", "MustParseUUID", "(", "s", "string", ")", "UUID", "{", "u", ",", "err", ":=", "ParseUUID", "(", "s", ")", "\n", "if", "err", "!=", "nil", "{", "panic", "(", "err", ")", "\n", "}", "\n", "return", "u", "\n", "}" ]
// MustParseUUID parses a standard-format UUID string, // like ParseUUID, but panics in case of error.
[ "MustParseUUID", "parses", "a", "standard", "-", "format", "UUID", "string", "like", "ParseUUID", "but", "panics", "in", "case", "of", "error", "." ]
4ae819d591cfc94c496c45deb55928469542beec
https://github.com/paypal/gatt/blob/4ae819d591cfc94c496c45deb55928469542beec/uuid.go#L41-L47
5,436
paypal/gatt
uuid.go
Equal
func (u UUID) Equal(v UUID) bool { return bytes.Equal(u.b, v.b) }
go
func (u UUID) Equal(v UUID) bool { return bytes.Equal(u.b, v.b) }
[ "func", "(", "u", "UUID", ")", "Equal", "(", "v", "UUID", ")", "bool", "{", "return", "bytes", ".", "Equal", "(", "u", ".", "b", ",", "v", ".", "b", ")", "\n", "}" ]
// Equal returns a boolean reporting whether v represent the same UUID as u.
[ "Equal", "returns", "a", "boolean", "reporting", "whether", "v", "represent", "the", "same", "UUID", "as", "u", "." ]
4ae819d591cfc94c496c45deb55928469542beec
https://github.com/paypal/gatt/blob/4ae819d591cfc94c496c45deb55928469542beec/uuid.go#L70-L72
5,437
paypal/gatt
uuid.go
reverse
func reverse(u []byte) []byte { // Special-case 16 bit UUIDS for speed. l := len(u) if l == 2 { return []byte{u[1], u[0]} } b := make([]byte, l) for i := 0; i < l/2+1; i++ { b[i], b[l-i-1] = u[l-i-1], u[i] } return b }
go
func reverse(u []byte) []byte { // Special-case 16 bit UUIDS for speed. l := len(u) if l == 2 { return []byte{u[1], u[0]} } b := make([]byte, l) for i := 0; i < l/2+1; i++ { b[i], b[l-i-1] = u[l-i-1], u[i] } return b }
[ "func", "reverse", "(", "u", "[", "]", "byte", ")", "[", "]", "byte", "{", "// Special-case 16 bit UUIDS for speed.", "l", ":=", "len", "(", "u", ")", "\n", "if", "l", "==", "2", "{", "return", "[", "]", "byte", "{", "u", "[", "1", "]", ",", "u", "[", "0", "]", "}", "\n", "}", "\n", "b", ":=", "make", "(", "[", "]", "byte", ",", "l", ")", "\n", "for", "i", ":=", "0", ";", "i", "<", "l", "/", "2", "+", "1", ";", "i", "++", "{", "b", "[", "i", "]", ",", "b", "[", "l", "-", "i", "-", "1", "]", "=", "u", "[", "l", "-", "i", "-", "1", "]", ",", "u", "[", "i", "]", "\n", "}", "\n", "return", "b", "\n", "}" ]
// reverse returns a reversed copy of u.
[ "reverse", "returns", "a", "reversed", "copy", "of", "u", "." ]
4ae819d591cfc94c496c45deb55928469542beec
https://github.com/paypal/gatt/blob/4ae819d591cfc94c496c45deb55928469542beec/uuid.go#L75-L86
5,438
paypal/gatt
device.go
Handle
func (d *device) Handle(hh ...Handler) { for _, h := range hh { h(d) } }
go
func (d *device) Handle(hh ...Handler) { for _, h := range hh { h(d) } }
[ "func", "(", "d", "*", "device", ")", "Handle", "(", "hh", "...", "Handler", ")", "{", "for", "_", ",", "h", ":=", "range", "hh", "{", "h", "(", "d", ")", "\n", "}", "\n", "}" ]
// Handle registers the specified handlers.
[ "Handle", "registers", "the", "specified", "handlers", "." ]
4ae819d591cfc94c496c45deb55928469542beec
https://github.com/paypal/gatt/blob/4ae819d591cfc94c496c45deb55928469542beec/device.go#L114-L118
5,439
paypal/gatt
device.go
CentralConnected
func CentralConnected(f func(Central)) Handler { return func(d Device) { d.(*device).centralConnected = f } }
go
func CentralConnected(f func(Central)) Handler { return func(d Device) { d.(*device).centralConnected = f } }
[ "func", "CentralConnected", "(", "f", "func", "(", "Central", ")", ")", "Handler", "{", "return", "func", "(", "d", "Device", ")", "{", "d", ".", "(", "*", "device", ")", ".", "centralConnected", "=", "f", "}", "\n", "}" ]
// CentralConnected returns a Handler, which sets the specified function to be called when a device connects to the server.
[ "CentralConnected", "returns", "a", "Handler", "which", "sets", "the", "specified", "function", "to", "be", "called", "when", "a", "device", "connects", "to", "the", "server", "." ]
4ae819d591cfc94c496c45deb55928469542beec
https://github.com/paypal/gatt/blob/4ae819d591cfc94c496c45deb55928469542beec/device.go#L121-L123
5,440
paypal/gatt
device.go
CentralDisconnected
func CentralDisconnected(f func(Central)) Handler { return func(d Device) { d.(*device).centralDisconnected = f } }
go
func CentralDisconnected(f func(Central)) Handler { return func(d Device) { d.(*device).centralDisconnected = f } }
[ "func", "CentralDisconnected", "(", "f", "func", "(", "Central", ")", ")", "Handler", "{", "return", "func", "(", "d", "Device", ")", "{", "d", ".", "(", "*", "device", ")", ".", "centralDisconnected", "=", "f", "}", "\n", "}" ]
// CentralDisconnected returns a Handler, which sets the specified function to be called when a device disconnects from the server.
[ "CentralDisconnected", "returns", "a", "Handler", "which", "sets", "the", "specified", "function", "to", "be", "called", "when", "a", "device", "disconnects", "from", "the", "server", "." ]
4ae819d591cfc94c496c45deb55928469542beec
https://github.com/paypal/gatt/blob/4ae819d591cfc94c496c45deb55928469542beec/device.go#L126-L128
5,441
paypal/gatt
device.go
PeripheralDiscovered
func PeripheralDiscovered(f func(Peripheral, *Advertisement, int)) Handler { return func(d Device) { d.(*device).peripheralDiscovered = f } }
go
func PeripheralDiscovered(f func(Peripheral, *Advertisement, int)) Handler { return func(d Device) { d.(*device).peripheralDiscovered = f } }
[ "func", "PeripheralDiscovered", "(", "f", "func", "(", "Peripheral", ",", "*", "Advertisement", ",", "int", ")", ")", "Handler", "{", "return", "func", "(", "d", "Device", ")", "{", "d", ".", "(", "*", "device", ")", ".", "peripheralDiscovered", "=", "f", "}", "\n", "}" ]
// PeripheralDiscovered returns a Handler, which sets the specified function to be called when a remote peripheral device is found during scan procedure.
[ "PeripheralDiscovered", "returns", "a", "Handler", "which", "sets", "the", "specified", "function", "to", "be", "called", "when", "a", "remote", "peripheral", "device", "is", "found", "during", "scan", "procedure", "." ]
4ae819d591cfc94c496c45deb55928469542beec
https://github.com/paypal/gatt/blob/4ae819d591cfc94c496c45deb55928469542beec/device.go#L131-L133
5,442
paypal/gatt
device.go
PeripheralConnected
func PeripheralConnected(f func(Peripheral, error)) Handler { return func(d Device) { d.(*device).peripheralConnected = f } }
go
func PeripheralConnected(f func(Peripheral, error)) Handler { return func(d Device) { d.(*device).peripheralConnected = f } }
[ "func", "PeripheralConnected", "(", "f", "func", "(", "Peripheral", ",", "error", ")", ")", "Handler", "{", "return", "func", "(", "d", "Device", ")", "{", "d", ".", "(", "*", "device", ")", ".", "peripheralConnected", "=", "f", "}", "\n", "}" ]
// PeripheralConnected returns a Handler, which sets the specified function to be called when a remote peripheral device connects.
[ "PeripheralConnected", "returns", "a", "Handler", "which", "sets", "the", "specified", "function", "to", "be", "called", "when", "a", "remote", "peripheral", "device", "connects", "." ]
4ae819d591cfc94c496c45deb55928469542beec
https://github.com/paypal/gatt/blob/4ae819d591cfc94c496c45deb55928469542beec/device.go#L136-L138
5,443
paypal/gatt
device.go
PeripheralDisconnected
func PeripheralDisconnected(f func(Peripheral, error)) Handler { return func(d Device) { d.(*device).peripheralDisconnected = f } }
go
func PeripheralDisconnected(f func(Peripheral, error)) Handler { return func(d Device) { d.(*device).peripheralDisconnected = f } }
[ "func", "PeripheralDisconnected", "(", "f", "func", "(", "Peripheral", ",", "error", ")", ")", "Handler", "{", "return", "func", "(", "d", "Device", ")", "{", "d", ".", "(", "*", "device", ")", ".", "peripheralDisconnected", "=", "f", "}", "\n", "}" ]
// PeripheralDisconnected returns a Handler, which sets the specified function to be called when a remote peripheral device disconnects.
[ "PeripheralDisconnected", "returns", "a", "Handler", "which", "sets", "the", "specified", "function", "to", "be", "called", "when", "a", "remote", "peripheral", "device", "disconnects", "." ]
4ae819d591cfc94c496c45deb55928469542beec
https://github.com/paypal/gatt/blob/4ae819d591cfc94c496c45deb55928469542beec/device.go#L141-L143
5,444
paypal/gatt
device.go
Option
func (d *device) Option(opts ...Option) error { var err error for _, opt := range opts { err = opt(d) } return err }
go
func (d *device) Option(opts ...Option) error { var err error for _, opt := range opts { err = opt(d) } return err }
[ "func", "(", "d", "*", "device", ")", "Option", "(", "opts", "...", "Option", ")", "error", "{", "var", "err", "error", "\n", "for", "_", ",", "opt", ":=", "range", "opts", "{", "err", "=", "opt", "(", "d", ")", "\n", "}", "\n", "return", "err", "\n", "}" ]
// Option sets the options specified. // Some options can only be set before the device is initialized; they are best used with NewDevice instead of Option.
[ "Option", "sets", "the", "options", "specified", ".", "Some", "options", "can", "only", "be", "set", "before", "the", "device", "is", "initialized", ";", "they", "are", "best", "used", "with", "NewDevice", "instead", "of", "Option", "." ]
4ae819d591cfc94c496c45deb55928469542beec
https://github.com/paypal/gatt/blob/4ae819d591cfc94c496c45deb55928469542beec/device.go#L152-L158
5,445
paypal/gatt
attr.go
At
func (r *attrRange) At(h uint16) (a attr, ok bool) { i := r.idx(int(h)) if i < 0 { return attr{}, false } return r.aa[i], true }
go
func (r *attrRange) At(h uint16) (a attr, ok bool) { i := r.idx(int(h)) if i < 0 { return attr{}, false } return r.aa[i], true }
[ "func", "(", "r", "*", "attrRange", ")", "At", "(", "h", "uint16", ")", "(", "a", "attr", ",", "ok", "bool", ")", "{", "i", ":=", "r", ".", "idx", "(", "int", "(", "h", ")", ")", "\n", "if", "i", "<", "0", "{", "return", "attr", "{", "}", ",", "false", "\n", "}", "\n", "return", "r", ".", "aa", "[", "i", "]", ",", "true", "\n", "}" ]
// At returns attr a.
[ "At", "returns", "attr", "a", "." ]
4ae819d591cfc94c496c45deb55928469542beec
https://github.com/paypal/gatt/blob/4ae819d591cfc94c496c45deb55928469542beec/attr.go#L42-L48
5,446
paypal/gatt
l2cap_writer_linux.go
Chunk
func (w *l2capWriter) Chunk() { if w.chunked { panic("l2capWriter: chunk called twice without committing") } w.chunked = true if w.chunk == nil { w.chunk = make([]byte, 0, w.mtu) } }
go
func (w *l2capWriter) Chunk() { if w.chunked { panic("l2capWriter: chunk called twice without committing") } w.chunked = true if w.chunk == nil { w.chunk = make([]byte, 0, w.mtu) } }
[ "func", "(", "w", "*", "l2capWriter", ")", "Chunk", "(", ")", "{", "if", "w", ".", "chunked", "{", "panic", "(", "\"", "\"", ")", "\n", "}", "\n", "w", ".", "chunked", "=", "true", "\n", "if", "w", ".", "chunk", "==", "nil", "{", "w", ".", "chunk", "=", "make", "(", "[", "]", "byte", ",", "0", ",", "w", ".", "mtu", ")", "\n", "}", "\n", "}" ]
// Chunk starts writing a new chunk. This chunk // is not committed until Commit is called. // Chunk panics if another chunk has already been // started and not committed.
[ "Chunk", "starts", "writing", "a", "new", "chunk", ".", "This", "chunk", "is", "not", "committed", "until", "Commit", "is", "called", ".", "Chunk", "panics", "if", "another", "chunk", "has", "already", "been", "started", "and", "not", "committed", "." ]
4ae819d591cfc94c496c45deb55928469542beec
https://github.com/paypal/gatt/blob/4ae819d591cfc94c496c45deb55928469542beec/l2cap_writer_linux.go#L25-L33
5,447
paypal/gatt
l2cap_writer_linux.go
Commit
func (w *l2capWriter) Commit() bool { if !w.chunked { panic("l2capWriter: commit without starting a chunk") } var success bool if len(w.b)+len(w.chunk) <= w.mtu { success = true w.b = append(w.b, w.chunk...) } w.chunk = w.chunk[:0] w.chunked = false return success }
go
func (w *l2capWriter) Commit() bool { if !w.chunked { panic("l2capWriter: commit without starting a chunk") } var success bool if len(w.b)+len(w.chunk) <= w.mtu { success = true w.b = append(w.b, w.chunk...) } w.chunk = w.chunk[:0] w.chunked = false return success }
[ "func", "(", "w", "*", "l2capWriter", ")", "Commit", "(", ")", "bool", "{", "if", "!", "w", ".", "chunked", "{", "panic", "(", "\"", "\"", ")", "\n", "}", "\n", "var", "success", "bool", "\n", "if", "len", "(", "w", ".", "b", ")", "+", "len", "(", "w", ".", "chunk", ")", "<=", "w", ".", "mtu", "{", "success", "=", "true", "\n", "w", ".", "b", "=", "append", "(", "w", ".", "b", ",", "w", ".", "chunk", "...", ")", "\n", "}", "\n", "w", ".", "chunk", "=", "w", ".", "chunk", "[", ":", "0", "]", "\n", "w", ".", "chunked", "=", "false", "\n", "return", "success", "\n", "}" ]
// Commit writes the current chunk and reports whether the // write succeeded. The write succeeds iff there is enough room. // Commit panics if no chunk has been started.
[ "Commit", "writes", "the", "current", "chunk", "and", "reports", "whether", "the", "write", "succeeded", ".", "The", "write", "succeeds", "iff", "there", "is", "enough", "room", ".", "Commit", "panics", "if", "no", "chunk", "has", "been", "started", "." ]
4ae819d591cfc94c496c45deb55928469542beec
https://github.com/paypal/gatt/blob/4ae819d591cfc94c496c45deb55928469542beec/l2cap_writer_linux.go#L38-L50
5,448
paypal/gatt
l2cap_writer_linux.go
CommitFit
func (w *l2capWriter) CommitFit() { if !w.chunked { panic("l2capWriter: CommitFit without starting a chunk") } writeable := w.mtu - len(w.b) if writeable > len(w.chunk) { writeable = len(w.chunk) } w.b = append(w.b, w.chunk[:writeable]...) w.chunk = w.chunk[:0] w.chunked = false }
go
func (w *l2capWriter) CommitFit() { if !w.chunked { panic("l2capWriter: CommitFit without starting a chunk") } writeable := w.mtu - len(w.b) if writeable > len(w.chunk) { writeable = len(w.chunk) } w.b = append(w.b, w.chunk[:writeable]...) w.chunk = w.chunk[:0] w.chunked = false }
[ "func", "(", "w", "*", "l2capWriter", ")", "CommitFit", "(", ")", "{", "if", "!", "w", ".", "chunked", "{", "panic", "(", "\"", "\"", ")", "\n", "}", "\n", "writeable", ":=", "w", ".", "mtu", "-", "len", "(", "w", ".", "b", ")", "\n", "if", "writeable", ">", "len", "(", "w", ".", "chunk", ")", "{", "writeable", "=", "len", "(", "w", ".", "chunk", ")", "\n", "}", "\n", "w", ".", "b", "=", "append", "(", "w", ".", "b", ",", "w", ".", "chunk", "[", ":", "writeable", "]", "...", ")", "\n", "w", ".", "chunk", "=", "w", ".", "chunk", "[", ":", "0", "]", "\n", "w", ".", "chunked", "=", "false", "\n", "}" ]
// CommitFit writes as much of the current chunk as possible, // truncating as needed. // CommitFit panics if no chunk has been started.
[ "CommitFit", "writes", "as", "much", "of", "the", "current", "chunk", "as", "possible", "truncating", "as", "needed", ".", "CommitFit", "panics", "if", "no", "chunk", "has", "been", "started", "." ]
4ae819d591cfc94c496c45deb55928469542beec
https://github.com/paypal/gatt/blob/4ae819d591cfc94c496c45deb55928469542beec/l2cap_writer_linux.go#L55-L66
5,449
paypal/gatt
l2cap_writer_linux.go
WriteByteFit
func (w *l2capWriter) WriteByteFit(b byte) bool { return w.WriteFit([]byte{b}) }
go
func (w *l2capWriter) WriteByteFit(b byte) bool { return w.WriteFit([]byte{b}) }
[ "func", "(", "w", "*", "l2capWriter", ")", "WriteByteFit", "(", "b", "byte", ")", "bool", "{", "return", "w", ".", "WriteFit", "(", "[", "]", "byte", "{", "b", "}", ")", "\n", "}" ]
// WriteByteFit writes b. // It reports whether the write succeeded, // using the criteria of WriteFit.
[ "WriteByteFit", "writes", "b", ".", "It", "reports", "whether", "the", "write", "succeeded", "using", "the", "criteria", "of", "WriteFit", "." ]
4ae819d591cfc94c496c45deb55928469542beec
https://github.com/paypal/gatt/blob/4ae819d591cfc94c496c45deb55928469542beec/l2cap_writer_linux.go#L71-L73
5,450
paypal/gatt
l2cap_writer_linux.go
Writeable
func (w *l2capWriter) Writeable(pad int, b []byte) int { if w.chunked { return len(b) } avail := w.mtu - len(w.b) - pad if avail > len(b) { return len(b) } if avail < 0 { return 0 } return avail }
go
func (w *l2capWriter) Writeable(pad int, b []byte) int { if w.chunked { return len(b) } avail := w.mtu - len(w.b) - pad if avail > len(b) { return len(b) } if avail < 0 { return 0 } return avail }
[ "func", "(", "w", "*", "l2capWriter", ")", "Writeable", "(", "pad", "int", ",", "b", "[", "]", "byte", ")", "int", "{", "if", "w", ".", "chunked", "{", "return", "len", "(", "b", ")", "\n", "}", "\n", "avail", ":=", "w", ".", "mtu", "-", "len", "(", "w", ".", "b", ")", "-", "pad", "\n", "if", "avail", ">", "len", "(", "b", ")", "{", "return", "len", "(", "b", ")", "\n", "}", "\n", "if", "avail", "<", "0", "{", "return", "0", "\n", "}", "\n", "return", "avail", "\n", "}" ]
// Writeable returns the number of bytes from b // that would be written if pad bytes were written, // then as much of b as fits were written. When // writing to a chunk, any amount of bytes may be // written.
[ "Writeable", "returns", "the", "number", "of", "bytes", "from", "b", "that", "would", "be", "written", "if", "pad", "bytes", "were", "written", "then", "as", "much", "of", "b", "as", "fits", "were", "written", ".", "When", "writing", "to", "a", "chunk", "any", "amount", "of", "bytes", "may", "be", "written", "." ]
4ae819d591cfc94c496c45deb55928469542beec
https://github.com/paypal/gatt/blob/4ae819d591cfc94c496c45deb55928469542beec/l2cap_writer_linux.go#L96-L108
5,451
paypal/gatt
l2cap_writer_linux.go
ChunkSeek
func (w *l2capWriter) ChunkSeek(offset uint16) bool { if !w.chunked { panic("l2capWriter: ChunkSeek requested without chunked write in progress") } if len(w.chunk) < int(offset) { w.chunk = w.chunk[:0] return false } w.chunk = w.chunk[offset:] return true }
go
func (w *l2capWriter) ChunkSeek(offset uint16) bool { if !w.chunked { panic("l2capWriter: ChunkSeek requested without chunked write in progress") } if len(w.chunk) < int(offset) { w.chunk = w.chunk[:0] return false } w.chunk = w.chunk[offset:] return true }
[ "func", "(", "w", "*", "l2capWriter", ")", "ChunkSeek", "(", "offset", "uint16", ")", "bool", "{", "if", "!", "w", ".", "chunked", "{", "panic", "(", "\"", "\"", ")", "\n", "}", "\n", "if", "len", "(", "w", ".", "chunk", ")", "<", "int", "(", "offset", ")", "{", "w", ".", "chunk", "=", "w", ".", "chunk", "[", ":", "0", "]", "\n", "return", "false", "\n", "}", "\n", "w", ".", "chunk", "=", "w", ".", "chunk", "[", "offset", ":", "]", "\n", "return", "true", "\n", "}" ]
// ChunkSeek discards the first offset bytes from the // current chunk. It reports whether there were at least // offset bytes available to discard. // It panics if a chunked write is not in progress.
[ "ChunkSeek", "discards", "the", "first", "offset", "bytes", "from", "the", "current", "chunk", ".", "It", "reports", "whether", "there", "were", "at", "least", "offset", "bytes", "available", "to", "discard", ".", "It", "panics", "if", "a", "chunked", "write", "is", "not", "in", "progress", "." ]
4ae819d591cfc94c496c45deb55928469542beec
https://github.com/paypal/gatt/blob/4ae819d591cfc94c496c45deb55928469542beec/l2cap_writer_linux.go#L133-L143
5,452
pquerna/otp
hotp/hotp.go
Validate
func Validate(passcode string, counter uint64, secret string) bool { rv, _ := ValidateCustom( passcode, counter, secret, ValidateOpts{ Digits: otp.DigitsSix, Algorithm: otp.AlgorithmSHA1, }, ) return rv }
go
func Validate(passcode string, counter uint64, secret string) bool { rv, _ := ValidateCustom( passcode, counter, secret, ValidateOpts{ Digits: otp.DigitsSix, Algorithm: otp.AlgorithmSHA1, }, ) return rv }
[ "func", "Validate", "(", "passcode", "string", ",", "counter", "uint64", ",", "secret", "string", ")", "bool", "{", "rv", ",", "_", ":=", "ValidateCustom", "(", "passcode", ",", "counter", ",", "secret", ",", "ValidateOpts", "{", "Digits", ":", "otp", ".", "DigitsSix", ",", "Algorithm", ":", "otp", ".", "AlgorithmSHA1", ",", "}", ",", ")", "\n", "return", "rv", "\n", "}" ]
// Validate a HOTP passcode given a counter and secret. // This is a shortcut for ValidateCustom, with parameters that // are compataible with Google-Authenticator.
[ "Validate", "a", "HOTP", "passcode", "given", "a", "counter", "and", "secret", ".", "This", "is", "a", "shortcut", "for", "ValidateCustom", "with", "parameters", "that", "are", "compataible", "with", "Google", "-", "Authenticator", "." ]
be78767b3e392ce45ea73444451022a6fc32ad0d
https://github.com/pquerna/otp/blob/be78767b3e392ce45ea73444451022a6fc32ad0d/hotp/hotp.go#L39-L50
5,453
pquerna/otp
hotp/hotp.go
GenerateCode
func GenerateCode(secret string, counter uint64) (string, error) { return GenerateCodeCustom(secret, counter, ValidateOpts{ Digits: otp.DigitsSix, Algorithm: otp.AlgorithmSHA1, }) }
go
func GenerateCode(secret string, counter uint64) (string, error) { return GenerateCodeCustom(secret, counter, ValidateOpts{ Digits: otp.DigitsSix, Algorithm: otp.AlgorithmSHA1, }) }
[ "func", "GenerateCode", "(", "secret", "string", ",", "counter", "uint64", ")", "(", "string", ",", "error", ")", "{", "return", "GenerateCodeCustom", "(", "secret", ",", "counter", ",", "ValidateOpts", "{", "Digits", ":", "otp", ".", "DigitsSix", ",", "Algorithm", ":", "otp", ".", "AlgorithmSHA1", ",", "}", ")", "\n", "}" ]
// GenerateCode creates a HOTP passcode given a counter and secret. // This is a shortcut for GenerateCodeCustom, with parameters that // are compataible with Google-Authenticator.
[ "GenerateCode", "creates", "a", "HOTP", "passcode", "given", "a", "counter", "and", "secret", ".", "This", "is", "a", "shortcut", "for", "GenerateCodeCustom", "with", "parameters", "that", "are", "compataible", "with", "Google", "-", "Authenticator", "." ]
be78767b3e392ce45ea73444451022a6fc32ad0d
https://github.com/pquerna/otp/blob/be78767b3e392ce45ea73444451022a6fc32ad0d/hotp/hotp.go#L63-L68
5,454
pquerna/otp
hotp/hotp.go
GenerateCodeCustom
func GenerateCodeCustom(secret string, counter uint64, opts ValidateOpts) (passcode string, err error) { // As noted in issue #10 and #17 this adds support for TOTP secrets that are // missing their padding. secret = strings.TrimSpace(secret) if n := len(secret) % 8; n != 0 { secret = secret + strings.Repeat("=", 8-n) } // As noted in issue #24 Google has started producing base32 in lower case, // but the StdEncoding (and the RFC), expect a dictionary of only upper case letters. secret = strings.ToUpper(secret) secretBytes, err := base32.StdEncoding.DecodeString(secret) if err != nil { return "", otp.ErrValidateSecretInvalidBase32 } buf := make([]byte, 8) mac := hmac.New(opts.Algorithm.Hash, secretBytes) binary.BigEndian.PutUint64(buf, counter) if debug { fmt.Printf("counter=%v\n", counter) fmt.Printf("buf=%v\n", buf) } mac.Write(buf) sum := mac.Sum(nil) // "Dynamic truncation" in RFC 4226 // http://tools.ietf.org/html/rfc4226#section-5.4 offset := sum[len(sum)-1] & 0xf value := int64(((int(sum[offset]) & 0x7f) << 24) | ((int(sum[offset+1] & 0xff)) << 16) | ((int(sum[offset+2] & 0xff)) << 8) | (int(sum[offset+3]) & 0xff)) l := opts.Digits.Length() mod := int32(value % int64(math.Pow10(l))) if debug { fmt.Printf("offset=%v\n", offset) fmt.Printf("value=%v\n", value) fmt.Printf("mod'ed=%v\n", mod) } return opts.Digits.Format(mod), nil }
go
func GenerateCodeCustom(secret string, counter uint64, opts ValidateOpts) (passcode string, err error) { // As noted in issue #10 and #17 this adds support for TOTP secrets that are // missing their padding. secret = strings.TrimSpace(secret) if n := len(secret) % 8; n != 0 { secret = secret + strings.Repeat("=", 8-n) } // As noted in issue #24 Google has started producing base32 in lower case, // but the StdEncoding (and the RFC), expect a dictionary of only upper case letters. secret = strings.ToUpper(secret) secretBytes, err := base32.StdEncoding.DecodeString(secret) if err != nil { return "", otp.ErrValidateSecretInvalidBase32 } buf := make([]byte, 8) mac := hmac.New(opts.Algorithm.Hash, secretBytes) binary.BigEndian.PutUint64(buf, counter) if debug { fmt.Printf("counter=%v\n", counter) fmt.Printf("buf=%v\n", buf) } mac.Write(buf) sum := mac.Sum(nil) // "Dynamic truncation" in RFC 4226 // http://tools.ietf.org/html/rfc4226#section-5.4 offset := sum[len(sum)-1] & 0xf value := int64(((int(sum[offset]) & 0x7f) << 24) | ((int(sum[offset+1] & 0xff)) << 16) | ((int(sum[offset+2] & 0xff)) << 8) | (int(sum[offset+3]) & 0xff)) l := opts.Digits.Length() mod := int32(value % int64(math.Pow10(l))) if debug { fmt.Printf("offset=%v\n", offset) fmt.Printf("value=%v\n", value) fmt.Printf("mod'ed=%v\n", mod) } return opts.Digits.Format(mod), nil }
[ "func", "GenerateCodeCustom", "(", "secret", "string", ",", "counter", "uint64", ",", "opts", "ValidateOpts", ")", "(", "passcode", "string", ",", "err", "error", ")", "{", "// As noted in issue #10 and #17 this adds support for TOTP secrets that are", "// missing their padding.", "secret", "=", "strings", ".", "TrimSpace", "(", "secret", ")", "\n", "if", "n", ":=", "len", "(", "secret", ")", "%", "8", ";", "n", "!=", "0", "{", "secret", "=", "secret", "+", "strings", ".", "Repeat", "(", "\"", "\"", ",", "8", "-", "n", ")", "\n", "}", "\n\n", "// As noted in issue #24 Google has started producing base32 in lower case,", "// but the StdEncoding (and the RFC), expect a dictionary of only upper case letters.", "secret", "=", "strings", ".", "ToUpper", "(", "secret", ")", "\n\n", "secretBytes", ",", "err", ":=", "base32", ".", "StdEncoding", ".", "DecodeString", "(", "secret", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "otp", ".", "ErrValidateSecretInvalidBase32", "\n", "}", "\n\n", "buf", ":=", "make", "(", "[", "]", "byte", ",", "8", ")", "\n", "mac", ":=", "hmac", ".", "New", "(", "opts", ".", "Algorithm", ".", "Hash", ",", "secretBytes", ")", "\n", "binary", ".", "BigEndian", ".", "PutUint64", "(", "buf", ",", "counter", ")", "\n", "if", "debug", "{", "fmt", ".", "Printf", "(", "\"", "\\n", "\"", ",", "counter", ")", "\n", "fmt", ".", "Printf", "(", "\"", "\\n", "\"", ",", "buf", ")", "\n", "}", "\n\n", "mac", ".", "Write", "(", "buf", ")", "\n", "sum", ":=", "mac", ".", "Sum", "(", "nil", ")", "\n\n", "// \"Dynamic truncation\" in RFC 4226", "// http://tools.ietf.org/html/rfc4226#section-5.4", "offset", ":=", "sum", "[", "len", "(", "sum", ")", "-", "1", "]", "&", "0xf", "\n", "value", ":=", "int64", "(", "(", "(", "int", "(", "sum", "[", "offset", "]", ")", "&", "0x7f", ")", "<<", "24", ")", "|", "(", "(", "int", "(", "sum", "[", "offset", "+", "1", "]", "&", "0xff", ")", ")", "<<", "16", ")", "|", "(", "(", "int", "(", "sum", "[", "offset", "+", "2", "]", "&", "0xff", ")", ")", "<<", "8", ")", "|", "(", "int", "(", "sum", "[", "offset", "+", "3", "]", ")", "&", "0xff", ")", ")", "\n\n", "l", ":=", "opts", ".", "Digits", ".", "Length", "(", ")", "\n", "mod", ":=", "int32", "(", "value", "%", "int64", "(", "math", ".", "Pow10", "(", "l", ")", ")", ")", "\n\n", "if", "debug", "{", "fmt", ".", "Printf", "(", "\"", "\\n", "\"", ",", "offset", ")", "\n", "fmt", ".", "Printf", "(", "\"", "\\n", "\"", ",", "value", ")", "\n", "fmt", ".", "Printf", "(", "\"", "\\n", "\"", ",", "mod", ")", "\n", "}", "\n\n", "return", "opts", ".", "Digits", ".", "Format", "(", "mod", ")", ",", "nil", "\n", "}" ]
// GenerateCodeCustom uses a counter and secret value and options struct to // create a passcode.
[ "GenerateCodeCustom", "uses", "a", "counter", "and", "secret", "value", "and", "options", "struct", "to", "create", "a", "passcode", "." ]
be78767b3e392ce45ea73444451022a6fc32ad0d
https://github.com/pquerna/otp/blob/be78767b3e392ce45ea73444451022a6fc32ad0d/hotp/hotp.go#L72-L118
5,455
pquerna/otp
hotp/hotp.go
Generate
func Generate(opts GenerateOpts) (*otp.Key, error) { // url encode the Issuer/AccountName if opts.Issuer == "" { return nil, otp.ErrGenerateMissingIssuer } if opts.AccountName == "" { return nil, otp.ErrGenerateMissingAccountName } if opts.SecretSize == 0 { opts.SecretSize = 10 } if opts.Digits == 0 { opts.Digits = otp.DigitsSix } // otpauth://totp/Example:[email protected]?secret=JBSWY3DPEHPK3PXP&issuer=Example v := url.Values{} secret := make([]byte, opts.SecretSize) _, err := rand.Read(secret) if err != nil { return nil, err } v.Set("secret", strings.TrimRight(base32.StdEncoding.EncodeToString(secret), "=")) v.Set("issuer", opts.Issuer) v.Set("algorithm", opts.Algorithm.String()) v.Set("digits", opts.Digits.String()) u := url.URL{ Scheme: "otpauth", Host: "hotp", Path: "/" + opts.Issuer + ":" + opts.AccountName, RawQuery: v.Encode(), } return otp.NewKeyFromURL(u.String()) }
go
func Generate(opts GenerateOpts) (*otp.Key, error) { // url encode the Issuer/AccountName if opts.Issuer == "" { return nil, otp.ErrGenerateMissingIssuer } if opts.AccountName == "" { return nil, otp.ErrGenerateMissingAccountName } if opts.SecretSize == 0 { opts.SecretSize = 10 } if opts.Digits == 0 { opts.Digits = otp.DigitsSix } // otpauth://totp/Example:[email protected]?secret=JBSWY3DPEHPK3PXP&issuer=Example v := url.Values{} secret := make([]byte, opts.SecretSize) _, err := rand.Read(secret) if err != nil { return nil, err } v.Set("secret", strings.TrimRight(base32.StdEncoding.EncodeToString(secret), "=")) v.Set("issuer", opts.Issuer) v.Set("algorithm", opts.Algorithm.String()) v.Set("digits", opts.Digits.String()) u := url.URL{ Scheme: "otpauth", Host: "hotp", Path: "/" + opts.Issuer + ":" + opts.AccountName, RawQuery: v.Encode(), } return otp.NewKeyFromURL(u.String()) }
[ "func", "Generate", "(", "opts", "GenerateOpts", ")", "(", "*", "otp", ".", "Key", ",", "error", ")", "{", "// url encode the Issuer/AccountName", "if", "opts", ".", "Issuer", "==", "\"", "\"", "{", "return", "nil", ",", "otp", ".", "ErrGenerateMissingIssuer", "\n", "}", "\n\n", "if", "opts", ".", "AccountName", "==", "\"", "\"", "{", "return", "nil", ",", "otp", ".", "ErrGenerateMissingAccountName", "\n", "}", "\n\n", "if", "opts", ".", "SecretSize", "==", "0", "{", "opts", ".", "SecretSize", "=", "10", "\n", "}", "\n\n", "if", "opts", ".", "Digits", "==", "0", "{", "opts", ".", "Digits", "=", "otp", ".", "DigitsSix", "\n", "}", "\n\n", "// otpauth://totp/Example:[email protected]?secret=JBSWY3DPEHPK3PXP&issuer=Example", "v", ":=", "url", ".", "Values", "{", "}", "\n", "secret", ":=", "make", "(", "[", "]", "byte", ",", "opts", ".", "SecretSize", ")", "\n", "_", ",", "err", ":=", "rand", ".", "Read", "(", "secret", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "v", ".", "Set", "(", "\"", "\"", ",", "strings", ".", "TrimRight", "(", "base32", ".", "StdEncoding", ".", "EncodeToString", "(", "secret", ")", ",", "\"", "\"", ")", ")", "\n", "v", ".", "Set", "(", "\"", "\"", ",", "opts", ".", "Issuer", ")", "\n", "v", ".", "Set", "(", "\"", "\"", ",", "opts", ".", "Algorithm", ".", "String", "(", ")", ")", "\n", "v", ".", "Set", "(", "\"", "\"", ",", "opts", ".", "Digits", ".", "String", "(", ")", ")", "\n\n", "u", ":=", "url", ".", "URL", "{", "Scheme", ":", "\"", "\"", ",", "Host", ":", "\"", "\"", ",", "Path", ":", "\"", "\"", "+", "opts", ".", "Issuer", "+", "\"", "\"", "+", "opts", ".", "AccountName", ",", "RawQuery", ":", "v", ".", "Encode", "(", ")", ",", "}", "\n\n", "return", "otp", ".", "NewKeyFromURL", "(", "u", ".", "String", "(", ")", ")", "\n", "}" ]
// Generate creates a new HOTP Key.
[ "Generate", "creates", "a", "new", "HOTP", "Key", "." ]
be78767b3e392ce45ea73444451022a6fc32ad0d
https://github.com/pquerna/otp/blob/be78767b3e392ce45ea73444451022a6fc32ad0d/hotp/hotp.go#L156-L196
5,456
pquerna/otp
totp/totp.go
Validate
func Validate(passcode string, secret string) bool { rv, _ := ValidateCustom( passcode, secret, time.Now().UTC(), ValidateOpts{ Period: 30, Skew: 1, Digits: otp.DigitsSix, Algorithm: otp.AlgorithmSHA1, }, ) return rv }
go
func Validate(passcode string, secret string) bool { rv, _ := ValidateCustom( passcode, secret, time.Now().UTC(), ValidateOpts{ Period: 30, Skew: 1, Digits: otp.DigitsSix, Algorithm: otp.AlgorithmSHA1, }, ) return rv }
[ "func", "Validate", "(", "passcode", "string", ",", "secret", "string", ")", "bool", "{", "rv", ",", "_", ":=", "ValidateCustom", "(", "passcode", ",", "secret", ",", "time", ".", "Now", "(", ")", ".", "UTC", "(", ")", ",", "ValidateOpts", "{", "Period", ":", "30", ",", "Skew", ":", "1", ",", "Digits", ":", "otp", ".", "DigitsSix", ",", "Algorithm", ":", "otp", ".", "AlgorithmSHA1", ",", "}", ",", ")", "\n", "return", "rv", "\n", "}" ]
// Validate a TOTP using the current time. // A shortcut for ValidateCustom, Validate uses a configuration // that is compatible with Google-Authenticator and most clients.
[ "Validate", "a", "TOTP", "using", "the", "current", "time", ".", "A", "shortcut", "for", "ValidateCustom", "Validate", "uses", "a", "configuration", "that", "is", "compatible", "with", "Google", "-", "Authenticator", "and", "most", "clients", "." ]
be78767b3e392ce45ea73444451022a6fc32ad0d
https://github.com/pquerna/otp/blob/be78767b3e392ce45ea73444451022a6fc32ad0d/totp/totp.go#L37-L50
5,457
pquerna/otp
totp/totp.go
GenerateCode
func GenerateCode(secret string, t time.Time) (string, error) { return GenerateCodeCustom(secret, t, ValidateOpts{ Period: 30, Skew: 1, Digits: otp.DigitsSix, Algorithm: otp.AlgorithmSHA1, }) }
go
func GenerateCode(secret string, t time.Time) (string, error) { return GenerateCodeCustom(secret, t, ValidateOpts{ Period: 30, Skew: 1, Digits: otp.DigitsSix, Algorithm: otp.AlgorithmSHA1, }) }
[ "func", "GenerateCode", "(", "secret", "string", ",", "t", "time", ".", "Time", ")", "(", "string", ",", "error", ")", "{", "return", "GenerateCodeCustom", "(", "secret", ",", "t", ",", "ValidateOpts", "{", "Period", ":", "30", ",", "Skew", ":", "1", ",", "Digits", ":", "otp", ".", "DigitsSix", ",", "Algorithm", ":", "otp", ".", "AlgorithmSHA1", ",", "}", ")", "\n", "}" ]
// GenerateCode creates a TOTP token using the current time. // A shortcut for GenerateCodeCustom, GenerateCode uses a configuration // that is compatible with Google-Authenticator and most clients.
[ "GenerateCode", "creates", "a", "TOTP", "token", "using", "the", "current", "time", ".", "A", "shortcut", "for", "GenerateCodeCustom", "GenerateCode", "uses", "a", "configuration", "that", "is", "compatible", "with", "Google", "-", "Authenticator", "and", "most", "clients", "." ]
be78767b3e392ce45ea73444451022a6fc32ad0d
https://github.com/pquerna/otp/blob/be78767b3e392ce45ea73444451022a6fc32ad0d/totp/totp.go#L55-L62
5,458
pquerna/otp
otp.go
Issuer
func (k *Key) Issuer() string { q := k.url.Query() issuer := q.Get("issuer") if issuer != "" { return issuer } p := strings.TrimPrefix(k.url.Path, "/") i := strings.Index(p, ":") if i == -1 { return "" } return p[:i] }
go
func (k *Key) Issuer() string { q := k.url.Query() issuer := q.Get("issuer") if issuer != "" { return issuer } p := strings.TrimPrefix(k.url.Path, "/") i := strings.Index(p, ":") if i == -1 { return "" } return p[:i] }
[ "func", "(", "k", "*", "Key", ")", "Issuer", "(", ")", "string", "{", "q", ":=", "k", ".", "url", ".", "Query", "(", ")", "\n\n", "issuer", ":=", "q", ".", "Get", "(", "\"", "\"", ")", "\n\n", "if", "issuer", "!=", "\"", "\"", "{", "return", "issuer", "\n", "}", "\n\n", "p", ":=", "strings", ".", "TrimPrefix", "(", "k", ".", "url", ".", "Path", ",", "\"", "\"", ")", "\n", "i", ":=", "strings", ".", "Index", "(", "p", ",", "\"", "\"", ")", "\n\n", "if", "i", "==", "-", "1", "{", "return", "\"", "\"", "\n", "}", "\n\n", "return", "p", "[", ":", "i", "]", "\n", "}" ]
// Issuer returns the name of the issuing organization.
[ "Issuer", "returns", "the", "name", "of", "the", "issuing", "organization", "." ]
be78767b3e392ce45ea73444451022a6fc32ad0d
https://github.com/pquerna/otp/blob/be78767b3e392ce45ea73444451022a6fc32ad0d/otp.go#L103-L120
5,459
pquerna/otp
otp.go
AccountName
func (k *Key) AccountName() string { p := strings.TrimPrefix(k.url.Path, "/") i := strings.Index(p, ":") if i == -1 { return p } return p[i+1:] }
go
func (k *Key) AccountName() string { p := strings.TrimPrefix(k.url.Path, "/") i := strings.Index(p, ":") if i == -1 { return p } return p[i+1:] }
[ "func", "(", "k", "*", "Key", ")", "AccountName", "(", ")", "string", "{", "p", ":=", "strings", ".", "TrimPrefix", "(", "k", ".", "url", ".", "Path", ",", "\"", "\"", ")", "\n", "i", ":=", "strings", ".", "Index", "(", "p", ",", "\"", "\"", ")", "\n\n", "if", "i", "==", "-", "1", "{", "return", "p", "\n", "}", "\n\n", "return", "p", "[", "i", "+", "1", ":", "]", "\n", "}" ]
// AccountName returns the name of the user's account.
[ "AccountName", "returns", "the", "name", "of", "the", "user", "s", "account", "." ]
be78767b3e392ce45ea73444451022a6fc32ad0d
https://github.com/pquerna/otp/blob/be78767b3e392ce45ea73444451022a6fc32ad0d/otp.go#L123-L132
5,460
pquerna/otp
otp.go
Secret
func (k *Key) Secret() string { q := k.url.Query() return q.Get("secret") }
go
func (k *Key) Secret() string { q := k.url.Query() return q.Get("secret") }
[ "func", "(", "k", "*", "Key", ")", "Secret", "(", ")", "string", "{", "q", ":=", "k", ".", "url", ".", "Query", "(", ")", "\n\n", "return", "q", ".", "Get", "(", "\"", "\"", ")", "\n", "}" ]
// Secret returns the opaque secret for this Key.
[ "Secret", "returns", "the", "opaque", "secret", "for", "this", "Key", "." ]
be78767b3e392ce45ea73444451022a6fc32ad0d
https://github.com/pquerna/otp/blob/be78767b3e392ce45ea73444451022a6fc32ad0d/otp.go#L135-L139
5,461
pquerna/otp
otp.go
Format
func (d Digits) Format(in int32) string { f := fmt.Sprintf("%%0%dd", d) return fmt.Sprintf(f, in) }
go
func (d Digits) Format(in int32) string { f := fmt.Sprintf("%%0%dd", d) return fmt.Sprintf(f, in) }
[ "func", "(", "d", "Digits", ")", "Format", "(", "in", "int32", ")", "string", "{", "f", ":=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "d", ")", "\n", "return", "fmt", ".", "Sprintf", "(", "f", ",", "in", ")", "\n", "}" ]
// Format converts an integer into the zero-filled size for this Digits.
[ "Format", "converts", "an", "integer", "into", "the", "zero", "-", "filled", "size", "for", "this", "Digits", "." ]
be78767b3e392ce45ea73444451022a6fc32ad0d
https://github.com/pquerna/otp/blob/be78767b3e392ce45ea73444451022a6fc32ad0d/otp.go#L195-L198
5,462
githubnemo/CompileDaemon
daemon.go
build
func build() bool { log.Println(okColor("Running build command!")) args := strings.Split(*flag_build, " ") if len(args) == 0 { // If the user has specified and empty then we are done. return true } cmd := exec.Command(args[0], args[1:]...) if *flag_build_dir != "" { cmd.Dir = *flag_build_dir } else { cmd.Dir = *flag_directory } output, err := cmd.CombinedOutput() if err == nil { log.Println(okColor("Build ok.")) } else { log.Println(failColor("Error while building:\n"), failColor(string(output))) } return err == nil }
go
func build() bool { log.Println(okColor("Running build command!")) args := strings.Split(*flag_build, " ") if len(args) == 0 { // If the user has specified and empty then we are done. return true } cmd := exec.Command(args[0], args[1:]...) if *flag_build_dir != "" { cmd.Dir = *flag_build_dir } else { cmd.Dir = *flag_directory } output, err := cmd.CombinedOutput() if err == nil { log.Println(okColor("Build ok.")) } else { log.Println(failColor("Error while building:\n"), failColor(string(output))) } return err == nil }
[ "func", "build", "(", ")", "bool", "{", "log", ".", "Println", "(", "okColor", "(", "\"", "\"", ")", ")", "\n\n", "args", ":=", "strings", ".", "Split", "(", "*", "flag_build", ",", "\"", "\"", ")", "\n", "if", "len", "(", "args", ")", "==", "0", "{", "// If the user has specified and empty then we are done.", "return", "true", "\n", "}", "\n\n", "cmd", ":=", "exec", ".", "Command", "(", "args", "[", "0", "]", ",", "args", "[", "1", ":", "]", "...", ")", "\n\n", "if", "*", "flag_build_dir", "!=", "\"", "\"", "{", "cmd", ".", "Dir", "=", "*", "flag_build_dir", "\n", "}", "else", "{", "cmd", ".", "Dir", "=", "*", "flag_directory", "\n", "}", "\n\n", "output", ",", "err", ":=", "cmd", ".", "CombinedOutput", "(", ")", "\n\n", "if", "err", "==", "nil", "{", "log", ".", "Println", "(", "okColor", "(", "\"", "\"", ")", ")", "\n", "}", "else", "{", "log", ".", "Println", "(", "failColor", "(", "\"", "\\n", "\"", ")", ",", "failColor", "(", "string", "(", "output", ")", ")", ")", "\n", "}", "\n\n", "return", "err", "==", "nil", "\n", "}" ]
// Run `go build` and print the output if something's gone wrong.
[ "Run", "go", "build", "and", "print", "the", "output", "if", "something", "s", "gone", "wrong", "." ]
00947fbd6fc5312efc02a8c12e4296a8b76a6ddf
https://github.com/githubnemo/CompileDaemon/blob/00947fbd6fc5312efc02a8c12e4296a8b76a6ddf/daemon.go#L147-L173
5,463
githubnemo/CompileDaemon
daemon.go
builder
func builder(jobs <-chan string, buildStarted chan<- string, buildDone chan<- bool) { createThreshold := func() <-chan time.Time { return time.After(time.Duration(WorkDelay * time.Millisecond)) } threshold := createThreshold() eventPath := "" for { select { case eventPath = <-jobs: threshold = createThreshold() case <-threshold: buildStarted <- eventPath buildDone <- build() } } }
go
func builder(jobs <-chan string, buildStarted chan<- string, buildDone chan<- bool) { createThreshold := func() <-chan time.Time { return time.After(time.Duration(WorkDelay * time.Millisecond)) } threshold := createThreshold() eventPath := "" for { select { case eventPath = <-jobs: threshold = createThreshold() case <-threshold: buildStarted <- eventPath buildDone <- build() } } }
[ "func", "builder", "(", "jobs", "<-", "chan", "string", ",", "buildStarted", "chan", "<-", "string", ",", "buildDone", "chan", "<-", "bool", ")", "{", "createThreshold", ":=", "func", "(", ")", "<-", "chan", "time", ".", "Time", "{", "return", "time", ".", "After", "(", "time", ".", "Duration", "(", "WorkDelay", "*", "time", ".", "Millisecond", ")", ")", "\n", "}", "\n\n", "threshold", ":=", "createThreshold", "(", ")", "\n", "eventPath", ":=", "\"", "\"", "\n\n", "for", "{", "select", "{", "case", "eventPath", "=", "<-", "jobs", ":", "threshold", "=", "createThreshold", "(", ")", "\n", "case", "<-", "threshold", ":", "buildStarted", "<-", "eventPath", "\n", "buildDone", "<-", "build", "(", ")", "\n", "}", "\n", "}", "\n", "}" ]
// Accept build jobs and start building when there are no jobs rushing in. // The inrush protection is WorkDelay milliseconds long, in this period // every incoming job will reset the timer.
[ "Accept", "build", "jobs", "and", "start", "building", "when", "there", "are", "no", "jobs", "rushing", "in", ".", "The", "inrush", "protection", "is", "WorkDelay", "milliseconds", "long", "in", "this", "period", "every", "incoming", "job", "will", "reset", "the", "timer", "." ]
00947fbd6fc5312efc02a8c12e4296a8b76a6ddf
https://github.com/githubnemo/CompileDaemon/blob/00947fbd6fc5312efc02a8c12e4296a8b76a6ddf/daemon.go#L182-L199
5,464
githubnemo/CompileDaemon
daemon.go
startCommand
func startCommand(command string) (cmd *exec.Cmd, stdout io.ReadCloser, stderr io.ReadCloser, err error) { args := strings.Split(command, " ") cmd = exec.Command(args[0], args[1:]...) if *flag_run_dir != "" { cmd.Dir = *flag_run_dir } if stdout, err = cmd.StdoutPipe(); err != nil { err = fmt.Errorf("can't get stdout pipe for command: %s", err) return } if stderr, err = cmd.StderrPipe(); err != nil { err = fmt.Errorf("can't get stderr pipe for command: %s", err) return } if err = cmd.Start(); err != nil { err = fmt.Errorf("can't start command: %s", err) return } return }
go
func startCommand(command string) (cmd *exec.Cmd, stdout io.ReadCloser, stderr io.ReadCloser, err error) { args := strings.Split(command, " ") cmd = exec.Command(args[0], args[1:]...) if *flag_run_dir != "" { cmd.Dir = *flag_run_dir } if stdout, err = cmd.StdoutPipe(); err != nil { err = fmt.Errorf("can't get stdout pipe for command: %s", err) return } if stderr, err = cmd.StderrPipe(); err != nil { err = fmt.Errorf("can't get stderr pipe for command: %s", err) return } if err = cmd.Start(); err != nil { err = fmt.Errorf("can't start command: %s", err) return } return }
[ "func", "startCommand", "(", "command", "string", ")", "(", "cmd", "*", "exec", ".", "Cmd", ",", "stdout", "io", ".", "ReadCloser", ",", "stderr", "io", ".", "ReadCloser", ",", "err", "error", ")", "{", "args", ":=", "strings", ".", "Split", "(", "command", ",", "\"", "\"", ")", "\n", "cmd", "=", "exec", ".", "Command", "(", "args", "[", "0", "]", ",", "args", "[", "1", ":", "]", "...", ")", "\n", "if", "*", "flag_run_dir", "!=", "\"", "\"", "{", "cmd", ".", "Dir", "=", "*", "flag_run_dir", "\n", "}", "\n\n", "if", "stdout", ",", "err", "=", "cmd", ".", "StdoutPipe", "(", ")", ";", "err", "!=", "nil", "{", "err", "=", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "return", "\n", "}", "\n\n", "if", "stderr", ",", "err", "=", "cmd", ".", "StderrPipe", "(", ")", ";", "err", "!=", "nil", "{", "err", "=", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "return", "\n", "}", "\n\n", "if", "err", "=", "cmd", ".", "Start", "(", ")", ";", "err", "!=", "nil", "{", "err", "=", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "return", "\n", "}", "\n\n", "return", "\n", "}" ]
// Start the supplied command and return stdout and stderr pipes for logging.
[ "Start", "the", "supplied", "command", "and", "return", "stdout", "and", "stderr", "pipes", "for", "logging", "." ]
00947fbd6fc5312efc02a8c12e4296a8b76a6ddf
https://github.com/githubnemo/CompileDaemon/blob/00947fbd6fc5312efc02a8c12e4296a8b76a6ddf/daemon.go#L231-L255
5,465
githubnemo/CompileDaemon
daemon.go
runner
func runner(commandTemplate string, buildStarted <-chan string, buildSuccess <-chan bool) { var currentProcess *os.Process pipeChan := make(chan io.ReadCloser) go logger(pipeChan) go func() { sigChan := make(chan os.Signal, 1) signal.Notify(sigChan, fatalSignals...) <-sigChan log.Println(okColor("Received signal, terminating cleanly.")) if currentProcess != nil { killProcess(currentProcess) } os.Exit(0) }() for { eventPath := <-buildStarted // append %0.s to use format specifier even if not supplied by user // to suppress warning in returned string. command := fmt.Sprintf("%0.s"+commandTemplate, eventPath) if !*flag_command_stop { if !<-buildSuccess { continue } } if currentProcess != nil { killProcess(currentProcess) } if *flag_command_stop { log.Println(okColor("Command stopped. Waiting for build to complete.")) if !<-buildSuccess { continue } } log.Println(okColor("Restarting the given command.")) cmd, stdoutPipe, stderrPipe, err := startCommand(command) if err != nil { log.Fatal(failColor("Could not start command: %s", err)) } pipeChan <- stdoutPipe pipeChan <- stderrPipe currentProcess = cmd.Process } }
go
func runner(commandTemplate string, buildStarted <-chan string, buildSuccess <-chan bool) { var currentProcess *os.Process pipeChan := make(chan io.ReadCloser) go logger(pipeChan) go func() { sigChan := make(chan os.Signal, 1) signal.Notify(sigChan, fatalSignals...) <-sigChan log.Println(okColor("Received signal, terminating cleanly.")) if currentProcess != nil { killProcess(currentProcess) } os.Exit(0) }() for { eventPath := <-buildStarted // append %0.s to use format specifier even if not supplied by user // to suppress warning in returned string. command := fmt.Sprintf("%0.s"+commandTemplate, eventPath) if !*flag_command_stop { if !<-buildSuccess { continue } } if currentProcess != nil { killProcess(currentProcess) } if *flag_command_stop { log.Println(okColor("Command stopped. Waiting for build to complete.")) if !<-buildSuccess { continue } } log.Println(okColor("Restarting the given command.")) cmd, stdoutPipe, stderrPipe, err := startCommand(command) if err != nil { log.Fatal(failColor("Could not start command: %s", err)) } pipeChan <- stdoutPipe pipeChan <- stderrPipe currentProcess = cmd.Process } }
[ "func", "runner", "(", "commandTemplate", "string", ",", "buildStarted", "<-", "chan", "string", ",", "buildSuccess", "<-", "chan", "bool", ")", "{", "var", "currentProcess", "*", "os", ".", "Process", "\n", "pipeChan", ":=", "make", "(", "chan", "io", ".", "ReadCloser", ")", "\n\n", "go", "logger", "(", "pipeChan", ")", "\n\n", "go", "func", "(", ")", "{", "sigChan", ":=", "make", "(", "chan", "os", ".", "Signal", ",", "1", ")", "\n", "signal", ".", "Notify", "(", "sigChan", ",", "fatalSignals", "...", ")", "\n", "<-", "sigChan", "\n", "log", ".", "Println", "(", "okColor", "(", "\"", "\"", ")", ")", "\n", "if", "currentProcess", "!=", "nil", "{", "killProcess", "(", "currentProcess", ")", "\n", "}", "\n", "os", ".", "Exit", "(", "0", ")", "\n", "}", "(", ")", "\n\n", "for", "{", "eventPath", ":=", "<-", "buildStarted", "\n\n", "// append %0.s to use format specifier even if not supplied by user", "// to suppress warning in returned string.", "command", ":=", "fmt", ".", "Sprintf", "(", "\"", "\"", "+", "commandTemplate", ",", "eventPath", ")", "\n\n", "if", "!", "*", "flag_command_stop", "{", "if", "!", "<-", "buildSuccess", "{", "continue", "\n", "}", "\n", "}", "\n\n", "if", "currentProcess", "!=", "nil", "{", "killProcess", "(", "currentProcess", ")", "\n", "}", "\n", "if", "*", "flag_command_stop", "{", "log", ".", "Println", "(", "okColor", "(", "\"", "\"", ")", ")", "\n", "if", "!", "<-", "buildSuccess", "{", "continue", "\n", "}", "\n", "}", "\n\n", "log", ".", "Println", "(", "okColor", "(", "\"", "\"", ")", ")", "\n", "cmd", ",", "stdoutPipe", ",", "stderrPipe", ",", "err", ":=", "startCommand", "(", "command", ")", "\n\n", "if", "err", "!=", "nil", "{", "log", ".", "Fatal", "(", "failColor", "(", "\"", "\"", ",", "err", ")", ")", "\n", "}", "\n\n", "pipeChan", "<-", "stdoutPipe", "\n", "pipeChan", "<-", "stderrPipe", "\n\n", "currentProcess", "=", "cmd", ".", "Process", "\n", "}", "\n", "}" ]
// Run the command in the given string and restart it after // a message was received on the buildDone channel.
[ "Run", "the", "command", "in", "the", "given", "string", "and", "restart", "it", "after", "a", "message", "was", "received", "on", "the", "buildDone", "channel", "." ]
00947fbd6fc5312efc02a8c12e4296a8b76a6ddf
https://github.com/githubnemo/CompileDaemon/blob/00947fbd6fc5312efc02a8c12e4296a8b76a6ddf/daemon.go#L259-L311
5,466
actgardner/gogen-avro
generator/function_name_list.go
Less
func (f FunctionNameList) Less(i, j int) bool { if f[i].Str == "" && f[j].Str != "" { return true } if f[i].Str != "" && f[j].Str == "" { return false } if f[i].Str != "" && f[j].Str != "" { if f[i].Str > f[j].Str { return true } else if f[i].Str < f[j].Str { return false } } return f[i].Name < f[j].Name }
go
func (f FunctionNameList) Less(i, j int) bool { if f[i].Str == "" && f[j].Str != "" { return true } if f[i].Str != "" && f[j].Str == "" { return false } if f[i].Str != "" && f[j].Str != "" { if f[i].Str > f[j].Str { return true } else if f[i].Str < f[j].Str { return false } } return f[i].Name < f[j].Name }
[ "func", "(", "f", "FunctionNameList", ")", "Less", "(", "i", ",", "j", "int", ")", "bool", "{", "if", "f", "[", "i", "]", ".", "Str", "==", "\"", "\"", "&&", "f", "[", "j", "]", ".", "Str", "!=", "\"", "\"", "{", "return", "true", "\n", "}", "\n", "if", "f", "[", "i", "]", ".", "Str", "!=", "\"", "\"", "&&", "f", "[", "j", "]", ".", "Str", "==", "\"", "\"", "{", "return", "false", "\n", "}", "\n", "if", "f", "[", "i", "]", ".", "Str", "!=", "\"", "\"", "&&", "f", "[", "j", "]", ".", "Str", "!=", "\"", "\"", "{", "if", "f", "[", "i", "]", ".", "Str", ">", "f", "[", "j", "]", ".", "Str", "{", "return", "true", "\n", "}", "else", "if", "f", "[", "i", "]", ".", "Str", "<", "f", "[", "j", "]", ".", "Str", "{", "return", "false", "\n", "}", "\n", "}", "\n", "return", "f", "[", "i", "]", ".", "Name", "<", "f", "[", "j", "]", ".", "Name", "\n", "}" ]
// Sort functions by the struct to which they're attached first, then the name of the method itself. If the function isn't attached to a struct, put it at the bottom
[ "Sort", "functions", "by", "the", "struct", "to", "which", "they", "re", "attached", "first", "then", "the", "name", "of", "the", "method", "itself", ".", "If", "the", "function", "isn", "t", "attached", "to", "a", "struct", "put", "it", "at", "the", "bottom" ]
fd08cc477d17abc4fbb71e40721601df8871ee24
https://github.com/actgardner/gogen-avro/blob/fd08cc477d17abc4fbb71e40721601df8871ee24/generator/function_name_list.go#L15-L30
5,467
actgardner/gogen-avro
container/writer.go
NewWriter
func NewWriter(writer io.Writer, codec Codec, recordsPerBlock int64, schema string) (*Writer, error) { blockBytes := make([]byte, 0) blockBuffer := bytes.NewBuffer(blockBytes) avroWriter := &Writer{ writer: writer, syncMarker: [16]byte{'g', 'o', 'g', 'e', 'n', 'a', 'v', 'r', 'o', 'm', 'a', 'g', 'i', 'c', '1', '0'}, codec: codec, recordsPerBlock: recordsPerBlock, blockBuffer: blockBuffer, } var err error if codec == Deflate { avroWriter.compressedWriter, err = flate.NewWriter(avroWriter.blockBuffer, flate.DefaultCompression) if err != nil { return nil, err } } else if codec == Snappy { avroWriter.compressedWriter = newSnappyWriter(avroWriter.blockBuffer) } else { avroWriter.compressedWriter = avroWriter.blockBuffer } err = avroWriter.writeHeader(schema) if err != nil { return nil, err } return avroWriter, nil }
go
func NewWriter(writer io.Writer, codec Codec, recordsPerBlock int64, schema string) (*Writer, error) { blockBytes := make([]byte, 0) blockBuffer := bytes.NewBuffer(blockBytes) avroWriter := &Writer{ writer: writer, syncMarker: [16]byte{'g', 'o', 'g', 'e', 'n', 'a', 'v', 'r', 'o', 'm', 'a', 'g', 'i', 'c', '1', '0'}, codec: codec, recordsPerBlock: recordsPerBlock, blockBuffer: blockBuffer, } var err error if codec == Deflate { avroWriter.compressedWriter, err = flate.NewWriter(avroWriter.blockBuffer, flate.DefaultCompression) if err != nil { return nil, err } } else if codec == Snappy { avroWriter.compressedWriter = newSnappyWriter(avroWriter.blockBuffer) } else { avroWriter.compressedWriter = avroWriter.blockBuffer } err = avroWriter.writeHeader(schema) if err != nil { return nil, err } return avroWriter, nil }
[ "func", "NewWriter", "(", "writer", "io", ".", "Writer", ",", "codec", "Codec", ",", "recordsPerBlock", "int64", ",", "schema", "string", ")", "(", "*", "Writer", ",", "error", ")", "{", "blockBytes", ":=", "make", "(", "[", "]", "byte", ",", "0", ")", "\n", "blockBuffer", ":=", "bytes", ".", "NewBuffer", "(", "blockBytes", ")", "\n\n", "avroWriter", ":=", "&", "Writer", "{", "writer", ":", "writer", ",", "syncMarker", ":", "[", "16", "]", "byte", "{", "'g'", ",", "'o'", ",", "'g'", ",", "'e'", ",", "'n'", ",", "'a'", ",", "'v'", ",", "'r'", ",", "'o'", ",", "'m'", ",", "'a'", ",", "'g'", ",", "'i'", ",", "'c'", ",", "'1'", ",", "'0'", "}", ",", "codec", ":", "codec", ",", "recordsPerBlock", ":", "recordsPerBlock", ",", "blockBuffer", ":", "blockBuffer", ",", "}", "\n", "var", "err", "error", "\n", "if", "codec", "==", "Deflate", "{", "avroWriter", ".", "compressedWriter", ",", "err", "=", "flate", ".", "NewWriter", "(", "avroWriter", ".", "blockBuffer", ",", "flate", ".", "DefaultCompression", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "}", "else", "if", "codec", "==", "Snappy", "{", "avroWriter", ".", "compressedWriter", "=", "newSnappyWriter", "(", "avroWriter", ".", "blockBuffer", ")", "\n", "}", "else", "{", "avroWriter", ".", "compressedWriter", "=", "avroWriter", ".", "blockBuffer", "\n", "}", "\n\n", "err", "=", "avroWriter", ".", "writeHeader", "(", "schema", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "return", "avroWriter", ",", "nil", "\n", "}" ]
// Create a new Writer wrapping the provided io.Writer with the given Codec and number of records per block. // The Writer will lazily write the container file header when WriteRecord is called the first time. // You must call Flush on the Writer before closing the underlying io.Writer, to ensure the final block is written. // A schema string must be passed to ensure that a correct header is written even if no records are written. This // is required to produce valid empty Avro container files.
[ "Create", "a", "new", "Writer", "wrapping", "the", "provided", "io", ".", "Writer", "with", "the", "given", "Codec", "and", "number", "of", "records", "per", "block", ".", "The", "Writer", "will", "lazily", "write", "the", "container", "file", "header", "when", "WriteRecord", "is", "called", "the", "first", "time", ".", "You", "must", "call", "Flush", "on", "the", "Writer", "before", "closing", "the", "underlying", "io", ".", "Writer", "to", "ensure", "the", "final", "block", "is", "written", ".", "A", "schema", "string", "must", "be", "passed", "to", "ensure", "that", "a", "correct", "header", "is", "written", "even", "if", "no", "records", "are", "written", ".", "This", "is", "required", "to", "produce", "valid", "empty", "Avro", "container", "files", "." ]
fd08cc477d17abc4fbb71e40721601df8871ee24
https://github.com/actgardner/gogen-avro/blob/fd08cc477d17abc4fbb71e40721601df8871ee24/container/writer.go#L48-L77
5,468
actgardner/gogen-avro
container/writer.go
WriteRecord
func (avroWriter *Writer) WriteRecord(record AvroRecord) error { var err error // Serialize the new record into the compressed writer err = record.Serialize(avroWriter.compressedWriter) if err != nil { return err } avroWriter.nextBlockRecords += 1 // If the block if full, flush and reset the compressed writer, // write the header and the block contents if avroWriter.nextBlockRecords >= avroWriter.recordsPerBlock { return avroWriter.Flush() } return nil }
go
func (avroWriter *Writer) WriteRecord(record AvroRecord) error { var err error // Serialize the new record into the compressed writer err = record.Serialize(avroWriter.compressedWriter) if err != nil { return err } avroWriter.nextBlockRecords += 1 // If the block if full, flush and reset the compressed writer, // write the header and the block contents if avroWriter.nextBlockRecords >= avroWriter.recordsPerBlock { return avroWriter.Flush() } return nil }
[ "func", "(", "avroWriter", "*", "Writer", ")", "WriteRecord", "(", "record", "AvroRecord", ")", "error", "{", "var", "err", "error", "\n", "// Serialize the new record into the compressed writer", "err", "=", "record", ".", "Serialize", "(", "avroWriter", ".", "compressedWriter", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "avroWriter", ".", "nextBlockRecords", "+=", "1", "\n\n", "// If the block if full, flush and reset the compressed writer,", "// write the header and the block contents", "if", "avroWriter", ".", "nextBlockRecords", ">=", "avroWriter", ".", "recordsPerBlock", "{", "return", "avroWriter", ".", "Flush", "(", ")", "\n", "}", "\n\n", "return", "nil", "\n", "}" ]
// Write an AvroRecord to the container file. All gogen-avro generated structs // fulfill the AvroRecord interface. Note that all records in a given container file // must be of the same Avro type.
[ "Write", "an", "AvroRecord", "to", "the", "container", "file", ".", "All", "gogen", "-", "avro", "generated", "structs", "fulfill", "the", "AvroRecord", "interface", ".", "Note", "that", "all", "records", "in", "a", "given", "container", "file", "must", "be", "of", "the", "same", "Avro", "type", "." ]
fd08cc477d17abc4fbb71e40721601df8871ee24
https://github.com/actgardner/gogen-avro/blob/fd08cc477d17abc4fbb71e40721601df8871ee24/container/writer.go#L94-L110
5,469
actgardner/gogen-avro
container/writer.go
Flush
func (avroWriter *Writer) Flush() error { if avroWriter.nextBlockRecords == 0 { return nil } // Write out all of the buffered records as a new block // Must be called before closing to ensure the last block is written if fwWriter, ok := avroWriter.compressedWriter.(CloseableResettableWriter); ok { fwWriter.Close() fwWriter.Reset(avroWriter.blockBuffer) } if avroWriter.nextBlockRecords > 0 { block := &avro.AvroContainerBlock{ NumRecords: avroWriter.nextBlockRecords, RecordBytes: avroWriter.blockBuffer.Bytes(), Sync: avroWriter.syncMarker, } err := block.Serialize(avroWriter.writer) if err != nil { return err } } avroWriter.blockBuffer.Reset() avroWriter.nextBlockRecords = 0 return nil }
go
func (avroWriter *Writer) Flush() error { if avroWriter.nextBlockRecords == 0 { return nil } // Write out all of the buffered records as a new block // Must be called before closing to ensure the last block is written if fwWriter, ok := avroWriter.compressedWriter.(CloseableResettableWriter); ok { fwWriter.Close() fwWriter.Reset(avroWriter.blockBuffer) } if avroWriter.nextBlockRecords > 0 { block := &avro.AvroContainerBlock{ NumRecords: avroWriter.nextBlockRecords, RecordBytes: avroWriter.blockBuffer.Bytes(), Sync: avroWriter.syncMarker, } err := block.Serialize(avroWriter.writer) if err != nil { return err } } avroWriter.blockBuffer.Reset() avroWriter.nextBlockRecords = 0 return nil }
[ "func", "(", "avroWriter", "*", "Writer", ")", "Flush", "(", ")", "error", "{", "if", "avroWriter", ".", "nextBlockRecords", "==", "0", "{", "return", "nil", "\n", "}", "\n\n", "// Write out all of the buffered records as a new block", "// Must be called before closing to ensure the last block is written", "if", "fwWriter", ",", "ok", ":=", "avroWriter", ".", "compressedWriter", ".", "(", "CloseableResettableWriter", ")", ";", "ok", "{", "fwWriter", ".", "Close", "(", ")", "\n", "fwWriter", ".", "Reset", "(", "avroWriter", ".", "blockBuffer", ")", "\n", "}", "\n\n", "if", "avroWriter", ".", "nextBlockRecords", ">", "0", "{", "block", ":=", "&", "avro", ".", "AvroContainerBlock", "{", "NumRecords", ":", "avroWriter", ".", "nextBlockRecords", ",", "RecordBytes", ":", "avroWriter", ".", "blockBuffer", ".", "Bytes", "(", ")", ",", "Sync", ":", "avroWriter", ".", "syncMarker", ",", "}", "\n", "err", ":=", "block", ".", "Serialize", "(", "avroWriter", ".", "writer", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "}", "\n\n", "avroWriter", ".", "blockBuffer", ".", "Reset", "(", ")", "\n", "avroWriter", ".", "nextBlockRecords", "=", "0", "\n\n", "return", "nil", "\n", "}" ]
// Write the current block to the file if it has been filled. It is // best-practise to always call this before the underlying io.Writer is closed.
[ "Write", "the", "current", "block", "to", "the", "file", "if", "it", "has", "been", "filled", ".", "It", "is", "best", "-", "practise", "to", "always", "call", "this", "before", "the", "underlying", "io", ".", "Writer", "is", "closed", "." ]
fd08cc477d17abc4fbb71e40721601df8871ee24
https://github.com/actgardner/gogen-avro/blob/fd08cc477d17abc4fbb71e40721601df8871ee24/container/writer.go#L114-L142
5,470
actgardner/gogen-avro
generator/namer.go
NewNamespaceNamer
func NewNamespaceNamer(shortNames bool) *NamespaceNamer { return &NamespaceNamer{shortNames: shortNames, re: regexp.MustCompile(invalidTokensExpr)} }
go
func NewNamespaceNamer(shortNames bool) *NamespaceNamer { return &NamespaceNamer{shortNames: shortNames, re: regexp.MustCompile(invalidTokensExpr)} }
[ "func", "NewNamespaceNamer", "(", "shortNames", "bool", ")", "*", "NamespaceNamer", "{", "return", "&", "NamespaceNamer", "{", "shortNames", ":", "shortNames", ",", "re", ":", "regexp", ".", "MustCompile", "(", "invalidTokensExpr", ")", "}", "\n", "}" ]
// NewNamespaceNamer returns a namespace-aware namer.
[ "NewNamespaceNamer", "returns", "a", "namespace", "-", "aware", "namer", "." ]
fd08cc477d17abc4fbb71e40721601df8871ee24
https://github.com/actgardner/gogen-avro/blob/fd08cc477d17abc4fbb71e40721601df8871ee24/generator/namer.go#L40-L42
5,471
actgardner/gogen-avro
generator/namer.go
ToPublicName
func (n *NamespaceNamer) ToPublicName(name string) string { if n.shortNames { if parts := strings.Split(name, "."); len(parts) > 2 { name = strings.Join(parts[len(parts)-2:], ".") } } name = n.re.ReplaceAllString(name, " ") return strings.Replace(strings.Title(name), " ", "", -1) }
go
func (n *NamespaceNamer) ToPublicName(name string) string { if n.shortNames { if parts := strings.Split(name, "."); len(parts) > 2 { name = strings.Join(parts[len(parts)-2:], ".") } } name = n.re.ReplaceAllString(name, " ") return strings.Replace(strings.Title(name), " ", "", -1) }
[ "func", "(", "n", "*", "NamespaceNamer", ")", "ToPublicName", "(", "name", "string", ")", "string", "{", "if", "n", ".", "shortNames", "{", "if", "parts", ":=", "strings", ".", "Split", "(", "name", ",", "\"", "\"", ")", ";", "len", "(", "parts", ")", ">", "2", "{", "name", "=", "strings", ".", "Join", "(", "parts", "[", "len", "(", "parts", ")", "-", "2", ":", "]", ",", "\"", "\"", ")", "\n", "}", "\n", "}", "\n", "name", "=", "n", ".", "re", ".", "ReplaceAllString", "(", "name", ",", "\"", "\"", ")", "\n", "return", "strings", ".", "Replace", "(", "strings", ".", "Title", "(", "name", ")", ",", "\"", "\"", ",", "\"", "\"", ",", "-", "1", ")", "\n", "}" ]
// ToPublicName implements the go-idiomatic public name as in DefaultNamer's // struct, but with additional treatment applied in order to remove possible // invalid tokens from it. Final string is then converted to camel-case.
[ "ToPublicName", "implements", "the", "go", "-", "idiomatic", "public", "name", "as", "in", "DefaultNamer", "s", "struct", "but", "with", "additional", "treatment", "applied", "in", "order", "to", "remove", "possible", "invalid", "tokens", "from", "it", ".", "Final", "string", "is", "then", "converted", "to", "camel", "-", "case", "." ]
fd08cc477d17abc4fbb71e40721601df8871ee24
https://github.com/actgardner/gogen-avro/blob/fd08cc477d17abc4fbb71e40721601df8871ee24/generator/namer.go#L58-L66
5,472
actgardner/gogen-avro
compiler/instruction.go
CompileToVM
func (b *blockStartIRInstruction) CompileToVM(p *irProgram) ([]vm.Instruction, error) { block := p.blocks[b.blockId] return []vm.Instruction{ vm.Instruction{vm.Read, vm.Long}, vm.Instruction{vm.EvalEqual, 0}, vm.Instruction{vm.CondJump, block.end + 5}, vm.Instruction{vm.EvalGreater, 0}, vm.Instruction{vm.CondJump, block.start + 7}, vm.Instruction{vm.Read, vm.UnusedLong}, vm.Instruction{vm.MultLong, -1}, vm.Instruction{vm.PushLoop, 0}, }, nil }
go
func (b *blockStartIRInstruction) CompileToVM(p *irProgram) ([]vm.Instruction, error) { block := p.blocks[b.blockId] return []vm.Instruction{ vm.Instruction{vm.Read, vm.Long}, vm.Instruction{vm.EvalEqual, 0}, vm.Instruction{vm.CondJump, block.end + 5}, vm.Instruction{vm.EvalGreater, 0}, vm.Instruction{vm.CondJump, block.start + 7}, vm.Instruction{vm.Read, vm.UnusedLong}, vm.Instruction{vm.MultLong, -1}, vm.Instruction{vm.PushLoop, 0}, }, nil }
[ "func", "(", "b", "*", "blockStartIRInstruction", ")", "CompileToVM", "(", "p", "*", "irProgram", ")", "(", "[", "]", "vm", ".", "Instruction", ",", "error", ")", "{", "block", ":=", "p", ".", "blocks", "[", "b", ".", "blockId", "]", "\n", "return", "[", "]", "vm", ".", "Instruction", "{", "vm", ".", "Instruction", "{", "vm", ".", "Read", ",", "vm", ".", "Long", "}", ",", "vm", ".", "Instruction", "{", "vm", ".", "EvalEqual", ",", "0", "}", ",", "vm", ".", "Instruction", "{", "vm", ".", "CondJump", ",", "block", ".", "end", "+", "5", "}", ",", "vm", ".", "Instruction", "{", "vm", ".", "EvalGreater", ",", "0", "}", ",", "vm", ".", "Instruction", "{", "vm", ".", "CondJump", ",", "block", ".", "start", "+", "7", "}", ",", "vm", ".", "Instruction", "{", "vm", ".", "Read", ",", "vm", ".", "UnusedLong", "}", ",", "vm", ".", "Instruction", "{", "vm", ".", "MultLong", ",", "-", "1", "}", ",", "vm", ".", "Instruction", "{", "vm", ".", "PushLoop", ",", "0", "}", ",", "}", ",", "nil", "\n", "}" ]
// At the beginning of a block, read the length into the Long register // If the block length is 0, jump past the block body because we're done // If the block length is negative, read the byte count, throw it away, multiply the length by -1 // Once we've figured out the number of iterations, push the loop length onto the loop stack
[ "At", "the", "beginning", "of", "a", "block", "read", "the", "length", "into", "the", "Long", "register", "If", "the", "block", "length", "is", "0", "jump", "past", "the", "block", "body", "because", "we", "re", "done", "If", "the", "block", "length", "is", "negative", "read", "the", "byte", "count", "throw", "it", "away", "multiply", "the", "length", "by", "-", "1", "Once", "we", "ve", "figured", "out", "the", "number", "of", "iterations", "push", "the", "loop", "length", "onto", "the", "loop", "stack" ]
fd08cc477d17abc4fbb71e40721601df8871ee24
https://github.com/actgardner/gogen-avro/blob/fd08cc477d17abc4fbb71e40721601df8871ee24/compiler/instruction.go#L54-L66
5,473
actgardner/gogen-avro
compiler/instruction.go
CompileToVM
func (b *blockEndIRInstruction) CompileToVM(p *irProgram) ([]vm.Instruction, error) { block := p.blocks[b.blockId] return []vm.Instruction{ vm.Instruction{vm.PopLoop, 0}, vm.Instruction{vm.AddLong, -1}, vm.Instruction{vm.EvalEqual, 0}, vm.Instruction{vm.CondJump, block.start}, vm.Instruction{vm.Jump, block.start + 7}, }, nil }
go
func (b *blockEndIRInstruction) CompileToVM(p *irProgram) ([]vm.Instruction, error) { block := p.blocks[b.blockId] return []vm.Instruction{ vm.Instruction{vm.PopLoop, 0}, vm.Instruction{vm.AddLong, -1}, vm.Instruction{vm.EvalEqual, 0}, vm.Instruction{vm.CondJump, block.start}, vm.Instruction{vm.Jump, block.start + 7}, }, nil }
[ "func", "(", "b", "*", "blockEndIRInstruction", ")", "CompileToVM", "(", "p", "*", "irProgram", ")", "(", "[", "]", "vm", ".", "Instruction", ",", "error", ")", "{", "block", ":=", "p", ".", "blocks", "[", "b", ".", "blockId", "]", "\n", "return", "[", "]", "vm", ".", "Instruction", "{", "vm", ".", "Instruction", "{", "vm", ".", "PopLoop", ",", "0", "}", ",", "vm", ".", "Instruction", "{", "vm", ".", "AddLong", ",", "-", "1", "}", ",", "vm", ".", "Instruction", "{", "vm", ".", "EvalEqual", ",", "0", "}", ",", "vm", ".", "Instruction", "{", "vm", ".", "CondJump", ",", "block", ".", "start", "}", ",", "vm", ".", "Instruction", "{", "vm", ".", "Jump", ",", "block", ".", "start", "+", "7", "}", ",", "}", ",", "nil", "\n", "}" ]
// At the end of a block, pop the loop count and decrement it. If it's zero, go back to the very // top to read a new block. otherwise jump to start + 7, which pushes the value back on the loop stack
[ "At", "the", "end", "of", "a", "block", "pop", "the", "loop", "count", "and", "decrement", "it", ".", "If", "it", "s", "zero", "go", "back", "to", "the", "very", "top", "to", "read", "a", "new", "block", ".", "otherwise", "jump", "to", "start", "+", "7", "which", "pushes", "the", "value", "back", "on", "the", "loop", "stack" ]
fd08cc477d17abc4fbb71e40721601df8871ee24
https://github.com/actgardner/gogen-avro/blob/fd08cc477d17abc4fbb71e40721601df8871ee24/compiler/instruction.go#L78-L87
5,474
actgardner/gogen-avro
schema/namespace.go
RegisterDefinition
func (n *Namespace) RegisterDefinition(d Definition) error { if curDef, ok := n.Definitions[d.AvroName()]; ok { if !reflect.DeepEqual(curDef, d) { return fmt.Errorf("Conflicting definitions for %v", d.AvroName()) } return nil } n.Definitions[d.AvroName()] = d for _, alias := range d.Aliases() { if existing, ok := n.Definitions[alias]; ok { return fmt.Errorf("Alias for %q is %q, but %q is already aliased with that name", d.AvroName(), alias, existing.AvroName()) } n.Definitions[alias] = d } return nil }
go
func (n *Namespace) RegisterDefinition(d Definition) error { if curDef, ok := n.Definitions[d.AvroName()]; ok { if !reflect.DeepEqual(curDef, d) { return fmt.Errorf("Conflicting definitions for %v", d.AvroName()) } return nil } n.Definitions[d.AvroName()] = d for _, alias := range d.Aliases() { if existing, ok := n.Definitions[alias]; ok { return fmt.Errorf("Alias for %q is %q, but %q is already aliased with that name", d.AvroName(), alias, existing.AvroName()) } n.Definitions[alias] = d } return nil }
[ "func", "(", "n", "*", "Namespace", ")", "RegisterDefinition", "(", "d", "Definition", ")", "error", "{", "if", "curDef", ",", "ok", ":=", "n", ".", "Definitions", "[", "d", ".", "AvroName", "(", ")", "]", ";", "ok", "{", "if", "!", "reflect", ".", "DeepEqual", "(", "curDef", ",", "d", ")", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "d", ".", "AvroName", "(", ")", ")", "\n", "}", "\n", "return", "nil", "\n", "}", "\n", "n", ".", "Definitions", "[", "d", ".", "AvroName", "(", ")", "]", "=", "d", "\n\n", "for", "_", ",", "alias", ":=", "range", "d", ".", "Aliases", "(", ")", "{", "if", "existing", ",", "ok", ":=", "n", ".", "Definitions", "[", "alias", "]", ";", "ok", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "d", ".", "AvroName", "(", ")", ",", "alias", ",", "existing", ".", "AvroName", "(", ")", ")", "\n", "}", "\n", "n", ".", "Definitions", "[", "alias", "]", "=", "d", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// RegisterDefinition adds a new type definition to the namespace. Returns an error if the type is already defined.
[ "RegisterDefinition", "adds", "a", "new", "type", "definition", "to", "the", "namespace", ".", "Returns", "an", "error", "if", "the", "type", "is", "already", "defined", "." ]
fd08cc477d17abc4fbb71e40721601df8871ee24
https://github.com/actgardner/gogen-avro/blob/fd08cc477d17abc4fbb71e40721601df8871ee24/schema/namespace.go#L66-L82
5,475
actgardner/gogen-avro
schema/namespace.go
decodeRecordDefinition
func (n *Namespace) decodeRecordDefinition(namespace string, schemaMap map[string]interface{}) (Definition, error) { typeStr, err := getMapString(schemaMap, "type") if err != nil { return nil, err } if typeStr != "record" { return nil, fmt.Errorf("Type of record must be 'record'") } name, err := getMapString(schemaMap, "name") if err != nil { return nil, err } var rDocString string if rDoc, ok := schemaMap["doc"]; ok { rDocString, ok = rDoc.(string) if !ok { return nil, NewWrongMapValueTypeError("doc", "string", rDoc) } } if _, ok := schemaMap["namespace"]; ok { namespace, err = getMapString(schemaMap, "namespace") if err != nil { return nil, err } } fieldList, err := getMapArray(schemaMap, "fields") if err != nil { return nil, err } decodedFields := make([]*Field, 0) for i, f := range fieldList { field, ok := f.(map[string]interface{}) if !ok { return nil, NewWrongMapValueTypeError("fields", "map[]", field) } fieldName, err := getMapString(field, "name") if err != nil { return nil, err } t, ok := field["type"] if !ok { return nil, NewRequiredMapKeyError("type") } fieldType, err := n.decodeTypeDefinition(fieldName, namespace, t) if err != nil { return nil, err } var docString string if doc, ok := field["doc"]; ok { docString, ok = doc.(string) if !ok { return nil, NewWrongMapValueTypeError("doc", "string", doc) } } var fieldTags string if tags, ok := field["golang.tags"]; ok { fieldTags, ok = tags.(string) if !ok { return nil, NewWrongMapValueTypeError("golang.tags", "string", tags) } } def, hasDef := field["default"] fieldStruct := NewField(fieldName, fieldType, def, hasDef, docString, field, i, fieldTags) decodedFields = append(decodedFields, fieldStruct) } aliases, err := parseAliases(schemaMap, namespace) if err != nil { return nil, err } return NewRecordDefinition(ParseAvroName(namespace, name), aliases, decodedFields, rDocString, schemaMap), nil }
go
func (n *Namespace) decodeRecordDefinition(namespace string, schemaMap map[string]interface{}) (Definition, error) { typeStr, err := getMapString(schemaMap, "type") if err != nil { return nil, err } if typeStr != "record" { return nil, fmt.Errorf("Type of record must be 'record'") } name, err := getMapString(schemaMap, "name") if err != nil { return nil, err } var rDocString string if rDoc, ok := schemaMap["doc"]; ok { rDocString, ok = rDoc.(string) if !ok { return nil, NewWrongMapValueTypeError("doc", "string", rDoc) } } if _, ok := schemaMap["namespace"]; ok { namespace, err = getMapString(schemaMap, "namespace") if err != nil { return nil, err } } fieldList, err := getMapArray(schemaMap, "fields") if err != nil { return nil, err } decodedFields := make([]*Field, 0) for i, f := range fieldList { field, ok := f.(map[string]interface{}) if !ok { return nil, NewWrongMapValueTypeError("fields", "map[]", field) } fieldName, err := getMapString(field, "name") if err != nil { return nil, err } t, ok := field["type"] if !ok { return nil, NewRequiredMapKeyError("type") } fieldType, err := n.decodeTypeDefinition(fieldName, namespace, t) if err != nil { return nil, err } var docString string if doc, ok := field["doc"]; ok { docString, ok = doc.(string) if !ok { return nil, NewWrongMapValueTypeError("doc", "string", doc) } } var fieldTags string if tags, ok := field["golang.tags"]; ok { fieldTags, ok = tags.(string) if !ok { return nil, NewWrongMapValueTypeError("golang.tags", "string", tags) } } def, hasDef := field["default"] fieldStruct := NewField(fieldName, fieldType, def, hasDef, docString, field, i, fieldTags) decodedFields = append(decodedFields, fieldStruct) } aliases, err := parseAliases(schemaMap, namespace) if err != nil { return nil, err } return NewRecordDefinition(ParseAvroName(namespace, name), aliases, decodedFields, rDocString, schemaMap), nil }
[ "func", "(", "n", "*", "Namespace", ")", "decodeRecordDefinition", "(", "namespace", "string", ",", "schemaMap", "map", "[", "string", "]", "interface", "{", "}", ")", "(", "Definition", ",", "error", ")", "{", "typeStr", ",", "err", ":=", "getMapString", "(", "schemaMap", ",", "\"", "\"", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "if", "typeStr", "!=", "\"", "\"", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n\n", "name", ",", "err", ":=", "getMapString", "(", "schemaMap", ",", "\"", "\"", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "var", "rDocString", "string", "\n", "if", "rDoc", ",", "ok", ":=", "schemaMap", "[", "\"", "\"", "]", ";", "ok", "{", "rDocString", ",", "ok", "=", "rDoc", ".", "(", "string", ")", "\n", "if", "!", "ok", "{", "return", "nil", ",", "NewWrongMapValueTypeError", "(", "\"", "\"", ",", "\"", "\"", ",", "rDoc", ")", "\n", "}", "\n", "}", "\n\n", "if", "_", ",", "ok", ":=", "schemaMap", "[", "\"", "\"", "]", ";", "ok", "{", "namespace", ",", "err", "=", "getMapString", "(", "schemaMap", ",", "\"", "\"", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "}", "\n\n", "fieldList", ",", "err", ":=", "getMapArray", "(", "schemaMap", ",", "\"", "\"", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "decodedFields", ":=", "make", "(", "[", "]", "*", "Field", ",", "0", ")", "\n", "for", "i", ",", "f", ":=", "range", "fieldList", "{", "field", ",", "ok", ":=", "f", ".", "(", "map", "[", "string", "]", "interface", "{", "}", ")", "\n", "if", "!", "ok", "{", "return", "nil", ",", "NewWrongMapValueTypeError", "(", "\"", "\"", ",", "\"", "\"", ",", "field", ")", "\n", "}", "\n\n", "fieldName", ",", "err", ":=", "getMapString", "(", "field", ",", "\"", "\"", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "t", ",", "ok", ":=", "field", "[", "\"", "\"", "]", "\n", "if", "!", "ok", "{", "return", "nil", ",", "NewRequiredMapKeyError", "(", "\"", "\"", ")", "\n", "}", "\n\n", "fieldType", ",", "err", ":=", "n", ".", "decodeTypeDefinition", "(", "fieldName", ",", "namespace", ",", "t", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "var", "docString", "string", "\n", "if", "doc", ",", "ok", ":=", "field", "[", "\"", "\"", "]", ";", "ok", "{", "docString", ",", "ok", "=", "doc", ".", "(", "string", ")", "\n", "if", "!", "ok", "{", "return", "nil", ",", "NewWrongMapValueTypeError", "(", "\"", "\"", ",", "\"", "\"", ",", "doc", ")", "\n", "}", "\n", "}", "\n\n", "var", "fieldTags", "string", "\n", "if", "tags", ",", "ok", ":=", "field", "[", "\"", "\"", "]", ";", "ok", "{", "fieldTags", ",", "ok", "=", "tags", ".", "(", "string", ")", "\n", "if", "!", "ok", "{", "return", "nil", ",", "NewWrongMapValueTypeError", "(", "\"", "\"", ",", "\"", "\"", ",", "tags", ")", "\n", "}", "\n", "}", "\n\n", "def", ",", "hasDef", ":=", "field", "[", "\"", "\"", "]", "\n", "fieldStruct", ":=", "NewField", "(", "fieldName", ",", "fieldType", ",", "def", ",", "hasDef", ",", "docString", ",", "field", ",", "i", ",", "fieldTags", ")", "\n\n", "decodedFields", "=", "append", "(", "decodedFields", ",", "fieldStruct", ")", "\n", "}", "\n\n", "aliases", ",", "err", ":=", "parseAliases", "(", "schemaMap", ",", "namespace", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "return", "NewRecordDefinition", "(", "ParseAvroName", "(", "namespace", ",", "name", ")", ",", "aliases", ",", "decodedFields", ",", "rDocString", ",", "schemaMap", ")", ",", "nil", "\n", "}" ]
// Given a map representing a record definition, validate the definition and build the RecordDefinition struct.
[ "Given", "a", "map", "representing", "a", "record", "definition", "validate", "the", "definition", "and", "build", "the", "RecordDefinition", "struct", "." ]
fd08cc477d17abc4fbb71e40721601df8871ee24
https://github.com/actgardner/gogen-avro/blob/fd08cc477d17abc4fbb71e40721601df8871ee24/schema/namespace.go#L133-L218
5,476
actgardner/gogen-avro
schema/namespace.go
decodeEnumDefinition
func (n *Namespace) decodeEnumDefinition(namespace string, schemaMap map[string]interface{}) (Definition, error) { typeStr, err := getMapString(schemaMap, "type") if err != nil { return nil, err } if typeStr != "enum" { return nil, fmt.Errorf("Type of enum must be 'enum'") } if _, ok := schemaMap["namespace"]; ok { namespace, err = getMapString(schemaMap, "namespace") if err != nil { return nil, err } } name, err := getMapString(schemaMap, "name") if err != nil { return nil, err } symbolSlice, err := getMapArray(schemaMap, "symbols") if err != nil { return nil, err } symbolStr, ok := interfaceSliceToStringSlice(symbolSlice) if !ok { return nil, fmt.Errorf("'symbols' must be an array of strings") } aliases, err := parseAliases(schemaMap, namespace) if err != nil { return nil, err } var docString string if doc, ok := schemaMap["doc"]; ok { if docString, ok = doc.(string); !ok { return nil, fmt.Errorf("'doc' must be a string") } } return NewEnumDefinition(ParseAvroName(namespace, name), aliases, symbolStr, docString, schemaMap), nil }
go
func (n *Namespace) decodeEnumDefinition(namespace string, schemaMap map[string]interface{}) (Definition, error) { typeStr, err := getMapString(schemaMap, "type") if err != nil { return nil, err } if typeStr != "enum" { return nil, fmt.Errorf("Type of enum must be 'enum'") } if _, ok := schemaMap["namespace"]; ok { namespace, err = getMapString(schemaMap, "namespace") if err != nil { return nil, err } } name, err := getMapString(schemaMap, "name") if err != nil { return nil, err } symbolSlice, err := getMapArray(schemaMap, "symbols") if err != nil { return nil, err } symbolStr, ok := interfaceSliceToStringSlice(symbolSlice) if !ok { return nil, fmt.Errorf("'symbols' must be an array of strings") } aliases, err := parseAliases(schemaMap, namespace) if err != nil { return nil, err } var docString string if doc, ok := schemaMap["doc"]; ok { if docString, ok = doc.(string); !ok { return nil, fmt.Errorf("'doc' must be a string") } } return NewEnumDefinition(ParseAvroName(namespace, name), aliases, symbolStr, docString, schemaMap), nil }
[ "func", "(", "n", "*", "Namespace", ")", "decodeEnumDefinition", "(", "namespace", "string", ",", "schemaMap", "map", "[", "string", "]", "interface", "{", "}", ")", "(", "Definition", ",", "error", ")", "{", "typeStr", ",", "err", ":=", "getMapString", "(", "schemaMap", ",", "\"", "\"", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "if", "typeStr", "!=", "\"", "\"", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n\n", "if", "_", ",", "ok", ":=", "schemaMap", "[", "\"", "\"", "]", ";", "ok", "{", "namespace", ",", "err", "=", "getMapString", "(", "schemaMap", ",", "\"", "\"", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "}", "\n\n", "name", ",", "err", ":=", "getMapString", "(", "schemaMap", ",", "\"", "\"", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "symbolSlice", ",", "err", ":=", "getMapArray", "(", "schemaMap", ",", "\"", "\"", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "symbolStr", ",", "ok", ":=", "interfaceSliceToStringSlice", "(", "symbolSlice", ")", "\n", "if", "!", "ok", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n\n", "aliases", ",", "err", ":=", "parseAliases", "(", "schemaMap", ",", "namespace", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "var", "docString", "string", "\n", "if", "doc", ",", "ok", ":=", "schemaMap", "[", "\"", "\"", "]", ";", "ok", "{", "if", "docString", ",", "ok", "=", "doc", ".", "(", "string", ")", ";", "!", "ok", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n", "}", "\n\n", "return", "NewEnumDefinition", "(", "ParseAvroName", "(", "namespace", ",", "name", ")", ",", "aliases", ",", "symbolStr", ",", "docString", ",", "schemaMap", ")", ",", "nil", "\n", "}" ]
// decodeEnumDefinition accepts a namespace and a map representing an enum definition, // it validates the definition and build the EnumDefinition struct.
[ "decodeEnumDefinition", "accepts", "a", "namespace", "and", "a", "map", "representing", "an", "enum", "definition", "it", "validates", "the", "definition", "and", "build", "the", "EnumDefinition", "struct", "." ]
fd08cc477d17abc4fbb71e40721601df8871ee24
https://github.com/actgardner/gogen-avro/blob/fd08cc477d17abc4fbb71e40721601df8871ee24/schema/namespace.go#L222-L267
5,477
actgardner/gogen-avro
schema/namespace.go
decodeFixedDefinition
func (n *Namespace) decodeFixedDefinition(namespace string, schemaMap map[string]interface{}) (Definition, error) { typeStr, err := getMapString(schemaMap, "type") if err != nil { return nil, err } if typeStr != "fixed" { return nil, fmt.Errorf("Type of fixed must be 'fixed'") } if _, ok := schemaMap["namespace"]; ok { namespace, err = getMapString(schemaMap, "namespace") if err != nil { return nil, err } } name, err := getMapString(schemaMap, "name") if err != nil { return nil, err } sizeBytes, err := getMapFloat(schemaMap, "size") if err != nil { return nil, err } aliases, err := parseAliases(schemaMap, namespace) if err != nil { return nil, err } return NewFixedDefinition(ParseAvroName(namespace, name), aliases, int(sizeBytes), schemaMap), nil }
go
func (n *Namespace) decodeFixedDefinition(namespace string, schemaMap map[string]interface{}) (Definition, error) { typeStr, err := getMapString(schemaMap, "type") if err != nil { return nil, err } if typeStr != "fixed" { return nil, fmt.Errorf("Type of fixed must be 'fixed'") } if _, ok := schemaMap["namespace"]; ok { namespace, err = getMapString(schemaMap, "namespace") if err != nil { return nil, err } } name, err := getMapString(schemaMap, "name") if err != nil { return nil, err } sizeBytes, err := getMapFloat(schemaMap, "size") if err != nil { return nil, err } aliases, err := parseAliases(schemaMap, namespace) if err != nil { return nil, err } return NewFixedDefinition(ParseAvroName(namespace, name), aliases, int(sizeBytes), schemaMap), nil }
[ "func", "(", "n", "*", "Namespace", ")", "decodeFixedDefinition", "(", "namespace", "string", ",", "schemaMap", "map", "[", "string", "]", "interface", "{", "}", ")", "(", "Definition", ",", "error", ")", "{", "typeStr", ",", "err", ":=", "getMapString", "(", "schemaMap", ",", "\"", "\"", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "if", "typeStr", "!=", "\"", "\"", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n\n", "if", "_", ",", "ok", ":=", "schemaMap", "[", "\"", "\"", "]", ";", "ok", "{", "namespace", ",", "err", "=", "getMapString", "(", "schemaMap", ",", "\"", "\"", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "}", "\n\n", "name", ",", "err", ":=", "getMapString", "(", "schemaMap", ",", "\"", "\"", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "sizeBytes", ",", "err", ":=", "getMapFloat", "(", "schemaMap", ",", "\"", "\"", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "aliases", ",", "err", ":=", "parseAliases", "(", "schemaMap", ",", "namespace", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "return", "NewFixedDefinition", "(", "ParseAvroName", "(", "namespace", ",", "name", ")", ",", "aliases", ",", "int", "(", "sizeBytes", ")", ",", "schemaMap", ")", ",", "nil", "\n", "}" ]
// decodeFixedDefinition accepts a namespace and a map representing a fixed definition, // it validates the definition and build the FixedDefinition struct.
[ "decodeFixedDefinition", "accepts", "a", "namespace", "and", "a", "map", "representing", "a", "fixed", "definition", "it", "validates", "the", "definition", "and", "build", "the", "FixedDefinition", "struct", "." ]
fd08cc477d17abc4fbb71e40721601df8871ee24
https://github.com/actgardner/gogen-avro/blob/fd08cc477d17abc4fbb71e40721601df8871ee24/schema/namespace.go#L271-L304
5,478
actgardner/gogen-avro
schema/namespace.go
parseAliases
func parseAliases(objectMap map[string]interface{}, namespace string) ([]QualifiedName, error) { aliases, ok := objectMap["aliases"] if !ok { return make([]QualifiedName, 0), nil } aliasList, ok := aliases.([]interface{}) if !ok { return nil, fmt.Errorf("Field aliases expected to be array, got %v", aliases) } qualifiedAliases := make([]QualifiedName, 0, len(aliasList)) for _, alias := range aliasList { aliasString, ok := alias.(string) if !ok { return nil, fmt.Errorf("Field aliases expected to be array of strings, got %v", aliases) } qualifiedAliases = append(qualifiedAliases, ParseAvroName(namespace, aliasString)) } return qualifiedAliases, nil }
go
func parseAliases(objectMap map[string]interface{}, namespace string) ([]QualifiedName, error) { aliases, ok := objectMap["aliases"] if !ok { return make([]QualifiedName, 0), nil } aliasList, ok := aliases.([]interface{}) if !ok { return nil, fmt.Errorf("Field aliases expected to be array, got %v", aliases) } qualifiedAliases := make([]QualifiedName, 0, len(aliasList)) for _, alias := range aliasList { aliasString, ok := alias.(string) if !ok { return nil, fmt.Errorf("Field aliases expected to be array of strings, got %v", aliases) } qualifiedAliases = append(qualifiedAliases, ParseAvroName(namespace, aliasString)) } return qualifiedAliases, nil }
[ "func", "parseAliases", "(", "objectMap", "map", "[", "string", "]", "interface", "{", "}", ",", "namespace", "string", ")", "(", "[", "]", "QualifiedName", ",", "error", ")", "{", "aliases", ",", "ok", ":=", "objectMap", "[", "\"", "\"", "]", "\n", "if", "!", "ok", "{", "return", "make", "(", "[", "]", "QualifiedName", ",", "0", ")", ",", "nil", "\n", "}", "\n\n", "aliasList", ",", "ok", ":=", "aliases", ".", "(", "[", "]", "interface", "{", "}", ")", "\n", "if", "!", "ok", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "aliases", ")", "\n", "}", "\n\n", "qualifiedAliases", ":=", "make", "(", "[", "]", "QualifiedName", ",", "0", ",", "len", "(", "aliasList", ")", ")", "\n\n", "for", "_", ",", "alias", ":=", "range", "aliasList", "{", "aliasString", ",", "ok", ":=", "alias", ".", "(", "string", ")", "\n", "if", "!", "ok", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "aliases", ")", "\n", "}", "\n", "qualifiedAliases", "=", "append", "(", "qualifiedAliases", ",", "ParseAvroName", "(", "namespace", ",", "aliasString", ")", ")", "\n", "}", "\n", "return", "qualifiedAliases", ",", "nil", "\n", "}" ]
// parseAliases parses out all the aliases from a definition map - returns an empty slice if no aliases exist. // Returns an error if the aliases key exists but the value isn't a list of strings.
[ "parseAliases", "parses", "out", "all", "the", "aliases", "from", "a", "definition", "map", "-", "returns", "an", "empty", "slice", "if", "no", "aliases", "exist", ".", "Returns", "an", "error", "if", "the", "aliases", "key", "exists", "but", "the", "value", "isn", "t", "a", "list", "of", "strings", "." ]
fd08cc477d17abc4fbb71e40721601df8871ee24
https://github.com/actgardner/gogen-avro/blob/fd08cc477d17abc4fbb71e40721601df8871ee24/schema/namespace.go#L433-L454
5,479
actgardner/gogen-avro
gogen-avro/config.go
parseCmdLine
func parseCmdLine() config { cfg := config{} flag.StringVar(&cfg.packageName, "package", defaultPackageName, "Name of generated package.") flag.BoolVar(&cfg.containers, "containers", defaultContainers, "Whether to generate container writer methods.") flag.BoolVar(&cfg.shortUnions, "short-unions", defaultShortUnions, "Whether to use shorter names for Union types.") flag.StringVar(&cfg.namespacedNames, "namespaced-names", defaultNamespacedNames, "Whether to generate namespaced names for types. Default is \"none\"; \"short\" uses the last part of the namespace (last word after a separator); \"full\" uses all namespace string.") flag.Usage = func() { fmt.Fprintf(os.Stderr, "Usage: %s [flags] <target directory> <schema files>\n\nWhere 'flags' are:\n", os.Args[0]) flag.PrintDefaults() os.Exit(1) } flag.Parse() if flag.NArg() < 2 { flag.Usage() } cfg.namespacedNames = strings.ToLower(cfg.namespacedNames) switch cfg.namespacedNames { case nsNone, nsShort, nsFull: default: fmt.Fprintf(os.Stderr, "namespaced-names: invalid value '%s'\n\n", cfg.namespacedNames) flag.Usage() } cfg.targetDir = flag.Arg(0) cfg.files = make([]string, 0) for _, glob := range flag.Args()[1:] { files, err := filepath.Glob(glob) if err != nil { fmt.Fprintf(os.Stderr, "Error parsing input file as glob: %v", err) os.Exit(1) } cfg.files = append(cfg.files, files...) } return cfg }
go
func parseCmdLine() config { cfg := config{} flag.StringVar(&cfg.packageName, "package", defaultPackageName, "Name of generated package.") flag.BoolVar(&cfg.containers, "containers", defaultContainers, "Whether to generate container writer methods.") flag.BoolVar(&cfg.shortUnions, "short-unions", defaultShortUnions, "Whether to use shorter names for Union types.") flag.StringVar(&cfg.namespacedNames, "namespaced-names", defaultNamespacedNames, "Whether to generate namespaced names for types. Default is \"none\"; \"short\" uses the last part of the namespace (last word after a separator); \"full\" uses all namespace string.") flag.Usage = func() { fmt.Fprintf(os.Stderr, "Usage: %s [flags] <target directory> <schema files>\n\nWhere 'flags' are:\n", os.Args[0]) flag.PrintDefaults() os.Exit(1) } flag.Parse() if flag.NArg() < 2 { flag.Usage() } cfg.namespacedNames = strings.ToLower(cfg.namespacedNames) switch cfg.namespacedNames { case nsNone, nsShort, nsFull: default: fmt.Fprintf(os.Stderr, "namespaced-names: invalid value '%s'\n\n", cfg.namespacedNames) flag.Usage() } cfg.targetDir = flag.Arg(0) cfg.files = make([]string, 0) for _, glob := range flag.Args()[1:] { files, err := filepath.Glob(glob) if err != nil { fmt.Fprintf(os.Stderr, "Error parsing input file as glob: %v", err) os.Exit(1) } cfg.files = append(cfg.files, files...) } return cfg }
[ "func", "parseCmdLine", "(", ")", "config", "{", "cfg", ":=", "config", "{", "}", "\n\n", "flag", ".", "StringVar", "(", "&", "cfg", ".", "packageName", ",", "\"", "\"", ",", "defaultPackageName", ",", "\"", "\"", ")", "\n", "flag", ".", "BoolVar", "(", "&", "cfg", ".", "containers", ",", "\"", "\"", ",", "defaultContainers", ",", "\"", "\"", ")", "\n", "flag", ".", "BoolVar", "(", "&", "cfg", ".", "shortUnions", ",", "\"", "\"", ",", "defaultShortUnions", ",", "\"", "\"", ")", "\n", "flag", ".", "StringVar", "(", "&", "cfg", ".", "namespacedNames", ",", "\"", "\"", ",", "defaultNamespacedNames", ",", "\"", "\\\"", "\\\"", "\\\"", "\\\"", "\\\"", "\\\"", "\"", ")", "\n\n", "flag", ".", "Usage", "=", "func", "(", ")", "{", "fmt", ".", "Fprintf", "(", "os", ".", "Stderr", ",", "\"", "\\n", "\\n", "\\n", "\"", ",", "os", ".", "Args", "[", "0", "]", ")", "\n", "flag", ".", "PrintDefaults", "(", ")", "\n", "os", ".", "Exit", "(", "1", ")", "\n", "}", "\n", "flag", ".", "Parse", "(", ")", "\n", "if", "flag", ".", "NArg", "(", ")", "<", "2", "{", "flag", ".", "Usage", "(", ")", "\n", "}", "\n\n", "cfg", ".", "namespacedNames", "=", "strings", ".", "ToLower", "(", "cfg", ".", "namespacedNames", ")", "\n", "switch", "cfg", ".", "namespacedNames", "{", "case", "nsNone", ",", "nsShort", ",", "nsFull", ":", "default", ":", "fmt", ".", "Fprintf", "(", "os", ".", "Stderr", ",", "\"", "\\n", "\\n", "\"", ",", "cfg", ".", "namespacedNames", ")", "\n", "flag", ".", "Usage", "(", ")", "\n", "}", "\n\n", "cfg", ".", "targetDir", "=", "flag", ".", "Arg", "(", "0", ")", "\n", "cfg", ".", "files", "=", "make", "(", "[", "]", "string", ",", "0", ")", "\n\n", "for", "_", ",", "glob", ":=", "range", "flag", ".", "Args", "(", ")", "[", "1", ":", "]", "{", "files", ",", "err", ":=", "filepath", ".", "Glob", "(", "glob", ")", "\n", "if", "err", "!=", "nil", "{", "fmt", ".", "Fprintf", "(", "os", ".", "Stderr", ",", "\"", "\"", ",", "err", ")", "\n", "os", ".", "Exit", "(", "1", ")", "\n", "}", "\n", "cfg", ".", "files", "=", "append", "(", "cfg", ".", "files", ",", "files", "...", ")", "\n", "}", "\n", "return", "cfg", "\n", "}" ]
// parseCmdLine takes care of building the flagset and checking if the // number of arguments matches the required ones
[ "parseCmdLine", "takes", "care", "of", "building", "the", "flagset", "and", "checking", "if", "the", "number", "of", "arguments", "matches", "the", "required", "ones" ]
fd08cc477d17abc4fbb71e40721601df8871ee24
https://github.com/actgardner/gogen-avro/blob/fd08cc477d17abc4fbb71e40721601df8871ee24/gogen-avro/config.go#L33-L71
5,480
actgardner/gogen-avro
compiler/compile.go
Compile
func Compile(writer, reader schema.AvroType) (*vm.Program, error) { log("Compile()\n writer:\n %v\n---\nreader: %v\n---\n", writer, reader) program := &irProgram{ methods: make(map[string]*irMethod), errors: make([]string, 0), } program.main = newIRMethod("main", program) err := program.main.compileType(writer, reader) if err != nil { return nil, err } log("%v", program) compiled, err := program.CompileToVM() log("%v", compiled) return compiled, err }
go
func Compile(writer, reader schema.AvroType) (*vm.Program, error) { log("Compile()\n writer:\n %v\n---\nreader: %v\n---\n", writer, reader) program := &irProgram{ methods: make(map[string]*irMethod), errors: make([]string, 0), } program.main = newIRMethod("main", program) err := program.main.compileType(writer, reader) if err != nil { return nil, err } log("%v", program) compiled, err := program.CompileToVM() log("%v", compiled) return compiled, err }
[ "func", "Compile", "(", "writer", ",", "reader", "schema", ".", "AvroType", ")", "(", "*", "vm", ".", "Program", ",", "error", ")", "{", "log", "(", "\"", "\\n", "\\n", "\\n", "\\n", "\\n", "\\n", "\"", ",", "writer", ",", "reader", ")", "\n\n", "program", ":=", "&", "irProgram", "{", "methods", ":", "make", "(", "map", "[", "string", "]", "*", "irMethod", ")", ",", "errors", ":", "make", "(", "[", "]", "string", ",", "0", ")", ",", "}", "\n", "program", ".", "main", "=", "newIRMethod", "(", "\"", "\"", ",", "program", ")", "\n\n", "err", ":=", "program", ".", "main", ".", "compileType", "(", "writer", ",", "reader", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "log", "(", "\"", "\"", ",", "program", ")", "\n", "compiled", ",", "err", ":=", "program", ".", "CompileToVM", "(", ")", "\n", "log", "(", "\"", "\"", ",", "compiled", ")", "\n", "return", "compiled", ",", "err", "\n", "}" ]
// Given two parsed Avro schemas, compile them into a program which can read the data // written by `writer` and store it in the structs generated for `reader`.
[ "Given", "two", "parsed", "Avro", "schemas", "compile", "them", "into", "a", "program", "which", "can", "read", "the", "data", "written", "by", "writer", "and", "store", "it", "in", "the", "structs", "generated", "for", "reader", "." ]
fd08cc477d17abc4fbb71e40721601df8871ee24
https://github.com/actgardner/gogen-avro/blob/fd08cc477d17abc4fbb71e40721601df8871ee24/compiler/compile.go#L43-L61
5,481
actgardner/gogen-avro
schema/util.go
mergeMaps
func mergeMaps(m1, m2 map[string]interface{}) map[string]interface{} { for k, v := range m2 { if _, ok := m1[k]; !ok { m1[k] = v } } return m1 }
go
func mergeMaps(m1, m2 map[string]interface{}) map[string]interface{} { for k, v := range m2 { if _, ok := m1[k]; !ok { m1[k] = v } } return m1 }
[ "func", "mergeMaps", "(", "m1", ",", "m2", "map", "[", "string", "]", "interface", "{", "}", ")", "map", "[", "string", "]", "interface", "{", "}", "{", "for", "k", ",", "v", ":=", "range", "m2", "{", "if", "_", ",", "ok", ":=", "m1", "[", "k", "]", ";", "!", "ok", "{", "m1", "[", "k", "]", "=", "v", "\n", "}", "\n", "}", "\n", "return", "m1", "\n", "}" ]
// Insert all the records from m2 into m1, unless the key already exists in m1
[ "Insert", "all", "the", "records", "from", "m2", "into", "m1", "unless", "the", "key", "already", "exists", "in", "m1" ]
fd08cc477d17abc4fbb71e40721601df8871ee24
https://github.com/actgardner/gogen-avro/blob/fd08cc477d17abc4fbb71e40721601df8871ee24/schema/util.go#L16-L23
5,482
kotakanbe/go-cve-dictionary
fetcher/nvd/util.go
UpdateMeta
func UpdateMeta(driver db.DB, metas []models.FeedMeta) error { for _, meta := range metas { meta.Hash = meta.LatestHash meta.LastModifiedDate = meta.LatestLastModifiedDate err := driver.UpsertFeedHash(meta) if err != nil { return fmt.Errorf("Failed to updte meta: %s, err: %s", meta.URL, err) } } return nil }
go
func UpdateMeta(driver db.DB, metas []models.FeedMeta) error { for _, meta := range metas { meta.Hash = meta.LatestHash meta.LastModifiedDate = meta.LatestLastModifiedDate err := driver.UpsertFeedHash(meta) if err != nil { return fmt.Errorf("Failed to updte meta: %s, err: %s", meta.URL, err) } } return nil }
[ "func", "UpdateMeta", "(", "driver", "db", ".", "DB", ",", "metas", "[", "]", "models", ".", "FeedMeta", ")", "error", "{", "for", "_", ",", "meta", ":=", "range", "metas", "{", "meta", ".", "Hash", "=", "meta", ".", "LatestHash", "\n", "meta", ".", "LastModifiedDate", "=", "meta", ".", "LatestLastModifiedDate", "\n", "err", ":=", "driver", ".", "UpsertFeedHash", "(", "meta", ")", "\n", "if", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "meta", ".", "URL", ",", "err", ")", "\n", "}", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// UpdateMeta updates meta table
[ "UpdateMeta", "updates", "meta", "table" ]
5fe52611f0b8dff9f95374d9cd7bdb23cc5fc67a
https://github.com/kotakanbe/go-cve-dictionary/blob/5fe52611f0b8dff9f95374d9cd7bdb23cc5fc67a/fetcher/nvd/util.go#L136-L147
5,483
kotakanbe/go-cve-dictionary
fetcher/nvd/util.go
MakeNvdMetaURLs
func MakeNvdMetaURLs(year int, xml bool) (url []string) { formatTemplate := "" if xml { // https://nvd.nist.gov/vuln/data-feeds#XML_FEED formatTemplate = "https://nvd.nist.gov/feeds/xml/cve/nvdcve-2.0-%s.meta" } else { // https: //nvd.nist.gov/vuln/data-feeds#JSON_FEED formatTemplate = "https://nvd.nist.gov/feeds/json/cve/1.0/nvdcve-1.0-%s.meta" } if year == c.Latest { for _, name := range []string{"modified", "recent"} { url = append(url, fmt.Sprintf(formatTemplate, name)) } } else { feed := strconv.Itoa(year) url = append(url, fmt.Sprintf(formatTemplate, feed)) } return }
go
func MakeNvdMetaURLs(year int, xml bool) (url []string) { formatTemplate := "" if xml { // https://nvd.nist.gov/vuln/data-feeds#XML_FEED formatTemplate = "https://nvd.nist.gov/feeds/xml/cve/nvdcve-2.0-%s.meta" } else { // https: //nvd.nist.gov/vuln/data-feeds#JSON_FEED formatTemplate = "https://nvd.nist.gov/feeds/json/cve/1.0/nvdcve-1.0-%s.meta" } if year == c.Latest { for _, name := range []string{"modified", "recent"} { url = append(url, fmt.Sprintf(formatTemplate, name)) } } else { feed := strconv.Itoa(year) url = append(url, fmt.Sprintf(formatTemplate, feed)) } return }
[ "func", "MakeNvdMetaURLs", "(", "year", "int", ",", "xml", "bool", ")", "(", "url", "[", "]", "string", ")", "{", "formatTemplate", ":=", "\"", "\"", "\n", "if", "xml", "{", "// https://nvd.nist.gov/vuln/data-feeds#XML_FEED", "formatTemplate", "=", "\"", "\"", "\n", "}", "else", "{", "// https: //nvd.nist.gov/vuln/data-feeds#JSON_FEED", "formatTemplate", "=", "\"", "\"", "\n", "}", "\n\n", "if", "year", "==", "c", ".", "Latest", "{", "for", "_", ",", "name", ":=", "range", "[", "]", "string", "{", "\"", "\"", ",", "\"", "\"", "}", "{", "url", "=", "append", "(", "url", ",", "fmt", ".", "Sprintf", "(", "formatTemplate", ",", "name", ")", ")", "\n", "}", "\n", "}", "else", "{", "feed", ":=", "strconv", ".", "Itoa", "(", "year", ")", "\n", "url", "=", "append", "(", "url", ",", "fmt", ".", "Sprintf", "(", "formatTemplate", ",", "feed", ")", ")", "\n", "}", "\n", "return", "\n", "}" ]
// MakeNvdMetaURLs returns a URL of NVD Feed
[ "MakeNvdMetaURLs", "returns", "a", "URL", "of", "NVD", "Feed" ]
5fe52611f0b8dff9f95374d9cd7bdb23cc5fc67a
https://github.com/kotakanbe/go-cve-dictionary/blob/5fe52611f0b8dff9f95374d9cd7bdb23cc5fc67a/fetcher/nvd/util.go#L150-L169
5,484
kotakanbe/go-cve-dictionary
db/rdb.go
NewRDB
func NewRDB(dbType, dbpath string, debugSQL bool) (driver *RDBDriver, locked bool, err error) { driver = &RDBDriver{ name: dbType, } log.Debugf("Opening DB (%s).", driver.Name()) if locked, err = driver.OpenDB(dbType, dbpath, debugSQL); err != nil { return nil, locked, err } log.Debugf("Migrating DB (%s).", driver.Name()) if err := driver.MigrateDB(); err != nil { return nil, false, err } return driver, false, nil }
go
func NewRDB(dbType, dbpath string, debugSQL bool) (driver *RDBDriver, locked bool, err error) { driver = &RDBDriver{ name: dbType, } log.Debugf("Opening DB (%s).", driver.Name()) if locked, err = driver.OpenDB(dbType, dbpath, debugSQL); err != nil { return nil, locked, err } log.Debugf("Migrating DB (%s).", driver.Name()) if err := driver.MigrateDB(); err != nil { return nil, false, err } return driver, false, nil }
[ "func", "NewRDB", "(", "dbType", ",", "dbpath", "string", ",", "debugSQL", "bool", ")", "(", "driver", "*", "RDBDriver", ",", "locked", "bool", ",", "err", "error", ")", "{", "driver", "=", "&", "RDBDriver", "{", "name", ":", "dbType", ",", "}", "\n\n", "log", ".", "Debugf", "(", "\"", "\"", ",", "driver", ".", "Name", "(", ")", ")", "\n", "if", "locked", ",", "err", "=", "driver", ".", "OpenDB", "(", "dbType", ",", "dbpath", ",", "debugSQL", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "locked", ",", "err", "\n", "}", "\n\n", "log", ".", "Debugf", "(", "\"", "\"", ",", "driver", ".", "Name", "(", ")", ")", "\n", "if", "err", ":=", "driver", ".", "MigrateDB", "(", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "false", ",", "err", "\n", "}", "\n", "return", "driver", ",", "false", ",", "nil", "\n", "}" ]
// NewRDB return RDB driver
[ "NewRDB", "return", "RDB", "driver" ]
5fe52611f0b8dff9f95374d9cd7bdb23cc5fc67a
https://github.com/kotakanbe/go-cve-dictionary/blob/5fe52611f0b8dff9f95374d9cd7bdb23cc5fc67a/db/rdb.go#L44-L59
5,485
kotakanbe/go-cve-dictionary
db/rdb.go
CloseDB
func (r *RDBDriver) CloseDB() (err error) { if err = r.conn.Close(); err != nil { log.Errorf("Failed to close DB. Type: %s. err: %s", r.name, err) return } return }
go
func (r *RDBDriver) CloseDB() (err error) { if err = r.conn.Close(); err != nil { log.Errorf("Failed to close DB. Type: %s. err: %s", r.name, err) return } return }
[ "func", "(", "r", "*", "RDBDriver", ")", "CloseDB", "(", ")", "(", "err", "error", ")", "{", "if", "err", "=", "r", ".", "conn", ".", "Close", "(", ")", ";", "err", "!=", "nil", "{", "log", ".", "Errorf", "(", "\"", "\"", ",", "r", ".", "name", ",", "err", ")", "\n", "return", "\n", "}", "\n", "return", "\n", "}" ]
// CloseDB close Database
[ "CloseDB", "close", "Database" ]
5fe52611f0b8dff9f95374d9cd7bdb23cc5fc67a
https://github.com/kotakanbe/go-cve-dictionary/blob/5fe52611f0b8dff9f95374d9cd7bdb23cc5fc67a/db/rdb.go#L379-L385
5,486
kotakanbe/go-cve-dictionary
db/rdb.go
getMatchingCpes
func (r *RDBDriver) getMatchingCpes(uri string) ([]models.Cpe, error) { // parse wfn, get vendor, product specified, err := naming.UnbindURI(uri) if err != nil { return nil, err } // sleect from cpe by vendor, product cpes := []models.Cpe{} err = r.conn.Where(&models.Cpe{ CpeBase: models.CpeBase{ CpeWFN: models.CpeWFN{ Vendor: fmt.Sprintf("%s", specified.Get(common.AttributeVendor)), Product: fmt.Sprintf("%s", specified.Get(common.AttributeProduct)), }, }}).Find(&cpes).Error if err != nil && err != gorm.ErrRecordNotFound { return nil, err } log.Debugf("specified: %s", uri) filtered := []models.Cpe{} checkedIDs := map[uint]bool{} for _, cpe := range cpes { match, err := match(uri, cpe) if err != nil { log.Debugf("Failed to compare the version:%s %s cpe_id:%d %#v", err, uri, cpe.ID, cpe) // Try to exact match by vendor, product and version if the version in CPE is not a semVer style. if cpe.NvdJSONID != 0 { if _, ok := checkedIDs[cpe.NvdJSONID]; ok { continue } affects := []models.Affect{} result := r.conn.Where(&models.Affect{NvdJSONID: cpe.NvdJSONID}).Find(&affects) if result.Error != nil && result.Error != gorm.ErrRecordNotFound { return nil, result.Error } ok, err := matchExactByAffects(uri, affects) if err != nil { return nil, err } if ok { filtered = append(filtered, cpe) } checkedIDs[cpe.NvdJSONID] = true } } else if match { filtered = append(filtered, cpe) } } return filtered, nil }
go
func (r *RDBDriver) getMatchingCpes(uri string) ([]models.Cpe, error) { // parse wfn, get vendor, product specified, err := naming.UnbindURI(uri) if err != nil { return nil, err } // sleect from cpe by vendor, product cpes := []models.Cpe{} err = r.conn.Where(&models.Cpe{ CpeBase: models.CpeBase{ CpeWFN: models.CpeWFN{ Vendor: fmt.Sprintf("%s", specified.Get(common.AttributeVendor)), Product: fmt.Sprintf("%s", specified.Get(common.AttributeProduct)), }, }}).Find(&cpes).Error if err != nil && err != gorm.ErrRecordNotFound { return nil, err } log.Debugf("specified: %s", uri) filtered := []models.Cpe{} checkedIDs := map[uint]bool{} for _, cpe := range cpes { match, err := match(uri, cpe) if err != nil { log.Debugf("Failed to compare the version:%s %s cpe_id:%d %#v", err, uri, cpe.ID, cpe) // Try to exact match by vendor, product and version if the version in CPE is not a semVer style. if cpe.NvdJSONID != 0 { if _, ok := checkedIDs[cpe.NvdJSONID]; ok { continue } affects := []models.Affect{} result := r.conn.Where(&models.Affect{NvdJSONID: cpe.NvdJSONID}).Find(&affects) if result.Error != nil && result.Error != gorm.ErrRecordNotFound { return nil, result.Error } ok, err := matchExactByAffects(uri, affects) if err != nil { return nil, err } if ok { filtered = append(filtered, cpe) } checkedIDs[cpe.NvdJSONID] = true } } else if match { filtered = append(filtered, cpe) } } return filtered, nil }
[ "func", "(", "r", "*", "RDBDriver", ")", "getMatchingCpes", "(", "uri", "string", ")", "(", "[", "]", "models", ".", "Cpe", ",", "error", ")", "{", "// parse wfn, get vendor, product", "specified", ",", "err", ":=", "naming", ".", "UnbindURI", "(", "uri", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "// sleect from cpe by vendor, product", "cpes", ":=", "[", "]", "models", ".", "Cpe", "{", "}", "\n", "err", "=", "r", ".", "conn", ".", "Where", "(", "&", "models", ".", "Cpe", "{", "CpeBase", ":", "models", ".", "CpeBase", "{", "CpeWFN", ":", "models", ".", "CpeWFN", "{", "Vendor", ":", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "specified", ".", "Get", "(", "common", ".", "AttributeVendor", ")", ")", ",", "Product", ":", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "specified", ".", "Get", "(", "common", ".", "AttributeProduct", ")", ")", ",", "}", ",", "}", "}", ")", ".", "Find", "(", "&", "cpes", ")", ".", "Error", "\n", "if", "err", "!=", "nil", "&&", "err", "!=", "gorm", ".", "ErrRecordNotFound", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "log", ".", "Debugf", "(", "\"", "\"", ",", "uri", ")", "\n", "filtered", ":=", "[", "]", "models", ".", "Cpe", "{", "}", "\n", "checkedIDs", ":=", "map", "[", "uint", "]", "bool", "{", "}", "\n", "for", "_", ",", "cpe", ":=", "range", "cpes", "{", "match", ",", "err", ":=", "match", "(", "uri", ",", "cpe", ")", "\n", "if", "err", "!=", "nil", "{", "log", ".", "Debugf", "(", "\"", "\"", ",", "err", ",", "uri", ",", "cpe", ".", "ID", ",", "cpe", ")", "\n\n", "// Try to exact match by vendor, product and version if the version in CPE is not a semVer style.", "if", "cpe", ".", "NvdJSONID", "!=", "0", "{", "if", "_", ",", "ok", ":=", "checkedIDs", "[", "cpe", ".", "NvdJSONID", "]", ";", "ok", "{", "continue", "\n", "}", "\n", "affects", ":=", "[", "]", "models", ".", "Affect", "{", "}", "\n", "result", ":=", "r", ".", "conn", ".", "Where", "(", "&", "models", ".", "Affect", "{", "NvdJSONID", ":", "cpe", ".", "NvdJSONID", "}", ")", ".", "Find", "(", "&", "affects", ")", "\n", "if", "result", ".", "Error", "!=", "nil", "&&", "result", ".", "Error", "!=", "gorm", ".", "ErrRecordNotFound", "{", "return", "nil", ",", "result", ".", "Error", "\n", "}", "\n\n", "ok", ",", "err", ":=", "matchExactByAffects", "(", "uri", ",", "affects", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "if", "ok", "{", "filtered", "=", "append", "(", "filtered", ",", "cpe", ")", "\n", "}", "\n", "checkedIDs", "[", "cpe", ".", "NvdJSONID", "]", "=", "true", "\n", "}", "\n", "}", "else", "if", "match", "{", "filtered", "=", "append", "(", "filtered", ",", "cpe", ")", "\n", "}", "\n", "}", "\n\n", "return", "filtered", ",", "nil", "\n", "}" ]
// getMatchingCpes returns matching CPEs by pseudo-CPE
[ "getMatchingCpes", "returns", "matching", "CPEs", "by", "pseudo", "-", "CPE" ]
5fe52611f0b8dff9f95374d9cd7bdb23cc5fc67a
https://github.com/kotakanbe/go-cve-dictionary/blob/5fe52611f0b8dff9f95374d9cd7bdb23cc5fc67a/db/rdb.go#L388-L443
5,487
kotakanbe/go-cve-dictionary
db/rdb.go
GetCveIDsByCpeURI
func (r *RDBDriver) GetCveIDsByCpeURI(uri string) ([]string, error) { filtered, err := r.getMatchingCpes(uri) if err != nil { return nil, err } cveIDs := make([]string, len(filtered)) // The cpes table is de-normalized. So the `First` is correct, don't be mislead. for i, cpe := range filtered { if cpe.JvnID != 0 { jvn := models.Jvn{} err = r.conn.Select("cve_id").Where("ID = ?", cpe.JvnID).First(&jvn).Error if err != nil && err != gorm.ErrRecordNotFound { return nil, err } cveIDs[i] = jvn.CveID } else if cpe.NvdXMLID != 0 { nvd := models.NvdXML{} err = r.conn.Select("cve_id").Where("ID = ?", cpe.NvdXMLID).First(&nvd).Error if err != nil && err != gorm.ErrRecordNotFound { return nil, err } cveIDs[i] = nvd.CveID } else if cpe.NvdJSONID != 0 { json := models.NvdJSON{} err = r.conn.Select("cve_id").Where("ID = ?", cpe.NvdJSONID).First(&json).Error if err != nil && err != gorm.ErrRecordNotFound { return nil, err } cveIDs[i] = json.CveID } // If we didn't find a CVE something is weird. if cveIDs[i] == "" { log.Infof("Missing cve_id for %s (id: %d)", cpe.URI, cpe.ID) } } return cveIDs, nil }
go
func (r *RDBDriver) GetCveIDsByCpeURI(uri string) ([]string, error) { filtered, err := r.getMatchingCpes(uri) if err != nil { return nil, err } cveIDs := make([]string, len(filtered)) // The cpes table is de-normalized. So the `First` is correct, don't be mislead. for i, cpe := range filtered { if cpe.JvnID != 0 { jvn := models.Jvn{} err = r.conn.Select("cve_id").Where("ID = ?", cpe.JvnID).First(&jvn).Error if err != nil && err != gorm.ErrRecordNotFound { return nil, err } cveIDs[i] = jvn.CveID } else if cpe.NvdXMLID != 0 { nvd := models.NvdXML{} err = r.conn.Select("cve_id").Where("ID = ?", cpe.NvdXMLID).First(&nvd).Error if err != nil && err != gorm.ErrRecordNotFound { return nil, err } cveIDs[i] = nvd.CveID } else if cpe.NvdJSONID != 0 { json := models.NvdJSON{} err = r.conn.Select("cve_id").Where("ID = ?", cpe.NvdJSONID).First(&json).Error if err != nil && err != gorm.ErrRecordNotFound { return nil, err } cveIDs[i] = json.CveID } // If we didn't find a CVE something is weird. if cveIDs[i] == "" { log.Infof("Missing cve_id for %s (id: %d)", cpe.URI, cpe.ID) } } return cveIDs, nil }
[ "func", "(", "r", "*", "RDBDriver", ")", "GetCveIDsByCpeURI", "(", "uri", "string", ")", "(", "[", "]", "string", ",", "error", ")", "{", "filtered", ",", "err", ":=", "r", ".", "getMatchingCpes", "(", "uri", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "cveIDs", ":=", "make", "(", "[", "]", "string", ",", "len", "(", "filtered", ")", ")", "\n\n", "// The cpes table is de-normalized. So the `First` is correct, don't be mislead.", "for", "i", ",", "cpe", ":=", "range", "filtered", "{", "if", "cpe", ".", "JvnID", "!=", "0", "{", "jvn", ":=", "models", ".", "Jvn", "{", "}", "\n", "err", "=", "r", ".", "conn", ".", "Select", "(", "\"", "\"", ")", ".", "Where", "(", "\"", "\"", ",", "cpe", ".", "JvnID", ")", ".", "First", "(", "&", "jvn", ")", ".", "Error", "\n", "if", "err", "!=", "nil", "&&", "err", "!=", "gorm", ".", "ErrRecordNotFound", "{", "return", "nil", ",", "err", "\n", "}", "\n", "cveIDs", "[", "i", "]", "=", "jvn", ".", "CveID", "\n", "}", "else", "if", "cpe", ".", "NvdXMLID", "!=", "0", "{", "nvd", ":=", "models", ".", "NvdXML", "{", "}", "\n", "err", "=", "r", ".", "conn", ".", "Select", "(", "\"", "\"", ")", ".", "Where", "(", "\"", "\"", ",", "cpe", ".", "NvdXMLID", ")", ".", "First", "(", "&", "nvd", ")", ".", "Error", "\n", "if", "err", "!=", "nil", "&&", "err", "!=", "gorm", ".", "ErrRecordNotFound", "{", "return", "nil", ",", "err", "\n", "}", "\n", "cveIDs", "[", "i", "]", "=", "nvd", ".", "CveID", "\n", "}", "else", "if", "cpe", ".", "NvdJSONID", "!=", "0", "{", "json", ":=", "models", ".", "NvdJSON", "{", "}", "\n", "err", "=", "r", ".", "conn", ".", "Select", "(", "\"", "\"", ")", ".", "Where", "(", "\"", "\"", ",", "cpe", ".", "NvdJSONID", ")", ".", "First", "(", "&", "json", ")", ".", "Error", "\n", "if", "err", "!=", "nil", "&&", "err", "!=", "gorm", ".", "ErrRecordNotFound", "{", "return", "nil", ",", "err", "\n", "}", "\n", "cveIDs", "[", "i", "]", "=", "json", ".", "CveID", "\n", "}", "\n\n", "// If we didn't find a CVE something is weird.", "if", "cveIDs", "[", "i", "]", "==", "\"", "\"", "{", "log", ".", "Infof", "(", "\"", "\"", ",", "cpe", ".", "URI", ",", "cpe", ".", "ID", ")", "\n", "}", "\n", "}", "\n\n", "return", "cveIDs", ",", "nil", "\n", "}" ]
// GetCveIDsByCpeURI Select Cve Ids by by pseudo-CPE
[ "GetCveIDsByCpeURI", "Select", "Cve", "Ids", "by", "by", "pseudo", "-", "CPE" ]
5fe52611f0b8dff9f95374d9cd7bdb23cc5fc67a
https://github.com/kotakanbe/go-cve-dictionary/blob/5fe52611f0b8dff9f95374d9cd7bdb23cc5fc67a/db/rdb.go#L446-L486
5,488
kotakanbe/go-cve-dictionary
db/rdb.go
GetFetchedFeedMeta
func (r *RDBDriver) GetFetchedFeedMeta(url string) (*models.FeedMeta, error) { meta := models.FeedMeta{} m := &models.FeedMeta{ URL: url, } err := r.conn.Where(m).First(&meta).Error if err != nil && err != gorm.ErrRecordNotFound { return nil, err } return &meta, nil }
go
func (r *RDBDriver) GetFetchedFeedMeta(url string) (*models.FeedMeta, error) { meta := models.FeedMeta{} m := &models.FeedMeta{ URL: url, } err := r.conn.Where(m).First(&meta).Error if err != nil && err != gorm.ErrRecordNotFound { return nil, err } return &meta, nil }
[ "func", "(", "r", "*", "RDBDriver", ")", "GetFetchedFeedMeta", "(", "url", "string", ")", "(", "*", "models", ".", "FeedMeta", ",", "error", ")", "{", "meta", ":=", "models", ".", "FeedMeta", "{", "}", "\n", "m", ":=", "&", "models", ".", "FeedMeta", "{", "URL", ":", "url", ",", "}", "\n", "err", ":=", "r", ".", "conn", ".", "Where", "(", "m", ")", ".", "First", "(", "&", "meta", ")", ".", "Error", "\n", "if", "err", "!=", "nil", "&&", "err", "!=", "gorm", ".", "ErrRecordNotFound", "{", "return", "nil", ",", "err", "\n", "}", "\n", "return", "&", "meta", ",", "nil", "\n", "}" ]
// GetFetchedFeedMeta selects fetchmeta of the year
[ "GetFetchedFeedMeta", "selects", "fetchmeta", "of", "the", "year" ]
5fe52611f0b8dff9f95374d9cd7bdb23cc5fc67a
https://github.com/kotakanbe/go-cve-dictionary/blob/5fe52611f0b8dff9f95374d9cd7bdb23cc5fc67a/db/rdb.go#L991-L1001
5,489
kotakanbe/go-cve-dictionary
db/rdb.go
UpsertFeedHash
func (r *RDBDriver) UpsertFeedHash(mm models.FeedMeta) error { meta := models.FeedMeta{} m := &models.FeedMeta{ URL: mm.URL, } err := r.conn.Where(m).First(&meta).Error if err != nil && err != gorm.ErrRecordNotFound { return err } tx := r.conn.Begin() if tx.Error != nil { return tx.Error } if err == gorm.ErrRecordNotFound { m.Hash = mm.Hash m.LastModifiedDate = mm.LastModifiedDate if err := tx.Create(m).Error; err != nil { return rollback(tx, err) } } else { meta.Hash = mm.Hash m.LastModifiedDate = mm.LastModifiedDate if err := tx.Save(&meta).Error; err != nil { return rollback(tx, err) } } if err := tx.Commit().Error; err != nil { return rollback(tx, err) } return nil }
go
func (r *RDBDriver) UpsertFeedHash(mm models.FeedMeta) error { meta := models.FeedMeta{} m := &models.FeedMeta{ URL: mm.URL, } err := r.conn.Where(m).First(&meta).Error if err != nil && err != gorm.ErrRecordNotFound { return err } tx := r.conn.Begin() if tx.Error != nil { return tx.Error } if err == gorm.ErrRecordNotFound { m.Hash = mm.Hash m.LastModifiedDate = mm.LastModifiedDate if err := tx.Create(m).Error; err != nil { return rollback(tx, err) } } else { meta.Hash = mm.Hash m.LastModifiedDate = mm.LastModifiedDate if err := tx.Save(&meta).Error; err != nil { return rollback(tx, err) } } if err := tx.Commit().Error; err != nil { return rollback(tx, err) } return nil }
[ "func", "(", "r", "*", "RDBDriver", ")", "UpsertFeedHash", "(", "mm", "models", ".", "FeedMeta", ")", "error", "{", "meta", ":=", "models", ".", "FeedMeta", "{", "}", "\n", "m", ":=", "&", "models", ".", "FeedMeta", "{", "URL", ":", "mm", ".", "URL", ",", "}", "\n", "err", ":=", "r", ".", "conn", ".", "Where", "(", "m", ")", ".", "First", "(", "&", "meta", ")", ".", "Error", "\n", "if", "err", "!=", "nil", "&&", "err", "!=", "gorm", ".", "ErrRecordNotFound", "{", "return", "err", "\n", "}", "\n\n", "tx", ":=", "r", ".", "conn", ".", "Begin", "(", ")", "\n", "if", "tx", ".", "Error", "!=", "nil", "{", "return", "tx", ".", "Error", "\n", "}", "\n\n", "if", "err", "==", "gorm", ".", "ErrRecordNotFound", "{", "m", ".", "Hash", "=", "mm", ".", "Hash", "\n", "m", ".", "LastModifiedDate", "=", "mm", ".", "LastModifiedDate", "\n", "if", "err", ":=", "tx", ".", "Create", "(", "m", ")", ".", "Error", ";", "err", "!=", "nil", "{", "return", "rollback", "(", "tx", ",", "err", ")", "\n", "}", "\n", "}", "else", "{", "meta", ".", "Hash", "=", "mm", ".", "Hash", "\n", "m", ".", "LastModifiedDate", "=", "mm", ".", "LastModifiedDate", "\n", "if", "err", ":=", "tx", ".", "Save", "(", "&", "meta", ")", ".", "Error", ";", "err", "!=", "nil", "{", "return", "rollback", "(", "tx", ",", "err", ")", "\n", "}", "\n", "}", "\n\n", "if", "err", ":=", "tx", ".", "Commit", "(", ")", ".", "Error", ";", "err", "!=", "nil", "{", "return", "rollback", "(", "tx", ",", "err", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// UpsertFeedHash selects sha1 in metafile of the year
[ "UpsertFeedHash", "selects", "sha1", "in", "metafile", "of", "the", "year" ]
5fe52611f0b8dff9f95374d9cd7bdb23cc5fc67a
https://github.com/kotakanbe/go-cve-dictionary/blob/5fe52611f0b8dff9f95374d9cd7bdb23cc5fc67a/db/rdb.go#L1004-L1037
5,490
kotakanbe/go-cve-dictionary
fetcher/fetcher.go
FetchFeedFiles
func FetchFeedFiles(reqs []FetchRequest) (results []FetchResult, err error) { reqChan := make(chan FetchRequest, len(reqs)) resChan := make(chan FetchResult, len(reqs)) errChan := make(chan error, len(reqs)) defer close(reqChan) defer close(resChan) defer close(errChan) for _, r := range reqs { log.Infof("Fetching... %s", r.URL) } go func() { for _, r := range reqs { reqChan <- r } }() concurrency := len(reqs) tasks := util.GenWorkers(concurrency) for range reqs { tasks <- func() { select { case req := <-reqChan: body, err := fetchFile(req, 20/len(reqs)) if err != nil { errChan <- err return } resChan <- FetchResult{ Year: req.Year, URL: req.URL, Body: body, } } return } } errs := []error{} timeout := time.After(10 * 60 * time.Second) for range reqs { select { case res := <-resChan: results = append(results, res) log.Infof("Fetched... %s", res.URL) case err := <-errChan: errs = append(errs, err) case <-timeout: return results, fmt.Errorf("Timeout Fetching") } } if 0 < len(errs) { return results, fmt.Errorf("%s", errs) } return results, nil }
go
func FetchFeedFiles(reqs []FetchRequest) (results []FetchResult, err error) { reqChan := make(chan FetchRequest, len(reqs)) resChan := make(chan FetchResult, len(reqs)) errChan := make(chan error, len(reqs)) defer close(reqChan) defer close(resChan) defer close(errChan) for _, r := range reqs { log.Infof("Fetching... %s", r.URL) } go func() { for _, r := range reqs { reqChan <- r } }() concurrency := len(reqs) tasks := util.GenWorkers(concurrency) for range reqs { tasks <- func() { select { case req := <-reqChan: body, err := fetchFile(req, 20/len(reqs)) if err != nil { errChan <- err return } resChan <- FetchResult{ Year: req.Year, URL: req.URL, Body: body, } } return } } errs := []error{} timeout := time.After(10 * 60 * time.Second) for range reqs { select { case res := <-resChan: results = append(results, res) log.Infof("Fetched... %s", res.URL) case err := <-errChan: errs = append(errs, err) case <-timeout: return results, fmt.Errorf("Timeout Fetching") } } if 0 < len(errs) { return results, fmt.Errorf("%s", errs) } return results, nil }
[ "func", "FetchFeedFiles", "(", "reqs", "[", "]", "FetchRequest", ")", "(", "results", "[", "]", "FetchResult", ",", "err", "error", ")", "{", "reqChan", ":=", "make", "(", "chan", "FetchRequest", ",", "len", "(", "reqs", ")", ")", "\n", "resChan", ":=", "make", "(", "chan", "FetchResult", ",", "len", "(", "reqs", ")", ")", "\n", "errChan", ":=", "make", "(", "chan", "error", ",", "len", "(", "reqs", ")", ")", "\n", "defer", "close", "(", "reqChan", ")", "\n", "defer", "close", "(", "resChan", ")", "\n", "defer", "close", "(", "errChan", ")", "\n\n", "for", "_", ",", "r", ":=", "range", "reqs", "{", "log", ".", "Infof", "(", "\"", "\"", ",", "r", ".", "URL", ")", "\n", "}", "\n\n", "go", "func", "(", ")", "{", "for", "_", ",", "r", ":=", "range", "reqs", "{", "reqChan", "<-", "r", "\n", "}", "\n", "}", "(", ")", "\n\n", "concurrency", ":=", "len", "(", "reqs", ")", "\n", "tasks", ":=", "util", ".", "GenWorkers", "(", "concurrency", ")", "\n", "for", "range", "reqs", "{", "tasks", "<-", "func", "(", ")", "{", "select", "{", "case", "req", ":=", "<-", "reqChan", ":", "body", ",", "err", ":=", "fetchFile", "(", "req", ",", "20", "/", "len", "(", "reqs", ")", ")", "\n", "if", "err", "!=", "nil", "{", "errChan", "<-", "err", "\n", "return", "\n", "}", "\n", "resChan", "<-", "FetchResult", "{", "Year", ":", "req", ".", "Year", ",", "URL", ":", "req", ".", "URL", ",", "Body", ":", "body", ",", "}", "\n", "}", "\n", "return", "\n", "}", "\n", "}", "\n\n", "errs", ":=", "[", "]", "error", "{", "}", "\n", "timeout", ":=", "time", ".", "After", "(", "10", "*", "60", "*", "time", ".", "Second", ")", "\n", "for", "range", "reqs", "{", "select", "{", "case", "res", ":=", "<-", "resChan", ":", "results", "=", "append", "(", "results", ",", "res", ")", "\n", "log", ".", "Infof", "(", "\"", "\"", ",", "res", ".", "URL", ")", "\n", "case", "err", ":=", "<-", "errChan", ":", "errs", "=", "append", "(", "errs", ",", "err", ")", "\n", "case", "<-", "timeout", ":", "return", "results", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n", "}", "\n", "if", "0", "<", "len", "(", "errs", ")", "{", "return", "results", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "errs", ")", "\n", "}", "\n", "return", "results", ",", "nil", "\n", "}" ]
//FetchFeedFiles fetches vulnerability feed file concurrently
[ "FetchFeedFiles", "fetches", "vulnerability", "feed", "file", "concurrently" ]
5fe52611f0b8dff9f95374d9cd7bdb23cc5fc67a
https://github.com/kotakanbe/go-cve-dictionary/blob/5fe52611f0b8dff9f95374d9cd7bdb23cc5fc67a/fetcher/fetcher.go#L33-L89
5,491
kotakanbe/go-cve-dictionary
util/util.go
GenWorkers
func GenWorkers(num int) chan<- func() { tasks := make(chan func()) for i := 0; i < num; i++ { go func() { for f := range tasks { f() } }() } return tasks }
go
func GenWorkers(num int) chan<- func() { tasks := make(chan func()) for i := 0; i < num; i++ { go func() { for f := range tasks { f() } }() } return tasks }
[ "func", "GenWorkers", "(", "num", "int", ")", "chan", "<-", "func", "(", ")", "{", "tasks", ":=", "make", "(", "chan", "func", "(", ")", ")", "\n", "for", "i", ":=", "0", ";", "i", "<", "num", ";", "i", "++", "{", "go", "func", "(", ")", "{", "for", "f", ":=", "range", "tasks", "{", "f", "(", ")", "\n", "}", "\n", "}", "(", ")", "\n", "}", "\n", "return", "tasks", "\n", "}" ]
// GenWorkers generate workders
[ "GenWorkers", "generate", "workders" ]
5fe52611f0b8dff9f95374d9cd7bdb23cc5fc67a
https://github.com/kotakanbe/go-cve-dictionary/blob/5fe52611f0b8dff9f95374d9cd7bdb23cc5fc67a/util/util.go#L10-L20
5,492
kotakanbe/go-cve-dictionary
util/util.go
GetDefaultLogDir
func GetDefaultLogDir() string { defaultLogDir := "/var/log/vuls" if runtime.GOOS == "windows" { defaultLogDir = filepath.Join(os.Getenv("APPDATA"), "vuls") } return defaultLogDir }
go
func GetDefaultLogDir() string { defaultLogDir := "/var/log/vuls" if runtime.GOOS == "windows" { defaultLogDir = filepath.Join(os.Getenv("APPDATA"), "vuls") } return defaultLogDir }
[ "func", "GetDefaultLogDir", "(", ")", "string", "{", "defaultLogDir", ":=", "\"", "\"", "\n", "if", "runtime", ".", "GOOS", "==", "\"", "\"", "{", "defaultLogDir", "=", "filepath", ".", "Join", "(", "os", ".", "Getenv", "(", "\"", "\"", ")", ",", "\"", "\"", ")", "\n", "}", "\n", "return", "defaultLogDir", "\n", "}" ]
// GetDefaultLogDir returns default log directory
[ "GetDefaultLogDir", "returns", "default", "log", "directory" ]
5fe52611f0b8dff9f95374d9cd7bdb23cc5fc67a
https://github.com/kotakanbe/go-cve-dictionary/blob/5fe52611f0b8dff9f95374d9cd7bdb23cc5fc67a/util/util.go#L23-L29
5,493
kotakanbe/go-cve-dictionary
fetcher/util.go
ParseCpeURI
func ParseCpeURI(uri string) (*models.CpeBase, error) { var wfn common.WellFormedName var err error if strings.HasPrefix(uri, "cpe:/") { val := strings.TrimPrefix(uri, "cpe:/") if strings.Contains(val, "/") { uri = "cpe:/" + strings.Replace(val, "/", `\/`, -1) } wfn, err = naming.UnbindURI(uri) if err != nil { return nil, err } } else { wfn, err = naming.UnbindFS(uri) if err != nil { return nil, err } } return &models.CpeBase{ URI: naming.BindToURI(wfn), FormattedString: naming.BindToFS(wfn), WellFormedName: wfn.String(), CpeWFN: models.CpeWFN{ Part: fmt.Sprintf("%s", wfn.Get(common.AttributePart)), Vendor: fmt.Sprintf("%s", wfn.Get(common.AttributeVendor)), Product: fmt.Sprintf("%s", wfn.Get(common.AttributeProduct)), Version: fmt.Sprintf("%s", wfn.Get(common.AttributeVersion)), Update: fmt.Sprintf("%s", wfn.Get(common.AttributeUpdate)), Edition: fmt.Sprintf("%s", wfn.Get(common.AttributeEdition)), Language: fmt.Sprintf("%s", wfn.Get(common.AttributeLanguage)), SoftwareEdition: fmt.Sprintf("%s", wfn.Get(common.AttributeSwEdition)), TargetSW: fmt.Sprintf("%s", wfn.Get(common.AttributeTargetSw)), TargetHW: fmt.Sprintf("%s", wfn.Get(common.AttributeTargetHw)), Other: fmt.Sprintf("%s", wfn.Get(common.AttributeOther)), }, }, nil }
go
func ParseCpeURI(uri string) (*models.CpeBase, error) { var wfn common.WellFormedName var err error if strings.HasPrefix(uri, "cpe:/") { val := strings.TrimPrefix(uri, "cpe:/") if strings.Contains(val, "/") { uri = "cpe:/" + strings.Replace(val, "/", `\/`, -1) } wfn, err = naming.UnbindURI(uri) if err != nil { return nil, err } } else { wfn, err = naming.UnbindFS(uri) if err != nil { return nil, err } } return &models.CpeBase{ URI: naming.BindToURI(wfn), FormattedString: naming.BindToFS(wfn), WellFormedName: wfn.String(), CpeWFN: models.CpeWFN{ Part: fmt.Sprintf("%s", wfn.Get(common.AttributePart)), Vendor: fmt.Sprintf("%s", wfn.Get(common.AttributeVendor)), Product: fmt.Sprintf("%s", wfn.Get(common.AttributeProduct)), Version: fmt.Sprintf("%s", wfn.Get(common.AttributeVersion)), Update: fmt.Sprintf("%s", wfn.Get(common.AttributeUpdate)), Edition: fmt.Sprintf("%s", wfn.Get(common.AttributeEdition)), Language: fmt.Sprintf("%s", wfn.Get(common.AttributeLanguage)), SoftwareEdition: fmt.Sprintf("%s", wfn.Get(common.AttributeSwEdition)), TargetSW: fmt.Sprintf("%s", wfn.Get(common.AttributeTargetSw)), TargetHW: fmt.Sprintf("%s", wfn.Get(common.AttributeTargetHw)), Other: fmt.Sprintf("%s", wfn.Get(common.AttributeOther)), }, }, nil }
[ "func", "ParseCpeURI", "(", "uri", "string", ")", "(", "*", "models", ".", "CpeBase", ",", "error", ")", "{", "var", "wfn", "common", ".", "WellFormedName", "\n", "var", "err", "error", "\n", "if", "strings", ".", "HasPrefix", "(", "uri", ",", "\"", "\"", ")", "{", "val", ":=", "strings", ".", "TrimPrefix", "(", "uri", ",", "\"", "\"", ")", "\n", "if", "strings", ".", "Contains", "(", "val", ",", "\"", "\"", ")", "{", "uri", "=", "\"", "\"", "+", "strings", ".", "Replace", "(", "val", ",", "\"", "\"", ",", "`\\/`", ",", "-", "1", ")", "\n", "}", "\n", "wfn", ",", "err", "=", "naming", ".", "UnbindURI", "(", "uri", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "}", "else", "{", "wfn", ",", "err", "=", "naming", ".", "UnbindFS", "(", "uri", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "}", "\n\n", "return", "&", "models", ".", "CpeBase", "{", "URI", ":", "naming", ".", "BindToURI", "(", "wfn", ")", ",", "FormattedString", ":", "naming", ".", "BindToFS", "(", "wfn", ")", ",", "WellFormedName", ":", "wfn", ".", "String", "(", ")", ",", "CpeWFN", ":", "models", ".", "CpeWFN", "{", "Part", ":", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "wfn", ".", "Get", "(", "common", ".", "AttributePart", ")", ")", ",", "Vendor", ":", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "wfn", ".", "Get", "(", "common", ".", "AttributeVendor", ")", ")", ",", "Product", ":", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "wfn", ".", "Get", "(", "common", ".", "AttributeProduct", ")", ")", ",", "Version", ":", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "wfn", ".", "Get", "(", "common", ".", "AttributeVersion", ")", ")", ",", "Update", ":", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "wfn", ".", "Get", "(", "common", ".", "AttributeUpdate", ")", ")", ",", "Edition", ":", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "wfn", ".", "Get", "(", "common", ".", "AttributeEdition", ")", ")", ",", "Language", ":", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "wfn", ".", "Get", "(", "common", ".", "AttributeLanguage", ")", ")", ",", "SoftwareEdition", ":", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "wfn", ".", "Get", "(", "common", ".", "AttributeSwEdition", ")", ")", ",", "TargetSW", ":", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "wfn", ".", "Get", "(", "common", ".", "AttributeTargetSw", ")", ")", ",", "TargetHW", ":", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "wfn", ".", "Get", "(", "common", ".", "AttributeTargetHw", ")", ")", ",", "Other", ":", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "wfn", ".", "Get", "(", "common", ".", "AttributeOther", ")", ")", ",", "}", ",", "}", ",", "nil", "\n", "}" ]
// ParseCpeURI parses cpe22uri and set to models.CpeBase
[ "ParseCpeURI", "parses", "cpe22uri", "and", "set", "to", "models", ".", "CpeBase" ]
5fe52611f0b8dff9f95374d9cd7bdb23cc5fc67a
https://github.com/kotakanbe/go-cve-dictionary/blob/5fe52611f0b8dff9f95374d9cd7bdb23cc5fc67a/fetcher/util.go#L15-L52
5,494
kotakanbe/go-cve-dictionary
fetcher/util.go
StringToFloat
func StringToFloat(str string) float64 { if len(str) == 0 { return 0 } var f float64 var ignorableError error if f, ignorableError = strconv.ParseFloat(str, 64); ignorableError != nil { log.Errorf("Failed to cast CVSS score. score: %s, err; %s", str, ignorableError, ) f = 0 } return f }
go
func StringToFloat(str string) float64 { if len(str) == 0 { return 0 } var f float64 var ignorableError error if f, ignorableError = strconv.ParseFloat(str, 64); ignorableError != nil { log.Errorf("Failed to cast CVSS score. score: %s, err; %s", str, ignorableError, ) f = 0 } return f }
[ "func", "StringToFloat", "(", "str", "string", ")", "float64", "{", "if", "len", "(", "str", ")", "==", "0", "{", "return", "0", "\n", "}", "\n", "var", "f", "float64", "\n", "var", "ignorableError", "error", "\n", "if", "f", ",", "ignorableError", "=", "strconv", ".", "ParseFloat", "(", "str", ",", "64", ")", ";", "ignorableError", "!=", "nil", "{", "log", ".", "Errorf", "(", "\"", "\"", ",", "str", ",", "ignorableError", ",", ")", "\n", "f", "=", "0", "\n", "}", "\n", "return", "f", "\n", "}" ]
// StringToFloat cast string to float64
[ "StringToFloat", "cast", "string", "to", "float64" ]
5fe52611f0b8dff9f95374d9cd7bdb23cc5fc67a
https://github.com/kotakanbe/go-cve-dictionary/blob/5fe52611f0b8dff9f95374d9cd7bdb23cc5fc67a/fetcher/util.go#L55-L69
5,495
kotakanbe/go-cve-dictionary
db/db.go
NewDB
func NewDB(dbType, dbpath string, debugSQL bool) (DB, bool, error) { switch dbType { case dialectSqlite3, dialectMysql, dialectPostgreSQL: return NewRDB(dbType, dbpath, debugSQL) case dialectRedis: return NewRedis(dbType, dbpath, debugSQL) } return nil, false, fmt.Errorf("Invalid database dialect, %s", dbType) }
go
func NewDB(dbType, dbpath string, debugSQL bool) (DB, bool, error) { switch dbType { case dialectSqlite3, dialectMysql, dialectPostgreSQL: return NewRDB(dbType, dbpath, debugSQL) case dialectRedis: return NewRedis(dbType, dbpath, debugSQL) } return nil, false, fmt.Errorf("Invalid database dialect, %s", dbType) }
[ "func", "NewDB", "(", "dbType", ",", "dbpath", "string", ",", "debugSQL", "bool", ")", "(", "DB", ",", "bool", ",", "error", ")", "{", "switch", "dbType", "{", "case", "dialectSqlite3", ",", "dialectMysql", ",", "dialectPostgreSQL", ":", "return", "NewRDB", "(", "dbType", ",", "dbpath", ",", "debugSQL", ")", "\n", "case", "dialectRedis", ":", "return", "NewRedis", "(", "dbType", ",", "dbpath", ",", "debugSQL", ")", "\n", "}", "\n", "return", "nil", ",", "false", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "dbType", ")", "\n", "}" ]
// NewDB return DB accessor.
[ "NewDB", "return", "DB", "accessor", "." ]
5fe52611f0b8dff9f95374d9cd7bdb23cc5fc67a
https://github.com/kotakanbe/go-cve-dictionary/blob/5fe52611f0b8dff9f95374d9cd7bdb23cc5fc67a/db/db.go#L35-L43
5,496
kotakanbe/go-cve-dictionary
config/config.go
Validate
func (c *Config) Validate() bool { if c.DBType == "sqlite3" { if ok, _ := valid.IsFilePath(c.DBPath); !ok { log.Errorf("SQLite3 DB path must be a *Absolute* file path. dbpath: %s", c.DBPath) return false } } if len(c.DumpPath) != 0 { if ok, _ := valid.IsFilePath(c.DumpPath); !ok { log.Errorf("JSON path must be a *Absolute* file path. dumppath: %s", c.DumpPath) return false } } _, err := valid.ValidateStruct(c) if err != nil { log.Errorf("error: " + err.Error()) return false } return true }
go
func (c *Config) Validate() bool { if c.DBType == "sqlite3" { if ok, _ := valid.IsFilePath(c.DBPath); !ok { log.Errorf("SQLite3 DB path must be a *Absolute* file path. dbpath: %s", c.DBPath) return false } } if len(c.DumpPath) != 0 { if ok, _ := valid.IsFilePath(c.DumpPath); !ok { log.Errorf("JSON path must be a *Absolute* file path. dumppath: %s", c.DumpPath) return false } } _, err := valid.ValidateStruct(c) if err != nil { log.Errorf("error: " + err.Error()) return false } return true }
[ "func", "(", "c", "*", "Config", ")", "Validate", "(", ")", "bool", "{", "if", "c", ".", "DBType", "==", "\"", "\"", "{", "if", "ok", ",", "_", ":=", "valid", ".", "IsFilePath", "(", "c", ".", "DBPath", ")", ";", "!", "ok", "{", "log", ".", "Errorf", "(", "\"", "\"", ",", "c", ".", "DBPath", ")", "\n", "return", "false", "\n", "}", "\n", "}", "\n\n", "if", "len", "(", "c", ".", "DumpPath", ")", "!=", "0", "{", "if", "ok", ",", "_", ":=", "valid", ".", "IsFilePath", "(", "c", ".", "DumpPath", ")", ";", "!", "ok", "{", "log", ".", "Errorf", "(", "\"", "\"", ",", "c", ".", "DumpPath", ")", "\n", "return", "false", "\n", "}", "\n", "}", "\n\n", "_", ",", "err", ":=", "valid", ".", "ValidateStruct", "(", "c", ")", "\n", "if", "err", "!=", "nil", "{", "log", ".", "Errorf", "(", "\"", "\"", "+", "err", ".", "Error", "(", ")", ")", "\n", "return", "false", "\n", "}", "\n", "return", "true", "\n", "}" ]
// Validate validates configuration
[ "Validate", "validates", "configuration" ]
5fe52611f0b8dff9f95374d9cd7bdb23cc5fc67a
https://github.com/kotakanbe/go-cve-dictionary/blob/5fe52611f0b8dff9f95374d9cd7bdb23cc5fc67a/config/config.go#L39-L60
5,497
kotakanbe/go-cve-dictionary
fetcher/jvn/xml/jvn.go
Fetch
func Fetch(metas []models.FeedMeta) ([]Item, error) { reqs := []fetcher.FetchRequest{} for _, meta := range metas { reqs = append(reqs, fetcher.FetchRequest{ URL: meta.URL, }) } results, err := fetcher.FetchFeedFiles(reqs) if err != nil { return nil, fmt.Errorf("Failed to fetch. err: %s", err) } items := []Item{} for _, res := range results { var rdf rdf if err = xml.Unmarshal([]byte(res.Body), &rdf); err != nil { return nil, fmt.Errorf( "Failed to unmarshal. url: %s, err: %s", res.URL, err) } items = append(items, rdf.Items...) } return items, nil }
go
func Fetch(metas []models.FeedMeta) ([]Item, error) { reqs := []fetcher.FetchRequest{} for _, meta := range metas { reqs = append(reqs, fetcher.FetchRequest{ URL: meta.URL, }) } results, err := fetcher.FetchFeedFiles(reqs) if err != nil { return nil, fmt.Errorf("Failed to fetch. err: %s", err) } items := []Item{} for _, res := range results { var rdf rdf if err = xml.Unmarshal([]byte(res.Body), &rdf); err != nil { return nil, fmt.Errorf( "Failed to unmarshal. url: %s, err: %s", res.URL, err) } items = append(items, rdf.Items...) } return items, nil }
[ "func", "Fetch", "(", "metas", "[", "]", "models", ".", "FeedMeta", ")", "(", "[", "]", "Item", ",", "error", ")", "{", "reqs", ":=", "[", "]", "fetcher", ".", "FetchRequest", "{", "}", "\n", "for", "_", ",", "meta", ":=", "range", "metas", "{", "reqs", "=", "append", "(", "reqs", ",", "fetcher", ".", "FetchRequest", "{", "URL", ":", "meta", ".", "URL", ",", "}", ")", "\n", "}", "\n\n", "results", ",", "err", ":=", "fetcher", ".", "FetchFeedFiles", "(", "reqs", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n\n", "items", ":=", "[", "]", "Item", "{", "}", "\n", "for", "_", ",", "res", ":=", "range", "results", "{", "var", "rdf", "rdf", "\n", "if", "err", "=", "xml", ".", "Unmarshal", "(", "[", "]", "byte", "(", "res", ".", "Body", ")", ",", "&", "rdf", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "res", ".", "URL", ",", "err", ")", "\n", "}", "\n", "items", "=", "append", "(", "items", ",", "rdf", ".", "Items", "...", ")", "\n", "}", "\n", "return", "items", ",", "nil", "\n\n", "}" ]
// Fetch fetches vulnerability information from JVN and convert it to model
[ "Fetch", "fetches", "vulnerability", "information", "from", "JVN", "and", "convert", "it", "to", "model" ]
5fe52611f0b8dff9f95374d9cd7bdb23cc5fc67a
https://github.com/kotakanbe/go-cve-dictionary/blob/5fe52611f0b8dff9f95374d9cd7bdb23cc5fc67a/fetcher/jvn/xml/jvn.go#L176-L201
5,498
kotakanbe/go-cve-dictionary
fetcher/jvn/xml/jvn.go
FetchConvert
func FetchConvert(metas []models.FeedMeta) (cves []models.CveDetail, err error) { items, err := Fetch(metas) if err != nil { return nil, err } return convert(items) }
go
func FetchConvert(metas []models.FeedMeta) (cves []models.CveDetail, err error) { items, err := Fetch(metas) if err != nil { return nil, err } return convert(items) }
[ "func", "FetchConvert", "(", "metas", "[", "]", "models", ".", "FeedMeta", ")", "(", "cves", "[", "]", "models", ".", "CveDetail", ",", "err", "error", ")", "{", "items", ",", "err", ":=", "Fetch", "(", "metas", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "return", "convert", "(", "items", ")", "\n", "}" ]
// FetchConvert fetches vulnerability information from JVN and convert it to model
[ "FetchConvert", "fetches", "vulnerability", "information", "from", "JVN", "and", "convert", "it", "to", "model" ]
5fe52611f0b8dff9f95374d9cd7bdb23cc5fc67a
https://github.com/kotakanbe/go-cve-dictionary/blob/5fe52611f0b8dff9f95374d9cd7bdb23cc5fc67a/fetcher/jvn/xml/jvn.go#L204-L210
5,499
kotakanbe/go-cve-dictionary
fetcher/nvd/xml/nvd.go
FetchConvert
func FetchConvert(metas []models.FeedMeta) (cves []models.CveDetail, err error) { reqs := []fetcher.FetchRequest{} for _, meta := range metas { reqs = append(reqs, fetcher.FetchRequest{ URL: meta.URL, GZIP: true, }) } results, err := fetcher.FetchFeedFiles(reqs) if err != nil { return nil, fmt.Errorf("Failed to fetch. err: %s", err) } for _, res := range results { nvd := NvdXML{} if err = xml.Unmarshal(res.Body, &nvd); err != nil { return nil, fmt.Errorf( "Failed to unmarshal. url: %s, err: %s", res.URL, err) } for _, e := range nvd.Entries { cve, err := convertToModel(e) if err != nil { return nil, fmt.Errorf("Failed to convert to model. cve: %s, err: %s", e.CveID, err) } cves = append(cves, *cve) } } return }
go
func FetchConvert(metas []models.FeedMeta) (cves []models.CveDetail, err error) { reqs := []fetcher.FetchRequest{} for _, meta := range metas { reqs = append(reqs, fetcher.FetchRequest{ URL: meta.URL, GZIP: true, }) } results, err := fetcher.FetchFeedFiles(reqs) if err != nil { return nil, fmt.Errorf("Failed to fetch. err: %s", err) } for _, res := range results { nvd := NvdXML{} if err = xml.Unmarshal(res.Body, &nvd); err != nil { return nil, fmt.Errorf( "Failed to unmarshal. url: %s, err: %s", res.URL, err) } for _, e := range nvd.Entries { cve, err := convertToModel(e) if err != nil { return nil, fmt.Errorf("Failed to convert to model. cve: %s, err: %s", e.CveID, err) } cves = append(cves, *cve) } } return }
[ "func", "FetchConvert", "(", "metas", "[", "]", "models", ".", "FeedMeta", ")", "(", "cves", "[", "]", "models", ".", "CveDetail", ",", "err", "error", ")", "{", "reqs", ":=", "[", "]", "fetcher", ".", "FetchRequest", "{", "}", "\n", "for", "_", ",", "meta", ":=", "range", "metas", "{", "reqs", "=", "append", "(", "reqs", ",", "fetcher", ".", "FetchRequest", "{", "URL", ":", "meta", ".", "URL", ",", "GZIP", ":", "true", ",", "}", ")", "\n", "}", "\n\n", "results", ",", "err", ":=", "fetcher", ".", "FetchFeedFiles", "(", "reqs", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n\n", "for", "_", ",", "res", ":=", "range", "results", "{", "nvd", ":=", "NvdXML", "{", "}", "\n", "if", "err", "=", "xml", ".", "Unmarshal", "(", "res", ".", "Body", ",", "&", "nvd", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "res", ".", "URL", ",", "err", ")", "\n", "}", "\n", "for", "_", ",", "e", ":=", "range", "nvd", ".", "Entries", "{", "cve", ",", "err", ":=", "convertToModel", "(", "e", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "e", ".", "CveID", ",", "err", ")", "\n", "}", "\n", "cves", "=", "append", "(", "cves", ",", "*", "cve", ")", "\n", "}", "\n", "}", "\n", "return", "\n", "}" ]
// FetchConvert Fetch CVE vulnerability informatino from JVN
[ "FetchConvert", "Fetch", "CVE", "vulnerability", "informatino", "from", "JVN" ]
5fe52611f0b8dff9f95374d9cd7bdb23cc5fc67a
https://github.com/kotakanbe/go-cve-dictionary/blob/5fe52611f0b8dff9f95374d9cd7bdb23cc5fc67a/fetcher/nvd/xml/nvd.go#L61-L93