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
listlengths
21
1.41k
docstring
stringlengths
6
2.61k
docstring_tokens
listlengths
3
215
sha
stringlengths
40
40
url
stringlengths
85
252
153,000
mssola/user_agent
user_agent.go
initialize
func (p *UserAgent) initialize() { p.ua = "" p.mozilla = "" p.platform = "" p.os = "" p.localization = "" p.browser.Engine = "" p.browser.EngineVersion = "" p.browser.Name = "" p.browser.Version = "" p.bot = false p.mobile = false p.undecided = false }
go
func (p *UserAgent) initialize() { p.ua = "" p.mozilla = "" p.platform = "" p.os = "" p.localization = "" p.browser.Engine = "" p.browser.EngineVersion = "" p.browser.Name = "" p.browser.Version = "" p.bot = false p.mobile = false p.undecided = false }
[ "func", "(", "p", "*", "UserAgent", ")", "initialize", "(", ")", "{", "p", ".", "ua", "=", "\"", "\"", "\n", "p", ".", "mozilla", "=", "\"", "\"", "\n", "p", ".", "platform", "=", "\"", "\"", "\n", "p", ".", "os", "=", "\"", "\"", "\n", "p"...
// Initialize the parser.
[ "Initialize", "the", "parser", "." ]
74451004a1beb37221bccd8a3931c6acf4a2e80e
https://github.com/mssola/user_agent/blob/74451004a1beb37221bccd8a3931c6acf4a2e80e/user_agent.go#L113-L126
153,001
mssola/user_agent
user_agent.go
New
func New(ua string) *UserAgent { o := &UserAgent{} o.Parse(ua) return o }
go
func New(ua string) *UserAgent { o := &UserAgent{} o.Parse(ua) return o }
[ "func", "New", "(", "ua", "string", ")", "*", "UserAgent", "{", "o", ":=", "&", "UserAgent", "{", "}", "\n", "o", ".", "Parse", "(", "ua", ")", "\n", "return", "o", "\n", "}" ]
// Parse the given User-Agent string and get the resulting UserAgent object. // // Returns an UserAgent object that has been initialized after parsing // the given User-Agent string.
[ "Parse", "the", "given", "User", "-", "Agent", "string", "and", "get", "the", "resulting", "UserAgent", "object", ".", "Returns", "an", "UserAgent", "object", "that", "has", "been", "initialized", "after", "parsing", "the", "given", "User", "-", "Agent", "st...
74451004a1beb37221bccd8a3931c6acf4a2e80e
https://github.com/mssola/user_agent/blob/74451004a1beb37221bccd8a3931c6acf4a2e80e/user_agent.go#L132-L136
153,002
mssola/user_agent
user_agent.go
Parse
func (p *UserAgent) Parse(ua string) { var sections []section p.initialize() p.ua = ua for index, limit := 0, len(ua); index < limit; { s := parseSection(ua, &index) if !p.mobile && s.name == "Mobile" { p.mobile = true } sections = append(sections, s) } if len(sections) > 0 { if sections[0].name == "Mozilla" { p.mozilla = sections[0].version } p.detectBrowser(sections) p.detectOS(sections[0]) if p.undecided { p.checkBot(sections) } } }
go
func (p *UserAgent) Parse(ua string) { var sections []section p.initialize() p.ua = ua for index, limit := 0, len(ua); index < limit; { s := parseSection(ua, &index) if !p.mobile && s.name == "Mobile" { p.mobile = true } sections = append(sections, s) } if len(sections) > 0 { if sections[0].name == "Mozilla" { p.mozilla = sections[0].version } p.detectBrowser(sections) p.detectOS(sections[0]) if p.undecided { p.checkBot(sections) } } }
[ "func", "(", "p", "*", "UserAgent", ")", "Parse", "(", "ua", "string", ")", "{", "var", "sections", "[", "]", "section", "\n\n", "p", ".", "initialize", "(", ")", "\n", "p", ".", "ua", "=", "ua", "\n", "for", "index", ",", "limit", ":=", "0", "...
// Parse the given User-Agent string. After calling this function, the // receiver will be setted up with all the information that we've extracted.
[ "Parse", "the", "given", "User", "-", "Agent", "string", ".", "After", "calling", "this", "function", "the", "receiver", "will", "be", "setted", "up", "with", "all", "the", "information", "that", "we", "ve", "extracted", "." ]
74451004a1beb37221bccd8a3931c6acf4a2e80e
https://github.com/mssola/user_agent/blob/74451004a1beb37221bccd8a3931c6acf4a2e80e/user_agent.go#L140-L165
153,003
mssola/user_agent
bot.go
getFromSite
func getFromSite(comment []string) string { if len(comment) == 0 { return "" } // Where we should check the website. idx := 2 if len(comment) < 3 { idx = 0 } else if len(comment) == 4 { idx = 3 } // Pick the site. results := botFromSiteRegexp.FindStringSubmatch(comment[idx]) if len(results) == 1 { // If it's a simple comment, just return the name of the site. if idx == 0 { return results[0] } // This is a large comment, usually the name will be in the previous // field of the comment. return strings.TrimSpace(comment[idx-1]) } return "" }
go
func getFromSite(comment []string) string { if len(comment) == 0 { return "" } // Where we should check the website. idx := 2 if len(comment) < 3 { idx = 0 } else if len(comment) == 4 { idx = 3 } // Pick the site. results := botFromSiteRegexp.FindStringSubmatch(comment[idx]) if len(results) == 1 { // If it's a simple comment, just return the name of the site. if idx == 0 { return results[0] } // This is a large comment, usually the name will be in the previous // field of the comment. return strings.TrimSpace(comment[idx-1]) } return "" }
[ "func", "getFromSite", "(", "comment", "[", "]", "string", ")", "string", "{", "if", "len", "(", "comment", ")", "==", "0", "{", "return", "\"", "\"", "\n", "}", "\n\n", "// Where we should check the website.", "idx", ":=", "2", "\n", "if", "len", "(", ...
// Get the name of the bot from the website that may be in the given comment. If // there is no website in the comment, then an empty string is returned.
[ "Get", "the", "name", "of", "the", "bot", "from", "the", "website", "that", "may", "be", "in", "the", "given", "comment", ".", "If", "there", "is", "no", "website", "in", "the", "comment", "then", "an", "empty", "string", "is", "returned", "." ]
74451004a1beb37221bccd8a3931c6acf4a2e80e
https://github.com/mssola/user_agent/blob/74451004a1beb37221bccd8a3931c6acf4a2e80e/bot.go#L16-L42
153,004
mssola/user_agent
bot.go
googleBot
func (p *UserAgent) googleBot() bool { // This is a hackish way to detect Google's mobile bot (Googlebot, AdsBot-Google-Mobile, etc.). // See https://support.google.com/webmasters/answer/1061943 if strings.Index(p.ua, "Google") != -1 { p.platform = "" p.undecided = true } return p.undecided }
go
func (p *UserAgent) googleBot() bool { // This is a hackish way to detect Google's mobile bot (Googlebot, AdsBot-Google-Mobile, etc.). // See https://support.google.com/webmasters/answer/1061943 if strings.Index(p.ua, "Google") != -1 { p.platform = "" p.undecided = true } return p.undecided }
[ "func", "(", "p", "*", "UserAgent", ")", "googleBot", "(", ")", "bool", "{", "// This is a hackish way to detect Google's mobile bot (Googlebot, AdsBot-Google-Mobile, etc.).", "// See https://support.google.com/webmasters/answer/1061943", "if", "strings", ".", "Index", "(", "p", ...
// Returns true if the info that we currently have corresponds to the Google // mobile bot. This function also modifies some attributes in the receiver // accordingly.
[ "Returns", "true", "if", "the", "info", "that", "we", "currently", "have", "corresponds", "to", "the", "Google", "mobile", "bot", ".", "This", "function", "also", "modifies", "some", "attributes", "in", "the", "receiver", "accordingly", "." ]
74451004a1beb37221bccd8a3931c6acf4a2e80e
https://github.com/mssola/user_agent/blob/74451004a1beb37221bccd8a3931c6acf4a2e80e/bot.go#L47-L55
153,005
mssola/user_agent
bot.go
setSimple
func (p *UserAgent) setSimple(name, version string, bot bool) { p.bot = bot if !bot { p.mozilla = "" } p.browser.Name = name p.browser.Version = version p.browser.Engine = "" p.browser.EngineVersion = "" p.os = "" p.localization = "" }
go
func (p *UserAgent) setSimple(name, version string, bot bool) { p.bot = bot if !bot { p.mozilla = "" } p.browser.Name = name p.browser.Version = version p.browser.Engine = "" p.browser.EngineVersion = "" p.os = "" p.localization = "" }
[ "func", "(", "p", "*", "UserAgent", ")", "setSimple", "(", "name", ",", "version", "string", ",", "bot", "bool", ")", "{", "p", ".", "bot", "=", "bot", "\n", "if", "!", "bot", "{", "p", ".", "mozilla", "=", "\"", "\"", "\n", "}", "\n", "p", "...
// Set the attributes of the receiver as given by the parameters. All the other // parameters are set to empty.
[ "Set", "the", "attributes", "of", "the", "receiver", "as", "given", "by", "the", "parameters", ".", "All", "the", "other", "parameters", "are", "set", "to", "empty", "." ]
74451004a1beb37221bccd8a3931c6acf4a2e80e
https://github.com/mssola/user_agent/blob/74451004a1beb37221bccd8a3931c6acf4a2e80e/bot.go#L59-L70
153,006
mssola/user_agent
bot.go
fixOther
func (p *UserAgent) fixOther(sections []section) { if len(sections) > 0 { p.browser.Name = sections[0].name p.browser.Version = sections[0].version p.mozilla = "" } }
go
func (p *UserAgent) fixOther(sections []section) { if len(sections) > 0 { p.browser.Name = sections[0].name p.browser.Version = sections[0].version p.mozilla = "" } }
[ "func", "(", "p", "*", "UserAgent", ")", "fixOther", "(", "sections", "[", "]", "section", ")", "{", "if", "len", "(", "sections", ")", ">", "0", "{", "p", ".", "browser", ".", "Name", "=", "sections", "[", "0", "]", ".", "name", "\n", "p", "."...
// Fix some values for some weird browsers.
[ "Fix", "some", "values", "for", "some", "weird", "browsers", "." ]
74451004a1beb37221bccd8a3931c6acf4a2e80e
https://github.com/mssola/user_agent/blob/74451004a1beb37221bccd8a3931c6acf4a2e80e/bot.go#L73-L79
153,007
mssola/user_agent
bot.go
checkBot
func (p *UserAgent) checkBot(sections []section) { // If there's only one element, and it's doesn't have the Mozilla string, // check whether this is a bot or not. if len(sections) == 1 && sections[0].name != "Mozilla" { p.mozilla = "" // Check whether the name has some suspicious "bot" or "crawler" in his name. if botRegex.Match([]byte(sections[0].name)) { p.setSimple(sections[0].name, "", true) return } // Tough luck, let's try to see if it has a website in his comment. if name := getFromSite(sections[0].comment); name != "" { // First of all, this is a bot. Moreover, since it doesn't have the // Mozilla string, we can assume that the name and the version are // the ones from the first section. p.setSimple(sections[0].name, sections[0].version, true) return } // At this point we are sure that this is not a bot, but some weirdo. p.setSimple(sections[0].name, sections[0].version, false) } else { // Let's iterate over the available comments and check for a website. for _, v := range sections { if name := getFromSite(v.comment); name != "" { // Ok, we've got a bot name. results := strings.SplitN(name, "/", 2) version := "" if len(results) == 2 { version = results[1] } p.setSimple(results[0], version, true) return } } // We will assume that this is some other weird browser. p.fixOther(sections) } }
go
func (p *UserAgent) checkBot(sections []section) { // If there's only one element, and it's doesn't have the Mozilla string, // check whether this is a bot or not. if len(sections) == 1 && sections[0].name != "Mozilla" { p.mozilla = "" // Check whether the name has some suspicious "bot" or "crawler" in his name. if botRegex.Match([]byte(sections[0].name)) { p.setSimple(sections[0].name, "", true) return } // Tough luck, let's try to see if it has a website in his comment. if name := getFromSite(sections[0].comment); name != "" { // First of all, this is a bot. Moreover, since it doesn't have the // Mozilla string, we can assume that the name and the version are // the ones from the first section. p.setSimple(sections[0].name, sections[0].version, true) return } // At this point we are sure that this is not a bot, but some weirdo. p.setSimple(sections[0].name, sections[0].version, false) } else { // Let's iterate over the available comments and check for a website. for _, v := range sections { if name := getFromSite(v.comment); name != "" { // Ok, we've got a bot name. results := strings.SplitN(name, "/", 2) version := "" if len(results) == 2 { version = results[1] } p.setSimple(results[0], version, true) return } } // We will assume that this is some other weird browser. p.fixOther(sections) } }
[ "func", "(", "p", "*", "UserAgent", ")", "checkBot", "(", "sections", "[", "]", "section", ")", "{", "// If there's only one element, and it's doesn't have the Mozilla string,", "// check whether this is a bot or not.", "if", "len", "(", "sections", ")", "==", "1", "&&"...
// Check if we're dealing with a bot or with some weird browser. If that is the // case, the receiver will be modified accordingly.
[ "Check", "if", "we", "re", "dealing", "with", "a", "bot", "or", "with", "some", "weird", "browser", ".", "If", "that", "is", "the", "case", "the", "receiver", "will", "be", "modified", "accordingly", "." ]
74451004a1beb37221bccd8a3931c6acf4a2e80e
https://github.com/mssola/user_agent/blob/74451004a1beb37221bccd8a3931c6acf4a2e80e/bot.go#L85-L126
153,008
minio/highwayhash
highwayhash.go
New
func New(key []byte) (hash.Hash, error) { if len(key) != Size { return nil, errKeySize } h := &digest{size: Size} copy(h.key[:], key) h.Reset() return h, nil }
go
func New(key []byte) (hash.Hash, error) { if len(key) != Size { return nil, errKeySize } h := &digest{size: Size} copy(h.key[:], key) h.Reset() return h, nil }
[ "func", "New", "(", "key", "[", "]", "byte", ")", "(", "hash", ".", "Hash", ",", "error", ")", "{", "if", "len", "(", "key", ")", "!=", "Size", "{", "return", "nil", ",", "errKeySize", "\n", "}", "\n", "h", ":=", "&", "digest", "{", "size", "...
// New returns a hash.Hash computing the HighwayHash-256 checksum. // It returns a non-nil error if the key is not 32 bytes long.
[ "New", "returns", "a", "hash", ".", "Hash", "computing", "the", "HighwayHash", "-", "256", "checksum", ".", "It", "returns", "a", "non", "-", "nil", "error", "if", "the", "key", "is", "not", "32", "bytes", "long", "." ]
02ca4b43caa3297fbb615700d8800acc7933be98
https://github.com/minio/highwayhash/blob/02ca4b43caa3297fbb615700d8800acc7933be98/highwayhash.go#L32-L40
153,009
minio/highwayhash
highwayhash.go
New64
func New64(key []byte) (hash.Hash64, error) { if len(key) != Size { return nil, errKeySize } h := new(digest64) h.size = Size64 copy(h.key[:], key) h.Reset() return h, nil }
go
func New64(key []byte) (hash.Hash64, error) { if len(key) != Size { return nil, errKeySize } h := new(digest64) h.size = Size64 copy(h.key[:], key) h.Reset() return h, nil }
[ "func", "New64", "(", "key", "[", "]", "byte", ")", "(", "hash", ".", "Hash64", ",", "error", ")", "{", "if", "len", "(", "key", ")", "!=", "Size", "{", "return", "nil", ",", "errKeySize", "\n", "}", "\n", "h", ":=", "new", "(", "digest64", ")"...
// New64 returns a hash.Hash computing the HighwayHash-64 checksum. // It returns a non-nil error if the key is not 32 bytes long.
[ "New64", "returns", "a", "hash", ".", "Hash", "computing", "the", "HighwayHash", "-", "64", "checksum", ".", "It", "returns", "a", "non", "-", "nil", "error", "if", "the", "key", "is", "not", "32", "bytes", "long", "." ]
02ca4b43caa3297fbb615700d8800acc7933be98
https://github.com/minio/highwayhash/blob/02ca4b43caa3297fbb615700d8800acc7933be98/highwayhash.go#L56-L65
153,010
minio/highwayhash
highwayhash.go
Sum
func Sum(data, key []byte) [Size]byte { if len(key) != Size { panic(errKeySize) } var state [16]uint64 initialize(&state, key) if n := len(data) & (^(Size - 1)); n > 0 { update(&state, data[:n]) data = data[n:] } if len(data) > 0 { var block [Size]byte offset := copy(block[:], data) hashBuffer(&state, &block, offset) } var hash [Size]byte finalize(hash[:], &state) return hash }
go
func Sum(data, key []byte) [Size]byte { if len(key) != Size { panic(errKeySize) } var state [16]uint64 initialize(&state, key) if n := len(data) & (^(Size - 1)); n > 0 { update(&state, data[:n]) data = data[n:] } if len(data) > 0 { var block [Size]byte offset := copy(block[:], data) hashBuffer(&state, &block, offset) } var hash [Size]byte finalize(hash[:], &state) return hash }
[ "func", "Sum", "(", "data", ",", "key", "[", "]", "byte", ")", "[", "Size", "]", "byte", "{", "if", "len", "(", "key", ")", "!=", "Size", "{", "panic", "(", "errKeySize", ")", "\n", "}", "\n", "var", "state", "[", "16", "]", "uint64", "\n", "...
// Sum computes the HighwayHash-256 checksum of data. // It panics if the key is not 32 bytes long.
[ "Sum", "computes", "the", "HighwayHash", "-", "256", "checksum", "of", "data", ".", "It", "panics", "if", "the", "key", "is", "not", "32", "bytes", "long", "." ]
02ca4b43caa3297fbb615700d8800acc7933be98
https://github.com/minio/highwayhash/blob/02ca4b43caa3297fbb615700d8800acc7933be98/highwayhash.go#L69-L87
153,011
minio/highwayhash
highwayhash.go
Sum64
func Sum64(data, key []byte) uint64 { if len(key) != Size { panic(errKeySize) } var state [16]uint64 initialize(&state, key) if n := len(data) & (^(Size - 1)); n > 0 { update(&state, data[:n]) data = data[n:] } if len(data) > 0 { var block [Size]byte offset := copy(block[:], data) hashBuffer(&state, &block, offset) } var hash [Size64]byte finalize(hash[:], &state) return binary.LittleEndian.Uint64(hash[:]) }
go
func Sum64(data, key []byte) uint64 { if len(key) != Size { panic(errKeySize) } var state [16]uint64 initialize(&state, key) if n := len(data) & (^(Size - 1)); n > 0 { update(&state, data[:n]) data = data[n:] } if len(data) > 0 { var block [Size]byte offset := copy(block[:], data) hashBuffer(&state, &block, offset) } var hash [Size64]byte finalize(hash[:], &state) return binary.LittleEndian.Uint64(hash[:]) }
[ "func", "Sum64", "(", "data", ",", "key", "[", "]", "byte", ")", "uint64", "{", "if", "len", "(", "key", ")", "!=", "Size", "{", "panic", "(", "errKeySize", ")", "\n", "}", "\n", "var", "state", "[", "16", "]", "uint64", "\n", "initialize", "(", ...
// Sum64 computes the HighwayHash-64 checksum of data. // It panics if the key is not 32 bytes long.
[ "Sum64", "computes", "the", "HighwayHash", "-", "64", "checksum", "of", "data", ".", "It", "panics", "if", "the", "key", "is", "not", "32", "bytes", "long", "." ]
02ca4b43caa3297fbb615700d8800acc7933be98
https://github.com/minio/highwayhash/blob/02ca4b43caa3297fbb615700d8800acc7933be98/highwayhash.go#L113-L131
153,012
chasex/redis-go-cluster
batch.go
NewBatch
func (cluster *Cluster) NewBatch() *Batch { return &Batch{ cluster: cluster, batches: make([]nodeBatch, 0), index: make([]int, 0), } }
go
func (cluster *Cluster) NewBatch() *Batch { return &Batch{ cluster: cluster, batches: make([]nodeBatch, 0), index: make([]int, 0), } }
[ "func", "(", "cluster", "*", "Cluster", ")", "NewBatch", "(", ")", "*", "Batch", "{", "return", "&", "Batch", "{", "cluster", ":", "cluster", ",", "batches", ":", "make", "(", "[", "]", "nodeBatch", ",", "0", ")", ",", "index", ":", "make", "(", ...
// NewBatch create a new batch to pack mutiple commands.
[ "NewBatch", "create", "a", "new", "batch", "to", "pack", "mutiple", "commands", "." ]
222d81891f1d3fa7cf8b5655020352c3e5b4ec0f
https://github.com/chasex/redis-go-cluster/blob/222d81891f1d3fa7cf8b5655020352c3e5b4ec0f/batch.go#L44-L50
153,013
chasex/redis-go-cluster
batch.go
RunBatch
func (cluster *Cluster) RunBatch(bat *Batch) ([]interface{}, error) { for i := range bat.batches { go doBatch(&bat.batches[i]) } for i := range bat.batches { <-bat.batches[i].done } var replies []interface{} for _, i := range bat.index { if bat.batches[i].err != nil { return nil, bat.batches[i].err } replies = append(replies, bat.batches[i].cmds[0].reply) bat.batches[i].cmds = bat.batches[i].cmds[1:] } return replies, nil }
go
func (cluster *Cluster) RunBatch(bat *Batch) ([]interface{}, error) { for i := range bat.batches { go doBatch(&bat.batches[i]) } for i := range bat.batches { <-bat.batches[i].done } var replies []interface{} for _, i := range bat.index { if bat.batches[i].err != nil { return nil, bat.batches[i].err } replies = append(replies, bat.batches[i].cmds[0].reply) bat.batches[i].cmds = bat.batches[i].cmds[1:] } return replies, nil }
[ "func", "(", "cluster", "*", "Cluster", ")", "RunBatch", "(", "bat", "*", "Batch", ")", "(", "[", "]", "interface", "{", "}", ",", "error", ")", "{", "for", "i", ":=", "range", "bat", ".", "batches", "{", "go", "doBatch", "(", "&", "bat", ".", ...
// RunBatch execute commands in batch simutaneously. If multiple commands are // directed to the same node, they will be merged and sent at once using pipeling.
[ "RunBatch", "execute", "commands", "in", "batch", "simutaneously", ".", "If", "multiple", "commands", "are", "directed", "to", "the", "same", "node", "they", "will", "be", "merged", "and", "sent", "at", "once", "using", "pipeling", "." ]
222d81891f1d3fa7cf8b5655020352c3e5b4ec0f
https://github.com/chasex/redis-go-cluster/blob/222d81891f1d3fa7cf8b5655020352c3e5b4ec0f/batch.go#L92-L112
153,014
chasex/redis-go-cluster
node.go
readLine
func (conn *redisConn) readLine() ([]byte, error) { var line []byte for { p, err := conn.br.ReadBytes('\n') if err != nil { return nil, err } n := len(p) - 2 if n < 0 { return nil, errors.New("invalid response") } // bulk string may contain '\n', such as CLUSTER NODES if p[n] != '\r' { if line != nil { line = append(line, p[:]...) } else { line = p } continue } if line != nil { return append(line, p[:n]...), nil } else { return p[:n], nil } } }
go
func (conn *redisConn) readLine() ([]byte, error) { var line []byte for { p, err := conn.br.ReadBytes('\n') if err != nil { return nil, err } n := len(p) - 2 if n < 0 { return nil, errors.New("invalid response") } // bulk string may contain '\n', such as CLUSTER NODES if p[n] != '\r' { if line != nil { line = append(line, p[:]...) } else { line = p } continue } if line != nil { return append(line, p[:n]...), nil } else { return p[:n], nil } } }
[ "func", "(", "conn", "*", "redisConn", ")", "readLine", "(", ")", "(", "[", "]", "byte", ",", "error", ")", "{", "var", "line", "[", "]", "byte", "\n", "for", "{", "p", ",", "err", ":=", "conn", ".", "br", ".", "ReadBytes", "(", "'\\n'", ")", ...
// readLine read a single line terminated with CRLF.
[ "readLine", "read", "a", "single", "line", "terminated", "with", "CRLF", "." ]
222d81891f1d3fa7cf8b5655020352c3e5b4ec0f
https://github.com/chasex/redis-go-cluster/blob/222d81891f1d3fa7cf8b5655020352c3e5b4ec0f/node.go#L297-L326
153,015
chasex/redis-go-cluster
node.go
parseLen
func parseLen(p []byte) (int, error) { if len(p) == 0 { return -1, errors.New("invalid response") } // null element. if p[0] == '-' && len(p) == 2 && p[1] == '1' { return -1, nil } var n int for _, b := range p { n *= 10 if b < '0' || b > '9' { return -1, errors.New("invalid response") } n += int(b - '0') } return n, nil }
go
func parseLen(p []byte) (int, error) { if len(p) == 0 { return -1, errors.New("invalid response") } // null element. if p[0] == '-' && len(p) == 2 && p[1] == '1' { return -1, nil } var n int for _, b := range p { n *= 10 if b < '0' || b > '9' { return -1, errors.New("invalid response") } n += int(b - '0') } return n, nil }
[ "func", "parseLen", "(", "p", "[", "]", "byte", ")", "(", "int", ",", "error", ")", "{", "if", "len", "(", "p", ")", "==", "0", "{", "return", "-", "1", ",", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n\n", "// null element.", "...
// parseLen parses bulk string and array length.
[ "parseLen", "parses", "bulk", "string", "and", "array", "length", "." ]
222d81891f1d3fa7cf8b5655020352c3e5b4ec0f
https://github.com/chasex/redis-go-cluster/blob/222d81891f1d3fa7cf8b5655020352c3e5b4ec0f/node.go#L329-L349
153,016
chasex/redis-go-cluster
node.go
parseInt
func parseInt(p []byte) (int64, error) { if len(p) == 0 { return 0, errors.New("invalid response") } var negate bool if p[0] == '-' { negate = true p = p[1:] if len(p) == 0 { return 0, errors.New("invalid response") } } var n int64 for _, b := range p { n *= 10 if b < '0' || b > '9' { return 0, errors.New("invalid response") } n += int64(b - '0') } if negate { n = -n } return n, nil }
go
func parseInt(p []byte) (int64, error) { if len(p) == 0 { return 0, errors.New("invalid response") } var negate bool if p[0] == '-' { negate = true p = p[1:] if len(p) == 0 { return 0, errors.New("invalid response") } } var n int64 for _, b := range p { n *= 10 if b < '0' || b > '9' { return 0, errors.New("invalid response") } n += int64(b - '0') } if negate { n = -n } return n, nil }
[ "func", "parseInt", "(", "p", "[", "]", "byte", ")", "(", "int64", ",", "error", ")", "{", "if", "len", "(", "p", ")", "==", "0", "{", "return", "0", ",", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n\n", "var", "negate", "bool",...
// parseInt parses an integer reply.
[ "parseInt", "parses", "an", "integer", "reply", "." ]
222d81891f1d3fa7cf8b5655020352c3e5b4ec0f
https://github.com/chasex/redis-go-cluster/blob/222d81891f1d3fa7cf8b5655020352c3e5b4ec0f/node.go#L352-L380
153,017
chasex/redis-go-cluster
cluster.go
NewCluster
func NewCluster(options *Options) (*Cluster, error) { cluster := &Cluster{ nodes: make(map[string]*redisNode), connTimeout: options.ConnTimeout, readTimeout: options.ReadTimeout, writeTimeout: options.WriteTimeout, keepAlive: options.KeepAlive, aliveTime: options.AliveTime, updateList: make(chan updateMesg), } for i := range options.StartNodes { node := &redisNode{ address: options.StartNodes[i], connTimeout: options.ConnTimeout, readTimeout: options.ReadTimeout, writeTimeout: options.WriteTimeout, keepAlive: options.KeepAlive, aliveTime: options.AliveTime, } err := cluster.update(node) if err != nil { continue } else { go cluster.handleUpdate() return cluster, nil } } return nil, fmt.Errorf("NewCluster: no valid node in %v", options.StartNodes) }
go
func NewCluster(options *Options) (*Cluster, error) { cluster := &Cluster{ nodes: make(map[string]*redisNode), connTimeout: options.ConnTimeout, readTimeout: options.ReadTimeout, writeTimeout: options.WriteTimeout, keepAlive: options.KeepAlive, aliveTime: options.AliveTime, updateList: make(chan updateMesg), } for i := range options.StartNodes { node := &redisNode{ address: options.StartNodes[i], connTimeout: options.ConnTimeout, readTimeout: options.ReadTimeout, writeTimeout: options.WriteTimeout, keepAlive: options.KeepAlive, aliveTime: options.AliveTime, } err := cluster.update(node) if err != nil { continue } else { go cluster.handleUpdate() return cluster, nil } } return nil, fmt.Errorf("NewCluster: no valid node in %v", options.StartNodes) }
[ "func", "NewCluster", "(", "options", "*", "Options", ")", "(", "*", "Cluster", ",", "error", ")", "{", "cluster", ":=", "&", "Cluster", "{", "nodes", ":", "make", "(", "map", "[", "string", "]", "*", "redisNode", ")", ",", "connTimeout", ":", "optio...
// NewCluster create a new redis cluster client with specified options.
[ "NewCluster", "create", "a", "new", "redis", "cluster", "client", "with", "specified", "options", "." ]
222d81891f1d3fa7cf8b5655020352c3e5b4ec0f
https://github.com/chasex/redis-go-cluster/blob/222d81891f1d3fa7cf8b5655020352c3e5b4ec0f/cluster.go#L67-L98
153,018
chasex/redis-go-cluster
cluster.go
Close
func (cluster *Cluster) Close() { cluster.rwLock.Lock() defer cluster.rwLock.Unlock() for addr, node := range cluster.nodes { node.shutdown() delete(cluster.nodes, addr) } cluster.closed = true }
go
func (cluster *Cluster) Close() { cluster.rwLock.Lock() defer cluster.rwLock.Unlock() for addr, node := range cluster.nodes { node.shutdown() delete(cluster.nodes, addr) } cluster.closed = true }
[ "func", "(", "cluster", "*", "Cluster", ")", "Close", "(", ")", "{", "cluster", ".", "rwLock", ".", "Lock", "(", ")", "\n", "defer", "cluster", ".", "rwLock", ".", "Unlock", "(", ")", "\n\n", "for", "addr", ",", "node", ":=", "range", "cluster", "....
// Close cluster connection, any subsequent method call will fail.
[ "Close", "cluster", "connection", "any", "subsequent", "method", "call", "will", "fail", "." ]
222d81891f1d3fa7cf8b5655020352c3e5b4ec0f
https://github.com/chasex/redis-go-cluster/blob/222d81891f1d3fa7cf8b5655020352c3e5b4ec0f/cluster.go#L153-L163
153,019
hairyhenderson/gomplate
gomplate.go
RunTemplates
func RunTemplates(o *Config) error { Metrics = newMetrics() defer runCleanupHooks() // make sure config is sane o.defaults() ds := append(o.DataSources, o.Contexts...) d, err := data.NewData(ds, o.DataSourceHeaders) if err != nil { return err } addCleanupHook(d.Cleanup) nested, err := parseTemplateArgs(o.Templates) if err != nil { return err } c, err := createContext(o.Contexts, d) if err != nil { return err } g := newGomplate(d, o.LDelim, o.RDelim, nested, c) return g.runTemplates(o) }
go
func RunTemplates(o *Config) error { Metrics = newMetrics() defer runCleanupHooks() // make sure config is sane o.defaults() ds := append(o.DataSources, o.Contexts...) d, err := data.NewData(ds, o.DataSourceHeaders) if err != nil { return err } addCleanupHook(d.Cleanup) nested, err := parseTemplateArgs(o.Templates) if err != nil { return err } c, err := createContext(o.Contexts, d) if err != nil { return err } g := newGomplate(d, o.LDelim, o.RDelim, nested, c) return g.runTemplates(o) }
[ "func", "RunTemplates", "(", "o", "*", "Config", ")", "error", "{", "Metrics", "=", "newMetrics", "(", ")", "\n", "defer", "runCleanupHooks", "(", ")", "\n", "// make sure config is sane", "o", ".", "defaults", "(", ")", "\n", "ds", ":=", "append", "(", ...
// RunTemplates - run all gomplate templates specified by the given configuration
[ "RunTemplates", "-", "run", "all", "gomplate", "templates", "specified", "by", "the", "given", "configuration" ]
20937becaa32cdec93e77a84ad04c73e9155b8e7
https://github.com/hairyhenderson/gomplate/blob/20937becaa32cdec93e77a84ad04c73e9155b8e7/gomplate.go#L107-L129
153,020
hairyhenderson/gomplate
funcs/uuid.go
IsValid
func (f *UUIDFuncs) IsValid(in interface{}) (bool, error) { _, err := f.Parse(in) return err == nil, nil }
go
func (f *UUIDFuncs) IsValid(in interface{}) (bool, error) { _, err := f.Parse(in) return err == nil, nil }
[ "func", "(", "f", "*", "UUIDFuncs", ")", "IsValid", "(", "in", "interface", "{", "}", ")", "(", "bool", ",", "error", ")", "{", "_", ",", "err", ":=", "f", ".", "Parse", "(", "in", ")", "\n", "return", "err", "==", "nil", ",", "nil", "\n", "}...
// IsValid - checks if the given UUID is in the correct format. It does not // validate whether the version or variant are correct.
[ "IsValid", "-", "checks", "if", "the", "given", "UUID", "is", "in", "the", "correct", "format", ".", "It", "does", "not", "validate", "whether", "the", "version", "or", "variant", "are", "correct", "." ]
20937becaa32cdec93e77a84ad04c73e9155b8e7
https://github.com/hairyhenderson/gomplate/blob/20937becaa32cdec93e77a84ad04c73e9155b8e7/funcs/uuid.go#L58-L61
153,021
hairyhenderson/gomplate
env/env.go
getenvVFS
func getenvVFS(fs afero.Fs, key string, def ...string) string { val := getenvFile(fs, key) if val == "" && len(def) > 0 { return def[0] } return val }
go
func getenvVFS(fs afero.Fs, key string, def ...string) string { val := getenvFile(fs, key) if val == "" && len(def) > 0 { return def[0] } return val }
[ "func", "getenvVFS", "(", "fs", "afero", ".", "Fs", ",", "key", "string", ",", "def", "...", "string", ")", "string", "{", "val", ":=", "getenvFile", "(", "fs", ",", "key", ")", "\n", "if", "val", "==", "\"", "\"", "&&", "len", "(", "def", ")", ...
// getenvVFS - a convenience function intended for internal use only!
[ "getenvVFS", "-", "a", "convenience", "function", "intended", "for", "internal", "use", "only!" ]
20937becaa32cdec93e77a84ad04c73e9155b8e7
https://github.com/hairyhenderson/gomplate/blob/20937becaa32cdec93e77a84ad04c73e9155b8e7/env/env.go#L32-L39
153,022
hairyhenderson/gomplate
funcs/crypto.go
WPAPSK
func (f *CryptoFuncs) WPAPSK(ssid, password interface{}) (string, error) { return f.PBKDF2(password, ssid, 4096, 32) }
go
func (f *CryptoFuncs) WPAPSK(ssid, password interface{}) (string, error) { return f.PBKDF2(password, ssid, 4096, 32) }
[ "func", "(", "f", "*", "CryptoFuncs", ")", "WPAPSK", "(", "ssid", ",", "password", "interface", "{", "}", ")", "(", "string", ",", "error", ")", "{", "return", "f", ".", "PBKDF2", "(", "password", ",", "ssid", ",", "4096", ",", "32", ")", "\n", "...
// WPAPSK - Convert an ASCII passphrase to WPA PSK for a given SSID
[ "WPAPSK", "-", "Convert", "an", "ASCII", "passphrase", "to", "WPA", "PSK", "for", "a", "given", "SSID" ]
20937becaa32cdec93e77a84ad04c73e9155b8e7
https://github.com/hairyhenderson/gomplate/blob/20937becaa32cdec93e77a84ad04c73e9155b8e7/funcs/crypto.go#L61-L63
153,023
hairyhenderson/gomplate
crypto/pbkdf2.go
StrToHash
func StrToHash(hash string) (crypto.Hash, error) { switch hash { case "SHA1", "SHA-1": return crypto.SHA1, nil case "SHA224", "SHA-224": return crypto.SHA224, nil case "SHA256", "SHA-256": return crypto.SHA256, nil case "SHA384", "SHA-384": return crypto.SHA384, nil case "SHA512", "SHA-512": return crypto.SHA512, nil case "SHA512_224", "SHA512/224", "SHA-512_224", "SHA-512/224": return crypto.SHA512_224, nil case "SHA512_256", "SHA512/256", "SHA-512_256", "SHA-512/256": return crypto.SHA512_256, nil } return 0, errors.Errorf("no such hash %s", hash) }
go
func StrToHash(hash string) (crypto.Hash, error) { switch hash { case "SHA1", "SHA-1": return crypto.SHA1, nil case "SHA224", "SHA-224": return crypto.SHA224, nil case "SHA256", "SHA-256": return crypto.SHA256, nil case "SHA384", "SHA-384": return crypto.SHA384, nil case "SHA512", "SHA-512": return crypto.SHA512, nil case "SHA512_224", "SHA512/224", "SHA-512_224", "SHA-512/224": return crypto.SHA512_224, nil case "SHA512_256", "SHA512/256", "SHA-512_256", "SHA-512/256": return crypto.SHA512_256, nil } return 0, errors.Errorf("no such hash %s", hash) }
[ "func", "StrToHash", "(", "hash", "string", ")", "(", "crypto", ".", "Hash", ",", "error", ")", "{", "switch", "hash", "{", "case", "\"", "\"", ",", "\"", "\"", ":", "return", "crypto", ".", "SHA1", ",", "nil", "\n", "case", "\"", "\"", ",", "\""...
// StrToHash - find a hash given a certain string
[ "StrToHash", "-", "find", "a", "hash", "given", "a", "certain", "string" ]
20937becaa32cdec93e77a84ad04c73e9155b8e7
https://github.com/hairyhenderson/gomplate/blob/20937becaa32cdec93e77a84ad04c73e9155b8e7/crypto/pbkdf2.go#L29-L47
153,024
hairyhenderson/gomplate
conv/conv.go
Join
func Join(in interface{}, sep string) (out string, err error) { s, ok := in.([]string) if ok { return strings.Join(s, sep), nil } var a []interface{} a, ok = in.([]interface{}) if !ok { a, err = interfaceSlice(in) if err != nil { return "", errors.Wrap(err, "Input to Join must be an array") } ok = true } if ok { b := make([]string, len(a)) for i := range a { b[i] = ToString(a[i]) } return strings.Join(b, sep), nil } return "", errors.New("Input to Join must be an array") }
go
func Join(in interface{}, sep string) (out string, err error) { s, ok := in.([]string) if ok { return strings.Join(s, sep), nil } var a []interface{} a, ok = in.([]interface{}) if !ok { a, err = interfaceSlice(in) if err != nil { return "", errors.Wrap(err, "Input to Join must be an array") } ok = true } if ok { b := make([]string, len(a)) for i := range a { b[i] = ToString(a[i]) } return strings.Join(b, sep), nil } return "", errors.New("Input to Join must be an array") }
[ "func", "Join", "(", "in", "interface", "{", "}", ",", "sep", "string", ")", "(", "out", "string", ",", "err", "error", ")", "{", "s", ",", "ok", ":=", "in", ".", "(", "[", "]", "string", ")", "\n", "if", "ok", "{", "return", "strings", ".", ...
// Join concatenates the elements of a to create a single string. // The separator string sep is placed between elements in the resulting string. // // This is functionally identical to strings.Join, except that each element is // coerced to a string first
[ "Join", "concatenates", "the", "elements", "of", "a", "to", "create", "a", "single", "string", ".", "The", "separator", "string", "sep", "is", "placed", "between", "elements", "in", "the", "resulting", "string", ".", "This", "is", "functionally", "identical", ...
20937becaa32cdec93e77a84ad04c73e9155b8e7
https://github.com/hairyhenderson/gomplate/blob/20937becaa32cdec93e77a84ad04c73e9155b8e7/conv/conv.go#L75-L99
153,025
hairyhenderson/gomplate
conv/conv.go
Has
func Has(in interface{}, key interface{}) bool { av := reflect.ValueOf(in) switch av.Kind() { case reflect.Map: kv := reflect.ValueOf(key) return av.MapIndex(kv).IsValid() case reflect.Slice, reflect.Array: l := av.Len() for i := 0; i < l; i++ { v := av.Index(i).Interface() if reflect.DeepEqual(v, key) { return true } } } return false }
go
func Has(in interface{}, key interface{}) bool { av := reflect.ValueOf(in) switch av.Kind() { case reflect.Map: kv := reflect.ValueOf(key) return av.MapIndex(kv).IsValid() case reflect.Slice, reflect.Array: l := av.Len() for i := 0; i < l; i++ { v := av.Index(i).Interface() if reflect.DeepEqual(v, key) { return true } } } return false }
[ "func", "Has", "(", "in", "interface", "{", "}", ",", "key", "interface", "{", "}", ")", "bool", "{", "av", ":=", "reflect", ".", "ValueOf", "(", "in", ")", "\n\n", "switch", "av", ".", "Kind", "(", ")", "{", "case", "reflect", ".", "Map", ":", ...
// Has determines whether or not a given object has a property with the given key
[ "Has", "determines", "whether", "or", "not", "a", "given", "object", "has", "a", "property", "with", "the", "given", "key" ]
20937becaa32cdec93e77a84ad04c73e9155b8e7
https://github.com/hairyhenderson/gomplate/blob/20937becaa32cdec93e77a84ad04c73e9155b8e7/conv/conv.go#L117-L135
153,026
hairyhenderson/gomplate
conv/conv.go
MustParseInt
func MustParseInt(s string, base, bitSize int) int64 { // nolint: gosec i, _ := strconv.ParseInt(s, base, bitSize) return i }
go
func MustParseInt(s string, base, bitSize int) int64 { // nolint: gosec i, _ := strconv.ParseInt(s, base, bitSize) return i }
[ "func", "MustParseInt", "(", "s", "string", ",", "base", ",", "bitSize", "int", ")", "int64", "{", "// nolint: gosec", "i", ",", "_", ":=", "strconv", ".", "ParseInt", "(", "s", ",", "base", ",", "bitSize", ")", "\n", "return", "i", "\n", "}" ]
// MustParseInt - wrapper for strconv.ParseInt that returns 0 in the case of error
[ "MustParseInt", "-", "wrapper", "for", "strconv", ".", "ParseInt", "that", "returns", "0", "in", "the", "case", "of", "error" ]
20937becaa32cdec93e77a84ad04c73e9155b8e7
https://github.com/hairyhenderson/gomplate/blob/20937becaa32cdec93e77a84ad04c73e9155b8e7/conv/conv.go#L166-L170
153,027
hairyhenderson/gomplate
conv/conv.go
MustParseFloat
func MustParseFloat(s string, bitSize int) float64 { // nolint: gosec i, _ := strconv.ParseFloat(s, bitSize) return i }
go
func MustParseFloat(s string, bitSize int) float64 { // nolint: gosec i, _ := strconv.ParseFloat(s, bitSize) return i }
[ "func", "MustParseFloat", "(", "s", "string", ",", "bitSize", "int", ")", "float64", "{", "// nolint: gosec", "i", ",", "_", ":=", "strconv", ".", "ParseFloat", "(", "s", ",", "bitSize", ")", "\n", "return", "i", "\n", "}" ]
// MustParseFloat - wrapper for strconv.ParseFloat that returns 0 in the case of error
[ "MustParseFloat", "-", "wrapper", "for", "strconv", ".", "ParseFloat", "that", "returns", "0", "in", "the", "case", "of", "error" ]
20937becaa32cdec93e77a84ad04c73e9155b8e7
https://github.com/hairyhenderson/gomplate/blob/20937becaa32cdec93e77a84ad04c73e9155b8e7/conv/conv.go#L173-L177
153,028
hairyhenderson/gomplate
conv/conv.go
MustParseUint
func MustParseUint(s string, base, bitSize int) uint64 { // nolint: gosec i, _ := strconv.ParseUint(s, base, bitSize) return i }
go
func MustParseUint(s string, base, bitSize int) uint64 { // nolint: gosec i, _ := strconv.ParseUint(s, base, bitSize) return i }
[ "func", "MustParseUint", "(", "s", "string", ",", "base", ",", "bitSize", "int", ")", "uint64", "{", "// nolint: gosec", "i", ",", "_", ":=", "strconv", ".", "ParseUint", "(", "s", ",", "base", ",", "bitSize", ")", "\n", "return", "i", "\n", "}" ]
// MustParseUint - wrapper for strconv.ParseUint that returns 0 in the case of error
[ "MustParseUint", "-", "wrapper", "for", "strconv", ".", "ParseUint", "that", "returns", "0", "in", "the", "case", "of", "error" ]
20937becaa32cdec93e77a84ad04c73e9155b8e7
https://github.com/hairyhenderson/gomplate/blob/20937becaa32cdec93e77a84ad04c73e9155b8e7/conv/conv.go#L180-L184
153,029
hairyhenderson/gomplate
conv/conv.go
MustAtoi
func MustAtoi(s string) int { // nolint: gosec i, _ := strconv.Atoi(s) return i }
go
func MustAtoi(s string) int { // nolint: gosec i, _ := strconv.Atoi(s) return i }
[ "func", "MustAtoi", "(", "s", "string", ")", "int", "{", "// nolint: gosec", "i", ",", "_", ":=", "strconv", ".", "Atoi", "(", "s", ")", "\n", "return", "i", "\n", "}" ]
// MustAtoi - wrapper for strconv.Atoi that returns 0 in the case of error
[ "MustAtoi", "-", "wrapper", "for", "strconv", ".", "Atoi", "that", "returns", "0", "in", "the", "case", "of", "error" ]
20937becaa32cdec93e77a84ad04c73e9155b8e7
https://github.com/hairyhenderson/gomplate/blob/20937becaa32cdec93e77a84ad04c73e9155b8e7/conv/conv.go#L187-L191
153,030
hairyhenderson/gomplate
conv/conv.go
ToInt64
func ToInt64(v interface{}) int64 { if str, ok := v.(string); ok { return strToInt64(str) } val := reflect.Indirect(reflect.ValueOf(v)) switch val.Kind() { case reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64, reflect.Int: return val.Int() case reflect.Uint8, reflect.Uint16, reflect.Uint32: return int64(val.Uint()) case reflect.Uint, reflect.Uint64: tv := val.Uint() // this can overflow and give -1, but IMO this is better than // returning maxint64 return int64(tv) case reflect.Float32, reflect.Float64: return int64(val.Float()) case reflect.Bool: if val.Bool() { return 1 } return 0 default: return 0 } }
go
func ToInt64(v interface{}) int64 { if str, ok := v.(string); ok { return strToInt64(str) } val := reflect.Indirect(reflect.ValueOf(v)) switch val.Kind() { case reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64, reflect.Int: return val.Int() case reflect.Uint8, reflect.Uint16, reflect.Uint32: return int64(val.Uint()) case reflect.Uint, reflect.Uint64: tv := val.Uint() // this can overflow and give -1, but IMO this is better than // returning maxint64 return int64(tv) case reflect.Float32, reflect.Float64: return int64(val.Float()) case reflect.Bool: if val.Bool() { return 1 } return 0 default: return 0 } }
[ "func", "ToInt64", "(", "v", "interface", "{", "}", ")", "int64", "{", "if", "str", ",", "ok", ":=", "v", ".", "(", "string", ")", ";", "ok", "{", "return", "strToInt64", "(", "str", ")", "\n", "}", "\n\n", "val", ":=", "reflect", ".", "Indirect"...
// ToInt64 - convert input to an int64, if convertible. Otherwise, returns 0.
[ "ToInt64", "-", "convert", "input", "to", "an", "int64", "if", "convertible", ".", "Otherwise", "returns", "0", "." ]
20937becaa32cdec93e77a84ad04c73e9155b8e7
https://github.com/hairyhenderson/gomplate/blob/20937becaa32cdec93e77a84ad04c73e9155b8e7/conv/conv.go#L194-L220
153,031
hairyhenderson/gomplate
conv/conv.go
ToFloat64
func ToFloat64(v interface{}) float64 { if str, ok := v.(string); ok { return strToFloat64(str) } val := reflect.Indirect(reflect.ValueOf(v)) switch val.Kind() { case reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64, reflect.Int: return float64(val.Int()) case reflect.Uint8, reflect.Uint16, reflect.Uint32: return float64(val.Uint()) case reflect.Uint, reflect.Uint64: return float64(val.Uint()) case reflect.Float32, reflect.Float64: return val.Float() case reflect.Bool: if val.Bool() { return 1 } return 0 default: return 0 } }
go
func ToFloat64(v interface{}) float64 { if str, ok := v.(string); ok { return strToFloat64(str) } val := reflect.Indirect(reflect.ValueOf(v)) switch val.Kind() { case reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64, reflect.Int: return float64(val.Int()) case reflect.Uint8, reflect.Uint16, reflect.Uint32: return float64(val.Uint()) case reflect.Uint, reflect.Uint64: return float64(val.Uint()) case reflect.Float32, reflect.Float64: return val.Float() case reflect.Bool: if val.Bool() { return 1 } return 0 default: return 0 } }
[ "func", "ToFloat64", "(", "v", "interface", "{", "}", ")", "float64", "{", "if", "str", ",", "ok", ":=", "v", ".", "(", "string", ")", ";", "ok", "{", "return", "strToFloat64", "(", "str", ")", "\n", "}", "\n\n", "val", ":=", "reflect", ".", "Ind...
// ToFloat64 - convert input to a float64, if convertible. Otherwise, returns 0.
[ "ToFloat64", "-", "convert", "input", "to", "a", "float64", "if", "convertible", ".", "Otherwise", "returns", "0", "." ]
20937becaa32cdec93e77a84ad04c73e9155b8e7
https://github.com/hairyhenderson/gomplate/blob/20937becaa32cdec93e77a84ad04c73e9155b8e7/conv/conv.go#L246-L269
153,032
hairyhenderson/gomplate
libkv/boltdb.go
NewBoltDB
func NewBoltDB(u *url.URL) (*LibKV, error) { boltdb.Register() config, err := setupBoltDB(u.Fragment) if err != nil { return nil, err } kv, err := libkv.NewStore(store.BOLTDB, []string{u.Path}, config) if err != nil { return nil, errors.Wrapf(err, "BoltDB store creation failed") } return &LibKV{kv}, nil }
go
func NewBoltDB(u *url.URL) (*LibKV, error) { boltdb.Register() config, err := setupBoltDB(u.Fragment) if err != nil { return nil, err } kv, err := libkv.NewStore(store.BOLTDB, []string{u.Path}, config) if err != nil { return nil, errors.Wrapf(err, "BoltDB store creation failed") } return &LibKV{kv}, nil }
[ "func", "NewBoltDB", "(", "u", "*", "url", ".", "URL", ")", "(", "*", "LibKV", ",", "error", ")", "{", "boltdb", ".", "Register", "(", ")", "\n\n", "config", ",", "err", ":=", "setupBoltDB", "(", "u", ".", "Fragment", ")", "\n", "if", "err", "!="...
// NewBoltDB - initialize a new BoltDB datasource handler
[ "NewBoltDB", "-", "initialize", "a", "new", "BoltDB", "datasource", "handler" ]
20937becaa32cdec93e77a84ad04c73e9155b8e7
https://github.com/hairyhenderson/gomplate/blob/20937becaa32cdec93e77a84ad04c73e9155b8e7/libkv/boltdb.go#L16-L28
153,033
hairyhenderson/gomplate
funcs/aws.go
AWSNS
func AWSNS() *Funcs { afInit.Do(func() { af = &Funcs{ awsopts: aws.GetClientOptions(), } }) return af }
go
func AWSNS() *Funcs { afInit.Do(func() { af = &Funcs{ awsopts: aws.GetClientOptions(), } }) return af }
[ "func", "AWSNS", "(", ")", "*", "Funcs", "{", "afInit", ".", "Do", "(", "func", "(", ")", "{", "af", "=", "&", "Funcs", "{", "awsopts", ":", "aws", ".", "GetClientOptions", "(", ")", ",", "}", "\n", "}", ")", "\n", "return", "af", "\n", "}" ]
// AWSNS - the aws namespace
[ "AWSNS", "-", "the", "aws", "namespace" ]
20937becaa32cdec93e77a84ad04c73e9155b8e7
https://github.com/hairyhenderson/gomplate/blob/20937becaa32cdec93e77a84ad04c73e9155b8e7/funcs/aws.go#L16-L23
153,034
hairyhenderson/gomplate
funcs/aws.go
ARN
func (a *Funcs) ARN() (string, error) { a.stsInit.Do(a.initSTS) return a.sts.Arn() }
go
func (a *Funcs) ARN() (string, error) { a.stsInit.Do(a.initSTS) return a.sts.Arn() }
[ "func", "(", "a", "*", "Funcs", ")", "ARN", "(", ")", "(", "string", ",", "error", ")", "{", "a", ".", "stsInit", ".", "Do", "(", "a", ".", "initSTS", ")", "\n", "return", "a", ".", "sts", ".", "Arn", "(", ")", "\n", "}" ]
// ARN - Gets the AWS ARN associated with the calling entity
[ "ARN", "-", "Gets", "the", "AWS", "ARN", "associated", "with", "the", "calling", "entity" ]
20937becaa32cdec93e77a84ad04c73e9155b8e7
https://github.com/hairyhenderson/gomplate/blob/20937becaa32cdec93e77a84ad04c73e9155b8e7/funcs/aws.go#L103-L106
153,035
hairyhenderson/gomplate
base64/base64.go
Encode
func Encode(in []byte) (string, error) { return b64.StdEncoding.EncodeToString(in), nil }
go
func Encode(in []byte) (string, error) { return b64.StdEncoding.EncodeToString(in), nil }
[ "func", "Encode", "(", "in", "[", "]", "byte", ")", "(", "string", ",", "error", ")", "{", "return", "b64", ".", "StdEncoding", ".", "EncodeToString", "(", "in", ")", ",", "nil", "\n", "}" ]
// Encode - Encode data in base64 format
[ "Encode", "-", "Encode", "data", "in", "base64", "format" ]
20937becaa32cdec93e77a84ad04c73e9155b8e7
https://github.com/hairyhenderson/gomplate/blob/20937becaa32cdec93e77a84ad04c73e9155b8e7/base64/base64.go#L8-L10
153,036
hairyhenderson/gomplate
base64/base64.go
Decode
func Decode(in string) ([]byte, error) { o, err := b64.StdEncoding.DecodeString(in) if err != nil { // maybe it's in the URL variant? o, err = b64.URLEncoding.DecodeString(in) if err != nil { // ok, just give up... return nil, err } } return o, nil }
go
func Decode(in string) ([]byte, error) { o, err := b64.StdEncoding.DecodeString(in) if err != nil { // maybe it's in the URL variant? o, err = b64.URLEncoding.DecodeString(in) if err != nil { // ok, just give up... return nil, err } } return o, nil }
[ "func", "Decode", "(", "in", "string", ")", "(", "[", "]", "byte", ",", "error", ")", "{", "o", ",", "err", ":=", "b64", ".", "StdEncoding", ".", "DecodeString", "(", "in", ")", "\n", "if", "err", "!=", "nil", "{", "// maybe it's in the URL variant?", ...
// Decode - Decode a base64-encoded string
[ "Decode", "-", "Decode", "a", "base64", "-", "encoded", "string" ]
20937becaa32cdec93e77a84ad04c73e9155b8e7
https://github.com/hairyhenderson/gomplate/blob/20937becaa32cdec93e77a84ad04c73e9155b8e7/base64/base64.go#L13-L24
153,037
hairyhenderson/gomplate
vault/auth.go
AppIDLogin
func (v *Vault) AppIDLogin() (string, error) { appID := env.Getenv("VAULT_APP_ID") userID := env.Getenv("VAULT_USER_ID") if appID == "" || userID == "" { return "", nil } mount := env.Getenv("VAULT_AUTH_APP_ID_MOUNT", "app-id") vars := map[string]interface{}{ "user_id": userID, } path := fmt.Sprintf("auth/%s/login/%s", mount, appID) secret, err := v.client.Logical().Write(path, vars) if err != nil { return "", errors.Wrapf(err, "AppID logon failed") } if secret == nil { return "", errors.New("Empty response from AppID logon") } return secret.Auth.ClientToken, nil }
go
func (v *Vault) AppIDLogin() (string, error) { appID := env.Getenv("VAULT_APP_ID") userID := env.Getenv("VAULT_USER_ID") if appID == "" || userID == "" { return "", nil } mount := env.Getenv("VAULT_AUTH_APP_ID_MOUNT", "app-id") vars := map[string]interface{}{ "user_id": userID, } path := fmt.Sprintf("auth/%s/login/%s", mount, appID) secret, err := v.client.Logical().Write(path, vars) if err != nil { return "", errors.Wrapf(err, "AppID logon failed") } if secret == nil { return "", errors.New("Empty response from AppID logon") } return secret.Auth.ClientToken, nil }
[ "func", "(", "v", "*", "Vault", ")", "AppIDLogin", "(", ")", "(", "string", ",", "error", ")", "{", "appID", ":=", "env", ".", "Getenv", "(", "\"", "\"", ")", "\n", "userID", ":=", "env", ".", "Getenv", "(", "\"", "\"", ")", "\n\n", "if", "appI...
// AppIDLogin - app-id auth backend
[ "AppIDLogin", "-", "app", "-", "id", "auth", "backend" ]
20937becaa32cdec93e77a84ad04c73e9155b8e7
https://github.com/hairyhenderson/gomplate/blob/20937becaa32cdec93e77a84ad04c73e9155b8e7/vault/auth.go#L37-L61
153,038
hairyhenderson/gomplate
vault/auth.go
GitHubLogin
func (v *Vault) GitHubLogin() (string, error) { githubToken := env.Getenv("VAULT_AUTH_GITHUB_TOKEN") if githubToken == "" { return "", nil } mount := env.Getenv("VAULT_AUTH_GITHUB_MOUNT", "github") vars := map[string]interface{}{ "token": githubToken, } path := fmt.Sprintf("auth/%s/login", mount) secret, err := v.client.Logical().Write(path, vars) if err != nil { return "", errors.Wrap(err, "AppRole logon failed") } if secret == nil { return "", errors.New("Empty response from AppRole logon") } return secret.Auth.ClientToken, nil }
go
func (v *Vault) GitHubLogin() (string, error) { githubToken := env.Getenv("VAULT_AUTH_GITHUB_TOKEN") if githubToken == "" { return "", nil } mount := env.Getenv("VAULT_AUTH_GITHUB_MOUNT", "github") vars := map[string]interface{}{ "token": githubToken, } path := fmt.Sprintf("auth/%s/login", mount) secret, err := v.client.Logical().Write(path, vars) if err != nil { return "", errors.Wrap(err, "AppRole logon failed") } if secret == nil { return "", errors.New("Empty response from AppRole logon") } return secret.Auth.ClientToken, nil }
[ "func", "(", "v", "*", "Vault", ")", "GitHubLogin", "(", ")", "(", "string", ",", "error", ")", "{", "githubToken", ":=", "env", ".", "Getenv", "(", "\"", "\"", ")", "\n\n", "if", "githubToken", "==", "\"", "\"", "{", "return", "\"", "\"", ",", "...
// GitHubLogin - github auth backend
[ "GitHubLogin", "-", "github", "auth", "backend" ]
20937becaa32cdec93e77a84ad04c73e9155b8e7
https://github.com/hairyhenderson/gomplate/blob/20937becaa32cdec93e77a84ad04c73e9155b8e7/vault/auth.go#L92-L115
153,039
hairyhenderson/gomplate
vault/auth.go
EC2Login
func (v *Vault) EC2Login() (string, error) { mount := env.Getenv("VAULT_AUTH_AWS_MOUNT", "aws") output := env.Getenv("VAULT_AUTH_AWS_NONCE_OUTPUT") nonce := env.Getenv("VAULT_AUTH_AWS_NONCE") vars, err := createEc2LoginVars(nonce) if err != nil { return "", err } if vars["pkcs7"] == "" { return "", nil } path := fmt.Sprintf("auth/%s/login", mount) secret, err := v.client.Logical().Write(path, vars) if err != nil { return "", errors.Wrapf(err, "AWS EC2 logon failed") } if secret == nil { return "", errors.New("Empty response from AWS EC2 logon") } if output != "" { if val, ok := secret.Auth.Metadata["nonce"]; ok { nonce = val } f, err := os.OpenFile(output, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, os.FileMode(0600)) if err != nil { return "", errors.Wrapf(err, "Error opening nonce output file") } n, err := f.Write([]byte(nonce + "\n")) if err != nil { return "", errors.Wrapf(err, "Error writing nonce output file") } if n == 0 { return "", errors.Wrapf(err, "No bytes written to nonce output file") } } return secret.Auth.ClientToken, nil }
go
func (v *Vault) EC2Login() (string, error) { mount := env.Getenv("VAULT_AUTH_AWS_MOUNT", "aws") output := env.Getenv("VAULT_AUTH_AWS_NONCE_OUTPUT") nonce := env.Getenv("VAULT_AUTH_AWS_NONCE") vars, err := createEc2LoginVars(nonce) if err != nil { return "", err } if vars["pkcs7"] == "" { return "", nil } path := fmt.Sprintf("auth/%s/login", mount) secret, err := v.client.Logical().Write(path, vars) if err != nil { return "", errors.Wrapf(err, "AWS EC2 logon failed") } if secret == nil { return "", errors.New("Empty response from AWS EC2 logon") } if output != "" { if val, ok := secret.Auth.Metadata["nonce"]; ok { nonce = val } f, err := os.OpenFile(output, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, os.FileMode(0600)) if err != nil { return "", errors.Wrapf(err, "Error opening nonce output file") } n, err := f.Write([]byte(nonce + "\n")) if err != nil { return "", errors.Wrapf(err, "Error writing nonce output file") } if n == 0 { return "", errors.Wrapf(err, "No bytes written to nonce output file") } } return secret.Auth.ClientToken, nil }
[ "func", "(", "v", "*", "Vault", ")", "EC2Login", "(", ")", "(", "string", ",", "error", ")", "{", "mount", ":=", "env", ".", "Getenv", "(", "\"", "\"", ",", "\"", "\"", ")", "\n", "output", ":=", "env", ".", "Getenv", "(", "\"", "\"", ")", "\...
// EC2Login - AWS EC2 auth backend
[ "EC2Login", "-", "AWS", "EC2", "auth", "backend" ]
20937becaa32cdec93e77a84ad04c73e9155b8e7
https://github.com/hairyhenderson/gomplate/blob/20937becaa32cdec93e77a84ad04c73e9155b8e7/vault/auth.go#L145-L186
153,040
hairyhenderson/gomplate
strings/strings.go
Indent
func Indent(width int, indent, s string) string { if width == 0 { return s } if width > 1 { indent = strings.Repeat(indent, width) } var res []byte bol := true for i := 0; i < len(s); i++ { c := s[i] if bol && c != '\n' { res = append(res, indent...) } res = append(res, c) bol = c == '\n' } return string(res) }
go
func Indent(width int, indent, s string) string { if width == 0 { return s } if width > 1 { indent = strings.Repeat(indent, width) } var res []byte bol := true for i := 0; i < len(s); i++ { c := s[i] if bol && c != '\n' { res = append(res, indent...) } res = append(res, c) bol = c == '\n' } return string(res) }
[ "func", "Indent", "(", "width", "int", ",", "indent", ",", "s", "string", ")", "string", "{", "if", "width", "==", "0", "{", "return", "s", "\n", "}", "\n", "if", "width", ">", "1", "{", "indent", "=", "strings", ".", "Repeat", "(", "indent", ","...
// Indent - indent each line of the string with the given indent string
[ "Indent", "-", "indent", "each", "line", "of", "the", "string", "with", "the", "given", "indent", "string" ]
20937becaa32cdec93e77a84ad04c73e9155b8e7
https://github.com/hairyhenderson/gomplate/blob/20937becaa32cdec93e77a84ad04c73e9155b8e7/strings/strings.go#L12-L30
153,041
hairyhenderson/gomplate
strings/strings.go
Trunc
func Trunc(length int, s string) string { if length < 0 { return s } if len(s) <= length { return s } return s[0:length] }
go
func Trunc(length int, s string) string { if length < 0 { return s } if len(s) <= length { return s } return s[0:length] }
[ "func", "Trunc", "(", "length", "int", ",", "s", "string", ")", "string", "{", "if", "length", "<", "0", "{", "return", "s", "\n", "}", "\n", "if", "len", "(", "s", ")", "<=", "length", "{", "return", "s", "\n", "}", "\n", "return", "s", "[", ...
// Trunc - truncate a string to the given length
[ "Trunc", "-", "truncate", "a", "string", "to", "the", "given", "length" ]
20937becaa32cdec93e77a84ad04c73e9155b8e7
https://github.com/hairyhenderson/gomplate/blob/20937becaa32cdec93e77a84ad04c73e9155b8e7/strings/strings.go#L33-L41
153,042
hairyhenderson/gomplate
strings/strings.go
wwDefaults
func wwDefaults(opts WordWrapOpts) WordWrapOpts { if opts.Width == 0 { opts.Width = 80 } if opts.LBSeq == "" { opts.LBSeq = "\n" } return opts }
go
func wwDefaults(opts WordWrapOpts) WordWrapOpts { if opts.Width == 0 { opts.Width = 80 } if opts.LBSeq == "" { opts.LBSeq = "\n" } return opts }
[ "func", "wwDefaults", "(", "opts", "WordWrapOpts", ")", "WordWrapOpts", "{", "if", "opts", ".", "Width", "==", "0", "{", "opts", ".", "Width", "=", "80", "\n", "}", "\n", "if", "opts", ".", "LBSeq", "==", "\"", "\"", "{", "opts", ".", "LBSeq", "=",...
// applies default options
[ "applies", "default", "options" ]
20937becaa32cdec93e77a84ad04c73e9155b8e7
https://github.com/hairyhenderson/gomplate/blob/20937becaa32cdec93e77a84ad04c73e9155b8e7/strings/strings.go#L97-L105
153,043
hairyhenderson/gomplate
strings/strings.go
WordWrap
func WordWrap(in string, opts WordWrapOpts) string { opts = wwDefaults(opts) return goutils.WrapCustom(in, int(opts.Width), opts.LBSeq, false) }
go
func WordWrap(in string, opts WordWrapOpts) string { opts = wwDefaults(opts) return goutils.WrapCustom(in, int(opts.Width), opts.LBSeq, false) }
[ "func", "WordWrap", "(", "in", "string", ",", "opts", "WordWrapOpts", ")", "string", "{", "opts", "=", "wwDefaults", "(", "opts", ")", "\n", "return", "goutils", ".", "WrapCustom", "(", "in", ",", "int", "(", "opts", ".", "Width", ")", ",", "opts", "...
// WordWrap - insert line-breaks into the string, before it reaches the given // width.
[ "WordWrap", "-", "insert", "line", "-", "breaks", "into", "the", "string", "before", "it", "reaches", "the", "given", "width", "." ]
20937becaa32cdec93e77a84ad04c73e9155b8e7
https://github.com/hairyhenderson/gomplate/blob/20937becaa32cdec93e77a84ad04c73e9155b8e7/strings/strings.go#L109-L112
153,044
hairyhenderson/gomplate
aws/kms.go
NewKMS
func NewKMS(option ClientOptions) *KMS { client := kms.New(SDKSession()) return &KMS{ Client: client, } }
go
func NewKMS(option ClientOptions) *KMS { client := kms.New(SDKSession()) return &KMS{ Client: client, } }
[ "func", "NewKMS", "(", "option", "ClientOptions", ")", "*", "KMS", "{", "client", ":=", "kms", ".", "New", "(", "SDKSession", "(", ")", ")", "\n", "return", "&", "KMS", "{", "Client", ":", "client", ",", "}", "\n", "}" ]
// NewKMS - Create new AWS KMS client using an SDKSession
[ "NewKMS", "-", "Create", "new", "AWS", "KMS", "client", "using", "an", "SDKSession" ]
20937becaa32cdec93e77a84ad04c73e9155b8e7
https://github.com/hairyhenderson/gomplate/blob/20937becaa32cdec93e77a84ad04c73e9155b8e7/aws/kms.go#L21-L26
153,045
hairyhenderson/gomplate
aws/kms.go
Encrypt
func (k *KMS) Encrypt(keyID, plaintext string) (string, error) { input := &kms.EncryptInput{ KeyId: &keyID, Plaintext: []byte(plaintext), } output, err := k.Client.Encrypt(input) if err != nil { return "", err } ciphertext, err := b64.Encode(output.CiphertextBlob) if err != nil { return "", err } return ciphertext, nil }
go
func (k *KMS) Encrypt(keyID, plaintext string) (string, error) { input := &kms.EncryptInput{ KeyId: &keyID, Plaintext: []byte(plaintext), } output, err := k.Client.Encrypt(input) if err != nil { return "", err } ciphertext, err := b64.Encode(output.CiphertextBlob) if err != nil { return "", err } return ciphertext, nil }
[ "func", "(", "k", "*", "KMS", ")", "Encrypt", "(", "keyID", ",", "plaintext", "string", ")", "(", "string", ",", "error", ")", "{", "input", ":=", "&", "kms", ".", "EncryptInput", "{", "KeyId", ":", "&", "keyID", ",", "Plaintext", ":", "[", "]", ...
// Encrypt plaintext using the specified key. // Returns a base64 encoded ciphertext
[ "Encrypt", "plaintext", "using", "the", "specified", "key", ".", "Returns", "a", "base64", "encoded", "ciphertext" ]
20937becaa32cdec93e77a84ad04c73e9155b8e7
https://github.com/hairyhenderson/gomplate/blob/20937becaa32cdec93e77a84ad04c73e9155b8e7/aws/kms.go#L30-L44
153,046
hairyhenderson/gomplate
aws/kms.go
Decrypt
func (k *KMS) Decrypt(ciphertext string) (string, error) { ciphertextBlob, err := b64.Decode(ciphertext) if err != nil { return "", err } input := &kms.DecryptInput{ CiphertextBlob: []byte(ciphertextBlob), } output, err := k.Client.Decrypt(input) if err != nil { return "", err } return string(output.Plaintext), nil }
go
func (k *KMS) Decrypt(ciphertext string) (string, error) { ciphertextBlob, err := b64.Decode(ciphertext) if err != nil { return "", err } input := &kms.DecryptInput{ CiphertextBlob: []byte(ciphertextBlob), } output, err := k.Client.Decrypt(input) if err != nil { return "", err } return string(output.Plaintext), nil }
[ "func", "(", "k", "*", "KMS", ")", "Decrypt", "(", "ciphertext", "string", ")", "(", "string", ",", "error", ")", "{", "ciphertextBlob", ",", "err", ":=", "b64", ".", "Decode", "(", "ciphertext", ")", "\n", "if", "err", "!=", "nil", "{", "return", ...
// Decrypt a base64 encoded ciphertext
[ "Decrypt", "a", "base64", "encoded", "ciphertext" ]
20937becaa32cdec93e77a84ad04c73e9155b8e7
https://github.com/hairyhenderson/gomplate/blob/20937becaa32cdec93e77a84ad04c73e9155b8e7/aws/kms.go#L47-L60
153,047
hairyhenderson/gomplate
template.go
loadContents
func (t *tplate) loadContents() (err error) { if t.contents == "" { t.contents, err = readInput(t.name) } return err }
go
func (t *tplate) loadContents() (err error) { if t.contents == "" { t.contents, err = readInput(t.name) } return err }
[ "func", "(", "t", "*", "tplate", ")", "loadContents", "(", ")", "(", "err", "error", ")", "{", "if", "t", ".", "contents", "==", "\"", "\"", "{", "t", ".", "contents", ",", "err", "=", "readInput", "(", "t", ".", "name", ")", "\n", "}", "\n", ...
// loadContents - reads the template in _once_ if it hasn't yet been read. Uses the name!
[ "loadContents", "-", "reads", "the", "template", "in", "_once_", "if", "it", "hasn", "t", "yet", "been", "read", ".", "Uses", "the", "name!" ]
20937becaa32cdec93e77a84ad04c73e9155b8e7
https://github.com/hairyhenderson/gomplate/blob/20937becaa32cdec93e77a84ad04c73e9155b8e7/template.go#L80-L85
153,048
hairyhenderson/gomplate
funcs/math.go
Seq
func (f *MathFuncs) Seq(n ...interface{}) ([]int64, error) { start := int64(1) end := int64(0) step := int64(1) if len(n) == 0 { return nil, fmt.Errorf("math.Seq must be given at least an 'end' value") } if len(n) == 1 { end = conv.ToInt64(n[0]) } if len(n) == 2 { start = conv.ToInt64(n[0]) end = conv.ToInt64(n[1]) } if len(n) == 3 { start = conv.ToInt64(n[0]) end = conv.ToInt64(n[1]) step = conv.ToInt64(n[2]) } return math.Seq(conv.ToInt64(start), conv.ToInt64(end), conv.ToInt64(step)), nil }
go
func (f *MathFuncs) Seq(n ...interface{}) ([]int64, error) { start := int64(1) end := int64(0) step := int64(1) if len(n) == 0 { return nil, fmt.Errorf("math.Seq must be given at least an 'end' value") } if len(n) == 1 { end = conv.ToInt64(n[0]) } if len(n) == 2 { start = conv.ToInt64(n[0]) end = conv.ToInt64(n[1]) } if len(n) == 3 { start = conv.ToInt64(n[0]) end = conv.ToInt64(n[1]) step = conv.ToInt64(n[2]) } return math.Seq(conv.ToInt64(start), conv.ToInt64(end), conv.ToInt64(step)), nil }
[ "func", "(", "f", "*", "MathFuncs", ")", "Seq", "(", "n", "...", "interface", "{", "}", ")", "(", "[", "]", "int64", ",", "error", ")", "{", "start", ":=", "int64", "(", "1", ")", "\n", "end", ":=", "int64", "(", "0", ")", "\n", "step", ":=",...
// Seq - return a sequence from `start` to `end`, in steps of `step` // start and step are optional, and default to 1.
[ "Seq", "-", "return", "a", "sequence", "from", "start", "to", "end", "in", "steps", "of", "step", "start", "and", "step", "are", "optional", "and", "default", "to", "1", "." ]
20937becaa32cdec93e77a84ad04c73e9155b8e7
https://github.com/hairyhenderson/gomplate/blob/20937becaa32cdec93e77a84ad04c73e9155b8e7/funcs/math.go#L165-L185
153,049
hairyhenderson/gomplate
data/datasource.go
registerReaders
func (d *Data) registerReaders() { d.sourceReaders = make(map[string]func(*Source, ...string) ([]byte, error)) d.sourceReaders["aws+smp"] = readAWSSMP d.sourceReaders["boltdb"] = readBoltDB d.sourceReaders["consul"] = readConsul d.sourceReaders["consul+http"] = readConsul d.sourceReaders["consul+https"] = readConsul d.sourceReaders["env"] = readEnv d.sourceReaders["file"] = readFile d.sourceReaders["http"] = readHTTP d.sourceReaders["https"] = readHTTP d.sourceReaders["merge"] = d.readMerge d.sourceReaders["stdin"] = readStdin d.sourceReaders["vault"] = readVault d.sourceReaders["vault+http"] = readVault d.sourceReaders["vault+https"] = readVault }
go
func (d *Data) registerReaders() { d.sourceReaders = make(map[string]func(*Source, ...string) ([]byte, error)) d.sourceReaders["aws+smp"] = readAWSSMP d.sourceReaders["boltdb"] = readBoltDB d.sourceReaders["consul"] = readConsul d.sourceReaders["consul+http"] = readConsul d.sourceReaders["consul+https"] = readConsul d.sourceReaders["env"] = readEnv d.sourceReaders["file"] = readFile d.sourceReaders["http"] = readHTTP d.sourceReaders["https"] = readHTTP d.sourceReaders["merge"] = d.readMerge d.sourceReaders["stdin"] = readStdin d.sourceReaders["vault"] = readVault d.sourceReaders["vault+http"] = readVault d.sourceReaders["vault+https"] = readVault }
[ "func", "(", "d", "*", "Data", ")", "registerReaders", "(", ")", "{", "d", ".", "sourceReaders", "=", "make", "(", "map", "[", "string", "]", "func", "(", "*", "Source", ",", "...", "string", ")", "(", "[", "]", "byte", ",", "error", ")", ")", ...
// registerReaders registers the source-reader functions
[ "registerReaders", "registers", "the", "source", "-", "reader", "functions" ]
20937becaa32cdec93e77a84ad04c73e9155b8e7
https://github.com/hairyhenderson/gomplate/blob/20937becaa32cdec93e77a84ad04c73e9155b8e7/data/datasource.go#L44-L61
153,050
hairyhenderson/gomplate
data/datasource.go
lookupReader
func (d *Data) lookupReader(scheme string) (func(*Source, ...string) ([]byte, error), error) { if d.sourceReaders == nil { d.registerReaders() } r, ok := d.sourceReaders[scheme] if !ok { return nil, errors.Errorf("scheme %s not registered", scheme) } return r, nil }
go
func (d *Data) lookupReader(scheme string) (func(*Source, ...string) ([]byte, error), error) { if d.sourceReaders == nil { d.registerReaders() } r, ok := d.sourceReaders[scheme] if !ok { return nil, errors.Errorf("scheme %s not registered", scheme) } return r, nil }
[ "func", "(", "d", "*", "Data", ")", "lookupReader", "(", "scheme", "string", ")", "(", "func", "(", "*", "Source", ",", "...", "string", ")", "(", "[", "]", "byte", ",", "error", ")", ",", "error", ")", "{", "if", "d", ".", "sourceReaders", "==",...
// lookupReader - return the reader function for the given scheme
[ "lookupReader", "-", "return", "the", "reader", "function", "for", "the", "given", "scheme" ]
20937becaa32cdec93e77a84ad04c73e9155b8e7
https://github.com/hairyhenderson/gomplate/blob/20937becaa32cdec93e77a84ad04c73e9155b8e7/data/datasource.go#L64-L73
153,051
hairyhenderson/gomplate
data/datasource.go
NewData
func NewData(datasourceArgs, headerArgs []string) (*Data, error) { headers, err := parseHeaderArgs(headerArgs) if err != nil { return nil, err } data := &Data{ Sources: make(map[string]*Source), extraHeaders: headers, } for _, v := range datasourceArgs { s, err := parseSource(v) if err != nil { return nil, errors.Wrapf(err, "error parsing datasource") } s.header = headers[s.Alias] // pop the header out of the map, so we end up with only the unreferenced ones delete(headers, s.Alias) data.Sources[s.Alias] = s } return data, nil }
go
func NewData(datasourceArgs, headerArgs []string) (*Data, error) { headers, err := parseHeaderArgs(headerArgs) if err != nil { return nil, err } data := &Data{ Sources: make(map[string]*Source), extraHeaders: headers, } for _, v := range datasourceArgs { s, err := parseSource(v) if err != nil { return nil, errors.Wrapf(err, "error parsing datasource") } s.header = headers[s.Alias] // pop the header out of the map, so we end up with only the unreferenced ones delete(headers, s.Alias) data.Sources[s.Alias] = s } return data, nil }
[ "func", "NewData", "(", "datasourceArgs", ",", "headerArgs", "[", "]", "string", ")", "(", "*", "Data", ",", "error", ")", "{", "headers", ",", "err", ":=", "parseHeaderArgs", "(", "headerArgs", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil"...
// NewData - constructor for Data
[ "NewData", "-", "constructor", "for", "Data" ]
20937becaa32cdec93e77a84ad04c73e9155b8e7
https://github.com/hairyhenderson/gomplate/blob/20937becaa32cdec93e77a84ad04c73e9155b8e7/data/datasource.go#L95-L118
153,052
hairyhenderson/gomplate
data/datasource.go
DatasourceReachable
func (d *Data) DatasourceReachable(alias string, args ...string) bool { source, ok := d.Sources[alias] if !ok { return false } _, err := d.readSource(source, args...) return err == nil }
go
func (d *Data) DatasourceReachable(alias string, args ...string) bool { source, ok := d.Sources[alias] if !ok { return false } _, err := d.readSource(source, args...) return err == nil }
[ "func", "(", "d", "*", "Data", ")", "DatasourceReachable", "(", "alias", "string", ",", "args", "...", "string", ")", "bool", "{", "source", ",", "ok", ":=", "d", ".", "Sources", "[", "alias", "]", "\n", "if", "!", "ok", "{", "return", "false", "\n...
// DatasourceReachable - Determines if the named datasource is reachable with // the given arguments. Reads from the datasource, and discards the returned data.
[ "DatasourceReachable", "-", "Determines", "if", "the", "named", "datasource", "is", "reachable", "with", "the", "given", "arguments", ".", "Reads", "from", "the", "datasource", "and", "discards", "the", "returned", "data", "." ]
20937becaa32cdec93e77a84ad04c73e9155b8e7
https://github.com/hairyhenderson/gomplate/blob/20937becaa32cdec93e77a84ad04c73e9155b8e7/data/datasource.go#L377-L384
153,053
hairyhenderson/gomplate
vault/vault.go
Read
func (v *Vault) Read(path string) ([]byte, error) { secret, err := v.client.Logical().Read(path) if err != nil { return nil, err } if secret == nil { return []byte{}, nil } var buf bytes.Buffer enc := json.NewEncoder(&buf) if err := enc.Encode(secret.Data); err != nil { return nil, err } return buf.Bytes(), nil }
go
func (v *Vault) Read(path string) ([]byte, error) { secret, err := v.client.Logical().Read(path) if err != nil { return nil, err } if secret == nil { return []byte{}, nil } var buf bytes.Buffer enc := json.NewEncoder(&buf) if err := enc.Encode(secret.Data); err != nil { return nil, err } return buf.Bytes(), nil }
[ "func", "(", "v", "*", "Vault", ")", "Read", "(", "path", "string", ")", "(", "[", "]", "byte", ",", "error", ")", "{", "secret", ",", "err", ":=", "v", ".", "client", ".", "Logical", "(", ")", ".", "Read", "(", "path", ")", "\n", "if", "err"...
// Read - returns the value of a given path. If no value is found at the given // path, returns empty slice.
[ "Read", "-", "returns", "the", "value", "of", "a", "given", "path", ".", "If", "no", "value", "is", "found", "at", "the", "given", "path", "returns", "empty", "slice", "." ]
20937becaa32cdec93e77a84ad04c73e9155b8e7
https://github.com/hairyhenderson/gomplate/blob/20937becaa32cdec93e77a84ad04c73e9155b8e7/vault/vault.go#L64-L79
153,054
hairyhenderson/gomplate
math/math.go
Seq
func Seq(start, end, step int64) []int64 { // a step of 0 just returns an empty sequence if step == 0 { return []int64{} } // handle cases where step has wrong sign if end < start && step > 0 { step = -step } if end > start && step < 0 { step = -step } // adjust the end so it aligns exactly (avoids infinite loop!) end = end - (end-start)%step seq := []int64{start} last := start for last != end { last = seq[len(seq)-1] + step seq = append(seq, last) } return seq }
go
func Seq(start, end, step int64) []int64 { // a step of 0 just returns an empty sequence if step == 0 { return []int64{} } // handle cases where step has wrong sign if end < start && step > 0 { step = -step } if end > start && step < 0 { step = -step } // adjust the end so it aligns exactly (avoids infinite loop!) end = end - (end-start)%step seq := []int64{start} last := start for last != end { last = seq[len(seq)-1] + step seq = append(seq, last) } return seq }
[ "func", "Seq", "(", "start", ",", "end", ",", "step", "int64", ")", "[", "]", "int64", "{", "// a step of 0 just returns an empty sequence", "if", "step", "==", "0", "{", "return", "[", "]", "int64", "{", "}", "\n", "}", "\n\n", "// handle cases where step h...
// Seq - return a sequence from `start` to `end`, in steps of `step`.
[ "Seq", "-", "return", "a", "sequence", "from", "start", "to", "end", "in", "steps", "of", "step", "." ]
20937becaa32cdec93e77a84ad04c73e9155b8e7
https://github.com/hairyhenderson/gomplate/blob/20937becaa32cdec93e77a84ad04c73e9155b8e7/math/math.go#L22-L46
153,055
hairyhenderson/gomplate
funcs/time.go
padRight
func padRight(in, pad string, length int) string { for { in += pad if len(in) > length { return in[0:length] } } }
go
func padRight(in, pad string, length int) string { for { in += pad if len(in) > length { return in[0:length] } } }
[ "func", "padRight", "(", "in", ",", "pad", "string", ",", "length", "int", ")", "string", "{", "for", "{", "in", "+=", "pad", "\n", "if", "len", "(", "in", ")", ">", "length", "{", "return", "in", "[", "0", ":", "length", "]", "\n", "}", "\n", ...
// pads a number with zeroes
[ "pads", "a", "number", "with", "zeroes" ]
20937becaa32cdec93e77a84ad04c73e9155b8e7
https://github.com/hairyhenderson/gomplate/blob/20937becaa32cdec93e77a84ad04c73e9155b8e7/funcs/time.go#L195-L202
153,056
hairyhenderson/gomplate
funcs.go
Funcs
func Funcs(d *data.Data) template.FuncMap { f := template.FuncMap{} funcs.AddDataFuncs(f, d) funcs.AWSFuncs(f) funcs.AddBase64Funcs(f) funcs.AddNetFuncs(f) funcs.AddReFuncs(f) funcs.AddStringFuncs(f) funcs.AddEnvFuncs(f) funcs.AddConvFuncs(f) funcs.AddTimeFuncs(f) funcs.AddMathFuncs(f) funcs.AddCryptoFuncs(f) funcs.AddFileFuncs(f) funcs.AddFilePathFuncs(f) funcs.AddPathFuncs(f) funcs.AddSockaddrFuncs(f) funcs.AddTestFuncs(f) funcs.AddCollFuncs(f) funcs.AddUUIDFuncs(f) funcs.AddRandomFuncs(f) return f }
go
func Funcs(d *data.Data) template.FuncMap { f := template.FuncMap{} funcs.AddDataFuncs(f, d) funcs.AWSFuncs(f) funcs.AddBase64Funcs(f) funcs.AddNetFuncs(f) funcs.AddReFuncs(f) funcs.AddStringFuncs(f) funcs.AddEnvFuncs(f) funcs.AddConvFuncs(f) funcs.AddTimeFuncs(f) funcs.AddMathFuncs(f) funcs.AddCryptoFuncs(f) funcs.AddFileFuncs(f) funcs.AddFilePathFuncs(f) funcs.AddPathFuncs(f) funcs.AddSockaddrFuncs(f) funcs.AddTestFuncs(f) funcs.AddCollFuncs(f) funcs.AddUUIDFuncs(f) funcs.AddRandomFuncs(f) return f }
[ "func", "Funcs", "(", "d", "*", "data", ".", "Data", ")", "template", ".", "FuncMap", "{", "f", ":=", "template", ".", "FuncMap", "{", "}", "\n", "funcs", ".", "AddDataFuncs", "(", "f", ",", "d", ")", "\n", "funcs", ".", "AWSFuncs", "(", "f", ")"...
// Funcs - The function mappings are defined here!
[ "Funcs", "-", "The", "function", "mappings", "are", "defined", "here!" ]
20937becaa32cdec93e77a84ad04c73e9155b8e7
https://github.com/hairyhenderson/gomplate/blob/20937becaa32cdec93e77a84ad04c73e9155b8e7/funcs.go#L11-L33
153,057
hairyhenderson/gomplate
data/data.go
JSON
func JSON(in string) (map[string]interface{}, error) { obj := make(map[string]interface{}) out, err := unmarshalObj(obj, in, yaml.Unmarshal) if err != nil { return out, err } _, ok := out[ejsonJson.PublicKeyField] if ok { out, err = decryptEJSON(in) } return out, err }
go
func JSON(in string) (map[string]interface{}, error) { obj := make(map[string]interface{}) out, err := unmarshalObj(obj, in, yaml.Unmarshal) if err != nil { return out, err } _, ok := out[ejsonJson.PublicKeyField] if ok { out, err = decryptEJSON(in) } return out, err }
[ "func", "JSON", "(", "in", "string", ")", "(", "map", "[", "string", "]", "interface", "{", "}", ",", "error", ")", "{", "obj", ":=", "make", "(", "map", "[", "string", "]", "interface", "{", "}", ")", "\n", "out", ",", "err", ":=", "unmarshalObj...
// JSON - Unmarshal a JSON Object. Can be ejson-encrypted.
[ "JSON", "-", "Unmarshal", "a", "JSON", "Object", ".", "Can", "be", "ejson", "-", "encrypted", "." ]
20937becaa32cdec93e77a84ad04c73e9155b8e7
https://github.com/hairyhenderson/gomplate/blob/20937becaa32cdec93e77a84ad04c73e9155b8e7/data/data.go#L47-L59
153,058
hairyhenderson/gomplate
data/data.go
decryptEJSON
func decryptEJSON(in string) (map[string]interface{}, error) { keyDir := env.Getenv("EJSON_KEYDIR", "/opt/ejson/keys") key := env.Getenv("EJSON_KEY") rIn := bytes.NewBufferString(in) rOut := &bytes.Buffer{} err := ejson.Decrypt(rIn, rOut, keyDir, key) if err != nil { return nil, errors.WithStack(err) } obj := make(map[string]interface{}) out, err := unmarshalObj(obj, rOut.String(), yaml.Unmarshal) if err != nil { return nil, errors.WithStack(err) } delete(out, ejsonJson.PublicKeyField) return out, nil }
go
func decryptEJSON(in string) (map[string]interface{}, error) { keyDir := env.Getenv("EJSON_KEYDIR", "/opt/ejson/keys") key := env.Getenv("EJSON_KEY") rIn := bytes.NewBufferString(in) rOut := &bytes.Buffer{} err := ejson.Decrypt(rIn, rOut, keyDir, key) if err != nil { return nil, errors.WithStack(err) } obj := make(map[string]interface{}) out, err := unmarshalObj(obj, rOut.String(), yaml.Unmarshal) if err != nil { return nil, errors.WithStack(err) } delete(out, ejsonJson.PublicKeyField) return out, nil }
[ "func", "decryptEJSON", "(", "in", "string", ")", "(", "map", "[", "string", "]", "interface", "{", "}", ",", "error", ")", "{", "keyDir", ":=", "env", ".", "Getenv", "(", "\"", "\"", ",", "\"", "\"", ")", "\n", "key", ":=", "env", ".", "Getenv",...
// decryptEJSON - decrypts an ejson input, and unmarshals it, stripping the _public_key field.
[ "decryptEJSON", "-", "decrypts", "an", "ejson", "input", "and", "unmarshals", "it", "stripping", "the", "_public_key", "field", "." ]
20937becaa32cdec93e77a84ad04c73e9155b8e7
https://github.com/hairyhenderson/gomplate/blob/20937becaa32cdec93e77a84ad04c73e9155b8e7/data/data.go#L62-L79
153,059
hairyhenderson/gomplate
data/data.go
JSONArray
func JSONArray(in string) ([]interface{}, error) { obj := make([]interface{}, 1) return unmarshalArray(obj, in, yaml.Unmarshal) }
go
func JSONArray(in string) ([]interface{}, error) { obj := make([]interface{}, 1) return unmarshalArray(obj, in, yaml.Unmarshal) }
[ "func", "JSONArray", "(", "in", "string", ")", "(", "[", "]", "interface", "{", "}", ",", "error", ")", "{", "obj", ":=", "make", "(", "[", "]", "interface", "{", "}", ",", "1", ")", "\n", "return", "unmarshalArray", "(", "obj", ",", "in", ",", ...
// JSONArray - Unmarshal a JSON Array
[ "JSONArray", "-", "Unmarshal", "a", "JSON", "Array" ]
20937becaa32cdec93e77a84ad04c73e9155b8e7
https://github.com/hairyhenderson/gomplate/blob/20937becaa32cdec93e77a84ad04c73e9155b8e7/data/data.go#L82-L85
153,060
hairyhenderson/gomplate
data/data.go
YAML
func YAML(in string) (map[string]interface{}, error) { obj := make(map[string]interface{}) return unmarshalObj(obj, in, yaml.Unmarshal) }
go
func YAML(in string) (map[string]interface{}, error) { obj := make(map[string]interface{}) return unmarshalObj(obj, in, yaml.Unmarshal) }
[ "func", "YAML", "(", "in", "string", ")", "(", "map", "[", "string", "]", "interface", "{", "}", ",", "error", ")", "{", "obj", ":=", "make", "(", "map", "[", "string", "]", "interface", "{", "}", ")", "\n", "return", "unmarshalObj", "(", "obj", ...
// YAML - Unmarshal a YAML Object
[ "YAML", "-", "Unmarshal", "a", "YAML", "Object" ]
20937becaa32cdec93e77a84ad04c73e9155b8e7
https://github.com/hairyhenderson/gomplate/blob/20937becaa32cdec93e77a84ad04c73e9155b8e7/data/data.go#L88-L91
153,061
hairyhenderson/gomplate
data/data.go
TOML
func TOML(in string) (interface{}, error) { obj := make(map[string]interface{}) return unmarshalObj(obj, in, toml.Unmarshal) }
go
func TOML(in string) (interface{}, error) { obj := make(map[string]interface{}) return unmarshalObj(obj, in, toml.Unmarshal) }
[ "func", "TOML", "(", "in", "string", ")", "(", "interface", "{", "}", ",", "error", ")", "{", "obj", ":=", "make", "(", "map", "[", "string", "]", "interface", "{", "}", ")", "\n", "return", "unmarshalObj", "(", "obj", ",", "in", ",", "toml", "."...
// TOML - Unmarshal a TOML Object
[ "TOML", "-", "Unmarshal", "a", "TOML", "Object" ]
20937becaa32cdec93e77a84ad04c73e9155b8e7
https://github.com/hairyhenderson/gomplate/blob/20937becaa32cdec93e77a84ad04c73e9155b8e7/data/data.go#L100-L103
153,062
hairyhenderson/gomplate
data/data.go
dotEnv
func dotEnv(in string) (interface{}, error) { env, err := godotenv.Unmarshal(in) if err != nil { return nil, err } out := make(map[string]interface{}) for k, v := range env { out[k] = v } return out, nil }
go
func dotEnv(in string) (interface{}, error) { env, err := godotenv.Unmarshal(in) if err != nil { return nil, err } out := make(map[string]interface{}) for k, v := range env { out[k] = v } return out, nil }
[ "func", "dotEnv", "(", "in", "string", ")", "(", "interface", "{", "}", ",", "error", ")", "{", "env", ",", "err", ":=", "godotenv", ".", "Unmarshal", "(", "in", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", ...
// dotEnv - Unmarshal a dotenv file
[ "dotEnv", "-", "Unmarshal", "a", "dotenv", "file" ]
20937becaa32cdec93e77a84ad04c73e9155b8e7
https://github.com/hairyhenderson/gomplate/blob/20937becaa32cdec93e77a84ad04c73e9155b8e7/data/data.go#L106-L116
153,063
hairyhenderson/gomplate
data/data.go
autoIndex
func autoIndex(i int) string { s := "" for n := 0; n <= i/26; n++ { s += string('A' + i%26) } return s }
go
func autoIndex(i int) string { s := "" for n := 0; n <= i/26; n++ { s += string('A' + i%26) } return s }
[ "func", "autoIndex", "(", "i", "int", ")", "string", "{", "s", ":=", "\"", "\"", "\n", "for", "n", ":=", "0", ";", "n", "<=", "i", "/", "26", ";", "n", "++", "{", "s", "+=", "string", "(", "'A'", "+", "i", "%", "26", ")", "\n", "}", "\n",...
// autoIndex - calculates a default string column name given a numeric value
[ "autoIndex", "-", "calculates", "a", "default", "string", "column", "name", "given", "a", "numeric", "value" ]
20937becaa32cdec93e77a84ad04c73e9155b8e7
https://github.com/hairyhenderson/gomplate/blob/20937becaa32cdec93e77a84ad04c73e9155b8e7/data/data.go#L164-L170
153,064
hairyhenderson/gomplate
data/data.go
ToJSON
func ToJSON(in interface{}) (string, error) { s, err := toJSONBytes(in) if err != nil { return "", err } return string(s), nil }
go
func ToJSON(in interface{}) (string, error) { s, err := toJSONBytes(in) if err != nil { return "", err } return string(s), nil }
[ "func", "ToJSON", "(", "in", "interface", "{", "}", ")", "(", "string", ",", "error", ")", "{", "s", ",", "err", ":=", "toJSONBytes", "(", "in", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "err", "\n", "}", "\n", "retur...
// ToJSON - Stringify a struct as JSON
[ "ToJSON", "-", "Stringify", "a", "struct", "as", "JSON" ]
20937becaa32cdec93e77a84ad04c73e9155b8e7
https://github.com/hairyhenderson/gomplate/blob/20937becaa32cdec93e77a84ad04c73e9155b8e7/data/data.go#L288-L294
153,065
hairyhenderson/gomplate
data/data.go
ToTOML
func ToTOML(in interface{}) (string, error) { buf := new(bytes.Buffer) err := toml.NewEncoder(buf).Encode(in) if err != nil { return "", errors.Wrapf(err, "Unable to marshal %s", in) } return buf.String(), nil }
go
func ToTOML(in interface{}) (string, error) { buf := new(bytes.Buffer) err := toml.NewEncoder(buf).Encode(in) if err != nil { return "", errors.Wrapf(err, "Unable to marshal %s", in) } return buf.String(), nil }
[ "func", "ToTOML", "(", "in", "interface", "{", "}", ")", "(", "string", ",", "error", ")", "{", "buf", ":=", "new", "(", "bytes", ".", "Buffer", ")", "\n", "err", ":=", "toml", ".", "NewEncoder", "(", "buf", ")", ".", "Encode", "(", "in", ")", ...
// ToTOML - Stringify a struct as TOML
[ "ToTOML", "-", "Stringify", "a", "struct", "as", "TOML" ]
20937becaa32cdec93e77a84ad04c73e9155b8e7
https://github.com/hairyhenderson/gomplate/blob/20937becaa32cdec93e77a84ad04c73e9155b8e7/data/data.go#L317-L324
153,066
hairyhenderson/gomplate
libkv/consul.go
NewConsul
func NewConsul(u *url.URL) (*LibKV, error) { consul.Register() c, err := consulURL(u) if err != nil { return nil, err } config, err := consulConfig(c.Scheme == https) if err != nil { return nil, err } if role := env.Getenv("CONSUL_VAULT_ROLE", ""); role != "" { mount := env.Getenv("CONSUL_VAULT_MOUNT", "consul") var client *vault.Vault client, err = vault.New(nil) if err != nil { return nil, err } err = client.Login() defer client.Logout() if err != nil { return nil, err } path := fmt.Sprintf("%s/creds/%s", mount, role) var data []byte data, err = client.Read(path) if err != nil { return nil, errors.Wrapf(err, "vault consul auth failed") } decoded := make(map[string]interface{}) err = yaml.Unmarshal(data, &decoded) if err != nil { return nil, errors.Wrapf(err, "Unable to unmarshal object") } token := decoded["token"].(string) // nolint: gosec _ = os.Setenv("CONSUL_HTTP_TOKEN", token) } var kv store.Store kv, err = libkv.NewStore(store.CONSUL, []string{c.String()}, config) if err != nil { return nil, errors.Wrapf(err, "Consul setup failed") } return &LibKV{kv}, nil }
go
func NewConsul(u *url.URL) (*LibKV, error) { consul.Register() c, err := consulURL(u) if err != nil { return nil, err } config, err := consulConfig(c.Scheme == https) if err != nil { return nil, err } if role := env.Getenv("CONSUL_VAULT_ROLE", ""); role != "" { mount := env.Getenv("CONSUL_VAULT_MOUNT", "consul") var client *vault.Vault client, err = vault.New(nil) if err != nil { return nil, err } err = client.Login() defer client.Logout() if err != nil { return nil, err } path := fmt.Sprintf("%s/creds/%s", mount, role) var data []byte data, err = client.Read(path) if err != nil { return nil, errors.Wrapf(err, "vault consul auth failed") } decoded := make(map[string]interface{}) err = yaml.Unmarshal(data, &decoded) if err != nil { return nil, errors.Wrapf(err, "Unable to unmarshal object") } token := decoded["token"].(string) // nolint: gosec _ = os.Setenv("CONSUL_HTTP_TOKEN", token) } var kv store.Store kv, err = libkv.NewStore(store.CONSUL, []string{c.String()}, config) if err != nil { return nil, errors.Wrapf(err, "Consul setup failed") } return &LibKV{kv}, nil }
[ "func", "NewConsul", "(", "u", "*", "url", ".", "URL", ")", "(", "*", "LibKV", ",", "error", ")", "{", "consul", ".", "Register", "(", ")", "\n", "c", ",", "err", ":=", "consulURL", "(", "u", ")", "\n", "if", "err", "!=", "nil", "{", "return", ...
// NewConsul - instantiate a new Consul datasource handler
[ "NewConsul", "-", "instantiate", "a", "new", "Consul", "datasource", "handler" ]
20937becaa32cdec93e77a84ad04c73e9155b8e7
https://github.com/hairyhenderson/gomplate/blob/20937becaa32cdec93e77a84ad04c73e9155b8e7/libkv/consul.go#L29-L78
153,067
hairyhenderson/gomplate
coll/coll.go
Keys
func Keys(in ...map[string]interface{}) ([]string, error) { if len(in) == 0 { return nil, fmt.Errorf("need at least one argument") } keys := []string{} for _, m := range in { k, _ := splitMap(m) keys = append(keys, k...) } return keys, nil }
go
func Keys(in ...map[string]interface{}) ([]string, error) { if len(in) == 0 { return nil, fmt.Errorf("need at least one argument") } keys := []string{} for _, m := range in { k, _ := splitMap(m) keys = append(keys, k...) } return keys, nil }
[ "func", "Keys", "(", "in", "...", "map", "[", "string", "]", "interface", "{", "}", ")", "(", "[", "]", "string", ",", "error", ")", "{", "if", "len", "(", "in", ")", "==", "0", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\""...
// Keys returns the list of keys in one or more maps. The returned list of keys // is ordered by map, each in sorted key order.
[ "Keys", "returns", "the", "list", "of", "keys", "in", "one", "or", "more", "maps", ".", "The", "returned", "list", "of", "keys", "is", "ordered", "by", "map", "each", "in", "sorted", "key", "order", "." ]
20937becaa32cdec93e77a84ad04c73e9155b8e7
https://github.com/hairyhenderson/gomplate/blob/20937becaa32cdec93e77a84ad04c73e9155b8e7/coll/coll.go#L74-L84
153,068
hairyhenderson/gomplate
coll/coll.go
mergeValues
func mergeValues(d map[string]interface{}, o map[string]interface{}) map[string]interface{} { def := copyMap(d) over := copyMap(o) for k, v := range over { // If the key doesn't exist already, then just set the key to that value if _, exists := def[k]; !exists { def[k] = v continue } nextMap, ok := v.(map[string]interface{}) // If it isn't another map, overwrite the value if !ok { def[k] = v continue } // Edge case: If the key exists in the default, but isn't a map defMap, isMap := def[k].(map[string]interface{}) // If the override map has a map for this key, prefer it if !isMap { def[k] = v continue } // If we got to this point, it is a map in both, so merge them def[k] = mergeValues(defMap, nextMap) } return def }
go
func mergeValues(d map[string]interface{}, o map[string]interface{}) map[string]interface{} { def := copyMap(d) over := copyMap(o) for k, v := range over { // If the key doesn't exist already, then just set the key to that value if _, exists := def[k]; !exists { def[k] = v continue } nextMap, ok := v.(map[string]interface{}) // If it isn't another map, overwrite the value if !ok { def[k] = v continue } // Edge case: If the key exists in the default, but isn't a map defMap, isMap := def[k].(map[string]interface{}) // If the override map has a map for this key, prefer it if !isMap { def[k] = v continue } // If we got to this point, it is a map in both, so merge them def[k] = mergeValues(defMap, nextMap) } return def }
[ "func", "mergeValues", "(", "d", "map", "[", "string", "]", "interface", "{", "}", ",", "o", "map", "[", "string", "]", "interface", "{", "}", ")", "map", "[", "string", "]", "interface", "{", "}", "{", "def", ":=", "copyMap", "(", "d", ")", "\n"...
// Merges a default and override map
[ "Merges", "a", "default", "and", "override", "map" ]
20937becaa32cdec93e77a84ad04c73e9155b8e7
https://github.com/hairyhenderson/gomplate/blob/20937becaa32cdec93e77a84ad04c73e9155b8e7/coll/coll.go#L184-L210
153,069
hairyhenderson/gomplate
coll/coll.go
Sort
func Sort(key string, list interface{}) (out []interface{}, err error) { if list == nil { return nil, nil } ia, err := interfaceSlice(list) if err != nil { return nil, err } // if the types are all the same, we can sort the slice if sameTypes(ia) { s := make([]interface{}, len(ia)) // make a copy so the original is unmodified copy(s, ia) sort.SliceStable(s, func(i, j int) bool { return lessThan(key)(s[i], s[j]) }) return s, nil } return ia, nil }
go
func Sort(key string, list interface{}) (out []interface{}, err error) { if list == nil { return nil, nil } ia, err := interfaceSlice(list) if err != nil { return nil, err } // if the types are all the same, we can sort the slice if sameTypes(ia) { s := make([]interface{}, len(ia)) // make a copy so the original is unmodified copy(s, ia) sort.SliceStable(s, func(i, j int) bool { return lessThan(key)(s[i], s[j]) }) return s, nil } return ia, nil }
[ "func", "Sort", "(", "key", "string", ",", "list", "interface", "{", "}", ")", "(", "out", "[", "]", "interface", "{", "}", ",", "err", "error", ")", "{", "if", "list", "==", "nil", "{", "return", "nil", ",", "nil", "\n", "}", "\n\n", "ia", ","...
// Sort a given array or slice. Uses natural sort order if possible. If a // non-empty key is given and the list elements are maps, this will attempt to // sort by the values of those entries. // // Does not modify the input list.
[ "Sort", "a", "given", "array", "or", "slice", ".", "Uses", "natural", "sort", "order", "if", "possible", ".", "If", "a", "non", "-", "empty", "key", "is", "given", "and", "the", "list", "elements", "are", "maps", "this", "will", "attempt", "to", "sort"...
20937becaa32cdec93e77a84ad04c73e9155b8e7
https://github.com/hairyhenderson/gomplate/blob/20937becaa32cdec93e77a84ad04c73e9155b8e7/coll/coll.go#L217-L237
153,070
hairyhenderson/gomplate
coll/coll.go
lessThan
func lessThan(key string) func(left, right interface{}) bool { return func(left, right interface{}) bool { val := reflect.Indirect(reflect.ValueOf(left)) rval := reflect.Indirect(reflect.ValueOf(right)) switch val.Kind() { case reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64, reflect.Int: return val.Int() < rval.Int() case reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint, reflect.Uint64: return val.Uint() < rval.Uint() case reflect.Float32, reflect.Float64: return val.Float() < rval.Float() case reflect.String: return val.String() < rval.String() case reflect.MapOf( reflect.TypeOf(reflect.String), reflect.TypeOf(reflect.Interface), ).Kind(): kval := reflect.ValueOf(key) if !val.MapIndex(kval).IsValid() { return false } newleft := val.MapIndex(kval).Interface() newright := rval.MapIndex(kval).Interface() return lessThan("")(newleft, newright) case reflect.Struct: if !val.FieldByName(key).IsValid() { return false } newleft := val.FieldByName(key).Interface() newright := rval.FieldByName(key).Interface() return lessThan("")(newleft, newright) default: // it's not really comparable, so... return false } } }
go
func lessThan(key string) func(left, right interface{}) bool { return func(left, right interface{}) bool { val := reflect.Indirect(reflect.ValueOf(left)) rval := reflect.Indirect(reflect.ValueOf(right)) switch val.Kind() { case reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64, reflect.Int: return val.Int() < rval.Int() case reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint, reflect.Uint64: return val.Uint() < rval.Uint() case reflect.Float32, reflect.Float64: return val.Float() < rval.Float() case reflect.String: return val.String() < rval.String() case reflect.MapOf( reflect.TypeOf(reflect.String), reflect.TypeOf(reflect.Interface), ).Kind(): kval := reflect.ValueOf(key) if !val.MapIndex(kval).IsValid() { return false } newleft := val.MapIndex(kval).Interface() newright := rval.MapIndex(kval).Interface() return lessThan("")(newleft, newright) case reflect.Struct: if !val.FieldByName(key).IsValid() { return false } newleft := val.FieldByName(key).Interface() newright := rval.FieldByName(key).Interface() return lessThan("")(newleft, newright) default: // it's not really comparable, so... return false } } }
[ "func", "lessThan", "(", "key", "string", ")", "func", "(", "left", ",", "right", "interface", "{", "}", ")", "bool", "{", "return", "func", "(", "left", ",", "right", "interface", "{", "}", ")", "bool", "{", "val", ":=", "reflect", ".", "Indirect", ...
// lessThan - compare two values of the same type
[ "lessThan", "-", "compare", "two", "values", "of", "the", "same", "type" ]
20937becaa32cdec93e77a84ad04c73e9155b8e7
https://github.com/hairyhenderson/gomplate/blob/20937becaa32cdec93e77a84ad04c73e9155b8e7/coll/coll.go#L240-L276
153,071
hairyhenderson/gomplate
config.go
getMode
func (o *Config) getMode() (os.FileMode, bool, error) { modeOverride := o.OutMode != "" m, err := strconv.ParseUint("0"+o.OutMode, 8, 32) if err != nil { return 0, false, err } mode := os.FileMode(m) if mode == 0 && o.Input != "" { mode = 0644 } return mode, modeOverride, nil }
go
func (o *Config) getMode() (os.FileMode, bool, error) { modeOverride := o.OutMode != "" m, err := strconv.ParseUint("0"+o.OutMode, 8, 32) if err != nil { return 0, false, err } mode := os.FileMode(m) if mode == 0 && o.Input != "" { mode = 0644 } return mode, modeOverride, nil }
[ "func", "(", "o", "*", "Config", ")", "getMode", "(", ")", "(", "os", ".", "FileMode", ",", "bool", ",", "error", ")", "{", "modeOverride", ":=", "o", ".", "OutMode", "!=", "\"", "\"", "\n", "m", ",", "err", ":=", "strconv", ".", "ParseUint", "("...
// parse an os.FileMode out of the string, and let us know if it's an override or not...
[ "parse", "an", "os", ".", "FileMode", "out", "of", "the", "string", "and", "let", "us", "know", "if", "it", "s", "an", "override", "or", "not", "..." ]
20937becaa32cdec93e77a84ad04c73e9155b8e7
https://github.com/hairyhenderson/gomplate/blob/20937becaa32cdec93e77a84ad04c73e9155b8e7/config.go#L52-L63
153,072
hairyhenderson/gomplate
random/random.go
StringBounds
func StringBounds(count int, lower, upper rune) (r string, err error) { chars := filterRange(lower, upper) if len(chars) == 0 { return "", errors.Errorf("No printable codepoints found between U%#q and U%#q.", lower, upper) } return rndString(count, chars) }
go
func StringBounds(count int, lower, upper rune) (r string, err error) { chars := filterRange(lower, upper) if len(chars) == 0 { return "", errors.Errorf("No printable codepoints found between U%#q and U%#q.", lower, upper) } return rndString(count, chars) }
[ "func", "StringBounds", "(", "count", "int", ",", "lower", ",", "upper", "rune", ")", "(", "r", "string", ",", "err", "error", ")", "{", "chars", ":=", "filterRange", "(", "lower", ",", "upper", ")", "\n", "if", "len", "(", "chars", ")", "==", "0",...
// StringBounds returns a random string of characters with a codepoint // between the lower and upper bounds. Only valid characters are returned // and if a range is given where no valid characters can be found, an error // will be returned.
[ "StringBounds", "returns", "a", "random", "string", "of", "characters", "with", "a", "codepoint", "between", "the", "lower", "and", "upper", "bounds", ".", "Only", "valid", "characters", "are", "returned", "and", "if", "a", "range", "is", "given", "where", "...
20937becaa32cdec93e77a84ad04c73e9155b8e7
https://github.com/hairyhenderson/gomplate/blob/20937becaa32cdec93e77a84ad04c73e9155b8e7/random/random.go#L38-L44
153,073
hairyhenderson/gomplate
random/random.go
rndString
func rndString(count int, chars []rune) (string, error) { s := make([]rune, count) for i := range s { s[i] = chars[Rnd.Intn(len(chars))] } return string(s), nil }
go
func rndString(count int, chars []rune) (string, error) { s := make([]rune, count) for i := range s { s[i] = chars[Rnd.Intn(len(chars))] } return string(s), nil }
[ "func", "rndString", "(", "count", "int", ",", "chars", "[", "]", "rune", ")", "(", "string", ",", "error", ")", "{", "s", ":=", "make", "(", "[", "]", "rune", ",", "count", ")", "\n", "for", "i", ":=", "range", "s", "{", "s", "[", "i", "]", ...
// produce a string containing a random selection of given characters
[ "produce", "a", "string", "containing", "a", "random", "selection", "of", "given", "characters" ]
20937becaa32cdec93e77a84ad04c73e9155b8e7
https://github.com/hairyhenderson/gomplate/blob/20937becaa32cdec93e77a84ad04c73e9155b8e7/random/random.go#L47-L53
153,074
hairyhenderson/gomplate
random/random.go
Float
func Float(min, max float64) (float64, error) { return min + Rnd.Float64()*(max-min), nil }
go
func Float(min, max float64) (float64, error) { return min + Rnd.Float64()*(max-min), nil }
[ "func", "Float", "(", "min", ",", "max", "float64", ")", "(", "float64", ",", "error", ")", "{", "return", "min", "+", "Rnd", ".", "Float64", "(", ")", "*", "(", "max", "-", "min", ")", ",", "nil", "\n", "}" ]
// Float - For now this is really just a wrapper around `rand.Float64`
[ "Float", "-", "For", "now", "this", "is", "really", "just", "a", "wrapper", "around", "rand", ".", "Float64" ]
20937becaa32cdec93e77a84ad04c73e9155b8e7
https://github.com/hairyhenderson/gomplate/blob/20937becaa32cdec93e77a84ad04c73e9155b8e7/random/random.go#L107-L109
153,075
hairyhenderson/gomplate
context.go
Env
func (c *context) Env() map[string]string { env := make(map[string]string) for _, i := range os.Environ() { sep := strings.Index(i, "=") env[i[0:sep]] = i[sep+1:] } return env }
go
func (c *context) Env() map[string]string { env := make(map[string]string) for _, i := range os.Environ() { sep := strings.Index(i, "=") env[i[0:sep]] = i[sep+1:] } return env }
[ "func", "(", "c", "*", "context", ")", "Env", "(", ")", "map", "[", "string", "]", "string", "{", "env", ":=", "make", "(", "map", "[", "string", "]", "string", ")", "\n", "for", "_", ",", "i", ":=", "range", "os", ".", "Environ", "(", ")", "...
// Env - Map environment variables for use in a template
[ "Env", "-", "Map", "environment", "variables", "for", "use", "in", "a", "template" ]
20937becaa32cdec93e77a84ad04c73e9155b8e7
https://github.com/hairyhenderson/gomplate/blob/20937becaa32cdec93e77a84ad04c73e9155b8e7/context.go#L14-L21
153,076
hairyhenderson/gomplate
aws/ec2meta.go
retrieveMetadata
func (e *Ec2Meta) retrieveMetadata(url string, def ...string) (string, error) { if value, ok := e.cache[url]; ok { return value, nil } if e.nonAWS { return returnDefault(def), nil } if e.Client == nil { timeout := e.options.Timeout if timeout == 0 { timeout = 500 * time.Millisecond } e.Client = &http.Client{Timeout: timeout} } resp, err := e.Client.Get(url) if err != nil { if unreachable(err) { e.nonAWS = true } return returnDefault(def), nil } // nolint: errcheck defer resp.Body.Close() if resp.StatusCode > 399 { return returnDefault(def), nil } body, err := ioutil.ReadAll(resp.Body) if err != nil { return "", errors.Wrapf(err, "Failed to read response body from %s", url) } value := strings.TrimSpace(string(body)) e.cache[url] = value return value, nil }
go
func (e *Ec2Meta) retrieveMetadata(url string, def ...string) (string, error) { if value, ok := e.cache[url]; ok { return value, nil } if e.nonAWS { return returnDefault(def), nil } if e.Client == nil { timeout := e.options.Timeout if timeout == 0 { timeout = 500 * time.Millisecond } e.Client = &http.Client{Timeout: timeout} } resp, err := e.Client.Get(url) if err != nil { if unreachable(err) { e.nonAWS = true } return returnDefault(def), nil } // nolint: errcheck defer resp.Body.Close() if resp.StatusCode > 399 { return returnDefault(def), nil } body, err := ioutil.ReadAll(resp.Body) if err != nil { return "", errors.Wrapf(err, "Failed to read response body from %s", url) } value := strings.TrimSpace(string(body)) e.cache[url] = value return value, nil }
[ "func", "(", "e", "*", "Ec2Meta", ")", "retrieveMetadata", "(", "url", "string", ",", "def", "...", "string", ")", "(", "string", ",", "error", ")", "{", "if", "value", ",", "ok", ":=", "e", ".", "cache", "[", "url", "]", ";", "ok", "{", "return"...
// retrieve EC2 metadata, defaulting if we're not in EC2 or if there's a non-OK // response. If there is an OK response, but we can't parse it, this errors
[ "retrieve", "EC2", "metadata", "defaulting", "if", "we", "re", "not", "in", "EC2", "or", "if", "there", "s", "a", "non", "-", "OK", "response", ".", "If", "there", "is", "an", "OK", "response", "but", "we", "can", "t", "parse", "it", "this", "errors"...
20937becaa32cdec93e77a84ad04c73e9155b8e7
https://github.com/hairyhenderson/gomplate/blob/20937becaa32cdec93e77a84ad04c73e9155b8e7/aws/ec2meta.go#L61-L99
153,077
muesli/smartcrop
smartcrop.go
NewAnalyzer
func NewAnalyzer(resizer options.Resizer) Analyzer { logger := Logger{ DebugMode: false, } return NewAnalyzerWithLogger(resizer, logger) }
go
func NewAnalyzer(resizer options.Resizer) Analyzer { logger := Logger{ DebugMode: false, } return NewAnalyzerWithLogger(resizer, logger) }
[ "func", "NewAnalyzer", "(", "resizer", "options", ".", "Resizer", ")", "Analyzer", "{", "logger", ":=", "Logger", "{", "DebugMode", ":", "false", ",", "}", "\n\n", "return", "NewAnalyzerWithLogger", "(", "resizer", ",", "logger", ")", "\n", "}" ]
// NewAnalyzer returns a new Analyzer using the given Resizer.
[ "NewAnalyzer", "returns", "a", "new", "Analyzer", "using", "the", "given", "Resizer", "." ]
548bbf0c0965feac4997e1b51c96764f30dba677
https://github.com/muesli/smartcrop/blob/548bbf0c0965feac4997e1b51c96764f30dba677/smartcrop.go#L111-L117
153,078
muesli/smartcrop
smartcrop.go
NewAnalyzerWithLogger
func NewAnalyzerWithLogger(resizer options.Resizer, logger Logger) Analyzer { if logger.Log == nil { logger.Log = log.New(ioutil.Discard, "", 0) } return &smartcropAnalyzer{Resizer: resizer, logger: logger} }
go
func NewAnalyzerWithLogger(resizer options.Resizer, logger Logger) Analyzer { if logger.Log == nil { logger.Log = log.New(ioutil.Discard, "", 0) } return &smartcropAnalyzer{Resizer: resizer, logger: logger} }
[ "func", "NewAnalyzerWithLogger", "(", "resizer", "options", ".", "Resizer", ",", "logger", "Logger", ")", "Analyzer", "{", "if", "logger", ".", "Log", "==", "nil", "{", "logger", ".", "Log", "=", "log", ".", "New", "(", "ioutil", ".", "Discard", ",", "...
// NewAnalyzerWithLogger returns a new analyzer with the given Resizer and Logger.
[ "NewAnalyzerWithLogger", "returns", "a", "new", "analyzer", "with", "the", "given", "Resizer", "and", "Logger", "." ]
548bbf0c0965feac4997e1b51c96764f30dba677
https://github.com/muesli/smartcrop/blob/548bbf0c0965feac4997e1b51c96764f30dba677/smartcrop.go#L120-L125
153,079
muesli/smartcrop
smartcrop.go
toRGBA
func toRGBA(img image.Image) *image.RGBA { switch img.(type) { case *image.RGBA: return img.(*image.RGBA) } out := image.NewRGBA(img.Bounds()) draw.Copy(out, image.Pt(0, 0), img, img.Bounds(), draw.Src, nil) return out }
go
func toRGBA(img image.Image) *image.RGBA { switch img.(type) { case *image.RGBA: return img.(*image.RGBA) } out := image.NewRGBA(img.Bounds()) draw.Copy(out, image.Pt(0, 0), img, img.Bounds(), draw.Src, nil) return out }
[ "func", "toRGBA", "(", "img", "image", ".", "Image", ")", "*", "image", ".", "RGBA", "{", "switch", "img", ".", "(", "type", ")", "{", "case", "*", "image", ".", "RGBA", ":", "return", "img", ".", "(", "*", "image", ".", "RGBA", ")", "\n", "}",...
// toRGBA converts an image.Image to an image.RGBA
[ "toRGBA", "converts", "an", "image", ".", "Image", "to", "an", "image", ".", "RGBA" ]
548bbf0c0965feac4997e1b51c96764f30dba677
https://github.com/muesli/smartcrop/blob/548bbf0c0965feac4997e1b51c96764f30dba677/smartcrop.go#L466-L474
153,080
mdlayher/raw
raw_bsd.go
configureBPF
func configureBPF(fd int, ifi *net.Interface, proto uint16) (int, error) { // Use specified interface with BPF device if err := syscall.SetBpfInterface(fd, ifi.Name); err != nil { return 0, err } // Inform BPF to send us its data immediately if err := syscall.SetBpfImmediate(fd, 1); err != nil { return 0, err } // Check buffer size of BPF device buflen, err := syscall.BpfBuflen(fd) if err != nil { return 0, err } // Do not automatically complete source address in ethernet headers if err := syscall.SetBpfHeadercmpl(fd, 1); err != nil { return 0, err } // Only retrieve incoming traffic using BPF device if err := setBPFDirection(fd, bpfDIn); err != nil { return 0, err } // Build and apply base BPF filter which checks for correct EtherType // on incoming packets prog, err := bpf.Assemble(baseInterfaceFilter(proto, ifi.MTU)) if err != nil { return 0, err } if err := syscall.SetBpf(fd, assembleBpfInsn(prog)); err != nil { return 0, err } // Flush any packets currently in the BPF device's buffer if err := syscall.FlushBpf(fd); err != nil { return 0, err } return buflen, nil }
go
func configureBPF(fd int, ifi *net.Interface, proto uint16) (int, error) { // Use specified interface with BPF device if err := syscall.SetBpfInterface(fd, ifi.Name); err != nil { return 0, err } // Inform BPF to send us its data immediately if err := syscall.SetBpfImmediate(fd, 1); err != nil { return 0, err } // Check buffer size of BPF device buflen, err := syscall.BpfBuflen(fd) if err != nil { return 0, err } // Do not automatically complete source address in ethernet headers if err := syscall.SetBpfHeadercmpl(fd, 1); err != nil { return 0, err } // Only retrieve incoming traffic using BPF device if err := setBPFDirection(fd, bpfDIn); err != nil { return 0, err } // Build and apply base BPF filter which checks for correct EtherType // on incoming packets prog, err := bpf.Assemble(baseInterfaceFilter(proto, ifi.MTU)) if err != nil { return 0, err } if err := syscall.SetBpf(fd, assembleBpfInsn(prog)); err != nil { return 0, err } // Flush any packets currently in the BPF device's buffer if err := syscall.FlushBpf(fd); err != nil { return 0, err } return buflen, nil }
[ "func", "configureBPF", "(", "fd", "int", ",", "ifi", "*", "net", ".", "Interface", ",", "proto", "uint16", ")", "(", "int", ",", "error", ")", "{", "// Use specified interface with BPF device", "if", "err", ":=", "syscall", ".", "SetBpfInterface", "(", "fd"...
// configureBPF configures a BPF device with the specified file descriptor to // use the specified network and interface and protocol.
[ "configureBPF", "configures", "a", "BPF", "device", "with", "the", "specified", "file", "descriptor", "to", "use", "the", "specified", "network", "and", "interface", "and", "protocol", "." ]
64193704e47285d33feb098cd01306301cdeba4b
https://github.com/mdlayher/raw/blob/64193704e47285d33feb098cd01306301cdeba4b/raw_bsd.go#L238-L281
153,081
mdlayher/raw
raw_bsd.go
assembleBpfInsn
func assembleBpfInsn(filter []bpf.RawInstruction) []syscall.BpfInsn { // Copy each bpf.RawInstruction into syscall.BpfInsn. If needed, // the structures have the same memory layout and could probably be // unsafely cast to each other for speed. insns := make([]syscall.BpfInsn, 0, len(filter)) for _, ins := range filter { insns = append(insns, syscall.BpfInsn{ Code: ins.Op, Jt: ins.Jt, Jf: ins.Jf, K: ins.K, }) } return insns }
go
func assembleBpfInsn(filter []bpf.RawInstruction) []syscall.BpfInsn { // Copy each bpf.RawInstruction into syscall.BpfInsn. If needed, // the structures have the same memory layout and could probably be // unsafely cast to each other for speed. insns := make([]syscall.BpfInsn, 0, len(filter)) for _, ins := range filter { insns = append(insns, syscall.BpfInsn{ Code: ins.Op, Jt: ins.Jt, Jf: ins.Jf, K: ins.K, }) } return insns }
[ "func", "assembleBpfInsn", "(", "filter", "[", "]", "bpf", ".", "RawInstruction", ")", "[", "]", "syscall", ".", "BpfInsn", "{", "// Copy each bpf.RawInstruction into syscall.BpfInsn. If needed,", "// the structures have the same memory layout and could probably be", "// unsafel...
// assembleBpfInsn assembles a slice of bpf.RawInstructions to the format required by // package syscall.
[ "assembleBpfInsn", "assembles", "a", "slice", "of", "bpf", ".", "RawInstructions", "to", "the", "format", "required", "by", "package", "syscall", "." ]
64193704e47285d33feb098cd01306301cdeba4b
https://github.com/mdlayher/raw/blob/64193704e47285d33feb098cd01306301cdeba4b/raw_bsd.go#L285-L300
153,082
mdlayher/raw
raw_bsd.go
baseInterfaceFilter
func baseInterfaceFilter(proto uint16, mtu int) []bpf.Instruction { return append( // Filter traffic based on EtherType baseFilter(proto), // Accept the packet bytes up to the interface's MTU bpf.RetConstant{ Val: uint32(mtu), }, ) }
go
func baseInterfaceFilter(proto uint16, mtu int) []bpf.Instruction { return append( // Filter traffic based on EtherType baseFilter(proto), // Accept the packet bytes up to the interface's MTU bpf.RetConstant{ Val: uint32(mtu), }, ) }
[ "func", "baseInterfaceFilter", "(", "proto", "uint16", ",", "mtu", "int", ")", "[", "]", "bpf", ".", "Instruction", "{", "return", "append", "(", "// Filter traffic based on EtherType", "baseFilter", "(", "proto", ")", ",", "// Accept the packet bytes up to the interf...
// baseInterfaceFilter creates a base BPF filter which filters traffic based // on its EtherType and returns up to "mtu" bytes of data for processing.
[ "baseInterfaceFilter", "creates", "a", "base", "BPF", "filter", "which", "filters", "traffic", "based", "on", "its", "EtherType", "and", "returns", "up", "to", "mtu", "bytes", "of", "data", "for", "processing", "." ]
64193704e47285d33feb098cd01306301cdeba4b
https://github.com/mdlayher/raw/blob/64193704e47285d33feb098cd01306301cdeba4b/raw_bsd.go#L304-L313
153,083
mdlayher/raw
raw_bsd.go
baseFilter
func baseFilter(proto uint16) []bpf.Instruction { // Offset | Length | Comment // ------------------------- // 00 | 06 | Ethernet destination MAC address // 06 | 06 | Ethernet source MAC address // 12 | 02 | Ethernet EtherType const ( etherTypeOffset = 12 etherTypeLength = 2 ) return []bpf.Instruction{ // Load EtherType value from Ethernet header bpf.LoadAbsolute{ Off: etherTypeOffset, Size: etherTypeLength, }, // If EtherType is equal to the protocol we are using, jump to instructions // added outside of this function. bpf.JumpIf{ Cond: bpf.JumpEqual, Val: uint32(proto), SkipTrue: 1, }, // EtherType does not match our protocol bpf.RetConstant{ Val: 0, }, } }
go
func baseFilter(proto uint16) []bpf.Instruction { // Offset | Length | Comment // ------------------------- // 00 | 06 | Ethernet destination MAC address // 06 | 06 | Ethernet source MAC address // 12 | 02 | Ethernet EtherType const ( etherTypeOffset = 12 etherTypeLength = 2 ) return []bpf.Instruction{ // Load EtherType value from Ethernet header bpf.LoadAbsolute{ Off: etherTypeOffset, Size: etherTypeLength, }, // If EtherType is equal to the protocol we are using, jump to instructions // added outside of this function. bpf.JumpIf{ Cond: bpf.JumpEqual, Val: uint32(proto), SkipTrue: 1, }, // EtherType does not match our protocol bpf.RetConstant{ Val: 0, }, } }
[ "func", "baseFilter", "(", "proto", "uint16", ")", "[", "]", "bpf", ".", "Instruction", "{", "// Offset | Length | Comment", "// -------------------------", "// 00 | 06 | Ethernet destination MAC address", "// 06 | 06 | Ethernet source MAC address", "// 12 | 02 ...
// baseFilter creates a base BPF filter which filters traffic based on its // EtherType. baseFilter can be prepended to other filters to handle common // filtering tasks.
[ "baseFilter", "creates", "a", "base", "BPF", "filter", "which", "filters", "traffic", "based", "on", "its", "EtherType", ".", "baseFilter", "can", "be", "prepended", "to", "other", "filters", "to", "handle", "common", "filtering", "tasks", "." ]
64193704e47285d33feb098cd01306301cdeba4b
https://github.com/mdlayher/raw/blob/64193704e47285d33feb098cd01306301cdeba4b/raw_bsd.go#L318-L347
153,084
mdlayher/raw
raw_others.go
listenPacket
func listenPacket(ifi *net.Interface, proto uint16, cfg Config) (*packetConn, error) { return nil, ErrNotImplemented }
go
func listenPacket(ifi *net.Interface, proto uint16, cfg Config) (*packetConn, error) { return nil, ErrNotImplemented }
[ "func", "listenPacket", "(", "ifi", "*", "net", ".", "Interface", ",", "proto", "uint16", ",", "cfg", "Config", ")", "(", "*", "packetConn", ",", "error", ")", "{", "return", "nil", ",", "ErrNotImplemented", "\n", "}" ]
// listenPacket is not currently implemented on this platform.
[ "listenPacket", "is", "not", "currently", "implemented", "on", "this", "platform", "." ]
64193704e47285d33feb098cd01306301cdeba4b
https://github.com/mdlayher/raw/blob/64193704e47285d33feb098cd01306301cdeba4b/raw_others.go#L21-L23
153,085
mdlayher/raw
raw_others.go
ReadFrom
func (p *packetConn) ReadFrom(b []byte) (int, net.Addr, error) { return 0, nil, ErrNotImplemented }
go
func (p *packetConn) ReadFrom(b []byte) (int, net.Addr, error) { return 0, nil, ErrNotImplemented }
[ "func", "(", "p", "*", "packetConn", ")", "ReadFrom", "(", "b", "[", "]", "byte", ")", "(", "int", ",", "net", ".", "Addr", ",", "error", ")", "{", "return", "0", ",", "nil", ",", "ErrNotImplemented", "\n", "}" ]
// ReadFrom is not currently implemented on this platform.
[ "ReadFrom", "is", "not", "currently", "implemented", "on", "this", "platform", "." ]
64193704e47285d33feb098cd01306301cdeba4b
https://github.com/mdlayher/raw/blob/64193704e47285d33feb098cd01306301cdeba4b/raw_others.go#L26-L28
153,086
mdlayher/raw
raw_others.go
WriteTo
func (p *packetConn) WriteTo(b []byte, addr net.Addr) (int, error) { return 0, ErrNotImplemented }
go
func (p *packetConn) WriteTo(b []byte, addr net.Addr) (int, error) { return 0, ErrNotImplemented }
[ "func", "(", "p", "*", "packetConn", ")", "WriteTo", "(", "b", "[", "]", "byte", ",", "addr", "net", ".", "Addr", ")", "(", "int", ",", "error", ")", "{", "return", "0", ",", "ErrNotImplemented", "\n", "}" ]
// WriteTo is not currently implemented on this platform.
[ "WriteTo", "is", "not", "currently", "implemented", "on", "this", "platform", "." ]
64193704e47285d33feb098cd01306301cdeba4b
https://github.com/mdlayher/raw/blob/64193704e47285d33feb098cd01306301cdeba4b/raw_others.go#L31-L33
153,087
mdlayher/raw
timeval.go
newTimeval
func newTimeval(timeout time.Duration) (*unix.Timeval, error) { if timeout < time.Microsecond { return nil, &timeoutError{} } return &unix.Timeval{ Sec: int64(timeout / time.Second), Usec: int64(timeout % time.Second / time.Microsecond), }, nil }
go
func newTimeval(timeout time.Duration) (*unix.Timeval, error) { if timeout < time.Microsecond { return nil, &timeoutError{} } return &unix.Timeval{ Sec: int64(timeout / time.Second), Usec: int64(timeout % time.Second / time.Microsecond), }, nil }
[ "func", "newTimeval", "(", "timeout", "time", ".", "Duration", ")", "(", "*", "unix", ".", "Timeval", ",", "error", ")", "{", "if", "timeout", "<", "time", ".", "Microsecond", "{", "return", "nil", ",", "&", "timeoutError", "{", "}", "\n", "}", "\n",...
// newTimeval transforms a duration into a unix.Timeval struct. // An error is returned in case of zero time value.
[ "newTimeval", "transforms", "a", "duration", "into", "a", "unix", ".", "Timeval", "struct", ".", "An", "error", "is", "returned", "in", "case", "of", "zero", "time", "value", "." ]
64193704e47285d33feb098cd01306301cdeba4b
https://github.com/mdlayher/raw/blob/64193704e47285d33feb098cd01306301cdeba4b/timeval.go#L13-L21
153,088
mdlayher/raw
raw_linux.go
newPacketConn
func newPacketConn(ifi *net.Interface, s socket, pbe uint16, filter []bpf.RawInstruction) (*packetConn, error) { pc := &packetConn{ ifi: ifi, s: s, pbe: pbe, } if len(filter) > 0 { if err := pc.SetBPF(filter); err != nil { return nil, err } } // Bind the packet socket to the interface specified by ifi // packet(7): // Only the sll_protocol and the sll_ifindex address fields are used for // purposes of binding. // This overrides the protocol given to socket(AF_PACKET). err := s.Bind(&unix.SockaddrLinklayer{ Protocol: pc.pbe, Ifindex: ifi.Index, }) if err != nil { return nil, err } return pc, nil }
go
func newPacketConn(ifi *net.Interface, s socket, pbe uint16, filter []bpf.RawInstruction) (*packetConn, error) { pc := &packetConn{ ifi: ifi, s: s, pbe: pbe, } if len(filter) > 0 { if err := pc.SetBPF(filter); err != nil { return nil, err } } // Bind the packet socket to the interface specified by ifi // packet(7): // Only the sll_protocol and the sll_ifindex address fields are used for // purposes of binding. // This overrides the protocol given to socket(AF_PACKET). err := s.Bind(&unix.SockaddrLinklayer{ Protocol: pc.pbe, Ifindex: ifi.Index, }) if err != nil { return nil, err } return pc, nil }
[ "func", "newPacketConn", "(", "ifi", "*", "net", ".", "Interface", ",", "s", "socket", ",", "pbe", "uint16", ",", "filter", "[", "]", "bpf", ".", "RawInstruction", ")", "(", "*", "packetConn", ",", "error", ")", "{", "pc", ":=", "&", "packetConn", "{...
// newPacketConn creates a net.PacketConn using the specified network // interface, wrapped socket and big endian protocol number. // // It is the entry point for tests in this package.
[ "newPacketConn", "creates", "a", "net", ".", "PacketConn", "using", "the", "specified", "network", "interface", "wrapped", "socket", "and", "big", "endian", "protocol", "number", ".", "It", "is", "the", "entry", "point", "for", "tests", "in", "this", "package"...
64193704e47285d33feb098cd01306301cdeba4b
https://github.com/mdlayher/raw/blob/64193704e47285d33feb098cd01306301cdeba4b/raw_linux.go#L107-L134
153,089
mdlayher/raw
raw_linux.go
SetWriteDeadline
func (p *packetConn) SetWriteDeadline(t time.Time) error { return p.s.SetWriteDeadline(t) }
go
func (p *packetConn) SetWriteDeadline(t time.Time) error { return p.s.SetWriteDeadline(t) }
[ "func", "(", "p", "*", "packetConn", ")", "SetWriteDeadline", "(", "t", "time", ".", "Time", ")", "error", "{", "return", "p", ".", "s", ".", "SetWriteDeadline", "(", "t", ")", "\n", "}" ]
// SetWriteDeadline implements the net.PacketConn.SetWriteDeadline method.
[ "SetWriteDeadline", "implements", "the", "net", ".", "PacketConn", ".", "SetWriteDeadline", "method", "." ]
64193704e47285d33feb098cd01306301cdeba4b
https://github.com/mdlayher/raw/blob/64193704e47285d33feb098cd01306301cdeba4b/raw_linux.go#L214-L216
153,090
mdlayher/raw
raw_linux.go
Stats
func (p *packetConn) Stats() (*Stats, error) { stats, err := p.s.GetSockoptTpacketStats(unix.SOL_PACKET, unix.PACKET_STATISTICS) if err != nil { return nil, err } return p.handleStats(stats), nil }
go
func (p *packetConn) Stats() (*Stats, error) { stats, err := p.s.GetSockoptTpacketStats(unix.SOL_PACKET, unix.PACKET_STATISTICS) if err != nil { return nil, err } return p.handleStats(stats), nil }
[ "func", "(", "p", "*", "packetConn", ")", "Stats", "(", ")", "(", "*", "Stats", ",", "error", ")", "{", "stats", ",", "err", ":=", "p", ".", "s", ".", "GetSockoptTpacketStats", "(", "unix", ".", "SOL_PACKET", ",", "unix", ".", "PACKET_STATISTICS", ")...
// Stats retrieves statistics from the Conn.
[ "Stats", "retrieves", "statistics", "from", "the", "Conn", "." ]
64193704e47285d33feb098cd01306301cdeba4b
https://github.com/mdlayher/raw/blob/64193704e47285d33feb098cd01306301cdeba4b/raw_linux.go#L253-L260
153,091
mdlayher/raw
raw_linux.go
handleStats
func (p *packetConn) handleStats(s *unix.TpacketStats) *Stats { // Does the caller want instantaneous stats as provided by Linux? If so, // return the structure directly. if p.noCumulativeStats { return &Stats{ Packets: uint64(s.Packets), Drops: uint64(s.Drops), } } // The caller wants cumulative stats. Add stats with the internal stats // structure and return a copy of the resulting stats. packets := atomic.AddUint64(&p.stats.Packets, uint64(s.Packets)) drops := atomic.AddUint64(&p.stats.Drops, uint64(s.Drops)) return &Stats{ Packets: packets, Drops: drops, } }
go
func (p *packetConn) handleStats(s *unix.TpacketStats) *Stats { // Does the caller want instantaneous stats as provided by Linux? If so, // return the structure directly. if p.noCumulativeStats { return &Stats{ Packets: uint64(s.Packets), Drops: uint64(s.Drops), } } // The caller wants cumulative stats. Add stats with the internal stats // structure and return a copy of the resulting stats. packets := atomic.AddUint64(&p.stats.Packets, uint64(s.Packets)) drops := atomic.AddUint64(&p.stats.Drops, uint64(s.Drops)) return &Stats{ Packets: packets, Drops: drops, } }
[ "func", "(", "p", "*", "packetConn", ")", "handleStats", "(", "s", "*", "unix", ".", "TpacketStats", ")", "*", "Stats", "{", "// Does the caller want instantaneous stats as provided by Linux? If so,", "// return the structure directly.", "if", "p", ".", "noCumulativeStat...
// handleStats handles creation of Stats structures from raw packet socket stats.
[ "handleStats", "handles", "creation", "of", "Stats", "structures", "from", "raw", "packet", "socket", "stats", "." ]
64193704e47285d33feb098cd01306301cdeba4b
https://github.com/mdlayher/raw/blob/64193704e47285d33feb098cd01306301cdeba4b/raw_linux.go#L263-L282
153,092
mdlayher/raw
raw.go
ReadFrom
func (c *Conn) ReadFrom(b []byte) (int, net.Addr, error) { return c.p.ReadFrom(b) }
go
func (c *Conn) ReadFrom(b []byte) (int, net.Addr, error) { return c.p.ReadFrom(b) }
[ "func", "(", "c", "*", "Conn", ")", "ReadFrom", "(", "b", "[", "]", "byte", ")", "(", "int", ",", "net", ".", "Addr", ",", "error", ")", "{", "return", "c", ".", "p", ".", "ReadFrom", "(", "b", ")", "\n", "}" ]
// ReadFrom implements the net.PacketConn ReadFrom method.
[ "ReadFrom", "implements", "the", "net", ".", "PacketConn", "ReadFrom", "method", "." ]
64193704e47285d33feb098cd01306301cdeba4b
https://github.com/mdlayher/raw/blob/64193704e47285d33feb098cd01306301cdeba4b/raw.go#L48-L50
153,093
mdlayher/raw
raw.go
WriteTo
func (c *Conn) WriteTo(b []byte, addr net.Addr) (int, error) { return c.p.WriteTo(b, addr) }
go
func (c *Conn) WriteTo(b []byte, addr net.Addr) (int, error) { return c.p.WriteTo(b, addr) }
[ "func", "(", "c", "*", "Conn", ")", "WriteTo", "(", "b", "[", "]", "byte", ",", "addr", "net", ".", "Addr", ")", "(", "int", ",", "error", ")", "{", "return", "c", ".", "p", ".", "WriteTo", "(", "b", ",", "addr", ")", "\n", "}" ]
// WriteTo implements the net.PacketConn WriteTo method.
[ "WriteTo", "implements", "the", "net", ".", "PacketConn", "WriteTo", "method", "." ]
64193704e47285d33feb098cd01306301cdeba4b
https://github.com/mdlayher/raw/blob/64193704e47285d33feb098cd01306301cdeba4b/raw.go#L53-L55
153,094
mdlayher/raw
raw.go
SetDeadline
func (c *Conn) SetDeadline(t time.Time) error { return c.p.SetDeadline(t) }
go
func (c *Conn) SetDeadline(t time.Time) error { return c.p.SetDeadline(t) }
[ "func", "(", "c", "*", "Conn", ")", "SetDeadline", "(", "t", "time", ".", "Time", ")", "error", "{", "return", "c", ".", "p", ".", "SetDeadline", "(", "t", ")", "\n", "}" ]
// SetDeadline implements the net.PacketConn SetDeadline method.
[ "SetDeadline", "implements", "the", "net", ".", "PacketConn", "SetDeadline", "method", "." ]
64193704e47285d33feb098cd01306301cdeba4b
https://github.com/mdlayher/raw/blob/64193704e47285d33feb098cd01306301cdeba4b/raw.go#L68-L70
153,095
mdlayher/raw
raw.go
SetReadDeadline
func (c *Conn) SetReadDeadline(t time.Time) error { return c.p.SetReadDeadline(t) }
go
func (c *Conn) SetReadDeadline(t time.Time) error { return c.p.SetReadDeadline(t) }
[ "func", "(", "c", "*", "Conn", ")", "SetReadDeadline", "(", "t", "time", ".", "Time", ")", "error", "{", "return", "c", ".", "p", ".", "SetReadDeadline", "(", "t", ")", "\n", "}" ]
// SetReadDeadline implements the net.PacketConn SetReadDeadline method.
[ "SetReadDeadline", "implements", "the", "net", ".", "PacketConn", "SetReadDeadline", "method", "." ]
64193704e47285d33feb098cd01306301cdeba4b
https://github.com/mdlayher/raw/blob/64193704e47285d33feb098cd01306301cdeba4b/raw.go#L73-L75
153,096
mdlayher/raw
raw.go
SetWriteDeadline
func (c *Conn) SetWriteDeadline(t time.Time) error { return c.p.SetWriteDeadline(t) }
go
func (c *Conn) SetWriteDeadline(t time.Time) error { return c.p.SetWriteDeadline(t) }
[ "func", "(", "c", "*", "Conn", ")", "SetWriteDeadline", "(", "t", "time", ".", "Time", ")", "error", "{", "return", "c", ".", "p", ".", "SetWriteDeadline", "(", "t", ")", "\n", "}" ]
// SetWriteDeadline implements the net.PacketConn SetWriteDeadline method.
[ "SetWriteDeadline", "implements", "the", "net", ".", "PacketConn", "SetWriteDeadline", "method", "." ]
64193704e47285d33feb098cd01306301cdeba4b
https://github.com/mdlayher/raw/blob/64193704e47285d33feb098cd01306301cdeba4b/raw.go#L78-L80
153,097
mdlayher/raw
raw.go
SetBPF
func (c *Conn) SetBPF(filter []bpf.RawInstruction) error { return c.p.SetBPF(filter) }
go
func (c *Conn) SetBPF(filter []bpf.RawInstruction) error { return c.p.SetBPF(filter) }
[ "func", "(", "c", "*", "Conn", ")", "SetBPF", "(", "filter", "[", "]", "bpf", ".", "RawInstruction", ")", "error", "{", "return", "c", ".", "p", ".", "SetBPF", "(", "filter", ")", "\n", "}" ]
// SetBPF attaches an assembled BPF program to the connection.
[ "SetBPF", "attaches", "an", "assembled", "BPF", "program", "to", "the", "connection", "." ]
64193704e47285d33feb098cd01306301cdeba4b
https://github.com/mdlayher/raw/blob/64193704e47285d33feb098cd01306301cdeba4b/raw.go#L85-L87
153,098
dave/jennifer
jen/tokens.go
Dot
func (s *Statement) Dot(name string) *Statement { d := token{ typ: delimiterToken, content: ".", } t := token{ typ: identifierToken, content: name, } *s = append(*s, d, t) return s }
go
func (s *Statement) Dot(name string) *Statement { d := token{ typ: delimiterToken, content: ".", } t := token{ typ: identifierToken, content: name, } *s = append(*s, d, t) return s }
[ "func", "(", "s", "*", "Statement", ")", "Dot", "(", "name", "string", ")", "*", "Statement", "{", "d", ":=", "token", "{", "typ", ":", "delimiterToken", ",", "content", ":", "\"", "\"", ",", "}", "\n", "t", ":=", "token", "{", "typ", ":", "ident...
// Dot renders a period followed by an identifier. Use for fields and selectors.
[ "Dot", "renders", "a", "period", "followed", "by", "an", "identifier", ".", "Use", "for", "fields", "and", "selectors", "." ]
14e399b6b5e8456c66c45c955fc27b568bacb5c9
https://github.com/dave/jennifer/blob/14e399b6b5e8456c66c45c955fc27b568bacb5c9/jen/tokens.go#L191-L202
153,099
dave/jennifer
jen/jen.go
Save
func (f *File) Save(filename string) error { // notest buf := &bytes.Buffer{} if err := f.Render(buf); err != nil { return err } if err := ioutil.WriteFile(filename, buf.Bytes(), 0644); err != nil { return err } return nil }
go
func (f *File) Save(filename string) error { // notest buf := &bytes.Buffer{} if err := f.Render(buf); err != nil { return err } if err := ioutil.WriteFile(filename, buf.Bytes(), 0644); err != nil { return err } return nil }
[ "func", "(", "f", "*", "File", ")", "Save", "(", "filename", "string", ")", "error", "{", "// notest", "buf", ":=", "&", "bytes", ".", "Buffer", "{", "}", "\n", "if", "err", ":=", "f", ".", "Render", "(", "buf", ")", ";", "err", "!=", "nil", "{...
// Save renders the file and saves to the filename provided.
[ "Save", "renders", "the", "file", "and", "saves", "to", "the", "filename", "provided", "." ]
14e399b6b5e8456c66c45c955fc27b568bacb5c9
https://github.com/dave/jennifer/blob/14e399b6b5e8456c66c45c955fc27b568bacb5c9/jen/jen.go#L21-L31