id
int32 0
167k
| repo
stringlengths 5
54
| path
stringlengths 4
155
| func_name
stringlengths 1
118
| original_string
stringlengths 52
85.5k
| language
stringclasses 1
value | code
stringlengths 52
85.5k
| code_tokens
sequence | docstring
stringlengths 6
2.61k
| docstring_tokens
sequence | sha
stringlengths 40
40
| url
stringlengths 85
252
|
---|---|---|---|---|---|---|---|---|---|---|---|
4,000 | robfig/soy | soymsg/soymsg.go | PlaceholderString | func PlaceholderString(n *ast.MsgNode) string {
var buf bytes.Buffer
writeFingerprint(&buf, n, true)
return buf.String()
} | go | func PlaceholderString(n *ast.MsgNode) string {
var buf bytes.Buffer
writeFingerprint(&buf, n, true)
return buf.String()
} | [
"func",
"PlaceholderString",
"(",
"n",
"*",
"ast",
".",
"MsgNode",
")",
"string",
"{",
"var",
"buf",
"bytes",
".",
"Buffer",
"\n",
"writeFingerprint",
"(",
"&",
"buf",
",",
"n",
",",
"true",
")",
"\n",
"return",
"buf",
".",
"String",
"(",
")",
"\n",
"}"
] | // PlaceholderString returns a string representation of the message containing
// braced placeholders for variables. | [
"PlaceholderString",
"returns",
"a",
"string",
"representation",
"of",
"the",
"message",
"containing",
"braced",
"placeholders",
"for",
"variables",
"."
] | 6b9d0368d4265c382c3e11fe774d93aa8d431064 | https://github.com/robfig/soy/blob/6b9d0368d4265c382c3e11fe774d93aa8d431064/soymsg/soymsg.go#L90-L94 |
4,001 | robfig/soy | soymsg/soymsg.go | Parts | func Parts(str string) []Part {
var pos = 0
var parts []Part
for _, loc := range phRegex.FindAllStringIndex(str, -1) {
var start, end = loc[0], loc[1]
if start > pos {
parts = append(parts, RawTextPart{str[pos:start]})
}
parts = append(parts, PlaceholderPart{str[start+1 : end-1]})
pos = end
}
if pos < len(str) {
parts = append(parts, RawTextPart{str[pos:]})
}
return parts
} | go | func Parts(str string) []Part {
var pos = 0
var parts []Part
for _, loc := range phRegex.FindAllStringIndex(str, -1) {
var start, end = loc[0], loc[1]
if start > pos {
parts = append(parts, RawTextPart{str[pos:start]})
}
parts = append(parts, PlaceholderPart{str[start+1 : end-1]})
pos = end
}
if pos < len(str) {
parts = append(parts, RawTextPart{str[pos:]})
}
return parts
} | [
"func",
"Parts",
"(",
"str",
"string",
")",
"[",
"]",
"Part",
"{",
"var",
"pos",
"=",
"0",
"\n",
"var",
"parts",
"[",
"]",
"Part",
"\n",
"for",
"_",
",",
"loc",
":=",
"range",
"phRegex",
".",
"FindAllStringIndex",
"(",
"str",
",",
"-",
"1",
")",
"{",
"var",
"start",
",",
"end",
"=",
"loc",
"[",
"0",
"]",
",",
"loc",
"[",
"1",
"]",
"\n",
"if",
"start",
">",
"pos",
"{",
"parts",
"=",
"append",
"(",
"parts",
",",
"RawTextPart",
"{",
"str",
"[",
"pos",
":",
"start",
"]",
"}",
")",
"\n",
"}",
"\n",
"parts",
"=",
"append",
"(",
"parts",
",",
"PlaceholderPart",
"{",
"str",
"[",
"start",
"+",
"1",
":",
"end",
"-",
"1",
"]",
"}",
")",
"\n",
"pos",
"=",
"end",
"\n",
"}",
"\n",
"if",
"pos",
"<",
"len",
"(",
"str",
")",
"{",
"parts",
"=",
"append",
"(",
"parts",
",",
"RawTextPart",
"{",
"str",
"[",
"pos",
":",
"]",
"}",
")",
"\n",
"}",
"\n",
"return",
"parts",
"\n",
"}"
] | // Parts returns the sequence of raw text and placeholders for the given
// message placeholder string. | [
"Parts",
"returns",
"the",
"sequence",
"of",
"raw",
"text",
"and",
"placeholders",
"for",
"the",
"given",
"message",
"placeholder",
"string",
"."
] | 6b9d0368d4265c382c3e11fe774d93aa8d431064 | https://github.com/robfig/soy/blob/6b9d0368d4265c382c3e11fe774d93aa8d431064/soymsg/soymsg.go#L100-L115 |
4,002 | robfig/soy | soymsg/soymsg.go | SetPlaceholdersAndID | func SetPlaceholdersAndID(n *ast.MsgNode) {
setPlaceholderNames(n)
n.ID = calcID(n)
} | go | func SetPlaceholdersAndID(n *ast.MsgNode) {
setPlaceholderNames(n)
n.ID = calcID(n)
} | [
"func",
"SetPlaceholdersAndID",
"(",
"n",
"*",
"ast",
".",
"MsgNode",
")",
"{",
"setPlaceholderNames",
"(",
"n",
")",
"\n",
"n",
".",
"ID",
"=",
"calcID",
"(",
"n",
")",
"\n",
"}"
] | // SetPlaceholdersAndID generates and sets placeholder names for all children
// nodes, and generates and sets the message ID. | [
"SetPlaceholdersAndID",
"generates",
"and",
"sets",
"placeholder",
"names",
"for",
"all",
"children",
"nodes",
"and",
"generates",
"and",
"sets",
"the",
"message",
"ID",
"."
] | 6b9d0368d4265c382c3e11fe774d93aa8d431064 | https://github.com/robfig/soy/blob/6b9d0368d4265c382c3e11fe774d93aa8d431064/soymsg/soymsg.go#L119-L122 |
4,003 | robfig/soy | bundle.go | WatchFiles | func (b *Bundle) WatchFiles(watch bool) *Bundle {
if watch && b.err == nil && b.watcher == nil {
b.watcher, b.err = fsnotify.NewWatcher()
}
return b
} | go | func (b *Bundle) WatchFiles(watch bool) *Bundle {
if watch && b.err == nil && b.watcher == nil {
b.watcher, b.err = fsnotify.NewWatcher()
}
return b
} | [
"func",
"(",
"b",
"*",
"Bundle",
")",
"WatchFiles",
"(",
"watch",
"bool",
")",
"*",
"Bundle",
"{",
"if",
"watch",
"&&",
"b",
".",
"err",
"==",
"nil",
"&&",
"b",
".",
"watcher",
"==",
"nil",
"{",
"b",
".",
"watcher",
",",
"b",
".",
"err",
"=",
"fsnotify",
".",
"NewWatcher",
"(",
")",
"\n",
"}",
"\n",
"return",
"b",
"\n",
"}"
] | // WatchFiles tells soy to watch any template files added to this bundle,
// re-compile as necessary, and propagate the updates to your tofu. It should
// be called once, before adding any files. | [
"WatchFiles",
"tells",
"soy",
"to",
"watch",
"any",
"template",
"files",
"added",
"to",
"this",
"bundle",
"re",
"-",
"compile",
"as",
"necessary",
"and",
"propagate",
"the",
"updates",
"to",
"your",
"tofu",
".",
"It",
"should",
"be",
"called",
"once",
"before",
"adding",
"any",
"files",
"."
] | 6b9d0368d4265c382c3e11fe774d93aa8d431064 | https://github.com/robfig/soy/blob/6b9d0368d4265c382c3e11fe774d93aa8d431064/bundle.go#L45-L50 |
4,004 | robfig/soy | bundle.go | AddTemplateFile | func (b *Bundle) AddTemplateFile(filename string) *Bundle {
content, err := ioutil.ReadFile(filename)
if err != nil {
b.err = err
}
if b.err == nil && b.watcher != nil {
b.err = b.watcher.Add(filename)
}
return b.AddTemplateString(filename, string(content))
} | go | func (b *Bundle) AddTemplateFile(filename string) *Bundle {
content, err := ioutil.ReadFile(filename)
if err != nil {
b.err = err
}
if b.err == nil && b.watcher != nil {
b.err = b.watcher.Add(filename)
}
return b.AddTemplateString(filename, string(content))
} | [
"func",
"(",
"b",
"*",
"Bundle",
")",
"AddTemplateFile",
"(",
"filename",
"string",
")",
"*",
"Bundle",
"{",
"content",
",",
"err",
":=",
"ioutil",
".",
"ReadFile",
"(",
"filename",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"b",
".",
"err",
"=",
"err",
"\n",
"}",
"\n",
"if",
"b",
".",
"err",
"==",
"nil",
"&&",
"b",
".",
"watcher",
"!=",
"nil",
"{",
"b",
".",
"err",
"=",
"b",
".",
"watcher",
".",
"Add",
"(",
"filename",
")",
"\n",
"}",
"\n",
"return",
"b",
".",
"AddTemplateString",
"(",
"filename",
",",
"string",
"(",
"content",
")",
")",
"\n",
"}"
] | // AddTemplateFile adds the given soy template file text to this bundle.
// If WatchFiles is on, it will be subsequently watched for updates. | [
"AddTemplateFile",
"adds",
"the",
"given",
"soy",
"template",
"file",
"text",
"to",
"this",
"bundle",
".",
"If",
"WatchFiles",
"is",
"on",
"it",
"will",
"be",
"subsequently",
"watched",
"for",
"updates",
"."
] | 6b9d0368d4265c382c3e11fe774d93aa8d431064 | https://github.com/robfig/soy/blob/6b9d0368d4265c382c3e11fe774d93aa8d431064/bundle.go#L76-L85 |
4,005 | robfig/soy | bundle.go | AddTemplateString | func (b *Bundle) AddTemplateString(filename, soyfile string) *Bundle {
b.files = append(b.files, soyFile{filename, soyfile})
return b
} | go | func (b *Bundle) AddTemplateString(filename, soyfile string) *Bundle {
b.files = append(b.files, soyFile{filename, soyfile})
return b
} | [
"func",
"(",
"b",
"*",
"Bundle",
")",
"AddTemplateString",
"(",
"filename",
",",
"soyfile",
"string",
")",
"*",
"Bundle",
"{",
"b",
".",
"files",
"=",
"append",
"(",
"b",
".",
"files",
",",
"soyFile",
"{",
"filename",
",",
"soyfile",
"}",
")",
"\n",
"return",
"b",
"\n",
"}"
] | // AddTemplateString adds the given template to the bundle. The name is only
// used for error messages - it does not need to be provided nor does it need to
// be a real filename. | [
"AddTemplateString",
"adds",
"the",
"given",
"template",
"to",
"the",
"bundle",
".",
"The",
"name",
"is",
"only",
"used",
"for",
"error",
"messages",
"-",
"it",
"does",
"not",
"need",
"to",
"be",
"provided",
"nor",
"does",
"it",
"need",
"to",
"be",
"a",
"real",
"filename",
"."
] | 6b9d0368d4265c382c3e11fe774d93aa8d431064 | https://github.com/robfig/soy/blob/6b9d0368d4265c382c3e11fe774d93aa8d431064/bundle.go#L90-L93 |
4,006 | robfig/soy | bundle.go | AddGlobalsFile | func (b *Bundle) AddGlobalsFile(filename string) *Bundle {
var f, err = os.Open(filename)
if err != nil {
b.err = err
return b
}
globals, err := ParseGlobals(f)
if err != nil {
b.err = err
}
f.Close()
return b.AddGlobalsMap(globals)
} | go | func (b *Bundle) AddGlobalsFile(filename string) *Bundle {
var f, err = os.Open(filename)
if err != nil {
b.err = err
return b
}
globals, err := ParseGlobals(f)
if err != nil {
b.err = err
}
f.Close()
return b.AddGlobalsMap(globals)
} | [
"func",
"(",
"b",
"*",
"Bundle",
")",
"AddGlobalsFile",
"(",
"filename",
"string",
")",
"*",
"Bundle",
"{",
"var",
"f",
",",
"err",
"=",
"os",
".",
"Open",
"(",
"filename",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"b",
".",
"err",
"=",
"err",
"\n",
"return",
"b",
"\n",
"}",
"\n",
"globals",
",",
"err",
":=",
"ParseGlobals",
"(",
"f",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"b",
".",
"err",
"=",
"err",
"\n",
"}",
"\n",
"f",
".",
"Close",
"(",
")",
"\n",
"return",
"b",
".",
"AddGlobalsMap",
"(",
"globals",
")",
"\n",
"}"
] | // AddGlobalsFile opens and parses the given filename for Soy globals, and adds
// the resulting data map to the bundle. | [
"AddGlobalsFile",
"opens",
"and",
"parses",
"the",
"given",
"filename",
"for",
"Soy",
"globals",
"and",
"adds",
"the",
"resulting",
"data",
"map",
"to",
"the",
"bundle",
"."
] | 6b9d0368d4265c382c3e11fe774d93aa8d431064 | https://github.com/robfig/soy/blob/6b9d0368d4265c382c3e11fe774d93aa8d431064/bundle.go#L97-L109 |
4,007 | robfig/soy | bundle.go | SetRecompilationCallback | func (b *Bundle) SetRecompilationCallback(c func(*template.Registry)) *Bundle {
b.recompilationCallback = c
return b
} | go | func (b *Bundle) SetRecompilationCallback(c func(*template.Registry)) *Bundle {
b.recompilationCallback = c
return b
} | [
"func",
"(",
"b",
"*",
"Bundle",
")",
"SetRecompilationCallback",
"(",
"c",
"func",
"(",
"*",
"template",
".",
"Registry",
")",
")",
"*",
"Bundle",
"{",
"b",
".",
"recompilationCallback",
"=",
"c",
"\n",
"return",
"b",
"\n",
"}"
] | // SetRecompilationCallback assigns the bundle a function to call after
// recompilation. This is called before updating the in-use registry. | [
"SetRecompilationCallback",
"assigns",
"the",
"bundle",
"a",
"function",
"to",
"call",
"after",
"recompilation",
".",
"This",
"is",
"called",
"before",
"updating",
"the",
"in",
"-",
"use",
"registry",
"."
] | 6b9d0368d4265c382c3e11fe774d93aa8d431064 | https://github.com/robfig/soy/blob/6b9d0368d4265c382c3e11fe774d93aa8d431064/bundle.go#L124-L127 |
4,008 | robfig/soy | bundle.go | AddParsePass | func (b *Bundle) AddParsePass(f func(template.Registry) error) *Bundle {
b.parsepasses = append(b.parsepasses, f)
return b
} | go | func (b *Bundle) AddParsePass(f func(template.Registry) error) *Bundle {
b.parsepasses = append(b.parsepasses, f)
return b
} | [
"func",
"(",
"b",
"*",
"Bundle",
")",
"AddParsePass",
"(",
"f",
"func",
"(",
"template",
".",
"Registry",
")",
"error",
")",
"*",
"Bundle",
"{",
"b",
".",
"parsepasses",
"=",
"append",
"(",
"b",
".",
"parsepasses",
",",
"f",
")",
"\n",
"return",
"b",
"\n",
"}"
] | // AddParsePass adds a function to the bundle that will be called
// after the soy is parsed | [
"AddParsePass",
"adds",
"a",
"function",
"to",
"the",
"bundle",
"that",
"will",
"be",
"called",
"after",
"the",
"soy",
"is",
"parsed"
] | 6b9d0368d4265c382c3e11fe774d93aa8d431064 | https://github.com/robfig/soy/blob/6b9d0368d4265c382c3e11fe774d93aa8d431064/bundle.go#L131-L134 |
4,009 | robfig/soy | bundle.go | Compile | func (b *Bundle) Compile() (*template.Registry, error) {
if b.err != nil {
return nil, b.err
}
// Compile all the soy (globals are already parsed)
var registry = template.Registry{}
for _, soyfile := range b.files {
var tree, err = parse.SoyFile(soyfile.name, soyfile.content)
if err != nil {
return nil, err
}
if err = registry.Add(tree); err != nil {
return nil, err
}
}
// Apply the post-parse processing
for _, parsepass := range b.parsepasses {
if err := parsepass(registry); err != nil {
return nil, err
}
}
if err := parsepasses.CheckDataRefs(registry); err != nil {
return nil, err
}
if err := parsepasses.SetGlobals(registry, b.globals); err != nil {
return nil, err
}
parsepasses.ProcessMessages(registry)
if b.watcher != nil {
go b.recompiler(®istry)
}
return ®istry, nil
} | go | func (b *Bundle) Compile() (*template.Registry, error) {
if b.err != nil {
return nil, b.err
}
// Compile all the soy (globals are already parsed)
var registry = template.Registry{}
for _, soyfile := range b.files {
var tree, err = parse.SoyFile(soyfile.name, soyfile.content)
if err != nil {
return nil, err
}
if err = registry.Add(tree); err != nil {
return nil, err
}
}
// Apply the post-parse processing
for _, parsepass := range b.parsepasses {
if err := parsepass(registry); err != nil {
return nil, err
}
}
if err := parsepasses.CheckDataRefs(registry); err != nil {
return nil, err
}
if err := parsepasses.SetGlobals(registry, b.globals); err != nil {
return nil, err
}
parsepasses.ProcessMessages(registry)
if b.watcher != nil {
go b.recompiler(®istry)
}
return ®istry, nil
} | [
"func",
"(",
"b",
"*",
"Bundle",
")",
"Compile",
"(",
")",
"(",
"*",
"template",
".",
"Registry",
",",
"error",
")",
"{",
"if",
"b",
".",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"b",
".",
"err",
"\n",
"}",
"\n\n",
"// Compile all the soy (globals are already parsed)",
"var",
"registry",
"=",
"template",
".",
"Registry",
"{",
"}",
"\n",
"for",
"_",
",",
"soyfile",
":=",
"range",
"b",
".",
"files",
"{",
"var",
"tree",
",",
"err",
"=",
"parse",
".",
"SoyFile",
"(",
"soyfile",
".",
"name",
",",
"soyfile",
".",
"content",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"if",
"err",
"=",
"registry",
".",
"Add",
"(",
"tree",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"}",
"\n\n",
"// Apply the post-parse processing",
"for",
"_",
",",
"parsepass",
":=",
"range",
"b",
".",
"parsepasses",
"{",
"if",
"err",
":=",
"parsepass",
"(",
"registry",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"}",
"\n",
"if",
"err",
":=",
"parsepasses",
".",
"CheckDataRefs",
"(",
"registry",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"if",
"err",
":=",
"parsepasses",
".",
"SetGlobals",
"(",
"registry",
",",
"b",
".",
"globals",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"parsepasses",
".",
"ProcessMessages",
"(",
"registry",
")",
"\n\n",
"if",
"b",
".",
"watcher",
"!=",
"nil",
"{",
"go",
"b",
".",
"recompiler",
"(",
"&",
"registry",
")",
"\n",
"}",
"\n",
"return",
"&",
"registry",
",",
"nil",
"\n",
"}"
] | // Compile parses all of the soy files in this bundle, verifies a number of
// rules about data references, and returns the completed template registry. | [
"Compile",
"parses",
"all",
"of",
"the",
"soy",
"files",
"in",
"this",
"bundle",
"verifies",
"a",
"number",
"of",
"rules",
"about",
"data",
"references",
"and",
"returns",
"the",
"completed",
"template",
"registry",
"."
] | 6b9d0368d4265c382c3e11fe774d93aa8d431064 | https://github.com/robfig/soy/blob/6b9d0368d4265c382c3e11fe774d93aa8d431064/bundle.go#L138-L173 |
4,010 | robfig/soy | bundle.go | CompileToTofu | func (b *Bundle) CompileToTofu() (*soyhtml.Tofu, error) {
var registry, err = b.Compile()
// TODO: Verify all used funcs exist and have the right # args.
return soyhtml.NewTofu(registry), err
} | go | func (b *Bundle) CompileToTofu() (*soyhtml.Tofu, error) {
var registry, err = b.Compile()
// TODO: Verify all used funcs exist and have the right # args.
return soyhtml.NewTofu(registry), err
} | [
"func",
"(",
"b",
"*",
"Bundle",
")",
"CompileToTofu",
"(",
")",
"(",
"*",
"soyhtml",
".",
"Tofu",
",",
"error",
")",
"{",
"var",
"registry",
",",
"err",
"=",
"b",
".",
"Compile",
"(",
")",
"\n",
"// TODO: Verify all used funcs exist and have the right # args.",
"return",
"soyhtml",
".",
"NewTofu",
"(",
"registry",
")",
",",
"err",
"\n",
"}"
] | // CompileToTofu returns a soyhtml.Tofu object that allows you to render soy
// templates to HTML. | [
"CompileToTofu",
"returns",
"a",
"soyhtml",
".",
"Tofu",
"object",
"that",
"allows",
"you",
"to",
"render",
"soy",
"templates",
"to",
"HTML",
"."
] | 6b9d0368d4265c382c3e11fe774d93aa8d431064 | https://github.com/robfig/soy/blob/6b9d0368d4265c382c3e11fe774d93aa8d431064/bundle.go#L177-L181 |
4,011 | robfig/soy | data/convert.go | NewWith | func NewWith(convert StructOptions, value interface{}) Value {
// quick return if we're passed an existing data.Value
if val, ok := value.(Value); ok {
return val
}
if value == nil {
return Null{}
}
// see if value implements MarshalValue
if mar, ok := value.(Marshaler); ok {
return mar.MarshalValue()
}
// drill through pointers and interfaces to the underlying type
var v = reflect.ValueOf(value)
for v.Kind() == reflect.Interface || v.Kind() == reflect.Ptr {
v = v.Elem()
}
if !v.IsValid() {
return Null{}
}
if v.Type() == timeType {
return String(v.Interface().(time.Time).Format(convert.TimeFormat))
}
switch v.Kind() {
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
return Int(v.Int())
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
return Int(v.Uint())
case reflect.Float32, reflect.Float64:
return Float(v.Float())
case reflect.Bool:
return Bool(v.Bool())
case reflect.String:
return String(v.String())
case reflect.Slice:
if v.IsNil() {
return List(nil)
}
slice := []Value{}
for i := 0; i < v.Len(); i++ {
slice = append(slice, NewWith(convert, v.Index(i).Interface()))
}
return List(slice)
case reflect.Map:
var m = make(map[string]Value)
for _, key := range v.MapKeys() {
if key.Kind() != reflect.String {
panic("map keys must be strings")
}
m[key.String()] = NewWith(convert, v.MapIndex(key).Interface())
}
return Map(m)
case reflect.Struct:
return convert.Data(v.Interface())
default:
panic(fmt.Errorf("unexpected data type: %T (%v)", value, value))
}
} | go | func NewWith(convert StructOptions, value interface{}) Value {
// quick return if we're passed an existing data.Value
if val, ok := value.(Value); ok {
return val
}
if value == nil {
return Null{}
}
// see if value implements MarshalValue
if mar, ok := value.(Marshaler); ok {
return mar.MarshalValue()
}
// drill through pointers and interfaces to the underlying type
var v = reflect.ValueOf(value)
for v.Kind() == reflect.Interface || v.Kind() == reflect.Ptr {
v = v.Elem()
}
if !v.IsValid() {
return Null{}
}
if v.Type() == timeType {
return String(v.Interface().(time.Time).Format(convert.TimeFormat))
}
switch v.Kind() {
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
return Int(v.Int())
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
return Int(v.Uint())
case reflect.Float32, reflect.Float64:
return Float(v.Float())
case reflect.Bool:
return Bool(v.Bool())
case reflect.String:
return String(v.String())
case reflect.Slice:
if v.IsNil() {
return List(nil)
}
slice := []Value{}
for i := 0; i < v.Len(); i++ {
slice = append(slice, NewWith(convert, v.Index(i).Interface()))
}
return List(slice)
case reflect.Map:
var m = make(map[string]Value)
for _, key := range v.MapKeys() {
if key.Kind() != reflect.String {
panic("map keys must be strings")
}
m[key.String()] = NewWith(convert, v.MapIndex(key).Interface())
}
return Map(m)
case reflect.Struct:
return convert.Data(v.Interface())
default:
panic(fmt.Errorf("unexpected data type: %T (%v)", value, value))
}
} | [
"func",
"NewWith",
"(",
"convert",
"StructOptions",
",",
"value",
"interface",
"{",
"}",
")",
"Value",
"{",
"// quick return if we're passed an existing data.Value",
"if",
"val",
",",
"ok",
":=",
"value",
".",
"(",
"Value",
")",
";",
"ok",
"{",
"return",
"val",
"\n",
"}",
"\n\n",
"if",
"value",
"==",
"nil",
"{",
"return",
"Null",
"{",
"}",
"\n",
"}",
"\n\n",
"// see if value implements MarshalValue",
"if",
"mar",
",",
"ok",
":=",
"value",
".",
"(",
"Marshaler",
")",
";",
"ok",
"{",
"return",
"mar",
".",
"MarshalValue",
"(",
")",
"\n",
"}",
"\n\n",
"// drill through pointers and interfaces to the underlying type",
"var",
"v",
"=",
"reflect",
".",
"ValueOf",
"(",
"value",
")",
"\n",
"for",
"v",
".",
"Kind",
"(",
")",
"==",
"reflect",
".",
"Interface",
"||",
"v",
".",
"Kind",
"(",
")",
"==",
"reflect",
".",
"Ptr",
"{",
"v",
"=",
"v",
".",
"Elem",
"(",
")",
"\n",
"}",
"\n",
"if",
"!",
"v",
".",
"IsValid",
"(",
")",
"{",
"return",
"Null",
"{",
"}",
"\n",
"}",
"\n\n",
"if",
"v",
".",
"Type",
"(",
")",
"==",
"timeType",
"{",
"return",
"String",
"(",
"v",
".",
"Interface",
"(",
")",
".",
"(",
"time",
".",
"Time",
")",
".",
"Format",
"(",
"convert",
".",
"TimeFormat",
")",
")",
"\n",
"}",
"\n\n",
"switch",
"v",
".",
"Kind",
"(",
")",
"{",
"case",
"reflect",
".",
"Int",
",",
"reflect",
".",
"Int8",
",",
"reflect",
".",
"Int16",
",",
"reflect",
".",
"Int32",
",",
"reflect",
".",
"Int64",
":",
"return",
"Int",
"(",
"v",
".",
"Int",
"(",
")",
")",
"\n",
"case",
"reflect",
".",
"Uint",
",",
"reflect",
".",
"Uint8",
",",
"reflect",
".",
"Uint16",
",",
"reflect",
".",
"Uint32",
",",
"reflect",
".",
"Uint64",
":",
"return",
"Int",
"(",
"v",
".",
"Uint",
"(",
")",
")",
"\n",
"case",
"reflect",
".",
"Float32",
",",
"reflect",
".",
"Float64",
":",
"return",
"Float",
"(",
"v",
".",
"Float",
"(",
")",
")",
"\n",
"case",
"reflect",
".",
"Bool",
":",
"return",
"Bool",
"(",
"v",
".",
"Bool",
"(",
")",
")",
"\n",
"case",
"reflect",
".",
"String",
":",
"return",
"String",
"(",
"v",
".",
"String",
"(",
")",
")",
"\n",
"case",
"reflect",
".",
"Slice",
":",
"if",
"v",
".",
"IsNil",
"(",
")",
"{",
"return",
"List",
"(",
"nil",
")",
"\n",
"}",
"\n",
"slice",
":=",
"[",
"]",
"Value",
"{",
"}",
"\n",
"for",
"i",
":=",
"0",
";",
"i",
"<",
"v",
".",
"Len",
"(",
")",
";",
"i",
"++",
"{",
"slice",
"=",
"append",
"(",
"slice",
",",
"NewWith",
"(",
"convert",
",",
"v",
".",
"Index",
"(",
"i",
")",
".",
"Interface",
"(",
")",
")",
")",
"\n",
"}",
"\n",
"return",
"List",
"(",
"slice",
")",
"\n",
"case",
"reflect",
".",
"Map",
":",
"var",
"m",
"=",
"make",
"(",
"map",
"[",
"string",
"]",
"Value",
")",
"\n",
"for",
"_",
",",
"key",
":=",
"range",
"v",
".",
"MapKeys",
"(",
")",
"{",
"if",
"key",
".",
"Kind",
"(",
")",
"!=",
"reflect",
".",
"String",
"{",
"panic",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"m",
"[",
"key",
".",
"String",
"(",
")",
"]",
"=",
"NewWith",
"(",
"convert",
",",
"v",
".",
"MapIndex",
"(",
"key",
")",
".",
"Interface",
"(",
")",
")",
"\n",
"}",
"\n",
"return",
"Map",
"(",
"m",
")",
"\n",
"case",
"reflect",
".",
"Struct",
":",
"return",
"convert",
".",
"Data",
"(",
"v",
".",
"Interface",
"(",
")",
")",
"\n",
"default",
":",
"panic",
"(",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"value",
",",
"value",
")",
")",
"\n",
"}",
"\n",
"}"
] | // NewWith converts the given data value soy data value, using the provided
// StructOptions for any structs encountered. | [
"NewWith",
"converts",
"the",
"given",
"data",
"value",
"soy",
"data",
"value",
"using",
"the",
"provided",
"StructOptions",
"for",
"any",
"structs",
"encountered",
"."
] | 6b9d0368d4265c382c3e11fe774d93aa8d431064 | https://github.com/robfig/soy/blob/6b9d0368d4265c382c3e11fe774d93aa8d431064/data/convert.go#L21-L83 |
4,012 | robfig/soy | soyjs/exec.go | Write | func Write(out io.Writer, node ast.Node, options Options) (err error) {
defer errRecover(&err)
if options.Formatter == nil {
options.Formatter = &ES5Formatter{}
}
var (
tmpOut = &bytes.Buffer{}
importsBuf = &bytes.Buffer{}
s = &state{
wr: tmpOut,
options: options,
funcsCalled: map[string]string{},
funcsInFile: map[string]bool{},
}
)
s.scope.push()
s.walk(node)
if len(s.funcsCalled) > 0 {
for _, f := range difference(s.funcsCalled, s.funcsInFile) {
importsBuf.WriteString(s.funcsCalled[f])
importsBuf.WriteRune('\n')
}
importsBuf.WriteRune('\n')
}
out.Write(importsBuf.Bytes())
out.Write(tmpOut.Bytes())
return nil
} | go | func Write(out io.Writer, node ast.Node, options Options) (err error) {
defer errRecover(&err)
if options.Formatter == nil {
options.Formatter = &ES5Formatter{}
}
var (
tmpOut = &bytes.Buffer{}
importsBuf = &bytes.Buffer{}
s = &state{
wr: tmpOut,
options: options,
funcsCalled: map[string]string{},
funcsInFile: map[string]bool{},
}
)
s.scope.push()
s.walk(node)
if len(s.funcsCalled) > 0 {
for _, f := range difference(s.funcsCalled, s.funcsInFile) {
importsBuf.WriteString(s.funcsCalled[f])
importsBuf.WriteRune('\n')
}
importsBuf.WriteRune('\n')
}
out.Write(importsBuf.Bytes())
out.Write(tmpOut.Bytes())
return nil
} | [
"func",
"Write",
"(",
"out",
"io",
".",
"Writer",
",",
"node",
"ast",
".",
"Node",
",",
"options",
"Options",
")",
"(",
"err",
"error",
")",
"{",
"defer",
"errRecover",
"(",
"&",
"err",
")",
"\n\n",
"if",
"options",
".",
"Formatter",
"==",
"nil",
"{",
"options",
".",
"Formatter",
"=",
"&",
"ES5Formatter",
"{",
"}",
"\n",
"}",
"\n\n",
"var",
"(",
"tmpOut",
"=",
"&",
"bytes",
".",
"Buffer",
"{",
"}",
"\n",
"importsBuf",
"=",
"&",
"bytes",
".",
"Buffer",
"{",
"}",
"\n",
"s",
"=",
"&",
"state",
"{",
"wr",
":",
"tmpOut",
",",
"options",
":",
"options",
",",
"funcsCalled",
":",
"map",
"[",
"string",
"]",
"string",
"{",
"}",
",",
"funcsInFile",
":",
"map",
"[",
"string",
"]",
"bool",
"{",
"}",
",",
"}",
"\n",
")",
"\n\n",
"s",
".",
"scope",
".",
"push",
"(",
")",
"\n",
"s",
".",
"walk",
"(",
"node",
")",
"\n\n",
"if",
"len",
"(",
"s",
".",
"funcsCalled",
")",
">",
"0",
"{",
"for",
"_",
",",
"f",
":=",
"range",
"difference",
"(",
"s",
".",
"funcsCalled",
",",
"s",
".",
"funcsInFile",
")",
"{",
"importsBuf",
".",
"WriteString",
"(",
"s",
".",
"funcsCalled",
"[",
"f",
"]",
")",
"\n",
"importsBuf",
".",
"WriteRune",
"(",
"'\\n'",
")",
"\n",
"}",
"\n",
"importsBuf",
".",
"WriteRune",
"(",
"'\\n'",
")",
"\n",
"}",
"\n\n",
"out",
".",
"Write",
"(",
"importsBuf",
".",
"Bytes",
"(",
")",
")",
"\n",
"out",
".",
"Write",
"(",
"tmpOut",
".",
"Bytes",
"(",
")",
")",
"\n\n",
"return",
"nil",
"\n",
"}"
] | // Write writes the javascript represented by the given node to the given
// writer. The first error encountered is returned. | [
"Write",
"writes",
"the",
"javascript",
"represented",
"by",
"the",
"given",
"node",
"to",
"the",
"given",
"writer",
".",
"The",
"first",
"error",
"encountered",
"is",
"returned",
"."
] | 6b9d0368d4265c382c3e11fe774d93aa8d431064 | https://github.com/robfig/soy/blob/6b9d0368d4265c382c3e11fe774d93aa8d431064/soyjs/exec.go#L44-L77 |
4,013 | robfig/soy | soyjs/exec.go | at | func (s *state) at(node ast.Node) {
s.lastNode = s.node
s.node = node
} | go | func (s *state) at(node ast.Node) {
s.lastNode = s.node
s.node = node
} | [
"func",
"(",
"s",
"*",
"state",
")",
"at",
"(",
"node",
"ast",
".",
"Node",
")",
"{",
"s",
".",
"lastNode",
"=",
"s",
".",
"node",
"\n",
"s",
".",
"node",
"=",
"node",
"\n",
"}"
] | // at marks the state to be on node n, for error reporting. | [
"at",
"marks",
"the",
"state",
"to",
"be",
"on",
"node",
"n",
"for",
"error",
"reporting",
"."
] | 6b9d0368d4265c382c3e11fe774d93aa8d431064 | https://github.com/robfig/soy/blob/6b9d0368d4265c382c3e11fe774d93aa8d431064/soyjs/exec.go#L80-L83 |
4,014 | robfig/soy | soyjs/exec.go | visitGlobal | func (s *state) visitGlobal(node *ast.GlobalNode) {
s.walk(s.nodeFromValue(node.Pos, node.Value))
} | go | func (s *state) visitGlobal(node *ast.GlobalNode) {
s.walk(s.nodeFromValue(node.Pos, node.Value))
} | [
"func",
"(",
"s",
"*",
"state",
")",
"visitGlobal",
"(",
"node",
"*",
"ast",
".",
"GlobalNode",
")",
"{",
"s",
".",
"walk",
"(",
"s",
".",
"nodeFromValue",
"(",
"node",
".",
"Pos",
",",
"node",
".",
"Value",
")",
")",
"\n",
"}"
] | // visitGlobal constructs a primitive node from its value and uses walk to
// render the right thing. | [
"visitGlobal",
"constructs",
"a",
"primitive",
"node",
"from",
"its",
"value",
"and",
"uses",
"walk",
"to",
"render",
"the",
"right",
"thing",
"."
] | 6b9d0368d4265c382c3e11fe774d93aa8d431064 | https://github.com/robfig/soy/blob/6b9d0368d4265c382c3e11fe774d93aa8d431064/soyjs/exec.go#L667-L669 |
4,015 | robfig/soy | soyjs/exec.go | block | func (s *state) block(node ast.Node) string {
var buf bytes.Buffer
(&state{
wr: &buf,
scope: s.scope,
options: s.options,
funcsCalled: s.funcsCalled,
funcsInFile: s.funcsInFile,
}).walk(node)
return buf.String()
} | go | func (s *state) block(node ast.Node) string {
var buf bytes.Buffer
(&state{
wr: &buf,
scope: s.scope,
options: s.options,
funcsCalled: s.funcsCalled,
funcsInFile: s.funcsInFile,
}).walk(node)
return buf.String()
} | [
"func",
"(",
"s",
"*",
"state",
")",
"block",
"(",
"node",
"ast",
".",
"Node",
")",
"string",
"{",
"var",
"buf",
"bytes",
".",
"Buffer",
"\n",
"(",
"&",
"state",
"{",
"wr",
":",
"&",
"buf",
",",
"scope",
":",
"s",
".",
"scope",
",",
"options",
":",
"s",
".",
"options",
",",
"funcsCalled",
":",
"s",
".",
"funcsCalled",
",",
"funcsInFile",
":",
"s",
".",
"funcsInFile",
",",
"}",
")",
".",
"walk",
"(",
"node",
")",
"\n",
"return",
"buf",
".",
"String",
"(",
")",
"\n",
"}"
] | // block renders the given node to a temporary buffer and returns the string. | [
"block",
"renders",
"the",
"given",
"node",
"to",
"a",
"temporary",
"buffer",
"and",
"returns",
"the",
"string",
"."
] | 6b9d0368d4265c382c3e11fe774d93aa8d431064 | https://github.com/robfig/soy/blob/6b9d0368d4265c382c3e11fe774d93aa8d431064/soyjs/exec.go#L709-L719 |
4,016 | robfig/soy | data/value.go | Index | func (v List) Index(i int) Value {
if !(0 <= i && i < len(v)) {
return Undefined{}
}
return v[i]
} | go | func (v List) Index(i int) Value {
if !(0 <= i && i < len(v)) {
return Undefined{}
}
return v[i]
} | [
"func",
"(",
"v",
"List",
")",
"Index",
"(",
"i",
"int",
")",
"Value",
"{",
"if",
"!",
"(",
"0",
"<=",
"i",
"&&",
"i",
"<",
"len",
"(",
"v",
")",
")",
"{",
"return",
"Undefined",
"{",
"}",
"\n",
"}",
"\n",
"return",
"v",
"[",
"i",
"]",
"\n",
"}"
] | // Index retrieves a value from this list, or Undefined if out of bounds. | [
"Index",
"retrieves",
"a",
"value",
"from",
"this",
"list",
"or",
"Undefined",
"if",
"out",
"of",
"bounds",
"."
] | 6b9d0368d4265c382c3e11fe774d93aa8d431064 | https://github.com/robfig/soy/blob/6b9d0368d4265c382c3e11fe774d93aa8d431064/data/value.go#L40-L45 |
4,017 | robfig/soy | data/value.go | Key | func (v Map) Key(k string) Value {
var result, ok = v[k]
if !ok {
return Undefined{}
}
return result
} | go | func (v Map) Key(k string) Value {
var result, ok = v[k]
if !ok {
return Undefined{}
}
return result
} | [
"func",
"(",
"v",
"Map",
")",
"Key",
"(",
"k",
"string",
")",
"Value",
"{",
"var",
"result",
",",
"ok",
"=",
"v",
"[",
"k",
"]",
"\n",
"if",
"!",
"ok",
"{",
"return",
"Undefined",
"{",
"}",
"\n",
"}",
"\n",
"return",
"result",
"\n",
"}"
] | // Key retrieves a value under the named key, or Undefined if it doesn't exist. | [
"Key",
"retrieves",
"a",
"value",
"under",
"the",
"named",
"key",
"or",
"Undefined",
"if",
"it",
"doesn",
"t",
"exist",
"."
] | 6b9d0368d4265c382c3e11fe774d93aa8d431064 | https://github.com/robfig/soy/blob/6b9d0368d4265c382c3e11fe774d93aa8d431064/data/value.go#L48-L54 |
4,018 | robfig/soy | soyjs/generator.go | WriteFile | func (gen *Generator) WriteFile(out io.Writer, filename string) error {
for _, soyfile := range gen.registry.SoyFiles {
if soyfile.Name == filename {
return Write(out, soyfile, Options{})
}
}
return ErrNotFound
} | go | func (gen *Generator) WriteFile(out io.Writer, filename string) error {
for _, soyfile := range gen.registry.SoyFiles {
if soyfile.Name == filename {
return Write(out, soyfile, Options{})
}
}
return ErrNotFound
} | [
"func",
"(",
"gen",
"*",
"Generator",
")",
"WriteFile",
"(",
"out",
"io",
".",
"Writer",
",",
"filename",
"string",
")",
"error",
"{",
"for",
"_",
",",
"soyfile",
":=",
"range",
"gen",
".",
"registry",
".",
"SoyFiles",
"{",
"if",
"soyfile",
".",
"Name",
"==",
"filename",
"{",
"return",
"Write",
"(",
"out",
",",
"soyfile",
",",
"Options",
"{",
"}",
")",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"ErrNotFound",
"\n",
"}"
] | // WriteFile generates javascript corresponding to the soy file of the given name. | [
"WriteFile",
"generates",
"javascript",
"corresponding",
"to",
"the",
"soy",
"file",
"of",
"the",
"given",
"name",
"."
] | 6b9d0368d4265c382c3e11fe774d93aa8d431064 | https://github.com/robfig/soy/blob/6b9d0368d4265c382c3e11fe774d93aa8d431064/soyjs/generator.go#L35-L42 |
4,019 | robfig/soy | soyjs/formatters.go | Template | func (f ES6Formatter) Template(name string) (string, string) {
return ES6Identifier(name), "export function " + ES6Identifier(name)
} | go | func (f ES6Formatter) Template(name string) (string, string) {
return ES6Identifier(name), "export function " + ES6Identifier(name)
} | [
"func",
"(",
"f",
"ES6Formatter",
")",
"Template",
"(",
"name",
"string",
")",
"(",
"string",
",",
"string",
")",
"{",
"return",
"ES6Identifier",
"(",
"name",
")",
",",
"\"",
"\"",
"+",
"ES6Identifier",
"(",
"name",
")",
"\n",
"}"
] | // Template returns two values, the name of the template to save
// in the defined functions map, and how the function should be defined.
// For ES6, the function is not defined globally, but exported | [
"Template",
"returns",
"two",
"values",
"the",
"name",
"of",
"the",
"template",
"to",
"save",
"in",
"the",
"defined",
"functions",
"map",
"and",
"how",
"the",
"function",
"should",
"be",
"defined",
".",
"For",
"ES6",
"the",
"function",
"is",
"not",
"defined",
"globally",
"but",
"exported"
] | 6b9d0368d4265c382c3e11fe774d93aa8d431064 | https://github.com/robfig/soy/blob/6b9d0368d4265c382c3e11fe774d93aa8d431064/soyjs/formatters.go#L88-L90 |
4,020 | robfig/soy | soyjs/formatters.go | Call | func (f ES6Formatter) Call(name string) (string, string) {
return ES6Identifier(name), "import { " + ES6Identifier(name) + " } from '" + name + ".js';"
} | go | func (f ES6Formatter) Call(name string) (string, string) {
return ES6Identifier(name), "import { " + ES6Identifier(name) + " } from '" + name + ".js';"
} | [
"func",
"(",
"f",
"ES6Formatter",
")",
"Call",
"(",
"name",
"string",
")",
"(",
"string",
",",
"string",
")",
"{",
"return",
"ES6Identifier",
"(",
"name",
")",
",",
"\"",
"\"",
"+",
"ES6Identifier",
"(",
"name",
")",
"+",
"\"",
"\"",
"+",
"name",
"+",
"\"",
"\"",
"\n",
"}"
] | // Call returns two values, the name of the template to save
// in the called functions map, and a string that is written
// into the imports | [
"Call",
"returns",
"two",
"values",
"the",
"name",
"of",
"the",
"template",
"to",
"save",
"in",
"the",
"called",
"functions",
"map",
"and",
"a",
"string",
"that",
"is",
"written",
"into",
"the",
"imports"
] | 6b9d0368d4265c382c3e11fe774d93aa8d431064 | https://github.com/robfig/soy/blob/6b9d0368d4265c382c3e11fe774d93aa8d431064/soyjs/formatters.go#L95-L97 |
4,021 | robfig/soy | soyjs/formatters.go | Directive | func (f ES6Formatter) Directive(dir PrintDirective) string {
return "import { " + ES6Identifier(dir.Name) + " } from '" + dir.Name + ".js';"
} | go | func (f ES6Formatter) Directive(dir PrintDirective) string {
return "import { " + ES6Identifier(dir.Name) + " } from '" + dir.Name + ".js';"
} | [
"func",
"(",
"f",
"ES6Formatter",
")",
"Directive",
"(",
"dir",
"PrintDirective",
")",
"string",
"{",
"return",
"\"",
"\"",
"+",
"ES6Identifier",
"(",
"dir",
".",
"Name",
")",
"+",
"\"",
"\"",
"+",
"dir",
".",
"Name",
"+",
"\"",
"\"",
"\n",
"}"
] | // Directive takes in a PrintDirective and returns a string
// that is written into the imports | [
"Directive",
"takes",
"in",
"a",
"PrintDirective",
"and",
"returns",
"a",
"string",
"that",
"is",
"written",
"into",
"the",
"imports"
] | 6b9d0368d4265c382c3e11fe774d93aa8d431064 | https://github.com/robfig/soy/blob/6b9d0368d4265c382c3e11fe774d93aa8d431064/soyjs/formatters.go#L101-L103 |
4,022 | robfig/soy | soyjs/formatters.go | Function | func (f ES6Formatter) Function(fn Func) string {
return "import { " + ES6Identifier(fn.Name) + " } from '" + fn.Name + ".js';"
} | go | func (f ES6Formatter) Function(fn Func) string {
return "import { " + ES6Identifier(fn.Name) + " } from '" + fn.Name + ".js';"
} | [
"func",
"(",
"f",
"ES6Formatter",
")",
"Function",
"(",
"fn",
"Func",
")",
"string",
"{",
"return",
"\"",
"\"",
"+",
"ES6Identifier",
"(",
"fn",
".",
"Name",
")",
"+",
"\"",
"\"",
"+",
"fn",
".",
"Name",
"+",
"\"",
"\"",
"\n",
"}"
] | // Function takes in a Func and returns a string
// that is written into the imports | [
"Function",
"takes",
"in",
"a",
"Func",
"and",
"returns",
"a",
"string",
"that",
"is",
"written",
"into",
"the",
"imports"
] | 6b9d0368d4265c382c3e11fe774d93aa8d431064 | https://github.com/robfig/soy/blob/6b9d0368d4265c382c3e11fe774d93aa8d431064/soyjs/formatters.go#L107-L109 |
4,023 | robfig/soy | template/registry.go | LineNumber | func (r *Registry) LineNumber(templateName string, node ast.Node) int {
var src, ok = r.sourceByTemplateName[templateName]
if !ok {
log.Println("template not found:", templateName)
return 0
}
return 1 + strings.Count(src[:node.Position()], "\n")
} | go | func (r *Registry) LineNumber(templateName string, node ast.Node) int {
var src, ok = r.sourceByTemplateName[templateName]
if !ok {
log.Println("template not found:", templateName)
return 0
}
return 1 + strings.Count(src[:node.Position()], "\n")
} | [
"func",
"(",
"r",
"*",
"Registry",
")",
"LineNumber",
"(",
"templateName",
"string",
",",
"node",
"ast",
".",
"Node",
")",
"int",
"{",
"var",
"src",
",",
"ok",
"=",
"r",
".",
"sourceByTemplateName",
"[",
"templateName",
"]",
"\n",
"if",
"!",
"ok",
"{",
"log",
".",
"Println",
"(",
"\"",
"\"",
",",
"templateName",
")",
"\n",
"return",
"0",
"\n",
"}",
"\n",
"return",
"1",
"+",
"strings",
".",
"Count",
"(",
"src",
"[",
":",
"node",
".",
"Position",
"(",
")",
"]",
",",
"\"",
"\\n",
"\"",
")",
"\n",
"}"
] | // LineNumber computes the line number in the input source for the given node
// within the given template. | [
"LineNumber",
"computes",
"the",
"line",
"number",
"in",
"the",
"input",
"source",
"for",
"the",
"given",
"node",
"within",
"the",
"given",
"template",
"."
] | 6b9d0368d4265c382c3e11fe774d93aa8d431064 | https://github.com/robfig/soy/blob/6b9d0368d4265c382c3e11fe774d93aa8d431064/template/registry.go#L81-L88 |
4,024 | robfig/soy | template/registry.go | ColNumber | func (r *Registry) ColNumber(templateName string, node ast.Node) int {
var src, ok = r.sourceByTemplateName[templateName]
if !ok {
log.Println("template not found:", templateName)
return 0
}
return 1 + int(node.Position()) - strings.LastIndex(src[:node.Position()], "\n")
} | go | func (r *Registry) ColNumber(templateName string, node ast.Node) int {
var src, ok = r.sourceByTemplateName[templateName]
if !ok {
log.Println("template not found:", templateName)
return 0
}
return 1 + int(node.Position()) - strings.LastIndex(src[:node.Position()], "\n")
} | [
"func",
"(",
"r",
"*",
"Registry",
")",
"ColNumber",
"(",
"templateName",
"string",
",",
"node",
"ast",
".",
"Node",
")",
"int",
"{",
"var",
"src",
",",
"ok",
"=",
"r",
".",
"sourceByTemplateName",
"[",
"templateName",
"]",
"\n",
"if",
"!",
"ok",
"{",
"log",
".",
"Println",
"(",
"\"",
"\"",
",",
"templateName",
")",
"\n",
"return",
"0",
"\n",
"}",
"\n",
"return",
"1",
"+",
"int",
"(",
"node",
".",
"Position",
"(",
")",
")",
"-",
"strings",
".",
"LastIndex",
"(",
"src",
"[",
":",
"node",
".",
"Position",
"(",
")",
"]",
",",
"\"",
"\\n",
"\"",
")",
"\n",
"}"
] | // ColNumber computes the column number in the relevant line of input source for the given node
// within the given template. | [
"ColNumber",
"computes",
"the",
"column",
"number",
"in",
"the",
"relevant",
"line",
"of",
"input",
"source",
"for",
"the",
"given",
"node",
"within",
"the",
"given",
"template",
"."
] | 6b9d0368d4265c382c3e11fe774d93aa8d431064 | https://github.com/robfig/soy/blob/6b9d0368d4265c382c3e11fe774d93aa8d431064/template/registry.go#L92-L99 |
4,025 | robfig/soy | template/registry.go | Filename | func (r *Registry) Filename(templateName string) string {
var f, ok = r.fileByTemplateName[templateName]
if !ok {
log.Println("template not found:", templateName)
return ""
}
return f
} | go | func (r *Registry) Filename(templateName string) string {
var f, ok = r.fileByTemplateName[templateName]
if !ok {
log.Println("template not found:", templateName)
return ""
}
return f
} | [
"func",
"(",
"r",
"*",
"Registry",
")",
"Filename",
"(",
"templateName",
"string",
")",
"string",
"{",
"var",
"f",
",",
"ok",
"=",
"r",
".",
"fileByTemplateName",
"[",
"templateName",
"]",
"\n",
"if",
"!",
"ok",
"{",
"log",
".",
"Println",
"(",
"\"",
"\"",
",",
"templateName",
")",
"\n",
"return",
"\"",
"\"",
"\n",
"}",
"\n",
"return",
"f",
"\n",
"}"
] | // Filename identifies the filename containing the specified template | [
"Filename",
"identifies",
"the",
"filename",
"containing",
"the",
"specified",
"template"
] | 6b9d0368d4265c382c3e11fe774d93aa8d431064 | https://github.com/robfig/soy/blob/6b9d0368d4265c382c3e11fe774d93aa8d431064/template/registry.go#L102-L109 |
4,026 | robfig/soy | soyjs/scope.go | makevar | func (s *scope) makevar(varname string) string {
s.n++
var genName = varname + strconv.Itoa(s.n)
s.stack[len(s.stack)-1][varname] = genName
return genName
} | go | func (s *scope) makevar(varname string) string {
s.n++
var genName = varname + strconv.Itoa(s.n)
s.stack[len(s.stack)-1][varname] = genName
return genName
} | [
"func",
"(",
"s",
"*",
"scope",
")",
"makevar",
"(",
"varname",
"string",
")",
"string",
"{",
"s",
".",
"n",
"++",
"\n",
"var",
"genName",
"=",
"varname",
"+",
"strconv",
".",
"Itoa",
"(",
"s",
".",
"n",
")",
"\n",
"s",
".",
"stack",
"[",
"len",
"(",
"s",
".",
"stack",
")",
"-",
"1",
"]",
"[",
"varname",
"]",
"=",
"genName",
"\n",
"return",
"genName",
"\n",
"}"
] | // makevar generates and returns a new JS name for the given variable name, adds
// that mapping to this scope. | [
"makevar",
"generates",
"and",
"returns",
"a",
"new",
"JS",
"name",
"for",
"the",
"given",
"variable",
"name",
"adds",
"that",
"mapping",
"to",
"this",
"scope",
"."
] | 6b9d0368d4265c382c3e11fe774d93aa8d431064 | https://github.com/robfig/soy/blob/6b9d0368d4265c382c3e11fe774d93aa8d431064/soyjs/scope.go#L22-L27 |
4,027 | robfig/soy | soyhtml/eval.go | EvalExpr | func EvalExpr(node ast.Node) (val data.Value, err error) {
state := &state{wr: ioutil.Discard}
defer state.errRecover(&err)
state.walk(node)
return state.val, nil
} | go | func EvalExpr(node ast.Node) (val data.Value, err error) {
state := &state{wr: ioutil.Discard}
defer state.errRecover(&err)
state.walk(node)
return state.val, nil
} | [
"func",
"EvalExpr",
"(",
"node",
"ast",
".",
"Node",
")",
"(",
"val",
"data",
".",
"Value",
",",
"err",
"error",
")",
"{",
"state",
":=",
"&",
"state",
"{",
"wr",
":",
"ioutil",
".",
"Discard",
"}",
"\n",
"defer",
"state",
".",
"errRecover",
"(",
"&",
"err",
")",
"\n",
"state",
".",
"walk",
"(",
"node",
")",
"\n",
"return",
"state",
".",
"val",
",",
"nil",
"\n",
"}"
] | // EvalExpr evaluates the given expression node and returns the result. The
// given node must be a simple Soy expression, such as what may appear inside a
// print tag.
//
// This is useful for evaluating Globals, or anything returned from parse.Expr. | [
"EvalExpr",
"evaluates",
"the",
"given",
"expression",
"node",
"and",
"returns",
"the",
"result",
".",
"The",
"given",
"node",
"must",
"be",
"a",
"simple",
"Soy",
"expression",
"such",
"as",
"what",
"may",
"appear",
"inside",
"a",
"print",
"tag",
".",
"This",
"is",
"useful",
"for",
"evaluating",
"Globals",
"or",
"anything",
"returned",
"from",
"parse",
".",
"Expr",
"."
] | 6b9d0368d4265c382c3e11fe774d93aa8d431064 | https://github.com/robfig/soy/blob/6b9d0368d4265c382c3e11fe774d93aa8d431064/soyhtml/eval.go#L15-L20 |
4,028 | robfig/soy | soyhtml/renderer.go | WithMessages | func (r *Renderer) WithMessages(bundle soymsg.Bundle) *Renderer {
r.msgs = bundle
return r
} | go | func (r *Renderer) WithMessages(bundle soymsg.Bundle) *Renderer {
r.msgs = bundle
return r
} | [
"func",
"(",
"r",
"*",
"Renderer",
")",
"WithMessages",
"(",
"bundle",
"soymsg",
".",
"Bundle",
")",
"*",
"Renderer",
"{",
"r",
".",
"msgs",
"=",
"bundle",
"\n",
"return",
"r",
"\n",
"}"
] | // WithMessages provides a message bundle to use during execution. | [
"WithMessages",
"provides",
"a",
"message",
"bundle",
"to",
"use",
"during",
"execution",
"."
] | 6b9d0368d4265c382c3e11fe774d93aa8d431064 | https://github.com/robfig/soy/blob/6b9d0368d4265c382c3e11fe774d93aa8d431064/soyhtml/renderer.go#L31-L34 |
4,029 | robfig/soy | soyhtml/renderer.go | Execute | func (t Renderer) Execute(wr io.Writer, obj data.Map) (err error) {
if t.tofu == nil || t.tofu.registry == nil {
return errors.New("Template Registry required")
}
if t.name == "" {
return errors.New("Template name required")
}
var tmpl, ok = t.tofu.registry.Template(t.name)
if !ok {
return ErrTemplateNotFound
}
var autoescapeMode = tmpl.Namespace.Autoescape
if autoescapeMode == ast.AutoescapeUnspecified {
autoescapeMode = ast.AutoescapeOn
}
var initialScope = newScope(obj)
initialScope.enter()
state := &state{
tmpl: tmpl,
registry: *t.tofu.registry,
namespace: tmpl.Namespace.Name,
autoescape: autoescapeMode,
wr: wr,
context: initialScope,
ij: t.ij,
msgs: t.msgs,
}
defer state.errRecover(&err)
state.walk(tmpl.Node)
return
} | go | func (t Renderer) Execute(wr io.Writer, obj data.Map) (err error) {
if t.tofu == nil || t.tofu.registry == nil {
return errors.New("Template Registry required")
}
if t.name == "" {
return errors.New("Template name required")
}
var tmpl, ok = t.tofu.registry.Template(t.name)
if !ok {
return ErrTemplateNotFound
}
var autoescapeMode = tmpl.Namespace.Autoescape
if autoescapeMode == ast.AutoescapeUnspecified {
autoescapeMode = ast.AutoescapeOn
}
var initialScope = newScope(obj)
initialScope.enter()
state := &state{
tmpl: tmpl,
registry: *t.tofu.registry,
namespace: tmpl.Namespace.Name,
autoescape: autoescapeMode,
wr: wr,
context: initialScope,
ij: t.ij,
msgs: t.msgs,
}
defer state.errRecover(&err)
state.walk(tmpl.Node)
return
} | [
"func",
"(",
"t",
"Renderer",
")",
"Execute",
"(",
"wr",
"io",
".",
"Writer",
",",
"obj",
"data",
".",
"Map",
")",
"(",
"err",
"error",
")",
"{",
"if",
"t",
".",
"tofu",
"==",
"nil",
"||",
"t",
".",
"tofu",
".",
"registry",
"==",
"nil",
"{",
"return",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"if",
"t",
".",
"name",
"==",
"\"",
"\"",
"{",
"return",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"var",
"tmpl",
",",
"ok",
"=",
"t",
".",
"tofu",
".",
"registry",
".",
"Template",
"(",
"t",
".",
"name",
")",
"\n",
"if",
"!",
"ok",
"{",
"return",
"ErrTemplateNotFound",
"\n",
"}",
"\n\n",
"var",
"autoescapeMode",
"=",
"tmpl",
".",
"Namespace",
".",
"Autoescape",
"\n",
"if",
"autoescapeMode",
"==",
"ast",
".",
"AutoescapeUnspecified",
"{",
"autoescapeMode",
"=",
"ast",
".",
"AutoescapeOn",
"\n",
"}",
"\n\n",
"var",
"initialScope",
"=",
"newScope",
"(",
"obj",
")",
"\n",
"initialScope",
".",
"enter",
"(",
")",
"\n\n",
"state",
":=",
"&",
"state",
"{",
"tmpl",
":",
"tmpl",
",",
"registry",
":",
"*",
"t",
".",
"tofu",
".",
"registry",
",",
"namespace",
":",
"tmpl",
".",
"Namespace",
".",
"Name",
",",
"autoescape",
":",
"autoescapeMode",
",",
"wr",
":",
"wr",
",",
"context",
":",
"initialScope",
",",
"ij",
":",
"t",
".",
"ij",
",",
"msgs",
":",
"t",
".",
"msgs",
",",
"}",
"\n",
"defer",
"state",
".",
"errRecover",
"(",
"&",
"err",
")",
"\n",
"state",
".",
"walk",
"(",
"tmpl",
".",
"Node",
")",
"\n",
"return",
"\n",
"}"
] | // Execute applies a parsed template to the specified data object,
// and writes the output to wr. | [
"Execute",
"applies",
"a",
"parsed",
"template",
"to",
"the",
"specified",
"data",
"object",
"and",
"writes",
"the",
"output",
"to",
"wr",
"."
] | 6b9d0368d4265c382c3e11fe774d93aa8d431064 | https://github.com/robfig/soy/blob/6b9d0368d4265c382c3e11fe774d93aa8d431064/soyhtml/renderer.go#L38-L72 |
4,030 | robfig/soy | errortypes/filepos.go | NewErrFilePosf | func NewErrFilePosf(file string, line, col int, format string, args ...interface{}) error {
return &errFilePos{
error: fmt.Errorf(format, args...),
file: file,
line: line,
col: col,
}
} | go | func NewErrFilePosf(file string, line, col int, format string, args ...interface{}) error {
return &errFilePos{
error: fmt.Errorf(format, args...),
file: file,
line: line,
col: col,
}
} | [
"func",
"NewErrFilePosf",
"(",
"file",
"string",
",",
"line",
",",
"col",
"int",
",",
"format",
"string",
",",
"args",
"...",
"interface",
"{",
"}",
")",
"error",
"{",
"return",
"&",
"errFilePos",
"{",
"error",
":",
"fmt",
".",
"Errorf",
"(",
"format",
",",
"args",
"...",
")",
",",
"file",
":",
"file",
",",
"line",
":",
"line",
",",
"col",
":",
"col",
",",
"}",
"\n",
"}"
] | // NewErrFilePosf creates an error conforming to the ErrFilePos interface. | [
"NewErrFilePosf",
"creates",
"an",
"error",
"conforming",
"to",
"the",
"ErrFilePos",
"interface",
"."
] | 6b9d0368d4265c382c3e11fe774d93aa8d431064 | https://github.com/robfig/soy/blob/6b9d0368d4265c382c3e11fe774d93aa8d431064/errortypes/filepos.go#L14-L21 |
4,031 | robfig/soy | errortypes/filepos.go | ToErrFilePos | func ToErrFilePos(err error) ErrFilePos {
if err == nil {
return nil
}
if out, isErrFilePos := err.(ErrFilePos); isErrFilePos {
return out
}
return nil
} | go | func ToErrFilePos(err error) ErrFilePos {
if err == nil {
return nil
}
if out, isErrFilePos := err.(ErrFilePos); isErrFilePos {
return out
}
return nil
} | [
"func",
"ToErrFilePos",
"(",
"err",
"error",
")",
"ErrFilePos",
"{",
"if",
"err",
"==",
"nil",
"{",
"return",
"nil",
"\n",
"}",
"\n",
"if",
"out",
",",
"isErrFilePos",
":=",
"err",
".",
"(",
"ErrFilePos",
")",
";",
"isErrFilePos",
"{",
"return",
"out",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] | // ToErrFilePos converts the input error to an ErrFilePos if possible, or nil if not.
// If IsErrFilePos returns true, this will not return nil. | [
"ToErrFilePos",
"converts",
"the",
"input",
"error",
"to",
"an",
"ErrFilePos",
"if",
"possible",
"or",
"nil",
"if",
"not",
".",
"If",
"IsErrFilePos",
"returns",
"true",
"this",
"will",
"not",
"return",
"nil",
"."
] | 6b9d0368d4265c382c3e11fe774d93aa8d431064 | https://github.com/robfig/soy/blob/6b9d0368d4265c382c3e11fe774d93aa8d431064/errortypes/filepos.go#L35-L43 |
4,032 | robfig/soy | parse/quote.go | quoteString | func quoteString(s string) string {
var q = make([]rune, 1, len(s)+10)
q[0] = '\''
for _, ch := range s {
if seq, ok := escapes[ch]; ok {
q = append(q, '\\', seq)
continue
}
q = append(q, ch)
}
return string(append(q, '\''))
} | go | func quoteString(s string) string {
var q = make([]rune, 1, len(s)+10)
q[0] = '\''
for _, ch := range s {
if seq, ok := escapes[ch]; ok {
q = append(q, '\\', seq)
continue
}
q = append(q, ch)
}
return string(append(q, '\''))
} | [
"func",
"quoteString",
"(",
"s",
"string",
")",
"string",
"{",
"var",
"q",
"=",
"make",
"(",
"[",
"]",
"rune",
",",
"1",
",",
"len",
"(",
"s",
")",
"+",
"10",
")",
"\n",
"q",
"[",
"0",
"]",
"=",
"'\\''",
"\n",
"for",
"_",
",",
"ch",
":=",
"range",
"s",
"{",
"if",
"seq",
",",
"ok",
":=",
"escapes",
"[",
"ch",
"]",
";",
"ok",
"{",
"q",
"=",
"append",
"(",
"q",
",",
"'\\\\'",
",",
"seq",
")",
"\n",
"continue",
"\n",
"}",
"\n",
"q",
"=",
"append",
"(",
"q",
",",
"ch",
")",
"\n",
"}",
"\n",
"return",
"string",
"(",
"append",
"(",
"q",
",",
"'\\''",
")",
")",
"\n",
"}"
] | // quoteString quotes the given string with single quotes, according to the Soy
// spec for string literals. | [
"quoteString",
"quotes",
"the",
"given",
"string",
"with",
"single",
"quotes",
"according",
"to",
"the",
"Soy",
"spec",
"for",
"string",
"literals",
"."
] | 6b9d0368d4265c382c3e11fe774d93aa8d431064 | https://github.com/robfig/soy/blob/6b9d0368d4265c382c3e11fe774d93aa8d431064/parse/quote.go#L29-L40 |
4,033 | robfig/soy | soymsg/placeholder.go | setPlaceholderNames | func setPlaceholderNames(n *ast.MsgNode) {
// Step 1: Determine representative nodes and build preliminary map
var (
baseNameToRepNodes = make(map[string][]ast.Node)
equivNodeToRepNodes = make(map[ast.Node]ast.Node)
)
var nodeQueue []ast.Node = phNodes(n.Body)
for len(nodeQueue) > 0 {
var node = nodeQueue[0]
nodeQueue = nodeQueue[1:]
var baseName string
switch node := node.(type) {
case *ast.MsgPlaceholderNode:
baseName = genBasePlaceholderName(node.Body, "XXX")
case *ast.MsgPluralNode:
nodeQueue = append(nodeQueue, pluralCaseBodies(node)...)
baseName = genBasePlaceholderName(node.Value, "NUM")
default:
panic("unexpected")
}
if nodes, ok := baseNameToRepNodes[baseName]; !ok {
baseNameToRepNodes[baseName] = []ast.Node{node}
} else {
var isNew = true
var str = node.String()
for _, other := range nodes {
if other.String() == str {
equivNodeToRepNodes[node] = other
isNew = false
break
}
}
if isNew {
baseNameToRepNodes[baseName] = append(nodes, node)
}
}
}
// Step 2: Build final maps of name to representative node
var nameToRepNodes = make(map[string]ast.Node)
for baseName, nodes := range baseNameToRepNodes {
if len(nodes) == 1 {
nameToRepNodes[baseName] = nodes[0]
continue
}
var nextSuffix = 1
for _, node := range nodes {
for {
var newName = baseName + "_" + strconv.Itoa(nextSuffix)
if _, ok := nameToRepNodes[newName]; !ok {
nameToRepNodes[newName] = node
break
}
nextSuffix++
}
}
}
// Step 3: Create maps of every node to its name
var nodeToName = make(map[ast.Node]string)
for name, node := range nameToRepNodes {
nodeToName[node] = name
}
for other, repNode := range equivNodeToRepNodes {
nodeToName[other] = nodeToName[repNode]
}
// Step 4: Set the calculated names on all the nodes.
for node, name := range nodeToName {
switch node := node.(type) {
case *ast.MsgPlaceholderNode:
node.Name = name
case *ast.MsgPluralNode:
node.VarName = name
default:
panic("unexpected: " + node.String())
}
}
} | go | func setPlaceholderNames(n *ast.MsgNode) {
// Step 1: Determine representative nodes and build preliminary map
var (
baseNameToRepNodes = make(map[string][]ast.Node)
equivNodeToRepNodes = make(map[ast.Node]ast.Node)
)
var nodeQueue []ast.Node = phNodes(n.Body)
for len(nodeQueue) > 0 {
var node = nodeQueue[0]
nodeQueue = nodeQueue[1:]
var baseName string
switch node := node.(type) {
case *ast.MsgPlaceholderNode:
baseName = genBasePlaceholderName(node.Body, "XXX")
case *ast.MsgPluralNode:
nodeQueue = append(nodeQueue, pluralCaseBodies(node)...)
baseName = genBasePlaceholderName(node.Value, "NUM")
default:
panic("unexpected")
}
if nodes, ok := baseNameToRepNodes[baseName]; !ok {
baseNameToRepNodes[baseName] = []ast.Node{node}
} else {
var isNew = true
var str = node.String()
for _, other := range nodes {
if other.String() == str {
equivNodeToRepNodes[node] = other
isNew = false
break
}
}
if isNew {
baseNameToRepNodes[baseName] = append(nodes, node)
}
}
}
// Step 2: Build final maps of name to representative node
var nameToRepNodes = make(map[string]ast.Node)
for baseName, nodes := range baseNameToRepNodes {
if len(nodes) == 1 {
nameToRepNodes[baseName] = nodes[0]
continue
}
var nextSuffix = 1
for _, node := range nodes {
for {
var newName = baseName + "_" + strconv.Itoa(nextSuffix)
if _, ok := nameToRepNodes[newName]; !ok {
nameToRepNodes[newName] = node
break
}
nextSuffix++
}
}
}
// Step 3: Create maps of every node to its name
var nodeToName = make(map[ast.Node]string)
for name, node := range nameToRepNodes {
nodeToName[node] = name
}
for other, repNode := range equivNodeToRepNodes {
nodeToName[other] = nodeToName[repNode]
}
// Step 4: Set the calculated names on all the nodes.
for node, name := range nodeToName {
switch node := node.(type) {
case *ast.MsgPlaceholderNode:
node.Name = name
case *ast.MsgPluralNode:
node.VarName = name
default:
panic("unexpected: " + node.String())
}
}
} | [
"func",
"setPlaceholderNames",
"(",
"n",
"*",
"ast",
".",
"MsgNode",
")",
"{",
"// Step 1: Determine representative nodes and build preliminary map",
"var",
"(",
"baseNameToRepNodes",
"=",
"make",
"(",
"map",
"[",
"string",
"]",
"[",
"]",
"ast",
".",
"Node",
")",
"\n",
"equivNodeToRepNodes",
"=",
"make",
"(",
"map",
"[",
"ast",
".",
"Node",
"]",
"ast",
".",
"Node",
")",
"\n",
")",
"\n\n",
"var",
"nodeQueue",
"[",
"]",
"ast",
".",
"Node",
"=",
"phNodes",
"(",
"n",
".",
"Body",
")",
"\n",
"for",
"len",
"(",
"nodeQueue",
")",
">",
"0",
"{",
"var",
"node",
"=",
"nodeQueue",
"[",
"0",
"]",
"\n",
"nodeQueue",
"=",
"nodeQueue",
"[",
"1",
":",
"]",
"\n\n",
"var",
"baseName",
"string",
"\n",
"switch",
"node",
":=",
"node",
".",
"(",
"type",
")",
"{",
"case",
"*",
"ast",
".",
"MsgPlaceholderNode",
":",
"baseName",
"=",
"genBasePlaceholderName",
"(",
"node",
".",
"Body",
",",
"\"",
"\"",
")",
"\n",
"case",
"*",
"ast",
".",
"MsgPluralNode",
":",
"nodeQueue",
"=",
"append",
"(",
"nodeQueue",
",",
"pluralCaseBodies",
"(",
"node",
")",
"...",
")",
"\n",
"baseName",
"=",
"genBasePlaceholderName",
"(",
"node",
".",
"Value",
",",
"\"",
"\"",
")",
"\n",
"default",
":",
"panic",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"if",
"nodes",
",",
"ok",
":=",
"baseNameToRepNodes",
"[",
"baseName",
"]",
";",
"!",
"ok",
"{",
"baseNameToRepNodes",
"[",
"baseName",
"]",
"=",
"[",
"]",
"ast",
".",
"Node",
"{",
"node",
"}",
"\n",
"}",
"else",
"{",
"var",
"isNew",
"=",
"true",
"\n",
"var",
"str",
"=",
"node",
".",
"String",
"(",
")",
"\n",
"for",
"_",
",",
"other",
":=",
"range",
"nodes",
"{",
"if",
"other",
".",
"String",
"(",
")",
"==",
"str",
"{",
"equivNodeToRepNodes",
"[",
"node",
"]",
"=",
"other",
"\n",
"isNew",
"=",
"false",
"\n",
"break",
"\n",
"}",
"\n",
"}",
"\n",
"if",
"isNew",
"{",
"baseNameToRepNodes",
"[",
"baseName",
"]",
"=",
"append",
"(",
"nodes",
",",
"node",
")",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n\n",
"// Step 2: Build final maps of name to representative node",
"var",
"nameToRepNodes",
"=",
"make",
"(",
"map",
"[",
"string",
"]",
"ast",
".",
"Node",
")",
"\n",
"for",
"baseName",
",",
"nodes",
":=",
"range",
"baseNameToRepNodes",
"{",
"if",
"len",
"(",
"nodes",
")",
"==",
"1",
"{",
"nameToRepNodes",
"[",
"baseName",
"]",
"=",
"nodes",
"[",
"0",
"]",
"\n",
"continue",
"\n",
"}",
"\n\n",
"var",
"nextSuffix",
"=",
"1",
"\n",
"for",
"_",
",",
"node",
":=",
"range",
"nodes",
"{",
"for",
"{",
"var",
"newName",
"=",
"baseName",
"+",
"\"",
"\"",
"+",
"strconv",
".",
"Itoa",
"(",
"nextSuffix",
")",
"\n",
"if",
"_",
",",
"ok",
":=",
"nameToRepNodes",
"[",
"newName",
"]",
";",
"!",
"ok",
"{",
"nameToRepNodes",
"[",
"newName",
"]",
"=",
"node",
"\n",
"break",
"\n",
"}",
"\n",
"nextSuffix",
"++",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n\n",
"// Step 3: Create maps of every node to its name",
"var",
"nodeToName",
"=",
"make",
"(",
"map",
"[",
"ast",
".",
"Node",
"]",
"string",
")",
"\n",
"for",
"name",
",",
"node",
":=",
"range",
"nameToRepNodes",
"{",
"nodeToName",
"[",
"node",
"]",
"=",
"name",
"\n",
"}",
"\n",
"for",
"other",
",",
"repNode",
":=",
"range",
"equivNodeToRepNodes",
"{",
"nodeToName",
"[",
"other",
"]",
"=",
"nodeToName",
"[",
"repNode",
"]",
"\n",
"}",
"\n\n",
"// Step 4: Set the calculated names on all the nodes.",
"for",
"node",
",",
"name",
":=",
"range",
"nodeToName",
"{",
"switch",
"node",
":=",
"node",
".",
"(",
"type",
")",
"{",
"case",
"*",
"ast",
".",
"MsgPlaceholderNode",
":",
"node",
".",
"Name",
"=",
"name",
"\n",
"case",
"*",
"ast",
".",
"MsgPluralNode",
":",
"node",
".",
"VarName",
"=",
"name",
"\n",
"default",
":",
"panic",
"(",
"\"",
"\"",
"+",
"node",
".",
"String",
"(",
")",
")",
"\n",
"}",
"\n",
"}",
"\n",
"}"
] | // setPlaceholderNames generates the placeholder names for all children of the
// given message node, setting the .Name property on them. | [
"setPlaceholderNames",
"generates",
"the",
"placeholder",
"names",
"for",
"all",
"children",
"of",
"the",
"given",
"message",
"node",
"setting",
"the",
".",
"Name",
"property",
"on",
"them",
"."
] | 6b9d0368d4265c382c3e11fe774d93aa8d431064 | https://github.com/robfig/soy/blob/6b9d0368d4265c382c3e11fe774d93aa8d431064/soymsg/placeholder.go#L14-L96 |
4,034 | robfig/soy | parsepasses/globals.go | SetGlobals | func SetGlobals(reg template.Registry, globals data.Map) error {
for _, t := range reg.Templates {
if err := SetNodeGlobals(t.Node, globals); err != nil {
return fmt.Errorf("template %v: %v", t.Node.Name, err)
}
}
return nil
} | go | func SetGlobals(reg template.Registry, globals data.Map) error {
for _, t := range reg.Templates {
if err := SetNodeGlobals(t.Node, globals); err != nil {
return fmt.Errorf("template %v: %v", t.Node.Name, err)
}
}
return nil
} | [
"func",
"SetGlobals",
"(",
"reg",
"template",
".",
"Registry",
",",
"globals",
"data",
".",
"Map",
")",
"error",
"{",
"for",
"_",
",",
"t",
":=",
"range",
"reg",
".",
"Templates",
"{",
"if",
"err",
":=",
"SetNodeGlobals",
"(",
"t",
".",
"Node",
",",
"globals",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"t",
".",
"Node",
".",
"Name",
",",
"err",
")",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] | // SetGlobals sets the value of all global nodes in the given registry.
// An error is returned if any globals were left undefined. | [
"SetGlobals",
"sets",
"the",
"value",
"of",
"all",
"global",
"nodes",
"in",
"the",
"given",
"registry",
".",
"An",
"error",
"is",
"returned",
"if",
"any",
"globals",
"were",
"left",
"undefined",
"."
] | 6b9d0368d4265c382c3e11fe774d93aa8d431064 | https://github.com/robfig/soy/blob/6b9d0368d4265c382c3e11fe774d93aa8d431064/parsepasses/globals.go#L13-L20 |
4,035 | robfig/soy | parsepasses/globals.go | SetNodeGlobals | func SetNodeGlobals(node ast.Node, globals data.Map) error {
switch node := node.(type) {
case *ast.GlobalNode:
if val, ok := globals[node.Name]; ok {
node.Value = val
} else {
return fmt.Errorf("global %q is undefined", node.Name)
}
default:
if parent, ok := node.(ast.ParentNode); ok {
for _, child := range parent.Children() {
if err := SetNodeGlobals(child, globals); err != nil {
return err
}
}
}
}
return nil
} | go | func SetNodeGlobals(node ast.Node, globals data.Map) error {
switch node := node.(type) {
case *ast.GlobalNode:
if val, ok := globals[node.Name]; ok {
node.Value = val
} else {
return fmt.Errorf("global %q is undefined", node.Name)
}
default:
if parent, ok := node.(ast.ParentNode); ok {
for _, child := range parent.Children() {
if err := SetNodeGlobals(child, globals); err != nil {
return err
}
}
}
}
return nil
} | [
"func",
"SetNodeGlobals",
"(",
"node",
"ast",
".",
"Node",
",",
"globals",
"data",
".",
"Map",
")",
"error",
"{",
"switch",
"node",
":=",
"node",
".",
"(",
"type",
")",
"{",
"case",
"*",
"ast",
".",
"GlobalNode",
":",
"if",
"val",
",",
"ok",
":=",
"globals",
"[",
"node",
".",
"Name",
"]",
";",
"ok",
"{",
"node",
".",
"Value",
"=",
"val",
"\n",
"}",
"else",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"node",
".",
"Name",
")",
"\n",
"}",
"\n",
"default",
":",
"if",
"parent",
",",
"ok",
":=",
"node",
".",
"(",
"ast",
".",
"ParentNode",
")",
";",
"ok",
"{",
"for",
"_",
",",
"child",
":=",
"range",
"parent",
".",
"Children",
"(",
")",
"{",
"if",
"err",
":=",
"SetNodeGlobals",
"(",
"child",
",",
"globals",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] | // SetNodeGlobals sets global values on the given node and all children nodes,
// using the given data map. An error is returned if any global nodes were left
// undefined. | [
"SetNodeGlobals",
"sets",
"global",
"values",
"on",
"the",
"given",
"node",
"and",
"all",
"children",
"nodes",
"using",
"the",
"given",
"data",
"map",
".",
"An",
"error",
"is",
"returned",
"if",
"any",
"global",
"nodes",
"were",
"left",
"undefined",
"."
] | 6b9d0368d4265c382c3e11fe774d93aa8d431064 | https://github.com/robfig/soy/blob/6b9d0368d4265c382c3e11fe774d93aa8d431064/parsepasses/globals.go#L25-L43 |
4,036 | robfig/soy | soyhtml/tofu.go | NewRenderer | func (tofu *Tofu) NewRenderer(name string) *Renderer {
return &Renderer{
tofu: tofu,
name: name,
}
} | go | func (tofu *Tofu) NewRenderer(name string) *Renderer {
return &Renderer{
tofu: tofu,
name: name,
}
} | [
"func",
"(",
"tofu",
"*",
"Tofu",
")",
"NewRenderer",
"(",
"name",
"string",
")",
"*",
"Renderer",
"{",
"return",
"&",
"Renderer",
"{",
"tofu",
":",
"tofu",
",",
"name",
":",
"name",
",",
"}",
"\n",
"}"
] | // NewRenderer returns a new instance of a soy html renderer, given the
// fully-qualified name of the template to render. | [
"NewRenderer",
"returns",
"a",
"new",
"instance",
"of",
"a",
"soy",
"html",
"renderer",
"given",
"the",
"fully",
"-",
"qualified",
"name",
"of",
"the",
"template",
"to",
"render",
"."
] | 6b9d0368d4265c382c3e11fe774d93aa8d431064 | https://github.com/robfig/soy/blob/6b9d0368d4265c382c3e11fe774d93aa8d431064/soyhtml/tofu.go#L45-L50 |
4,037 | FiloSottile/gvt | fetch.go | stripscheme | func stripscheme(path string) string {
u, err := url.Parse(path)
if err != nil {
panic(err)
}
return u.Host + u.Path
} | go | func stripscheme(path string) string {
u, err := url.Parse(path)
if err != nil {
panic(err)
}
return u.Host + u.Path
} | [
"func",
"stripscheme",
"(",
"path",
"string",
")",
"string",
"{",
"u",
",",
"err",
":=",
"url",
".",
"Parse",
"(",
"path",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"panic",
"(",
"err",
")",
"\n",
"}",
"\n",
"return",
"u",
".",
"Host",
"+",
"u",
".",
"Path",
"\n",
"}"
] | // stripscheme removes any scheme components from url like paths. | [
"stripscheme",
"removes",
"any",
"scheme",
"components",
"from",
"url",
"like",
"paths",
"."
] | 4899cb1641fb0c428601cad55c1f0ca1e92d7451 | https://github.com/FiloSottile/gvt/blob/4899cb1641fb0c428601cad55c1f0ca1e92d7451/fetch.go#L262-L268 |
4,038 | FiloSottile/gvt | fetch.go | contains | func contains(a, b string) bool {
return a == b || strings.HasPrefix(b, a+"/")
} | go | func contains(a, b string) bool {
return a == b || strings.HasPrefix(b, a+"/")
} | [
"func",
"contains",
"(",
"a",
",",
"b",
"string",
")",
"bool",
"{",
"return",
"a",
"==",
"b",
"||",
"strings",
".",
"HasPrefix",
"(",
"b",
",",
"a",
"+",
"\"",
"\"",
")",
"\n",
"}"
] | // Package a contains package b? | [
"Package",
"a",
"contains",
"package",
"b?"
] | 4899cb1641fb0c428601cad55c1f0ca1e92d7451 | https://github.com/FiloSottile/gvt/blob/4899cb1641fb0c428601cad55c1f0ca1e92d7451/fetch.go#L271-L273 |
4,039 | FiloSottile/gvt | fileutils/fileutils.go | Copypath | func Copypath(dst string, src string, tests, all bool) error {
err := filepath.Walk(src, func(path string, info os.FileInfo, err error) error {
if err != nil {
return err
}
skip := ShouldSkip(path, info, tests, all)
if skip {
if info.IsDir() {
return filepath.SkipDir
}
return nil
}
if info.IsDir() {
return nil
}
dst := filepath.Join(dst, path[len(src):])
if info.Mode()&os.ModeSymlink != 0 {
return Copylink(dst, path)
}
return Copyfile(dst, path)
})
if err != nil {
// if there was an error during copying, remove the partial copy.
RemoveAll(dst)
}
return err
} | go | func Copypath(dst string, src string, tests, all bool) error {
err := filepath.Walk(src, func(path string, info os.FileInfo, err error) error {
if err != nil {
return err
}
skip := ShouldSkip(path, info, tests, all)
if skip {
if info.IsDir() {
return filepath.SkipDir
}
return nil
}
if info.IsDir() {
return nil
}
dst := filepath.Join(dst, path[len(src):])
if info.Mode()&os.ModeSymlink != 0 {
return Copylink(dst, path)
}
return Copyfile(dst, path)
})
if err != nil {
// if there was an error during copying, remove the partial copy.
RemoveAll(dst)
}
return err
} | [
"func",
"Copypath",
"(",
"dst",
"string",
",",
"src",
"string",
",",
"tests",
",",
"all",
"bool",
")",
"error",
"{",
"err",
":=",
"filepath",
".",
"Walk",
"(",
"src",
",",
"func",
"(",
"path",
"string",
",",
"info",
"os",
".",
"FileInfo",
",",
"err",
"error",
")",
"error",
"{",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"skip",
":=",
"ShouldSkip",
"(",
"path",
",",
"info",
",",
"tests",
",",
"all",
")",
"\n\n",
"if",
"skip",
"{",
"if",
"info",
".",
"IsDir",
"(",
")",
"{",
"return",
"filepath",
".",
"SkipDir",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}",
"\n\n",
"if",
"info",
".",
"IsDir",
"(",
")",
"{",
"return",
"nil",
"\n",
"}",
"\n\n",
"dst",
":=",
"filepath",
".",
"Join",
"(",
"dst",
",",
"path",
"[",
"len",
"(",
"src",
")",
":",
"]",
")",
"\n\n",
"if",
"info",
".",
"Mode",
"(",
")",
"&",
"os",
".",
"ModeSymlink",
"!=",
"0",
"{",
"return",
"Copylink",
"(",
"dst",
",",
"path",
")",
"\n",
"}",
"\n\n",
"return",
"Copyfile",
"(",
"dst",
",",
"path",
")",
"\n",
"}",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"// if there was an error during copying, remove the partial copy.",
"RemoveAll",
"(",
"dst",
")",
"\n",
"}",
"\n",
"return",
"err",
"\n",
"}"
] | // Copypath copies the contents of src to dst, excluding any file that is not
// relevant to the Go compiler. | [
"Copypath",
"copies",
"the",
"contents",
"of",
"src",
"to",
"dst",
"excluding",
"any",
"file",
"that",
"is",
"not",
"relevant",
"to",
"the",
"Go",
"compiler",
"."
] | 4899cb1641fb0c428601cad55c1f0ca1e92d7451 | https://github.com/FiloSottile/gvt/blob/4899cb1641fb0c428601cad55c1f0ca1e92d7451/fileutils/fileutils.go#L78-L110 |
4,040 | FiloSottile/gvt | fileutils/fileutils.go | CopyLicense | func CopyLicense(dst, src string) error {
files, err := ioutil.ReadDir(src)
if err != nil {
return err
}
for _, f := range files {
if f.IsDir() {
continue
}
for _, candidate := range licenseFiles {
if strings.ToLower(candidate) == strings.TrimSuffix(
strings.TrimSuffix(strings.ToLower(f.Name()), ".md"), ".txt") {
if err := Copyfile(filepath.Join(dst, f.Name()),
filepath.Join(src, f.Name())); err != nil {
return err
}
}
}
}
return nil
} | go | func CopyLicense(dst, src string) error {
files, err := ioutil.ReadDir(src)
if err != nil {
return err
}
for _, f := range files {
if f.IsDir() {
continue
}
for _, candidate := range licenseFiles {
if strings.ToLower(candidate) == strings.TrimSuffix(
strings.TrimSuffix(strings.ToLower(f.Name()), ".md"), ".txt") {
if err := Copyfile(filepath.Join(dst, f.Name()),
filepath.Join(src, f.Name())); err != nil {
return err
}
}
}
}
return nil
} | [
"func",
"CopyLicense",
"(",
"dst",
",",
"src",
"string",
")",
"error",
"{",
"files",
",",
"err",
":=",
"ioutil",
".",
"ReadDir",
"(",
"src",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"for",
"_",
",",
"f",
":=",
"range",
"files",
"{",
"if",
"f",
".",
"IsDir",
"(",
")",
"{",
"continue",
"\n",
"}",
"\n",
"for",
"_",
",",
"candidate",
":=",
"range",
"licenseFiles",
"{",
"if",
"strings",
".",
"ToLower",
"(",
"candidate",
")",
"==",
"strings",
".",
"TrimSuffix",
"(",
"strings",
".",
"TrimSuffix",
"(",
"strings",
".",
"ToLower",
"(",
"f",
".",
"Name",
"(",
")",
")",
",",
"\"",
"\"",
")",
",",
"\"",
"\"",
")",
"{",
"if",
"err",
":=",
"Copyfile",
"(",
"filepath",
".",
"Join",
"(",
"dst",
",",
"f",
".",
"Name",
"(",
")",
")",
",",
"filepath",
".",
"Join",
"(",
"src",
",",
"f",
".",
"Name",
"(",
")",
")",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] | // CopyLicense copies the license file from folder src to folder dst. | [
"CopyLicense",
"copies",
"the",
"license",
"file",
"from",
"folder",
"src",
"to",
"folder",
"dst",
"."
] | 4899cb1641fb0c428601cad55c1f0ca1e92d7451 | https://github.com/FiloSottile/gvt/blob/4899cb1641fb0c428601cad55c1f0ca1e92d7451/fileutils/fileutils.go#L171-L191 |
4,041 | FiloSottile/gvt | downloader.go | Get | func (d *Downloader) Get(repo vendor.RemoteRepo, branch, tag, revision string) (vendor.WorkingCopy, error) {
key := cacheKey{
url: repo.URL(), repoType: repo.Type(),
branch: branch, tag: tag, revision: revision,
}
d.wcsMu.Lock()
if entry, ok := d.wcs[key]; ok {
d.wcsMu.Unlock()
entry.wg.Wait()
return entry.v, entry.err
}
entry := &cacheEntry{}
entry.wg.Add(1)
d.wcs[key] = entry
d.wcsMu.Unlock()
entry.v, entry.err = repo.Checkout(branch, tag, revision)
entry.wg.Done()
return entry.v, entry.err
} | go | func (d *Downloader) Get(repo vendor.RemoteRepo, branch, tag, revision string) (vendor.WorkingCopy, error) {
key := cacheKey{
url: repo.URL(), repoType: repo.Type(),
branch: branch, tag: tag, revision: revision,
}
d.wcsMu.Lock()
if entry, ok := d.wcs[key]; ok {
d.wcsMu.Unlock()
entry.wg.Wait()
return entry.v, entry.err
}
entry := &cacheEntry{}
entry.wg.Add(1)
d.wcs[key] = entry
d.wcsMu.Unlock()
entry.v, entry.err = repo.Checkout(branch, tag, revision)
entry.wg.Done()
return entry.v, entry.err
} | [
"func",
"(",
"d",
"*",
"Downloader",
")",
"Get",
"(",
"repo",
"vendor",
".",
"RemoteRepo",
",",
"branch",
",",
"tag",
",",
"revision",
"string",
")",
"(",
"vendor",
".",
"WorkingCopy",
",",
"error",
")",
"{",
"key",
":=",
"cacheKey",
"{",
"url",
":",
"repo",
".",
"URL",
"(",
")",
",",
"repoType",
":",
"repo",
".",
"Type",
"(",
")",
",",
"branch",
":",
"branch",
",",
"tag",
":",
"tag",
",",
"revision",
":",
"revision",
",",
"}",
"\n",
"d",
".",
"wcsMu",
".",
"Lock",
"(",
")",
"\n",
"if",
"entry",
",",
"ok",
":=",
"d",
".",
"wcs",
"[",
"key",
"]",
";",
"ok",
"{",
"d",
".",
"wcsMu",
".",
"Unlock",
"(",
")",
"\n",
"entry",
".",
"wg",
".",
"Wait",
"(",
")",
"\n",
"return",
"entry",
".",
"v",
",",
"entry",
".",
"err",
"\n",
"}",
"\n\n",
"entry",
":=",
"&",
"cacheEntry",
"{",
"}",
"\n",
"entry",
".",
"wg",
".",
"Add",
"(",
"1",
")",
"\n",
"d",
".",
"wcs",
"[",
"key",
"]",
"=",
"entry",
"\n",
"d",
".",
"wcsMu",
".",
"Unlock",
"(",
")",
"\n\n",
"entry",
".",
"v",
",",
"entry",
".",
"err",
"=",
"repo",
".",
"Checkout",
"(",
"branch",
",",
"tag",
",",
"revision",
")",
"\n",
"entry",
".",
"wg",
".",
"Done",
"(",
")",
"\n",
"return",
"entry",
".",
"v",
",",
"entry",
".",
"err",
"\n",
"}"
] | // Get returns a cached WorkingCopy, or runs RemoteRepo.Checkout | [
"Get",
"returns",
"a",
"cached",
"WorkingCopy",
"or",
"runs",
"RemoteRepo",
".",
"Checkout"
] | 4899cb1641fb0c428601cad55c1f0ca1e92d7451 | https://github.com/FiloSottile/gvt/blob/4899cb1641fb0c428601cad55c1f0ca1e92d7451/downloader.go#L40-L60 |
4,042 | FiloSottile/gvt | downloader.go | DeduceRemoteRepo | func (d *Downloader) DeduceRemoteRepo(path string, insecure bool) (vendor.RemoteRepo, string, error) {
cache := d.repos
if insecure {
cache = d.reposI
}
d.reposMu.RLock()
for p, repo := range cache {
if path == p || strings.HasPrefix(path, p+"/") {
d.reposMu.RUnlock()
extra := strings.Trim(strings.TrimPrefix(path, p), "/")
return repo, extra, nil
}
}
d.reposMu.RUnlock()
repo, extra, err := vendor.DeduceRemoteRepo(path, insecure)
if err != nil {
return repo, extra, err
}
if !strings.HasSuffix(path, extra) {
// Shouldn't happen, but in case just bypass the cache
return repo, extra, err
}
basePath := strings.Trim(strings.TrimSuffix(path, extra), "/")
d.reposMu.Lock()
cache[basePath] = repo
d.reposMu.Unlock()
return repo, extra, err
} | go | func (d *Downloader) DeduceRemoteRepo(path string, insecure bool) (vendor.RemoteRepo, string, error) {
cache := d.repos
if insecure {
cache = d.reposI
}
d.reposMu.RLock()
for p, repo := range cache {
if path == p || strings.HasPrefix(path, p+"/") {
d.reposMu.RUnlock()
extra := strings.Trim(strings.TrimPrefix(path, p), "/")
return repo, extra, nil
}
}
d.reposMu.RUnlock()
repo, extra, err := vendor.DeduceRemoteRepo(path, insecure)
if err != nil {
return repo, extra, err
}
if !strings.HasSuffix(path, extra) {
// Shouldn't happen, but in case just bypass the cache
return repo, extra, err
}
basePath := strings.Trim(strings.TrimSuffix(path, extra), "/")
d.reposMu.Lock()
cache[basePath] = repo
d.reposMu.Unlock()
return repo, extra, err
} | [
"func",
"(",
"d",
"*",
"Downloader",
")",
"DeduceRemoteRepo",
"(",
"path",
"string",
",",
"insecure",
"bool",
")",
"(",
"vendor",
".",
"RemoteRepo",
",",
"string",
",",
"error",
")",
"{",
"cache",
":=",
"d",
".",
"repos",
"\n",
"if",
"insecure",
"{",
"cache",
"=",
"d",
".",
"reposI",
"\n",
"}",
"\n\n",
"d",
".",
"reposMu",
".",
"RLock",
"(",
")",
"\n",
"for",
"p",
",",
"repo",
":=",
"range",
"cache",
"{",
"if",
"path",
"==",
"p",
"||",
"strings",
".",
"HasPrefix",
"(",
"path",
",",
"p",
"+",
"\"",
"\"",
")",
"{",
"d",
".",
"reposMu",
".",
"RUnlock",
"(",
")",
"\n",
"extra",
":=",
"strings",
".",
"Trim",
"(",
"strings",
".",
"TrimPrefix",
"(",
"path",
",",
"p",
")",
",",
"\"",
"\"",
")",
"\n",
"return",
"repo",
",",
"extra",
",",
"nil",
"\n",
"}",
"\n",
"}",
"\n",
"d",
".",
"reposMu",
".",
"RUnlock",
"(",
")",
"\n\n",
"repo",
",",
"extra",
",",
"err",
":=",
"vendor",
".",
"DeduceRemoteRepo",
"(",
"path",
",",
"insecure",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"repo",
",",
"extra",
",",
"err",
"\n",
"}",
"\n\n",
"if",
"!",
"strings",
".",
"HasSuffix",
"(",
"path",
",",
"extra",
")",
"{",
"// Shouldn't happen, but in case just bypass the cache",
"return",
"repo",
",",
"extra",
",",
"err",
"\n",
"}",
"\n",
"basePath",
":=",
"strings",
".",
"Trim",
"(",
"strings",
".",
"TrimSuffix",
"(",
"path",
",",
"extra",
")",
",",
"\"",
"\"",
")",
"\n",
"d",
".",
"reposMu",
".",
"Lock",
"(",
")",
"\n",
"cache",
"[",
"basePath",
"]",
"=",
"repo",
"\n",
"d",
".",
"reposMu",
".",
"Unlock",
"(",
")",
"\n\n",
"return",
"repo",
",",
"extra",
",",
"err",
"\n",
"}"
] | // DeduceRemoteRepo is a cached version of vendor.DeduceRemoteRepo | [
"DeduceRemoteRepo",
"is",
"a",
"cached",
"version",
"of",
"vendor",
".",
"DeduceRemoteRepo"
] | 4899cb1641fb0c428601cad55c1f0ca1e92d7451 | https://github.com/FiloSottile/gvt/blob/4899cb1641fb0c428601cad55c1f0ca1e92d7451/downloader.go#L79-L110 |
4,043 | apex/apex-go | proxy/decoder.go | UnmarshalJSON | func (a *authorizer) UnmarshalJSON(data []byte) error {
var cognito struct {
Claims *map[string]string
}
var custom map[string]string
err := json.Unmarshal(data, &cognito)
if err != nil {
return err
}
if cognito.Claims != nil {
*a = authorizer(*cognito.Claims)
return nil
}
err = json.Unmarshal(data, &custom)
if err != nil {
return err
}
*a = authorizer(custom)
return nil
} | go | func (a *authorizer) UnmarshalJSON(data []byte) error {
var cognito struct {
Claims *map[string]string
}
var custom map[string]string
err := json.Unmarshal(data, &cognito)
if err != nil {
return err
}
if cognito.Claims != nil {
*a = authorizer(*cognito.Claims)
return nil
}
err = json.Unmarshal(data, &custom)
if err != nil {
return err
}
*a = authorizer(custom)
return nil
} | [
"func",
"(",
"a",
"*",
"authorizer",
")",
"UnmarshalJSON",
"(",
"data",
"[",
"]",
"byte",
")",
"error",
"{",
"var",
"cognito",
"struct",
"{",
"Claims",
"*",
"map",
"[",
"string",
"]",
"string",
"\n",
"}",
"\n",
"var",
"custom",
"map",
"[",
"string",
"]",
"string",
"\n\n",
"err",
":=",
"json",
".",
"Unmarshal",
"(",
"data",
",",
"&",
"cognito",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"if",
"cognito",
".",
"Claims",
"!=",
"nil",
"{",
"*",
"a",
"=",
"authorizer",
"(",
"*",
"cognito",
".",
"Claims",
")",
"\n",
"return",
"nil",
"\n",
"}",
"\n\n",
"err",
"=",
"json",
".",
"Unmarshal",
"(",
"data",
",",
"&",
"custom",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"*",
"a",
"=",
"authorizer",
"(",
"custom",
")",
"\n",
"return",
"nil",
"\n",
"}"
] | // UnmarshalJSON interprets the data as a dynamic map which may carry either a
// Amazon Cognito set of claims or a custom set of attributes. It then choose
// the good one at runtime and fill the authorizer with it. | [
"UnmarshalJSON",
"interprets",
"the",
"data",
"as",
"a",
"dynamic",
"map",
"which",
"may",
"carry",
"either",
"a",
"Amazon",
"Cognito",
"set",
"of",
"claims",
"or",
"a",
"custom",
"set",
"of",
"attributes",
".",
"It",
"then",
"choose",
"the",
"good",
"one",
"at",
"runtime",
"and",
"fill",
"the",
"authorizer",
"with",
"it",
"."
] | 7694047593bfde5f329ede4f42cbcfaf3fdc9fee | https://github.com/apex/apex-go/blob/7694047593bfde5f329ede4f42cbcfaf3fdc9fee/proxy/decoder.go#L31-L54 |
4,044 | apex/apex-go | proxy/decoder.go | MarshalJSON | func (rc *RequestContext) MarshalJSON() ([]byte, error) {
return json.Marshal(&jsonRequestContext{
(*requestContextAlias)(rc),
rc.Authorizer,
})
} | go | func (rc *RequestContext) MarshalJSON() ([]byte, error) {
return json.Marshal(&jsonRequestContext{
(*requestContextAlias)(rc),
rc.Authorizer,
})
} | [
"func",
"(",
"rc",
"*",
"RequestContext",
")",
"MarshalJSON",
"(",
")",
"(",
"[",
"]",
"byte",
",",
"error",
")",
"{",
"return",
"json",
".",
"Marshal",
"(",
"&",
"jsonRequestContext",
"{",
"(",
"*",
"requestContextAlias",
")",
"(",
"rc",
")",
",",
"rc",
".",
"Authorizer",
",",
"}",
")",
"\n",
"}"
] | // MarshalJSON reverts the effect of type aliasing and struct embedding used
// during the marshalling step to make the pattern seamless. | [
"MarshalJSON",
"reverts",
"the",
"effect",
"of",
"type",
"aliasing",
"and",
"struct",
"embedding",
"used",
"during",
"the",
"marshalling",
"step",
"to",
"make",
"the",
"pattern",
"seamless",
"."
] | 7694047593bfde5f329ede4f42cbcfaf3fdc9fee | https://github.com/apex/apex-go/blob/7694047593bfde5f329ede4f42cbcfaf3fdc9fee/proxy/decoder.go#L78-L83 |
4,045 | apex/apex-go | proxy/proxy.go | Serve | func Serve(h http.Handler) apex.Handler {
if h == nil {
h = http.DefaultServeMux
}
return &handler{h}
} | go | func Serve(h http.Handler) apex.Handler {
if h == nil {
h = http.DefaultServeMux
}
return &handler{h}
} | [
"func",
"Serve",
"(",
"h",
"http",
".",
"Handler",
")",
"apex",
".",
"Handler",
"{",
"if",
"h",
"==",
"nil",
"{",
"h",
"=",
"http",
".",
"DefaultServeMux",
"\n",
"}",
"\n\n",
"return",
"&",
"handler",
"{",
"h",
"}",
"\n",
"}"
] | // Serve adaptes an http.Handler to the apex.Handler interface. | [
"Serve",
"adaptes",
"an",
"http",
".",
"Handler",
"to",
"the",
"apex",
".",
"Handler",
"interface",
"."
] | 7694047593bfde5f329ede4f42cbcfaf3fdc9fee | https://github.com/apex/apex-go/blob/7694047593bfde5f329ede4f42cbcfaf3fdc9fee/proxy/proxy.go#L12-L18 |
4,046 | apex/apex-go | proxy/proxy.go | Handle | func (p *handler) Handle(event json.RawMessage, ctx *apex.Context) (interface{}, error) {
proxyEvent := &Event{}
err := json.Unmarshal(event, proxyEvent)
if err != nil {
return nil, fmt.Errorf("Parse proxy event: %s", err)
}
req, err := buildRequest(proxyEvent, ctx)
if err != nil {
return nil, fmt.Errorf("Build request: %s", err)
}
res := &ResponseWriter{}
p.Handler.ServeHTTP(res, req)
res.finish()
return &res.response, nil
} | go | func (p *handler) Handle(event json.RawMessage, ctx *apex.Context) (interface{}, error) {
proxyEvent := &Event{}
err := json.Unmarshal(event, proxyEvent)
if err != nil {
return nil, fmt.Errorf("Parse proxy event: %s", err)
}
req, err := buildRequest(proxyEvent, ctx)
if err != nil {
return nil, fmt.Errorf("Build request: %s", err)
}
res := &ResponseWriter{}
p.Handler.ServeHTTP(res, req)
res.finish()
return &res.response, nil
} | [
"func",
"(",
"p",
"*",
"handler",
")",
"Handle",
"(",
"event",
"json",
".",
"RawMessage",
",",
"ctx",
"*",
"apex",
".",
"Context",
")",
"(",
"interface",
"{",
"}",
",",
"error",
")",
"{",
"proxyEvent",
":=",
"&",
"Event",
"{",
"}",
"\n\n",
"err",
":=",
"json",
".",
"Unmarshal",
"(",
"event",
",",
"proxyEvent",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n\n",
"req",
",",
"err",
":=",
"buildRequest",
"(",
"proxyEvent",
",",
"ctx",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n\n",
"res",
":=",
"&",
"ResponseWriter",
"{",
"}",
"\n",
"p",
".",
"Handler",
".",
"ServeHTTP",
"(",
"res",
",",
"req",
")",
"\n",
"res",
".",
"finish",
"(",
")",
"\n\n",
"return",
"&",
"res",
".",
"response",
",",
"nil",
"\n",
"}"
] | // Handle accepts a request from the apex shim and dispatches it to an http.Handler | [
"Handle",
"accepts",
"a",
"request",
"from",
"the",
"apex",
"shim",
"and",
"dispatches",
"it",
"to",
"an",
"http",
".",
"Handler"
] | 7694047593bfde5f329ede4f42cbcfaf3fdc9fee | https://github.com/apex/apex-go/blob/7694047593bfde5f329ede4f42cbcfaf3fdc9fee/proxy/proxy.go#L27-L45 |
4,047 | apex/apex-go | proxy/request.go | buildRequest | func buildRequest(proxyEvent *Event, ctx *apex.Context) (*http.Request, error) {
// Reconstruct the request URL
u, err := url.Parse(proxyEvent.Path)
if err != nil {
return nil, fmt.Errorf("Parse request path: %s", err)
}
q := u.Query()
for k, v := range proxyEvent.QueryStringParameters {
q.Set(k, v)
}
u.RawQuery = q.Encode()
// Decode the request body
dec := proxyEvent.Body
if proxyEvent.IsBase64Encoded {
data, err2 := base64.StdEncoding.DecodeString(dec)
if err2 != nil {
return nil, fmt.Errorf("Decode base64 request body: %s", err2)
}
dec = string(data)
}
// Create a new request object
req, err := http.NewRequest(proxyEvent.HTTPMethod, u.String(), strings.NewReader(dec))
if err != nil {
return nil, fmt.Errorf("Create request: %s", err)
}
// Copy event headers to request
for k, v := range proxyEvent.Headers {
req.Header.Set(k, v)
}
// Store the original event and context in the request headers
proxyEvent.Body = "... truncated"
hbody, err := json.Marshal(proxyEvent)
if err != nil {
return nil, fmt.Errorf("Marshal proxy event: %s", err)
}
req.Header.Set("X-ApiGatewayProxy-Event", string(hbody))
if ctx != nil {
req.Header.Set("X-ApiGatewayProxy-Context", string(ctx.ClientContext))
}
// Map additional request information
req.Host = proxyEvent.Headers["Host"]
return req, nil
} | go | func buildRequest(proxyEvent *Event, ctx *apex.Context) (*http.Request, error) {
// Reconstruct the request URL
u, err := url.Parse(proxyEvent.Path)
if err != nil {
return nil, fmt.Errorf("Parse request path: %s", err)
}
q := u.Query()
for k, v := range proxyEvent.QueryStringParameters {
q.Set(k, v)
}
u.RawQuery = q.Encode()
// Decode the request body
dec := proxyEvent.Body
if proxyEvent.IsBase64Encoded {
data, err2 := base64.StdEncoding.DecodeString(dec)
if err2 != nil {
return nil, fmt.Errorf("Decode base64 request body: %s", err2)
}
dec = string(data)
}
// Create a new request object
req, err := http.NewRequest(proxyEvent.HTTPMethod, u.String(), strings.NewReader(dec))
if err != nil {
return nil, fmt.Errorf("Create request: %s", err)
}
// Copy event headers to request
for k, v := range proxyEvent.Headers {
req.Header.Set(k, v)
}
// Store the original event and context in the request headers
proxyEvent.Body = "... truncated"
hbody, err := json.Marshal(proxyEvent)
if err != nil {
return nil, fmt.Errorf("Marshal proxy event: %s", err)
}
req.Header.Set("X-ApiGatewayProxy-Event", string(hbody))
if ctx != nil {
req.Header.Set("X-ApiGatewayProxy-Context", string(ctx.ClientContext))
}
// Map additional request information
req.Host = proxyEvent.Headers["Host"]
return req, nil
} | [
"func",
"buildRequest",
"(",
"proxyEvent",
"*",
"Event",
",",
"ctx",
"*",
"apex",
".",
"Context",
")",
"(",
"*",
"http",
".",
"Request",
",",
"error",
")",
"{",
"// Reconstruct the request URL",
"u",
",",
"err",
":=",
"url",
".",
"Parse",
"(",
"proxyEvent",
".",
"Path",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n",
"q",
":=",
"u",
".",
"Query",
"(",
")",
"\n",
"for",
"k",
",",
"v",
":=",
"range",
"proxyEvent",
".",
"QueryStringParameters",
"{",
"q",
".",
"Set",
"(",
"k",
",",
"v",
")",
"\n",
"}",
"\n",
"u",
".",
"RawQuery",
"=",
"q",
".",
"Encode",
"(",
")",
"\n\n",
"// Decode the request body",
"dec",
":=",
"proxyEvent",
".",
"Body",
"\n",
"if",
"proxyEvent",
".",
"IsBase64Encoded",
"{",
"data",
",",
"err2",
":=",
"base64",
".",
"StdEncoding",
".",
"DecodeString",
"(",
"dec",
")",
"\n",
"if",
"err2",
"!=",
"nil",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err2",
")",
"\n",
"}",
"\n",
"dec",
"=",
"string",
"(",
"data",
")",
"\n",
"}",
"\n\n",
"// Create a new request object",
"req",
",",
"err",
":=",
"http",
".",
"NewRequest",
"(",
"proxyEvent",
".",
"HTTPMethod",
",",
"u",
".",
"String",
"(",
")",
",",
"strings",
".",
"NewReader",
"(",
"dec",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n\n",
"// Copy event headers to request",
"for",
"k",
",",
"v",
":=",
"range",
"proxyEvent",
".",
"Headers",
"{",
"req",
".",
"Header",
".",
"Set",
"(",
"k",
",",
"v",
")",
"\n",
"}",
"\n\n",
"// Store the original event and context in the request headers",
"proxyEvent",
".",
"Body",
"=",
"\"",
"\"",
"\n",
"hbody",
",",
"err",
":=",
"json",
".",
"Marshal",
"(",
"proxyEvent",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n",
"req",
".",
"Header",
".",
"Set",
"(",
"\"",
"\"",
",",
"string",
"(",
"hbody",
")",
")",
"\n",
"if",
"ctx",
"!=",
"nil",
"{",
"req",
".",
"Header",
".",
"Set",
"(",
"\"",
"\"",
",",
"string",
"(",
"ctx",
".",
"ClientContext",
")",
")",
"\n",
"}",
"\n\n",
"// Map additional request information",
"req",
".",
"Host",
"=",
"proxyEvent",
".",
"Headers",
"[",
"\"",
"\"",
"]",
"\n\n",
"return",
"req",
",",
"nil",
"\n",
"}"
] | // Constructs an http.Request object from a proxyEvent | [
"Constructs",
"an",
"http",
".",
"Request",
"object",
"from",
"a",
"proxyEvent"
] | 7694047593bfde5f329ede4f42cbcfaf3fdc9fee | https://github.com/apex/apex-go/blob/7694047593bfde5f329ede4f42cbcfaf3fdc9fee/proxy/request.go#L37-L85 |
4,048 | apex/apex-go | proxy/responsewriter.go | SetTextContentTypes | func SetTextContentTypes(types []string) error {
pattern := "(" + types[0]
for _, t := range types {
pattern += "|" + t
}
pattern += `)\b.*`
r, err := regexp.Compile(pattern)
if err != nil {
return err
}
textContentTypesRegexp = r
return nil
} | go | func SetTextContentTypes(types []string) error {
pattern := "(" + types[0]
for _, t := range types {
pattern += "|" + t
}
pattern += `)\b.*`
r, err := regexp.Compile(pattern)
if err != nil {
return err
}
textContentTypesRegexp = r
return nil
} | [
"func",
"SetTextContentTypes",
"(",
"types",
"[",
"]",
"string",
")",
"error",
"{",
"pattern",
":=",
"\"",
"\"",
"+",
"types",
"[",
"0",
"]",
"\n",
"for",
"_",
",",
"t",
":=",
"range",
"types",
"{",
"pattern",
"+=",
"\"",
"\"",
"+",
"t",
"\n",
"}",
"\n",
"pattern",
"+=",
"`)\\b.*`",
"\n\n",
"r",
",",
"err",
":=",
"regexp",
".",
"Compile",
"(",
"pattern",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"textContentTypesRegexp",
"=",
"r",
"\n",
"return",
"nil",
"\n",
"}"
] | // SetTextContentTypes configures the proxy package to skip Base64 encoding of the response
// body for responses with a Content-Type header matching one of the provided types.
// Each type provided is a regular expression pattern. | [
"SetTextContentTypes",
"configures",
"the",
"proxy",
"package",
"to",
"skip",
"Base64",
"encoding",
"of",
"the",
"response",
"body",
"for",
"responses",
"with",
"a",
"Content",
"-",
"Type",
"header",
"matching",
"one",
"of",
"the",
"provided",
"types",
".",
"Each",
"type",
"provided",
"is",
"a",
"regular",
"expression",
"pattern",
"."
] | 7694047593bfde5f329ede4f42cbcfaf3fdc9fee | https://github.com/apex/apex-go/blob/7694047593bfde5f329ede4f42cbcfaf3fdc9fee/proxy/responsewriter.go#L34-L48 |
4,049 | apex/apex-go | proxy/responsewriter.go | finish | func (w *ResponseWriter) finish() {
// Determine if we should Base64 encode the output
contentType := w.response.Headers["Content-Type"]
// Only encode text content types without base64 encoding
w.response.IsBase64Encoded = !textContentTypesRegexp.MatchString(contentType)
if w.response.IsBase64Encoded {
w.response.Body = base64.StdEncoding.EncodeToString(w.output.Bytes())
} else {
w.response.Body = w.output.String()
}
} | go | func (w *ResponseWriter) finish() {
// Determine if we should Base64 encode the output
contentType := w.response.Headers["Content-Type"]
// Only encode text content types without base64 encoding
w.response.IsBase64Encoded = !textContentTypesRegexp.MatchString(contentType)
if w.response.IsBase64Encoded {
w.response.Body = base64.StdEncoding.EncodeToString(w.output.Bytes())
} else {
w.response.Body = w.output.String()
}
} | [
"func",
"(",
"w",
"*",
"ResponseWriter",
")",
"finish",
"(",
")",
"{",
"// Determine if we should Base64 encode the output",
"contentType",
":=",
"w",
".",
"response",
".",
"Headers",
"[",
"\"",
"\"",
"]",
"\n\n",
"// Only encode text content types without base64 encoding",
"w",
".",
"response",
".",
"IsBase64Encoded",
"=",
"!",
"textContentTypesRegexp",
".",
"MatchString",
"(",
"contentType",
")",
"\n\n",
"if",
"w",
".",
"response",
".",
"IsBase64Encoded",
"{",
"w",
".",
"response",
".",
"Body",
"=",
"base64",
".",
"StdEncoding",
".",
"EncodeToString",
"(",
"w",
".",
"output",
".",
"Bytes",
"(",
")",
")",
"\n",
"}",
"else",
"{",
"w",
".",
"response",
".",
"Body",
"=",
"w",
".",
"output",
".",
"String",
"(",
")",
"\n",
"}",
"\n",
"}"
] | // finish writes the accumulated output to the response.Body | [
"finish",
"writes",
"the",
"accumulated",
"output",
"to",
"the",
"response",
".",
"Body"
] | 7694047593bfde5f329ede4f42cbcfaf3fdc9fee | https://github.com/apex/apex-go/blob/7694047593bfde5f329ede4f42cbcfaf3fdc9fee/proxy/responsewriter.go#L138-L151 |
4,050 | apex/apex-go | apex.go | Handle | func (h HandlerFunc) Handle(event json.RawMessage, ctx *Context) (interface{}, error) {
return h(event, ctx)
} | go | func (h HandlerFunc) Handle(event json.RawMessage, ctx *Context) (interface{}, error) {
return h(event, ctx)
} | [
"func",
"(",
"h",
"HandlerFunc",
")",
"Handle",
"(",
"event",
"json",
".",
"RawMessage",
",",
"ctx",
"*",
"Context",
")",
"(",
"interface",
"{",
"}",
",",
"error",
")",
"{",
"return",
"h",
"(",
"event",
",",
"ctx",
")",
"\n",
"}"
] | // Handle Lambda event. | [
"Handle",
"Lambda",
"event",
"."
] | 7694047593bfde5f329ede4f42cbcfaf3fdc9fee | https://github.com/apex/apex-go/blob/7694047593bfde5f329ede4f42cbcfaf3fdc9fee/apex.go#L22-L24 |
4,051 | apex/apex-go | apex.go | Handle | func Handle(h Handler) {
m := &manager{
Reader: os.Stdin,
Writer: os.Stdout,
Handler: h,
}
m.Start()
} | go | func Handle(h Handler) {
m := &manager{
Reader: os.Stdin,
Writer: os.Stdout,
Handler: h,
}
m.Start()
} | [
"func",
"Handle",
"(",
"h",
"Handler",
")",
"{",
"m",
":=",
"&",
"manager",
"{",
"Reader",
":",
"os",
".",
"Stdin",
",",
"Writer",
":",
"os",
".",
"Stdout",
",",
"Handler",
":",
"h",
",",
"}",
"\n\n",
"m",
".",
"Start",
"(",
")",
"\n",
"}"
] | // Handle Lambda events with the given handler. | [
"Handle",
"Lambda",
"events",
"with",
"the",
"given",
"handler",
"."
] | 7694047593bfde5f329ede4f42cbcfaf3fdc9fee | https://github.com/apex/apex-go/blob/7694047593bfde5f329ede4f42cbcfaf3fdc9fee/apex.go#L48-L56 |
4,052 | apex/apex-go | apex.go | Start | func (m *manager) Start() {
dec := json.NewDecoder(m.Reader)
enc := json.NewEncoder(m.Writer)
for {
var msg input
err := dec.Decode(&msg)
if err == io.EOF {
break
}
if err != nil {
log.Printf("error decoding input: %s", err)
break
}
v, err := m.Handler.Handle(msg.Event, msg.Context)
out := output{ID: msg.ID, Value: v}
if err != nil {
out.Error = err.Error()
}
if err := enc.Encode(out); err != nil {
log.Printf("error encoding output: %s", err)
}
}
} | go | func (m *manager) Start() {
dec := json.NewDecoder(m.Reader)
enc := json.NewEncoder(m.Writer)
for {
var msg input
err := dec.Decode(&msg)
if err == io.EOF {
break
}
if err != nil {
log.Printf("error decoding input: %s", err)
break
}
v, err := m.Handler.Handle(msg.Event, msg.Context)
out := output{ID: msg.ID, Value: v}
if err != nil {
out.Error = err.Error()
}
if err := enc.Encode(out); err != nil {
log.Printf("error encoding output: %s", err)
}
}
} | [
"func",
"(",
"m",
"*",
"manager",
")",
"Start",
"(",
")",
"{",
"dec",
":=",
"json",
".",
"NewDecoder",
"(",
"m",
".",
"Reader",
")",
"\n",
"enc",
":=",
"json",
".",
"NewEncoder",
"(",
"m",
".",
"Writer",
")",
"\n\n",
"for",
"{",
"var",
"msg",
"input",
"\n",
"err",
":=",
"dec",
".",
"Decode",
"(",
"&",
"msg",
")",
"\n\n",
"if",
"err",
"==",
"io",
".",
"EOF",
"{",
"break",
"\n",
"}",
"\n\n",
"if",
"err",
"!=",
"nil",
"{",
"log",
".",
"Printf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"break",
"\n",
"}",
"\n\n",
"v",
",",
"err",
":=",
"m",
".",
"Handler",
".",
"Handle",
"(",
"msg",
".",
"Event",
",",
"msg",
".",
"Context",
")",
"\n",
"out",
":=",
"output",
"{",
"ID",
":",
"msg",
".",
"ID",
",",
"Value",
":",
"v",
"}",
"\n\n",
"if",
"err",
"!=",
"nil",
"{",
"out",
".",
"Error",
"=",
"err",
".",
"Error",
"(",
")",
"\n",
"}",
"\n\n",
"if",
"err",
":=",
"enc",
".",
"Encode",
"(",
"out",
")",
";",
"err",
"!=",
"nil",
"{",
"log",
".",
"Printf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n",
"}",
"\n",
"}"
] | // Start the manager. | [
"Start",
"the",
"manager",
"."
] | 7694047593bfde5f329ede4f42cbcfaf3fdc9fee | https://github.com/apex/apex-go/blob/7694047593bfde5f329ede4f42cbcfaf3fdc9fee/apex.go#L88-L116 |
4,053 | apex/apex-go | logs/logs.go | decode | func decode(record *Record, event *Event) error {
r, err := gzip.NewReader(bytes.NewReader(record.AWSLogs.Data))
if err != nil {
return err
}
if err = json.NewDecoder(r).Decode(&event); err != nil {
return err
}
if err := r.Close(); err != nil {
return err
}
return nil
} | go | func decode(record *Record, event *Event) error {
r, err := gzip.NewReader(bytes.NewReader(record.AWSLogs.Data))
if err != nil {
return err
}
if err = json.NewDecoder(r).Decode(&event); err != nil {
return err
}
if err := r.Close(); err != nil {
return err
}
return nil
} | [
"func",
"decode",
"(",
"record",
"*",
"Record",
",",
"event",
"*",
"Event",
")",
"error",
"{",
"r",
",",
"err",
":=",
"gzip",
".",
"NewReader",
"(",
"bytes",
".",
"NewReader",
"(",
"record",
".",
"AWSLogs",
".",
"Data",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"if",
"err",
"=",
"json",
".",
"NewDecoder",
"(",
"r",
")",
".",
"Decode",
"(",
"&",
"event",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"if",
"err",
":=",
"r",
".",
"Close",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"return",
"nil",
"\n",
"}"
] | // decode decodes the log payload which is gzipped. | [
"decode",
"decodes",
"the",
"log",
"payload",
"which",
"is",
"gzipped",
"."
] | 7694047593bfde5f329ede4f42cbcfaf3fdc9fee | https://github.com/apex/apex-go/blob/7694047593bfde5f329ede4f42cbcfaf3fdc9fee/logs/logs.go#L74-L89 |
4,054 | sendgridlabs/go-kinesis | kinesis.go | NewWithEndpoint | func NewWithEndpoint(auth Auth, region, endpoint string) *Kinesis {
// TODO: remove trailing slash on endpoint if there is one? does it matter?
// TODO: validate endpoint somehow?
return &Kinesis{client: NewClient(auth), version: KinesisVersion, region: region, endpoint: endpoint, streamType: "Kinesis"}
} | go | func NewWithEndpoint(auth Auth, region, endpoint string) *Kinesis {
// TODO: remove trailing slash on endpoint if there is one? does it matter?
// TODO: validate endpoint somehow?
return &Kinesis{client: NewClient(auth), version: KinesisVersion, region: region, endpoint: endpoint, streamType: "Kinesis"}
} | [
"func",
"NewWithEndpoint",
"(",
"auth",
"Auth",
",",
"region",
",",
"endpoint",
"string",
")",
"*",
"Kinesis",
"{",
"// TODO: remove trailing slash on endpoint if there is one? does it matter?",
"// TODO: validate endpoint somehow?",
"return",
"&",
"Kinesis",
"{",
"client",
":",
"NewClient",
"(",
"auth",
")",
",",
"version",
":",
"KinesisVersion",
",",
"region",
":",
"region",
",",
"endpoint",
":",
"endpoint",
",",
"streamType",
":",
"\"",
"\"",
"}",
"\n",
"}"
] | // NewWithEndpoint returns an initialized AWS Kinesis client using the specified endpoint.
// This is generally useful for testing, so a local Kinesis server can be used. | [
"NewWithEndpoint",
"returns",
"an",
"initialized",
"AWS",
"Kinesis",
"client",
"using",
"the",
"specified",
"endpoint",
".",
"This",
"is",
"generally",
"useful",
"for",
"testing",
"so",
"a",
"local",
"Kinesis",
"server",
"can",
"be",
"used",
"."
] | 8de9069567f65f2d1b06570525fdd89faf1c8bef | https://github.com/sendgridlabs/go-kinesis/blob/8de9069567f65f2d1b06570525fdd89faf1c8bef/kinesis.go#L86-L90 |
4,055 | sendgridlabs/go-kinesis | kinesis.go | makeParams | func makeParams(action string) map[string]string {
params := make(map[string]string)
params[ActionKey] = action
return params
} | go | func makeParams(action string) map[string]string {
params := make(map[string]string)
params[ActionKey] = action
return params
} | [
"func",
"makeParams",
"(",
"action",
"string",
")",
"map",
"[",
"string",
"]",
"string",
"{",
"params",
":=",
"make",
"(",
"map",
"[",
"string",
"]",
"string",
")",
"\n",
"params",
"[",
"ActionKey",
"]",
"=",
"action",
"\n",
"return",
"params",
"\n",
"}"
] | // Create params object for request | [
"Create",
"params",
"object",
"for",
"request"
] | 8de9069567f65f2d1b06570525fdd89faf1c8bef | https://github.com/sendgridlabs/go-kinesis/blob/8de9069567f65f2d1b06570525fdd89faf1c8bef/kinesis.go#L93-L97 |
4,056 | sendgridlabs/go-kinesis | kinesis.go | query | func (kinesis *Kinesis) query(params map[string]string, data interface{}, resp interface{}) error {
jsonData, err := json.Marshal(data)
if err != nil {
return err
}
// request
request, err := http.NewRequest(
"POST",
kinesis.getEndpoint(),
bytes.NewReader(jsonData),
)
if err != nil {
return err
}
// headers
request.Header.Set("Content-Type", "application/x-amz-json-1.1")
request.Header.Set("X-Amz-Target", fmt.Sprintf("%s_%s.%s", kinesis.getStreamType(), kinesis.getVersion(), params[ActionKey]))
request.Header.Set("User-Agent", "Golang Kinesis")
// response
response, err := kinesis.client.Do(request)
if err != nil {
return err
}
defer response.Body.Close()
if response.StatusCode != 200 {
return buildError(response)
}
if resp == nil {
return nil
}
return json.NewDecoder(response.Body).Decode(resp)
} | go | func (kinesis *Kinesis) query(params map[string]string, data interface{}, resp interface{}) error {
jsonData, err := json.Marshal(data)
if err != nil {
return err
}
// request
request, err := http.NewRequest(
"POST",
kinesis.getEndpoint(),
bytes.NewReader(jsonData),
)
if err != nil {
return err
}
// headers
request.Header.Set("Content-Type", "application/x-amz-json-1.1")
request.Header.Set("X-Amz-Target", fmt.Sprintf("%s_%s.%s", kinesis.getStreamType(), kinesis.getVersion(), params[ActionKey]))
request.Header.Set("User-Agent", "Golang Kinesis")
// response
response, err := kinesis.client.Do(request)
if err != nil {
return err
}
defer response.Body.Close()
if response.StatusCode != 200 {
return buildError(response)
}
if resp == nil {
return nil
}
return json.NewDecoder(response.Body).Decode(resp)
} | [
"func",
"(",
"kinesis",
"*",
"Kinesis",
")",
"query",
"(",
"params",
"map",
"[",
"string",
"]",
"string",
",",
"data",
"interface",
"{",
"}",
",",
"resp",
"interface",
"{",
"}",
")",
"error",
"{",
"jsonData",
",",
"err",
":=",
"json",
".",
"Marshal",
"(",
"data",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"// request",
"request",
",",
"err",
":=",
"http",
".",
"NewRequest",
"(",
"\"",
"\"",
",",
"kinesis",
".",
"getEndpoint",
"(",
")",
",",
"bytes",
".",
"NewReader",
"(",
"jsonData",
")",
",",
")",
"\n\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"// headers",
"request",
".",
"Header",
".",
"Set",
"(",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\n",
"request",
".",
"Header",
".",
"Set",
"(",
"\"",
"\"",
",",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"kinesis",
".",
"getStreamType",
"(",
")",
",",
"kinesis",
".",
"getVersion",
"(",
")",
",",
"params",
"[",
"ActionKey",
"]",
")",
")",
"\n",
"request",
".",
"Header",
".",
"Set",
"(",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\n\n",
"// response",
"response",
",",
"err",
":=",
"kinesis",
".",
"client",
".",
"Do",
"(",
"request",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"defer",
"response",
".",
"Body",
".",
"Close",
"(",
")",
"\n\n",
"if",
"response",
".",
"StatusCode",
"!=",
"200",
"{",
"return",
"buildError",
"(",
"response",
")",
"\n",
"}",
"\n\n",
"if",
"resp",
"==",
"nil",
"{",
"return",
"nil",
"\n",
"}",
"\n\n",
"return",
"json",
".",
"NewDecoder",
"(",
"response",
".",
"Body",
")",
".",
"Decode",
"(",
"resp",
")",
"\n",
"}"
] | // Query by AWS API | [
"Query",
"by",
"AWS",
"API"
] | 8de9069567f65f2d1b06570525fdd89faf1c8bef | https://github.com/sendgridlabs/go-kinesis/blob/8de9069567f65f2d1b06570525fdd89faf1c8bef/kinesis.go#L209-L247 |
4,057 | sendgridlabs/go-kinesis | kinesis.go | AddRecord | func (f *RequestArgs) AddRecord(value []byte, partitionKey string) {
r := Record{
Data: value,
PartitionKey: partitionKey,
}
f.Records = append(f.Records, r)
} | go | func (f *RequestArgs) AddRecord(value []byte, partitionKey string) {
r := Record{
Data: value,
PartitionKey: partitionKey,
}
f.Records = append(f.Records, r)
} | [
"func",
"(",
"f",
"*",
"RequestArgs",
")",
"AddRecord",
"(",
"value",
"[",
"]",
"byte",
",",
"partitionKey",
"string",
")",
"{",
"r",
":=",
"Record",
"{",
"Data",
":",
"value",
",",
"PartitionKey",
":",
"partitionKey",
",",
"}",
"\n",
"f",
".",
"Records",
"=",
"append",
"(",
"f",
".",
"Records",
",",
"r",
")",
"\n",
"}"
] | // AddRecord adds data and partition for sending multiple Records to Kinesis in one API call | [
"AddRecord",
"adds",
"data",
"and",
"partition",
"for",
"sending",
"multiple",
"Records",
"to",
"Kinesis",
"in",
"one",
"API",
"call"
] | 8de9069567f65f2d1b06570525fdd89faf1c8bef | https://github.com/sendgridlabs/go-kinesis/blob/8de9069567f65f2d1b06570525fdd89faf1c8bef/kinesis.go#L477-L483 |
4,058 | sendgridlabs/go-kinesis | batchproducer/batchproducer.go | sendBatch | func (b *batchProducer) sendBatch(batchSize int) int {
if len(b.records) == 0 {
return 0
}
// In the future, maybe this could be a RetryPolicy or something
if b.consecutiveErrors == 1 {
b.currentDelay = 50 * time.Millisecond
} else if b.consecutiveErrors > 1 {
b.currentDelay *= 2
}
if b.currentDelay > 0 {
b.logger.Printf("Delaying the batch by %v because of %v consecutive errors", b.currentDelay, b.consecutiveErrors)
time.Sleep(b.currentDelay)
}
records := b.takeRecordsFromBuffer(batchSize)
res, err := b.client.PutRecords(b.recordsToArgs(records))
if err != nil {
b.consecutiveErrors++
b.currentStat.KinesisErrorsSinceLastStat++
b.logger.Printf("Error occurred when sending PutRecords request to Kinesis stream %v: %v", b.streamName, err)
if b.consecutiveErrors >= 5 && b.isBufferFullOrNearlyFull() {
// In order to prevent Add from hanging indefinitely, we start dropping records
b.logger.Printf("DROPPING %v records because buffer is full or nearly full and there have been %v consecutive errors from Kinesis", len(records), b.consecutiveErrors)
} else {
b.logger.Printf("Returning %v records to buffer (%v consecutive errors)", len(records), b.consecutiveErrors)
// returnRecordsToBuffer can block if the buffer (channel) if full so we’ll
// call it in a goroutine. This might be problematic WRT ordering. TODO: revisit this.
go b.returnRecordsToBuffer(records)
}
return 0
}
b.consecutiveErrors = 0
b.currentDelay = 0
succeeded := len(records) - res.FailedRecordCount
b.currentStat.RecordsSentSuccessfullySinceLastStat += succeeded
if res.FailedRecordCount == 0 {
b.logger.Printf("PutRecords request succeeded: sent %v records to Kinesis stream %v", succeeded, b.streamName)
} else {
b.logger.Printf("Partial success when sending a PutRecords request to Kinesis stream %v: %v succeeded, %v failed. Re-enqueueing failed records.", b.streamName, succeeded, res.FailedRecordCount)
// returnSomeFailedRecordsToBuffer can block if the buffer (channel) if full so we’ll
// call it in a goroutine. This might be problematic WRT ordering. TODO: revisit this.
go b.returnSomeFailedRecordsToBuffer(res, records)
}
return succeeded
} | go | func (b *batchProducer) sendBatch(batchSize int) int {
if len(b.records) == 0 {
return 0
}
// In the future, maybe this could be a RetryPolicy or something
if b.consecutiveErrors == 1 {
b.currentDelay = 50 * time.Millisecond
} else if b.consecutiveErrors > 1 {
b.currentDelay *= 2
}
if b.currentDelay > 0 {
b.logger.Printf("Delaying the batch by %v because of %v consecutive errors", b.currentDelay, b.consecutiveErrors)
time.Sleep(b.currentDelay)
}
records := b.takeRecordsFromBuffer(batchSize)
res, err := b.client.PutRecords(b.recordsToArgs(records))
if err != nil {
b.consecutiveErrors++
b.currentStat.KinesisErrorsSinceLastStat++
b.logger.Printf("Error occurred when sending PutRecords request to Kinesis stream %v: %v", b.streamName, err)
if b.consecutiveErrors >= 5 && b.isBufferFullOrNearlyFull() {
// In order to prevent Add from hanging indefinitely, we start dropping records
b.logger.Printf("DROPPING %v records because buffer is full or nearly full and there have been %v consecutive errors from Kinesis", len(records), b.consecutiveErrors)
} else {
b.logger.Printf("Returning %v records to buffer (%v consecutive errors)", len(records), b.consecutiveErrors)
// returnRecordsToBuffer can block if the buffer (channel) if full so we’ll
// call it in a goroutine. This might be problematic WRT ordering. TODO: revisit this.
go b.returnRecordsToBuffer(records)
}
return 0
}
b.consecutiveErrors = 0
b.currentDelay = 0
succeeded := len(records) - res.FailedRecordCount
b.currentStat.RecordsSentSuccessfullySinceLastStat += succeeded
if res.FailedRecordCount == 0 {
b.logger.Printf("PutRecords request succeeded: sent %v records to Kinesis stream %v", succeeded, b.streamName)
} else {
b.logger.Printf("Partial success when sending a PutRecords request to Kinesis stream %v: %v succeeded, %v failed. Re-enqueueing failed records.", b.streamName, succeeded, res.FailedRecordCount)
// returnSomeFailedRecordsToBuffer can block if the buffer (channel) if full so we’ll
// call it in a goroutine. This might be problematic WRT ordering. TODO: revisit this.
go b.returnSomeFailedRecordsToBuffer(res, records)
}
return succeeded
} | [
"func",
"(",
"b",
"*",
"batchProducer",
")",
"sendBatch",
"(",
"batchSize",
"int",
")",
"int",
"{",
"if",
"len",
"(",
"b",
".",
"records",
")",
"==",
"0",
"{",
"return",
"0",
"\n",
"}",
"\n\n",
"// In the future, maybe this could be a RetryPolicy or something",
"if",
"b",
".",
"consecutiveErrors",
"==",
"1",
"{",
"b",
".",
"currentDelay",
"=",
"50",
"*",
"time",
".",
"Millisecond",
"\n",
"}",
"else",
"if",
"b",
".",
"consecutiveErrors",
">",
"1",
"{",
"b",
".",
"currentDelay",
"*=",
"2",
"\n",
"}",
"\n\n",
"if",
"b",
".",
"currentDelay",
">",
"0",
"{",
"b",
".",
"logger",
".",
"Printf",
"(",
"\"",
"\"",
",",
"b",
".",
"currentDelay",
",",
"b",
".",
"consecutiveErrors",
")",
"\n",
"time",
".",
"Sleep",
"(",
"b",
".",
"currentDelay",
")",
"\n",
"}",
"\n\n",
"records",
":=",
"b",
".",
"takeRecordsFromBuffer",
"(",
"batchSize",
")",
"\n",
"res",
",",
"err",
":=",
"b",
".",
"client",
".",
"PutRecords",
"(",
"b",
".",
"recordsToArgs",
"(",
"records",
")",
")",
"\n\n",
"if",
"err",
"!=",
"nil",
"{",
"b",
".",
"consecutiveErrors",
"++",
"\n",
"b",
".",
"currentStat",
".",
"KinesisErrorsSinceLastStat",
"++",
"\n",
"b",
".",
"logger",
".",
"Printf",
"(",
"\"",
"\"",
",",
"b",
".",
"streamName",
",",
"err",
")",
"\n\n",
"if",
"b",
".",
"consecutiveErrors",
">=",
"5",
"&&",
"b",
".",
"isBufferFullOrNearlyFull",
"(",
")",
"{",
"// In order to prevent Add from hanging indefinitely, we start dropping records",
"b",
".",
"logger",
".",
"Printf",
"(",
"\"",
"\"",
",",
"len",
"(",
"records",
")",
",",
"b",
".",
"consecutiveErrors",
")",
"\n",
"}",
"else",
"{",
"b",
".",
"logger",
".",
"Printf",
"(",
"\"",
"\"",
",",
"len",
"(",
"records",
")",
",",
"b",
".",
"consecutiveErrors",
")",
"\n",
"// returnRecordsToBuffer can block if the buffer (channel) if full so we’ll",
"// call it in a goroutine. This might be problematic WRT ordering. TODO: revisit this.",
"go",
"b",
".",
"returnRecordsToBuffer",
"(",
"records",
")",
"\n",
"}",
"\n\n",
"return",
"0",
"\n",
"}",
"\n\n",
"b",
".",
"consecutiveErrors",
"=",
"0",
"\n",
"b",
".",
"currentDelay",
"=",
"0",
"\n",
"succeeded",
":=",
"len",
"(",
"records",
")",
"-",
"res",
".",
"FailedRecordCount",
"\n\n",
"b",
".",
"currentStat",
".",
"RecordsSentSuccessfullySinceLastStat",
"+=",
"succeeded",
"\n\n",
"if",
"res",
".",
"FailedRecordCount",
"==",
"0",
"{",
"b",
".",
"logger",
".",
"Printf",
"(",
"\"",
"\"",
",",
"succeeded",
",",
"b",
".",
"streamName",
")",
"\n",
"}",
"else",
"{",
"b",
".",
"logger",
".",
"Printf",
"(",
"\"",
"\"",
",",
"b",
".",
"streamName",
",",
"succeeded",
",",
"res",
".",
"FailedRecordCount",
")",
"\n",
"// returnSomeFailedRecordsToBuffer can block if the buffer (channel) if full so we’ll",
"// call it in a goroutine. This might be problematic WRT ordering. TODO: revisit this.",
"go",
"b",
".",
"returnSomeFailedRecordsToBuffer",
"(",
"res",
",",
"records",
")",
"\n",
"}",
"\n\n",
"return",
"succeeded",
"\n",
"}"
] | // Sends batches of records to Kinesis, possibly re-enqueing them if there are any errors or failed
// records. Returns the number of records successfully sent, if any. | [
"Sends",
"batches",
"of",
"records",
"to",
"Kinesis",
"possibly",
"re",
"-",
"enqueing",
"them",
"if",
"there",
"are",
"any",
"errors",
"or",
"failed",
"records",
".",
"Returns",
"the",
"number",
"of",
"records",
"successfully",
"sent",
"if",
"any",
"."
] | 8de9069567f65f2d1b06570525fdd89faf1c8bef | https://github.com/sendgridlabs/go-kinesis/blob/8de9069567f65f2d1b06570525fdd89faf1c8bef/batchproducer/batchproducer.go#L321-L375 |
4,059 | sendgridlabs/go-kinesis | auth_static.go | NewAuth | func NewAuth(accessKey, secretKey, token string) Auth {
return &staticAuth{
staticCreds: &SigningKey{
AccessKeyId: accessKey,
SecretAccessKey: secretKey,
SessionToken: token,
},
}
} | go | func NewAuth(accessKey, secretKey, token string) Auth {
return &staticAuth{
staticCreds: &SigningKey{
AccessKeyId: accessKey,
SecretAccessKey: secretKey,
SessionToken: token,
},
}
} | [
"func",
"NewAuth",
"(",
"accessKey",
",",
"secretKey",
",",
"token",
"string",
")",
"Auth",
"{",
"return",
"&",
"staticAuth",
"{",
"staticCreds",
":",
"&",
"SigningKey",
"{",
"AccessKeyId",
":",
"accessKey",
",",
"SecretAccessKey",
":",
"secretKey",
",",
"SessionToken",
":",
"token",
",",
"}",
",",
"}",
"\n",
"}"
] | // NewAuth creates return an auth object that uses static
// credentials which do not automatically renew. | [
"NewAuth",
"creates",
"return",
"an",
"auth",
"object",
"that",
"uses",
"static",
"credentials",
"which",
"do",
"not",
"automatically",
"renew",
"."
] | 8de9069567f65f2d1b06570525fdd89faf1c8bef | https://github.com/sendgridlabs/go-kinesis/blob/8de9069567f65f2d1b06570525fdd89faf1c8bef/auth_static.go#L19-L27 |
4,060 | sendgridlabs/go-kinesis | auth_static.go | NewAuthFromEnv | func NewAuthFromEnv() (Auth, error) {
accessKey := os.Getenv(AccessEnvKey)
if accessKey == "" {
accessKey = os.Getenv(AccessEnvKeyId)
}
secretKey := os.Getenv(SecretEnvKey)
if secretKey == "" {
secretKey = os.Getenv(SecretEnvAccessKey)
}
token := os.Getenv(SecurityTokenEnvKey)
if accessKey == "" && secretKey == "" && token == "" {
return nil, fmt.Errorf("No access key (%s or %s), secret key (%s or %s), or security token (%s) env variables were set", AccessEnvKey, AccessEnvKeyId, SecretEnvKey, SecretEnvAccessKey, SecurityTokenEnvKey)
}
if accessKey == "" {
return nil, fmt.Errorf("Unable to retrieve access key from %s or %s env variables", AccessEnvKey, AccessEnvKeyId)
}
if secretKey == "" {
return nil, fmt.Errorf("Unable to retrieve secret key from %s or %s env variables", SecretEnvKey, SecretEnvAccessKey)
}
return NewAuth(accessKey, secretKey, token), nil
} | go | func NewAuthFromEnv() (Auth, error) {
accessKey := os.Getenv(AccessEnvKey)
if accessKey == "" {
accessKey = os.Getenv(AccessEnvKeyId)
}
secretKey := os.Getenv(SecretEnvKey)
if secretKey == "" {
secretKey = os.Getenv(SecretEnvAccessKey)
}
token := os.Getenv(SecurityTokenEnvKey)
if accessKey == "" && secretKey == "" && token == "" {
return nil, fmt.Errorf("No access key (%s or %s), secret key (%s or %s), or security token (%s) env variables were set", AccessEnvKey, AccessEnvKeyId, SecretEnvKey, SecretEnvAccessKey, SecurityTokenEnvKey)
}
if accessKey == "" {
return nil, fmt.Errorf("Unable to retrieve access key from %s or %s env variables", AccessEnvKey, AccessEnvKeyId)
}
if secretKey == "" {
return nil, fmt.Errorf("Unable to retrieve secret key from %s or %s env variables", SecretEnvKey, SecretEnvAccessKey)
}
return NewAuth(accessKey, secretKey, token), nil
} | [
"func",
"NewAuthFromEnv",
"(",
")",
"(",
"Auth",
",",
"error",
")",
"{",
"accessKey",
":=",
"os",
".",
"Getenv",
"(",
"AccessEnvKey",
")",
"\n",
"if",
"accessKey",
"==",
"\"",
"\"",
"{",
"accessKey",
"=",
"os",
".",
"Getenv",
"(",
"AccessEnvKeyId",
")",
"\n",
"}",
"\n\n",
"secretKey",
":=",
"os",
".",
"Getenv",
"(",
"SecretEnvKey",
")",
"\n",
"if",
"secretKey",
"==",
"\"",
"\"",
"{",
"secretKey",
"=",
"os",
".",
"Getenv",
"(",
"SecretEnvAccessKey",
")",
"\n",
"}",
"\n\n",
"token",
":=",
"os",
".",
"Getenv",
"(",
"SecurityTokenEnvKey",
")",
"\n\n",
"if",
"accessKey",
"==",
"\"",
"\"",
"&&",
"secretKey",
"==",
"\"",
"\"",
"&&",
"token",
"==",
"\"",
"\"",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"AccessEnvKey",
",",
"AccessEnvKeyId",
",",
"SecretEnvKey",
",",
"SecretEnvAccessKey",
",",
"SecurityTokenEnvKey",
")",
"\n",
"}",
"\n",
"if",
"accessKey",
"==",
"\"",
"\"",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"AccessEnvKey",
",",
"AccessEnvKeyId",
")",
"\n",
"}",
"\n",
"if",
"secretKey",
"==",
"\"",
"\"",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"SecretEnvKey",
",",
"SecretEnvAccessKey",
")",
"\n",
"}",
"\n\n",
"return",
"NewAuth",
"(",
"accessKey",
",",
"secretKey",
",",
"token",
")",
",",
"nil",
"\n",
"}"
] | // NewAuthFromEnv retrieves auth credentials from environment vars | [
"NewAuthFromEnv",
"retrieves",
"auth",
"credentials",
"from",
"environment",
"vars"
] | 8de9069567f65f2d1b06570525fdd89faf1c8bef | https://github.com/sendgridlabs/go-kinesis/blob/8de9069567f65f2d1b06570525fdd89faf1c8bef/auth_static.go#L30-L54 |
4,061 | sendgridlabs/go-kinesis | auth_assumerole.go | NewAuthWithAssumedRole | func NewAuthWithAssumedRole(roleArn, sessionName, region string, stsAuth Auth) (Auth, error) {
return newCachedMutexedWarmedUpAuth(&stsCreds{
RoleARN: roleArn,
SessionName: sessionName,
Region: region,
STSAuth: stsAuth,
})
} | go | func NewAuthWithAssumedRole(roleArn, sessionName, region string, stsAuth Auth) (Auth, error) {
return newCachedMutexedWarmedUpAuth(&stsCreds{
RoleARN: roleArn,
SessionName: sessionName,
Region: region,
STSAuth: stsAuth,
})
} | [
"func",
"NewAuthWithAssumedRole",
"(",
"roleArn",
",",
"sessionName",
",",
"region",
"string",
",",
"stsAuth",
"Auth",
")",
"(",
"Auth",
",",
"error",
")",
"{",
"return",
"newCachedMutexedWarmedUpAuth",
"(",
"&",
"stsCreds",
"{",
"RoleARN",
":",
"roleArn",
",",
"SessionName",
":",
"sessionName",
",",
"Region",
":",
"region",
",",
"STSAuth",
":",
"stsAuth",
",",
"}",
")",
"\n",
"}"
] | // NewAuthWithAssumedRole will call STS in a given region to assume a role
// stsAuth object is used to authenticate to STS to fetch temporary credentials
// for the desired role. | [
"NewAuthWithAssumedRole",
"will",
"call",
"STS",
"in",
"a",
"given",
"region",
"to",
"assume",
"a",
"role",
"stsAuth",
"object",
"is",
"used",
"to",
"authenticate",
"to",
"STS",
"to",
"fetch",
"temporary",
"credentials",
"for",
"the",
"desired",
"role",
"."
] | 8de9069567f65f2d1b06570525fdd89faf1c8bef | https://github.com/sendgridlabs/go-kinesis/blob/8de9069567f65f2d1b06570525fdd89faf1c8bef/auth_assumerole.go#L16-L23 |
4,062 | sendgridlabs/go-kinesis | sign.go | Sign | func Sign(authKeys Auth, r *http.Request) error {
sv := new(Service)
if awsKinesisRegexp.MatchString(r.Host) {
parts := strings.Split(r.Host, ".")
sv.Name = parts[0]
sv.Region = parts[1]
}
return sv.Sign(authKeys, r)
} | go | func Sign(authKeys Auth, r *http.Request) error {
sv := new(Service)
if awsKinesisRegexp.MatchString(r.Host) {
parts := strings.Split(r.Host, ".")
sv.Name = parts[0]
sv.Region = parts[1]
}
return sv.Sign(authKeys, r)
} | [
"func",
"Sign",
"(",
"authKeys",
"Auth",
",",
"r",
"*",
"http",
".",
"Request",
")",
"error",
"{",
"sv",
":=",
"new",
"(",
"Service",
")",
"\n",
"if",
"awsKinesisRegexp",
".",
"MatchString",
"(",
"r",
".",
"Host",
")",
"{",
"parts",
":=",
"strings",
".",
"Split",
"(",
"r",
".",
"Host",
",",
"\"",
"\"",
")",
"\n",
"sv",
".",
"Name",
"=",
"parts",
"[",
"0",
"]",
"\n",
"sv",
".",
"Region",
"=",
"parts",
"[",
"1",
"]",
"\n",
"}",
"\n",
"return",
"sv",
".",
"Sign",
"(",
"authKeys",
",",
"r",
")",
"\n",
"}"
] | // Sign signs a request with a Service derived from r.Host | [
"Sign",
"signs",
"a",
"request",
"with",
"a",
"Service",
"derived",
"from",
"r",
".",
"Host"
] | 8de9069567f65f2d1b06570525fdd89faf1c8bef | https://github.com/sendgridlabs/go-kinesis/blob/8de9069567f65f2d1b06570525fdd89faf1c8bef/sign.go#L38-L46 |
4,063 | sendgridlabs/go-kinesis | sign.go | Sign | func (s *Service) Sign(authKeys Auth, r *http.Request) error {
date := r.Header.Get("Date")
t := time.Now().UTC()
if date != "" {
var err error
t, err = time.Parse(http.TimeFormat, date)
if err != nil {
return err
}
}
r.Header.Set("Date", t.Format(iSO8601BasicFormat))
sk, err := authKeys.KeyForSigning(t)
if err != nil {
return err
}
k := ghmac([]byte("AWS4"+sk.SecretAccessKey), []byte(t.Format(iSO8601BasicFormatShort)))
k = ghmac(k, []byte(s.Region))
k = ghmac(k, []byte(s.Name))
k = ghmac(k, []byte(AWS4_URL))
h := hmac.New(sha256.New, k)
s.writeStringToSign(h, t, r)
auth := bytes.NewBufferString("AWS4-HMAC-SHA256 ")
auth.Write([]byte("Credential=" + sk.AccessKeyId + "/" + s.creds(t)))
auth.Write([]byte{',', ' '})
auth.Write([]byte("SignedHeaders="))
s.writeHeaderList(auth, r)
auth.Write([]byte{',', ' '})
auth.Write([]byte("Signature=" + fmt.Sprintf("%x", h.Sum(nil))))
r.Header.Set("Authorization", auth.String())
if sk.SessionToken != "" {
r.Header.Add(AWSSecurityTokenHeader, sk.SessionToken)
}
return nil
} | go | func (s *Service) Sign(authKeys Auth, r *http.Request) error {
date := r.Header.Get("Date")
t := time.Now().UTC()
if date != "" {
var err error
t, err = time.Parse(http.TimeFormat, date)
if err != nil {
return err
}
}
r.Header.Set("Date", t.Format(iSO8601BasicFormat))
sk, err := authKeys.KeyForSigning(t)
if err != nil {
return err
}
k := ghmac([]byte("AWS4"+sk.SecretAccessKey), []byte(t.Format(iSO8601BasicFormatShort)))
k = ghmac(k, []byte(s.Region))
k = ghmac(k, []byte(s.Name))
k = ghmac(k, []byte(AWS4_URL))
h := hmac.New(sha256.New, k)
s.writeStringToSign(h, t, r)
auth := bytes.NewBufferString("AWS4-HMAC-SHA256 ")
auth.Write([]byte("Credential=" + sk.AccessKeyId + "/" + s.creds(t)))
auth.Write([]byte{',', ' '})
auth.Write([]byte("SignedHeaders="))
s.writeHeaderList(auth, r)
auth.Write([]byte{',', ' '})
auth.Write([]byte("Signature=" + fmt.Sprintf("%x", h.Sum(nil))))
r.Header.Set("Authorization", auth.String())
if sk.SessionToken != "" {
r.Header.Add(AWSSecurityTokenHeader, sk.SessionToken)
}
return nil
} | [
"func",
"(",
"s",
"*",
"Service",
")",
"Sign",
"(",
"authKeys",
"Auth",
",",
"r",
"*",
"http",
".",
"Request",
")",
"error",
"{",
"date",
":=",
"r",
".",
"Header",
".",
"Get",
"(",
"\"",
"\"",
")",
"\n",
"t",
":=",
"time",
".",
"Now",
"(",
")",
".",
"UTC",
"(",
")",
"\n",
"if",
"date",
"!=",
"\"",
"\"",
"{",
"var",
"err",
"error",
"\n",
"t",
",",
"err",
"=",
"time",
".",
"Parse",
"(",
"http",
".",
"TimeFormat",
",",
"date",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"}",
"\n",
"r",
".",
"Header",
".",
"Set",
"(",
"\"",
"\"",
",",
"t",
".",
"Format",
"(",
"iSO8601BasicFormat",
")",
")",
"\n\n",
"sk",
",",
"err",
":=",
"authKeys",
".",
"KeyForSigning",
"(",
"t",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"k",
":=",
"ghmac",
"(",
"[",
"]",
"byte",
"(",
"\"",
"\"",
"+",
"sk",
".",
"SecretAccessKey",
")",
",",
"[",
"]",
"byte",
"(",
"t",
".",
"Format",
"(",
"iSO8601BasicFormatShort",
")",
")",
")",
"\n",
"k",
"=",
"ghmac",
"(",
"k",
",",
"[",
"]",
"byte",
"(",
"s",
".",
"Region",
")",
")",
"\n",
"k",
"=",
"ghmac",
"(",
"k",
",",
"[",
"]",
"byte",
"(",
"s",
".",
"Name",
")",
")",
"\n",
"k",
"=",
"ghmac",
"(",
"k",
",",
"[",
"]",
"byte",
"(",
"AWS4_URL",
")",
")",
"\n\n",
"h",
":=",
"hmac",
".",
"New",
"(",
"sha256",
".",
"New",
",",
"k",
")",
"\n",
"s",
".",
"writeStringToSign",
"(",
"h",
",",
"t",
",",
"r",
")",
"\n\n",
"auth",
":=",
"bytes",
".",
"NewBufferString",
"(",
"\"",
"\"",
")",
"\n",
"auth",
".",
"Write",
"(",
"[",
"]",
"byte",
"(",
"\"",
"\"",
"+",
"sk",
".",
"AccessKeyId",
"+",
"\"",
"\"",
"+",
"s",
".",
"creds",
"(",
"t",
")",
")",
")",
"\n",
"auth",
".",
"Write",
"(",
"[",
"]",
"byte",
"{",
"','",
",",
"' '",
"}",
")",
"\n",
"auth",
".",
"Write",
"(",
"[",
"]",
"byte",
"(",
"\"",
"\"",
")",
")",
"\n",
"s",
".",
"writeHeaderList",
"(",
"auth",
",",
"r",
")",
"\n",
"auth",
".",
"Write",
"(",
"[",
"]",
"byte",
"{",
"','",
",",
"' '",
"}",
")",
"\n",
"auth",
".",
"Write",
"(",
"[",
"]",
"byte",
"(",
"\"",
"\"",
"+",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"h",
".",
"Sum",
"(",
"nil",
")",
")",
")",
")",
"\n\n",
"r",
".",
"Header",
".",
"Set",
"(",
"\"",
"\"",
",",
"auth",
".",
"String",
"(",
")",
")",
"\n\n",
"if",
"sk",
".",
"SessionToken",
"!=",
"\"",
"\"",
"{",
"r",
".",
"Header",
".",
"Add",
"(",
"AWSSecurityTokenHeader",
",",
"sk",
".",
"SessionToken",
")",
"\n",
"}",
"\n\n",
"return",
"nil",
"\n",
"}"
] | // Sign signs an HTTP request with the given AWS keys for use on service s. | [
"Sign",
"signs",
"an",
"HTTP",
"request",
"with",
"the",
"given",
"AWS",
"keys",
"for",
"use",
"on",
"service",
"s",
"."
] | 8de9069567f65f2d1b06570525fdd89faf1c8bef | https://github.com/sendgridlabs/go-kinesis/blob/8de9069567f65f2d1b06570525fdd89faf1c8bef/sign.go#L49-L89 |
4,064 | sendgridlabs/go-kinesis | auth_cachedmutexedwarmedup.go | newCachedMutexedWarmedUpAuth | func newCachedMutexedWarmedUpAuth(underlying temporaryCredentialGenerator) (Auth, error) {
rv := &cachedMutexedAuth{
underlying: underlying,
}
_, err := rv.KeyForSigning(time.Now())
if err != nil {
return nil, err
}
return rv, nil
} | go | func newCachedMutexedWarmedUpAuth(underlying temporaryCredentialGenerator) (Auth, error) {
rv := &cachedMutexedAuth{
underlying: underlying,
}
_, err := rv.KeyForSigning(time.Now())
if err != nil {
return nil, err
}
return rv, nil
} | [
"func",
"newCachedMutexedWarmedUpAuth",
"(",
"underlying",
"temporaryCredentialGenerator",
")",
"(",
"Auth",
",",
"error",
")",
"{",
"rv",
":=",
"&",
"cachedMutexedAuth",
"{",
"underlying",
":",
"underlying",
",",
"}",
"\n",
"_",
",",
"err",
":=",
"rv",
".",
"KeyForSigning",
"(",
"time",
".",
"Now",
"(",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"return",
"rv",
",",
"nil",
"\n",
"}"
] | // newCachedMutexedWarmedUpAuth wraps another auth object
// with a cache that is thread-safe, and will always attempt
// to fetch credentials when initialised.
// The underlying Auth object will only be called if the time is
// past the last returned expiration time. | [
"newCachedMutexedWarmedUpAuth",
"wraps",
"another",
"auth",
"object",
"with",
"a",
"cache",
"that",
"is",
"thread",
"-",
"safe",
"and",
"will",
"always",
"attempt",
"to",
"fetch",
"credentials",
"when",
"initialised",
".",
"The",
"underlying",
"Auth",
"object",
"will",
"only",
"be",
"called",
"if",
"the",
"time",
"is",
"past",
"the",
"last",
"returned",
"expiration",
"time",
"."
] | 8de9069567f65f2d1b06570525fdd89faf1c8bef | https://github.com/sendgridlabs/go-kinesis/blob/8de9069567f65f2d1b06570525fdd89faf1c8bef/auth_cachedmutexedwarmedup.go#L13-L22 |
4,065 | sendgridlabs/go-kinesis | kinesis-cli/kinesis-cli.go | die | func die(printHelp bool, format string, args ...interface{}) {
if printHelp {
fmt.Print(HELP)
}
fmt.Printf(format, args...)
fmt.Println("")
os.Exit(1)
} | go | func die(printHelp bool, format string, args ...interface{}) {
if printHelp {
fmt.Print(HELP)
}
fmt.Printf(format, args...)
fmt.Println("")
os.Exit(1)
} | [
"func",
"die",
"(",
"printHelp",
"bool",
",",
"format",
"string",
",",
"args",
"...",
"interface",
"{",
"}",
")",
"{",
"if",
"printHelp",
"{",
"fmt",
".",
"Print",
"(",
"HELP",
")",
"\n",
"}",
"\n",
"fmt",
".",
"Printf",
"(",
"format",
",",
"args",
"...",
")",
"\n",
"fmt",
".",
"Println",
"(",
"\"",
"\"",
")",
"\n",
"os",
".",
"Exit",
"(",
"1",
")",
"\n",
"}"
] | //
// Command line helper functions
// | [
"Command",
"line",
"helper",
"functions"
] | 8de9069567f65f2d1b06570525fdd89faf1c8bef | https://github.com/sendgridlabs/go-kinesis/blob/8de9069567f65f2d1b06570525fdd89faf1c8bef/kinesis-cli/kinesis-cli.go#L150-L157 |
4,066 | sendgridlabs/go-kinesis | kinesis-cli/kinesis-cli.go | isBetween | func isBetween(lowStr, highStr, xStr string) bool {
low := bigIntFromStr(lowStr, 10)
high := bigIntFromStr(highStr, 10)
x := bigIntFromStr(xStr, 10)
return x.Cmp(low) == 1 && x.Cmp(high) == -1
} | go | func isBetween(lowStr, highStr, xStr string) bool {
low := bigIntFromStr(lowStr, 10)
high := bigIntFromStr(highStr, 10)
x := bigIntFromStr(xStr, 10)
return x.Cmp(low) == 1 && x.Cmp(high) == -1
} | [
"func",
"isBetween",
"(",
"lowStr",
",",
"highStr",
",",
"xStr",
"string",
")",
"bool",
"{",
"low",
":=",
"bigIntFromStr",
"(",
"lowStr",
",",
"10",
")",
"\n",
"high",
":=",
"bigIntFromStr",
"(",
"highStr",
",",
"10",
")",
"\n",
"x",
":=",
"bigIntFromStr",
"(",
"xStr",
",",
"10",
")",
"\n",
"return",
"x",
".",
"Cmp",
"(",
"low",
")",
"==",
"1",
"&&",
"x",
".",
"Cmp",
"(",
"high",
")",
"==",
"-",
"1",
"\n",
"}"
] | // Takes two large base 10 numeric strings low and high and returns low < x < high. | [
"Takes",
"two",
"large",
"base",
"10",
"numeric",
"strings",
"low",
"and",
"high",
"and",
"returns",
"low",
"<",
"x",
"<",
"high",
"."
] | 8de9069567f65f2d1b06570525fdd89faf1c8bef | https://github.com/sendgridlabs/go-kinesis/blob/8de9069567f65f2d1b06570525fdd89faf1c8bef/kinesis-cli/kinesis-cli.go#L220-L225 |
4,067 | sendgridlabs/go-kinesis | kinesis-cli/kinesis-cli.go | newClient | func newClient() kinesis.KinesisClient {
auth, _ := kinesis.NewAuthFromEnv()
return kinesis.New(auth, kinesis.NewRegionFromEnv())
} | go | func newClient() kinesis.KinesisClient {
auth, _ := kinesis.NewAuthFromEnv()
return kinesis.New(auth, kinesis.NewRegionFromEnv())
} | [
"func",
"newClient",
"(",
")",
"kinesis",
".",
"KinesisClient",
"{",
"auth",
",",
"_",
":=",
"kinesis",
".",
"NewAuthFromEnv",
"(",
")",
"\n",
"return",
"kinesis",
".",
"New",
"(",
"auth",
",",
"kinesis",
".",
"NewRegionFromEnv",
"(",
")",
")",
"\n",
"}"
] | //
// Kinesis helper functions
// | [
"Kinesis",
"helper",
"functions"
] | 8de9069567f65f2d1b06570525fdd89faf1c8bef | https://github.com/sendgridlabs/go-kinesis/blob/8de9069567f65f2d1b06570525fdd89faf1c8bef/kinesis-cli/kinesis-cli.go#L240-L243 |
4,068 | sendgridlabs/go-kinesis | client.go | NewClient | func NewClient(auth Auth) *Client {
return &Client{auth: auth, client: http.DefaultClient}
} | go | func NewClient(auth Auth) *Client {
return &Client{auth: auth, client: http.DefaultClient}
} | [
"func",
"NewClient",
"(",
"auth",
"Auth",
")",
"*",
"Client",
"{",
"return",
"&",
"Client",
"{",
"auth",
":",
"auth",
",",
"client",
":",
"http",
".",
"DefaultClient",
"}",
"\n",
"}"
] | // NewClient creates a new Client that uses the credentials in the specified
// Auth object.
//
// This function assumes the Auth object has been sanely initialized. If you
// wish to infer auth credentials from the environment, refer to NewAuth | [
"NewClient",
"creates",
"a",
"new",
"Client",
"that",
"uses",
"the",
"credentials",
"in",
"the",
"specified",
"Auth",
"object",
".",
"This",
"function",
"assumes",
"the",
"Auth",
"object",
"has",
"been",
"sanely",
"initialized",
".",
"If",
"you",
"wish",
"to",
"infer",
"auth",
"credentials",
"from",
"the",
"environment",
"refer",
"to",
"NewAuth"
] | 8de9069567f65f2d1b06570525fdd89faf1c8bef | https://github.com/sendgridlabs/go-kinesis/blob/8de9069567f65f2d1b06570525fdd89faf1c8bef/client.go#L20-L22 |
4,069 | sendgridlabs/go-kinesis | client.go | NewClientWithHTTPClient | func NewClientWithHTTPClient(auth Auth, httpClient *http.Client) *Client {
return &Client{auth: auth, client: httpClient}
} | go | func NewClientWithHTTPClient(auth Auth, httpClient *http.Client) *Client {
return &Client{auth: auth, client: httpClient}
} | [
"func",
"NewClientWithHTTPClient",
"(",
"auth",
"Auth",
",",
"httpClient",
"*",
"http",
".",
"Client",
")",
"*",
"Client",
"{",
"return",
"&",
"Client",
"{",
"auth",
":",
"auth",
",",
"client",
":",
"httpClient",
"}",
"\n",
"}"
] | // NewClientWithHTTPClient creates a client with a non-default http client
// ie. a timeout could be set on the HTTP client to timeout if Kinesis doesn't
// response in a timely manner like after the 5 minute mark where the current
// shard iterator expires | [
"NewClientWithHTTPClient",
"creates",
"a",
"client",
"with",
"a",
"non",
"-",
"default",
"http",
"client",
"ie",
".",
"a",
"timeout",
"could",
"be",
"set",
"on",
"the",
"HTTP",
"client",
"to",
"timeout",
"if",
"Kinesis",
"doesn",
"t",
"response",
"in",
"a",
"timely",
"manner",
"like",
"after",
"the",
"5",
"minute",
"mark",
"where",
"the",
"current",
"shard",
"iterator",
"expires"
] | 8de9069567f65f2d1b06570525fdd89faf1c8bef | https://github.com/sendgridlabs/go-kinesis/blob/8de9069567f65f2d1b06570525fdd89faf1c8bef/client.go#L28-L30 |
4,070 | sendgridlabs/go-kinesis | client.go | Do | func (c *Client) Do(req *http.Request) (*http.Response, error) {
err := Sign(c.auth, req)
if err != nil {
return nil, err
}
return c.client.Do(req)
} | go | func (c *Client) Do(req *http.Request) (*http.Response, error) {
err := Sign(c.auth, req)
if err != nil {
return nil, err
}
return c.client.Do(req)
} | [
"func",
"(",
"c",
"*",
"Client",
")",
"Do",
"(",
"req",
"*",
"http",
".",
"Request",
")",
"(",
"*",
"http",
".",
"Response",
",",
"error",
")",
"{",
"err",
":=",
"Sign",
"(",
"c",
".",
"auth",
",",
"req",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"return",
"c",
".",
"client",
".",
"Do",
"(",
"req",
")",
"\n",
"}"
] | // Do some request, but sign it before sending | [
"Do",
"some",
"request",
"but",
"sign",
"it",
"before",
"sending"
] | 8de9069567f65f2d1b06570525fdd89faf1c8bef | https://github.com/sendgridlabs/go-kinesis/blob/8de9069567f65f2d1b06570525fdd89faf1c8bef/client.go#L33-L40 |
4,071 | adjust/redismq | example/buffered_queue.go | main | func main() {
runtime.GOMAXPROCS(8)
server := redismq.NewServer("localhost", "6379", "", 9, "9999")
server.Start()
testQueue := redismq.CreateBufferedQueue("localhost", "6379", "", 9, "example", 200)
err := testQueue.Start()
if err != nil {
panic(err)
}
go write(testQueue)
go read(testQueue, "1")
go read(testQueue, "2")
go read(testQueue, "3")
go read(testQueue, "4")
go read(testQueue, "5")
go read(testQueue, "6")
go read(testQueue, "7")
go read(testQueue, "8")
select {}
} | go | func main() {
runtime.GOMAXPROCS(8)
server := redismq.NewServer("localhost", "6379", "", 9, "9999")
server.Start()
testQueue := redismq.CreateBufferedQueue("localhost", "6379", "", 9, "example", 200)
err := testQueue.Start()
if err != nil {
panic(err)
}
go write(testQueue)
go read(testQueue, "1")
go read(testQueue, "2")
go read(testQueue, "3")
go read(testQueue, "4")
go read(testQueue, "5")
go read(testQueue, "6")
go read(testQueue, "7")
go read(testQueue, "8")
select {}
} | [
"func",
"main",
"(",
")",
"{",
"runtime",
".",
"GOMAXPROCS",
"(",
"8",
")",
"\n",
"server",
":=",
"redismq",
".",
"NewServer",
"(",
"\"",
"\"",
",",
"\"",
"\"",
",",
"\"",
"\"",
",",
"9",
",",
"\"",
"\"",
")",
"\n",
"server",
".",
"Start",
"(",
")",
"\n",
"testQueue",
":=",
"redismq",
".",
"CreateBufferedQueue",
"(",
"\"",
"\"",
",",
"\"",
"\"",
",",
"\"",
"\"",
",",
"9",
",",
"\"",
"\"",
",",
"200",
")",
"\n",
"err",
":=",
"testQueue",
".",
"Start",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"panic",
"(",
"err",
")",
"\n",
"}",
"\n",
"go",
"write",
"(",
"testQueue",
")",
"\n\n",
"go",
"read",
"(",
"testQueue",
",",
"\"",
"\"",
")",
"\n",
"go",
"read",
"(",
"testQueue",
",",
"\"",
"\"",
")",
"\n",
"go",
"read",
"(",
"testQueue",
",",
"\"",
"\"",
")",
"\n",
"go",
"read",
"(",
"testQueue",
",",
"\"",
"\"",
")",
"\n",
"go",
"read",
"(",
"testQueue",
",",
"\"",
"\"",
")",
"\n",
"go",
"read",
"(",
"testQueue",
",",
"\"",
"\"",
")",
"\n",
"go",
"read",
"(",
"testQueue",
",",
"\"",
"\"",
")",
"\n",
"go",
"read",
"(",
"testQueue",
",",
"\"",
"\"",
")",
"\n\n",
"select",
"{",
"}",
"\n",
"}"
] | // This example demonstrates maximum performance | [
"This",
"example",
"demonstrates",
"maximum",
"performance"
] | e2a56d9bb404cb0e47cc737fdc3fe1fd6c095743 | https://github.com/adjust/redismq/blob/e2a56d9bb404cb0e47cc737fdc3fe1fd6c095743/example/buffered_queue.go#L12-L33 |
4,072 | adjust/redismq | queue.go | SelectQueue | func SelectQueue(redisHost, redisPort, redisPassword string, redisDB int64, name string) (queue *Queue, err error) {
redisClient := redis.NewClient(&redis.Options{
Addr: redisHost + ":" + redisPort,
Password: redisPassword,
DB: redisDB,
})
defer redisClient.Close()
isMember, err := redisClient.SIsMember(masterQueueKey(), name).Result()
if err != nil {
return nil, err
}
if !isMember {
return nil, fmt.Errorf("queue with this name doesn't exist")
}
return newQueue(redisHost, redisPort, redisPassword, redisDB, name), nil
} | go | func SelectQueue(redisHost, redisPort, redisPassword string, redisDB int64, name string) (queue *Queue, err error) {
redisClient := redis.NewClient(&redis.Options{
Addr: redisHost + ":" + redisPort,
Password: redisPassword,
DB: redisDB,
})
defer redisClient.Close()
isMember, err := redisClient.SIsMember(masterQueueKey(), name).Result()
if err != nil {
return nil, err
}
if !isMember {
return nil, fmt.Errorf("queue with this name doesn't exist")
}
return newQueue(redisHost, redisPort, redisPassword, redisDB, name), nil
} | [
"func",
"SelectQueue",
"(",
"redisHost",
",",
"redisPort",
",",
"redisPassword",
"string",
",",
"redisDB",
"int64",
",",
"name",
"string",
")",
"(",
"queue",
"*",
"Queue",
",",
"err",
"error",
")",
"{",
"redisClient",
":=",
"redis",
".",
"NewClient",
"(",
"&",
"redis",
".",
"Options",
"{",
"Addr",
":",
"redisHost",
"+",
"\"",
"\"",
"+",
"redisPort",
",",
"Password",
":",
"redisPassword",
",",
"DB",
":",
"redisDB",
",",
"}",
")",
"\n",
"defer",
"redisClient",
".",
"Close",
"(",
")",
"\n\n",
"isMember",
",",
"err",
":=",
"redisClient",
".",
"SIsMember",
"(",
"masterQueueKey",
"(",
")",
",",
"name",
")",
".",
"Result",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"if",
"!",
"isMember",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"return",
"newQueue",
"(",
"redisHost",
",",
"redisPort",
",",
"redisPassword",
",",
"redisDB",
",",
"name",
")",
",",
"nil",
"\n",
"}"
] | // SelectQueue returns a Queue if a queue with the name exists | [
"SelectQueue",
"returns",
"a",
"Queue",
"if",
"a",
"queue",
"with",
"the",
"name",
"exists"
] | e2a56d9bb404cb0e47cc737fdc3fe1fd6c095743 | https://github.com/adjust/redismq/blob/e2a56d9bb404cb0e47cc737fdc3fe1fd6c095743/queue.go#L35-L52 |
4,073 | adjust/redismq | queue.go | Delete | func (queue *Queue) Delete() error {
consumers, err := queue.getConsumers()
if err != nil {
return err
}
for _, name := range consumers {
if queue.isActiveConsumer(name) {
return fmt.Errorf("cannot delete queue with active consumers")
}
consumer, err := queue.AddConsumer(name)
if err != nil {
return err
}
err = consumer.ResetWorking()
if err != nil {
return err
}
err = queue.redisClient.SRem(queueWorkersKey(queue.Name), name).Err()
if err != nil {
return err
}
}
err = queue.ResetInput()
if err != nil {
return err
}
err = queue.ResetFailed()
if err != nil {
return err
}
err = queue.redisClient.SRem(masterQueueKey(), queue.Name).Err()
if err != nil {
return err
}
err = queue.redisClient.Del(queueWorkersKey(queue.Name)).Err()
if err != nil {
return err
}
queue.redisClient.Close()
return nil
} | go | func (queue *Queue) Delete() error {
consumers, err := queue.getConsumers()
if err != nil {
return err
}
for _, name := range consumers {
if queue.isActiveConsumer(name) {
return fmt.Errorf("cannot delete queue with active consumers")
}
consumer, err := queue.AddConsumer(name)
if err != nil {
return err
}
err = consumer.ResetWorking()
if err != nil {
return err
}
err = queue.redisClient.SRem(queueWorkersKey(queue.Name), name).Err()
if err != nil {
return err
}
}
err = queue.ResetInput()
if err != nil {
return err
}
err = queue.ResetFailed()
if err != nil {
return err
}
err = queue.redisClient.SRem(masterQueueKey(), queue.Name).Err()
if err != nil {
return err
}
err = queue.redisClient.Del(queueWorkersKey(queue.Name)).Err()
if err != nil {
return err
}
queue.redisClient.Close()
return nil
} | [
"func",
"(",
"queue",
"*",
"Queue",
")",
"Delete",
"(",
")",
"error",
"{",
"consumers",
",",
"err",
":=",
"queue",
".",
"getConsumers",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"for",
"_",
",",
"name",
":=",
"range",
"consumers",
"{",
"if",
"queue",
".",
"isActiveConsumer",
"(",
"name",
")",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"consumer",
",",
"err",
":=",
"queue",
".",
"AddConsumer",
"(",
"name",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"err",
"=",
"consumer",
".",
"ResetWorking",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"err",
"=",
"queue",
".",
"redisClient",
".",
"SRem",
"(",
"queueWorkersKey",
"(",
"queue",
".",
"Name",
")",
",",
"name",
")",
".",
"Err",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"}",
"\n\n",
"err",
"=",
"queue",
".",
"ResetInput",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"err",
"=",
"queue",
".",
"ResetFailed",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"err",
"=",
"queue",
".",
"redisClient",
".",
"SRem",
"(",
"masterQueueKey",
"(",
")",
",",
"queue",
".",
"Name",
")",
".",
"Err",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"err",
"=",
"queue",
".",
"redisClient",
".",
"Del",
"(",
"queueWorkersKey",
"(",
"queue",
".",
"Name",
")",
")",
".",
"Err",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"queue",
".",
"redisClient",
".",
"Close",
"(",
")",
"\n\n",
"return",
"nil",
"\n",
"}"
] | // Delete clears all input and failed queues as well as all consumers
// will not proceed as long as consumers are running | [
"Delete",
"clears",
"all",
"input",
"and",
"failed",
"queues",
"as",
"well",
"as",
"all",
"consumers",
"will",
"not",
"proceed",
"as",
"long",
"as",
"consumers",
"are",
"running"
] | e2a56d9bb404cb0e47cc737fdc3fe1fd6c095743 | https://github.com/adjust/redismq/blob/e2a56d9bb404cb0e47cc737fdc3fe1fd6c095743/queue.go#L68-L117 |
4,074 | adjust/redismq | queue.go | Put | func (queue *Queue) Put(payload string) error {
p := &Package{CreatedAt: time.Now(), Payload: payload, Queue: queue}
lpush := queue.redisClient.LPush(queueInputKey(queue.Name), p.getString())
queue.incrRate(queueInputRateKey(queue.Name), 1)
return lpush.Err()
} | go | func (queue *Queue) Put(payload string) error {
p := &Package{CreatedAt: time.Now(), Payload: payload, Queue: queue}
lpush := queue.redisClient.LPush(queueInputKey(queue.Name), p.getString())
queue.incrRate(queueInputRateKey(queue.Name), 1)
return lpush.Err()
} | [
"func",
"(",
"queue",
"*",
"Queue",
")",
"Put",
"(",
"payload",
"string",
")",
"error",
"{",
"p",
":=",
"&",
"Package",
"{",
"CreatedAt",
":",
"time",
".",
"Now",
"(",
")",
",",
"Payload",
":",
"payload",
",",
"Queue",
":",
"queue",
"}",
"\n",
"lpush",
":=",
"queue",
".",
"redisClient",
".",
"LPush",
"(",
"queueInputKey",
"(",
"queue",
".",
"Name",
")",
",",
"p",
".",
"getString",
"(",
")",
")",
"\n",
"queue",
".",
"incrRate",
"(",
"queueInputRateKey",
"(",
"queue",
".",
"Name",
")",
",",
"1",
")",
"\n",
"return",
"lpush",
".",
"Err",
"(",
")",
"\n",
"}"
] | // Put writes the payload into the input queue | [
"Put",
"writes",
"the",
"payload",
"into",
"the",
"input",
"queue"
] | e2a56d9bb404cb0e47cc737fdc3fe1fd6c095743 | https://github.com/adjust/redismq/blob/e2a56d9bb404cb0e47cc737fdc3fe1fd6c095743/queue.go#L120-L125 |
4,075 | adjust/redismq | queue.go | RequeueFailed | func (queue *Queue) RequeueFailed() error {
l := queue.GetFailedLength()
// TODO implement this in lua
for l > 0 {
err := queue.redisClient.RPopLPush(queueFailedKey(queue.Name), queueInputKey(queue.Name)).Err()
if err != nil {
return err
}
queue.incrRate(queueInputRateKey(queue.Name), 1)
l--
}
return nil
} | go | func (queue *Queue) RequeueFailed() error {
l := queue.GetFailedLength()
// TODO implement this in lua
for l > 0 {
err := queue.redisClient.RPopLPush(queueFailedKey(queue.Name), queueInputKey(queue.Name)).Err()
if err != nil {
return err
}
queue.incrRate(queueInputRateKey(queue.Name), 1)
l--
}
return nil
} | [
"func",
"(",
"queue",
"*",
"Queue",
")",
"RequeueFailed",
"(",
")",
"error",
"{",
"l",
":=",
"queue",
".",
"GetFailedLength",
"(",
")",
"\n",
"// TODO implement this in lua",
"for",
"l",
">",
"0",
"{",
"err",
":=",
"queue",
".",
"redisClient",
".",
"RPopLPush",
"(",
"queueFailedKey",
"(",
"queue",
".",
"Name",
")",
",",
"queueInputKey",
"(",
"queue",
".",
"Name",
")",
")",
".",
"Err",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"queue",
".",
"incrRate",
"(",
"queueInputRateKey",
"(",
"queue",
".",
"Name",
")",
",",
"1",
")",
"\n",
"l",
"--",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] | // RequeueFailed moves all failed packages back to the input queue | [
"RequeueFailed",
"moves",
"all",
"failed",
"packages",
"back",
"to",
"the",
"input",
"queue"
] | e2a56d9bb404cb0e47cc737fdc3fe1fd6c095743 | https://github.com/adjust/redismq/blob/e2a56d9bb404cb0e47cc737fdc3fe1fd6c095743/queue.go#L128-L140 |
4,076 | adjust/redismq | queue.go | ResetInput | func (queue *Queue) ResetInput() error {
return queue.redisClient.Del(queueInputKey(queue.Name)).Err()
} | go | func (queue *Queue) ResetInput() error {
return queue.redisClient.Del(queueInputKey(queue.Name)).Err()
} | [
"func",
"(",
"queue",
"*",
"Queue",
")",
"ResetInput",
"(",
")",
"error",
"{",
"return",
"queue",
".",
"redisClient",
".",
"Del",
"(",
"queueInputKey",
"(",
"queue",
".",
"Name",
")",
")",
".",
"Err",
"(",
")",
"\n",
"}"
] | // ResetInput deletes all packages from the input queue | [
"ResetInput",
"deletes",
"all",
"packages",
"from",
"the",
"input",
"queue"
] | e2a56d9bb404cb0e47cc737fdc3fe1fd6c095743 | https://github.com/adjust/redismq/blob/e2a56d9bb404cb0e47cc737fdc3fe1fd6c095743/queue.go#L143-L145 |
4,077 | adjust/redismq | queue.go | ResetFailed | func (queue *Queue) ResetFailed() error {
return queue.redisClient.Del(queueFailedKey(queue.Name)).Err()
} | go | func (queue *Queue) ResetFailed() error {
return queue.redisClient.Del(queueFailedKey(queue.Name)).Err()
} | [
"func",
"(",
"queue",
"*",
"Queue",
")",
"ResetFailed",
"(",
")",
"error",
"{",
"return",
"queue",
".",
"redisClient",
".",
"Del",
"(",
"queueFailedKey",
"(",
"queue",
".",
"Name",
")",
")",
".",
"Err",
"(",
")",
"\n",
"}"
] | // ResetFailed deletes all packages from the failed queue | [
"ResetFailed",
"deletes",
"all",
"packages",
"from",
"the",
"failed",
"queue"
] | e2a56d9bb404cb0e47cc737fdc3fe1fd6c095743 | https://github.com/adjust/redismq/blob/e2a56d9bb404cb0e47cc737fdc3fe1fd6c095743/queue.go#L148-L150 |
4,078 | adjust/redismq | queue.go | GetInputLength | func (queue *Queue) GetInputLength() int64 {
return queue.redisClient.LLen(queueInputKey(queue.Name)).Val()
} | go | func (queue *Queue) GetInputLength() int64 {
return queue.redisClient.LLen(queueInputKey(queue.Name)).Val()
} | [
"func",
"(",
"queue",
"*",
"Queue",
")",
"GetInputLength",
"(",
")",
"int64",
"{",
"return",
"queue",
".",
"redisClient",
".",
"LLen",
"(",
"queueInputKey",
"(",
"queue",
".",
"Name",
")",
")",
".",
"Val",
"(",
")",
"\n",
"}"
] | // GetInputLength returns the number of packages in the input queue | [
"GetInputLength",
"returns",
"the",
"number",
"of",
"packages",
"in",
"the",
"input",
"queue"
] | e2a56d9bb404cb0e47cc737fdc3fe1fd6c095743 | https://github.com/adjust/redismq/blob/e2a56d9bb404cb0e47cc737fdc3fe1fd6c095743/queue.go#L153-L155 |
4,079 | adjust/redismq | queue.go | GetFailedLength | func (queue *Queue) GetFailedLength() int64 {
return queue.redisClient.LLen(queueFailedKey(queue.Name)).Val()
} | go | func (queue *Queue) GetFailedLength() int64 {
return queue.redisClient.LLen(queueFailedKey(queue.Name)).Val()
} | [
"func",
"(",
"queue",
"*",
"Queue",
")",
"GetFailedLength",
"(",
")",
"int64",
"{",
"return",
"queue",
".",
"redisClient",
".",
"LLen",
"(",
"queueFailedKey",
"(",
"queue",
".",
"Name",
")",
")",
".",
"Val",
"(",
")",
"\n",
"}"
] | // GetFailedLength returns the number of packages in the failed queue | [
"GetFailedLength",
"returns",
"the",
"number",
"of",
"packages",
"in",
"the",
"failed",
"queue"
] | e2a56d9bb404cb0e47cc737fdc3fe1fd6c095743 | https://github.com/adjust/redismq/blob/e2a56d9bb404cb0e47cc737fdc3fe1fd6c095743/queue.go#L158-L160 |
4,080 | adjust/redismq | queue.go | AddConsumer | func (queue *Queue) AddConsumer(name string) (c *Consumer, err error) {
c = &Consumer{Name: name, Queue: queue}
//check uniqueness and start heartbeat
added, err := queue.redisClient.SAdd(queueWorkersKey(queue.Name), name).Result()
if err != nil {
return nil, err
}
if added == 0 {
if queue.isActiveConsumer(name) {
return nil, fmt.Errorf("consumer with this name is already active")
}
}
c.startHeartbeat()
return c, nil
} | go | func (queue *Queue) AddConsumer(name string) (c *Consumer, err error) {
c = &Consumer{Name: name, Queue: queue}
//check uniqueness and start heartbeat
added, err := queue.redisClient.SAdd(queueWorkersKey(queue.Name), name).Result()
if err != nil {
return nil, err
}
if added == 0 {
if queue.isActiveConsumer(name) {
return nil, fmt.Errorf("consumer with this name is already active")
}
}
c.startHeartbeat()
return c, nil
} | [
"func",
"(",
"queue",
"*",
"Queue",
")",
"AddConsumer",
"(",
"name",
"string",
")",
"(",
"c",
"*",
"Consumer",
",",
"err",
"error",
")",
"{",
"c",
"=",
"&",
"Consumer",
"{",
"Name",
":",
"name",
",",
"Queue",
":",
"queue",
"}",
"\n",
"//check uniqueness and start heartbeat",
"added",
",",
"err",
":=",
"queue",
".",
"redisClient",
".",
"SAdd",
"(",
"queueWorkersKey",
"(",
"queue",
".",
"Name",
")",
",",
"name",
")",
".",
"Result",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"if",
"added",
"==",
"0",
"{",
"if",
"queue",
".",
"isActiveConsumer",
"(",
"name",
")",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"}",
"\n",
"c",
".",
"startHeartbeat",
"(",
")",
"\n",
"return",
"c",
",",
"nil",
"\n",
"}"
] | // AddConsumer returns a conumser that can write from the queue | [
"AddConsumer",
"returns",
"a",
"conumser",
"that",
"can",
"write",
"from",
"the",
"queue"
] | e2a56d9bb404cb0e47cc737fdc3fe1fd6c095743 | https://github.com/adjust/redismq/blob/e2a56d9bb404cb0e47cc737fdc3fe1fd6c095743/queue.go#L217-L231 |
4,081 | adjust/redismq | buffered_queue.go | SelectBufferedQueue | func SelectBufferedQueue(redisHost, redisPort, redisPassword string, redisDB int64, name string, bufferSize int) (queue *BufferedQueue, err error) {
q, err := SelectQueue(redisHost, redisPort, redisPassword, redisDB, name)
if err != nil {
return nil, err
}
return &BufferedQueue{
Queue: q,
BufferSize: bufferSize,
Buffer: make(chan *Package, bufferSize*2),
flushStatus: make(chan chan bool, 1),
flushCommand: make(chan bool, bufferSize*2),
}, nil
} | go | func SelectBufferedQueue(redisHost, redisPort, redisPassword string, redisDB int64, name string, bufferSize int) (queue *BufferedQueue, err error) {
q, err := SelectQueue(redisHost, redisPort, redisPassword, redisDB, name)
if err != nil {
return nil, err
}
return &BufferedQueue{
Queue: q,
BufferSize: bufferSize,
Buffer: make(chan *Package, bufferSize*2),
flushStatus: make(chan chan bool, 1),
flushCommand: make(chan bool, bufferSize*2),
}, nil
} | [
"func",
"SelectBufferedQueue",
"(",
"redisHost",
",",
"redisPort",
",",
"redisPassword",
"string",
",",
"redisDB",
"int64",
",",
"name",
"string",
",",
"bufferSize",
"int",
")",
"(",
"queue",
"*",
"BufferedQueue",
",",
"err",
"error",
")",
"{",
"q",
",",
"err",
":=",
"SelectQueue",
"(",
"redisHost",
",",
"redisPort",
",",
"redisPassword",
",",
"redisDB",
",",
"name",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"return",
"&",
"BufferedQueue",
"{",
"Queue",
":",
"q",
",",
"BufferSize",
":",
"bufferSize",
",",
"Buffer",
":",
"make",
"(",
"chan",
"*",
"Package",
",",
"bufferSize",
"*",
"2",
")",
",",
"flushStatus",
":",
"make",
"(",
"chan",
"chan",
"bool",
",",
"1",
")",
",",
"flushCommand",
":",
"make",
"(",
"chan",
"bool",
",",
"bufferSize",
"*",
"2",
")",
",",
"}",
",",
"nil",
"\n",
"}"
] | // SelectBufferedQueue returns a BufferedQueue if a queue with the name exists | [
"SelectBufferedQueue",
"returns",
"a",
"BufferedQueue",
"if",
"a",
"queue",
"with",
"the",
"name",
"exists"
] | e2a56d9bb404cb0e47cc737fdc3fe1fd6c095743 | https://github.com/adjust/redismq/blob/e2a56d9bb404cb0e47cc737fdc3fe1fd6c095743/buffered_queue.go#L36-L49 |
4,082 | adjust/redismq | buffered_queue.go | Start | func (queue *BufferedQueue) Start() error {
queue.redisClient.SAdd(masterQueueKey(), queue.Name)
val := queue.redisClient.Get(queueHeartbeatKey(queue.Name)).Val()
if val == "ping" {
return fmt.Errorf("buffered queue with this name is already started")
}
queue.startHeartbeat()
queue.startWritingBufferToRedis()
queue.startPacemaker()
return nil
} | go | func (queue *BufferedQueue) Start() error {
queue.redisClient.SAdd(masterQueueKey(), queue.Name)
val := queue.redisClient.Get(queueHeartbeatKey(queue.Name)).Val()
if val == "ping" {
return fmt.Errorf("buffered queue with this name is already started")
}
queue.startHeartbeat()
queue.startWritingBufferToRedis()
queue.startPacemaker()
return nil
} | [
"func",
"(",
"queue",
"*",
"BufferedQueue",
")",
"Start",
"(",
")",
"error",
"{",
"queue",
".",
"redisClient",
".",
"SAdd",
"(",
"masterQueueKey",
"(",
")",
",",
"queue",
".",
"Name",
")",
"\n",
"val",
":=",
"queue",
".",
"redisClient",
".",
"Get",
"(",
"queueHeartbeatKey",
"(",
"queue",
".",
"Name",
")",
")",
".",
"Val",
"(",
")",
"\n",
"if",
"val",
"==",
"\"",
"\"",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"queue",
".",
"startHeartbeat",
"(",
")",
"\n",
"queue",
".",
"startWritingBufferToRedis",
"(",
")",
"\n",
"queue",
".",
"startPacemaker",
"(",
")",
"\n",
"return",
"nil",
"\n",
"}"
] | // Start dispatches the background writer that flushes the buffer.
// If there is already a BufferedQueue running it will return an error. | [
"Start",
"dispatches",
"the",
"background",
"writer",
"that",
"flushes",
"the",
"buffer",
".",
"If",
"there",
"is",
"already",
"a",
"BufferedQueue",
"running",
"it",
"will",
"return",
"an",
"error",
"."
] | e2a56d9bb404cb0e47cc737fdc3fe1fd6c095743 | https://github.com/adjust/redismq/blob/e2a56d9bb404cb0e47cc737fdc3fe1fd6c095743/buffered_queue.go#L53-L63 |
4,083 | adjust/redismq | buffered_queue.go | Put | func (queue *BufferedQueue) Put(payload string) error {
p := &Package{CreatedAt: time.Now(), Payload: payload, Queue: queue}
queue.Buffer <- p
queue.flushCommand <- true
return nil
} | go | func (queue *BufferedQueue) Put(payload string) error {
p := &Package{CreatedAt: time.Now(), Payload: payload, Queue: queue}
queue.Buffer <- p
queue.flushCommand <- true
return nil
} | [
"func",
"(",
"queue",
"*",
"BufferedQueue",
")",
"Put",
"(",
"payload",
"string",
")",
"error",
"{",
"p",
":=",
"&",
"Package",
"{",
"CreatedAt",
":",
"time",
".",
"Now",
"(",
")",
",",
"Payload",
":",
"payload",
",",
"Queue",
":",
"queue",
"}",
"\n",
"queue",
".",
"Buffer",
"<-",
"p",
"\n",
"queue",
".",
"flushCommand",
"<-",
"true",
"\n",
"return",
"nil",
"\n",
"}"
] | // Put writes the payload to the buffer | [
"Put",
"writes",
"the",
"payload",
"to",
"the",
"buffer"
] | e2a56d9bb404cb0e47cc737fdc3fe1fd6c095743 | https://github.com/adjust/redismq/blob/e2a56d9bb404cb0e47cc737fdc3fe1fd6c095743/buffered_queue.go#L66-L71 |
4,084 | adjust/redismq | buffered_queue.go | FlushBuffer | func (queue *BufferedQueue) FlushBuffer() {
flushing := make(chan bool, 1)
queue.flushStatus <- flushing
queue.flushCommand <- true
<-flushing
return
} | go | func (queue *BufferedQueue) FlushBuffer() {
flushing := make(chan bool, 1)
queue.flushStatus <- flushing
queue.flushCommand <- true
<-flushing
return
} | [
"func",
"(",
"queue",
"*",
"BufferedQueue",
")",
"FlushBuffer",
"(",
")",
"{",
"flushing",
":=",
"make",
"(",
"chan",
"bool",
",",
"1",
")",
"\n",
"queue",
".",
"flushStatus",
"<-",
"flushing",
"\n",
"queue",
".",
"flushCommand",
"<-",
"true",
"\n",
"<-",
"flushing",
"\n",
"return",
"\n",
"}"
] | // FlushBuffer tells the background writer to flush the buffer to redis | [
"FlushBuffer",
"tells",
"the",
"background",
"writer",
"to",
"flush",
"the",
"buffer",
"to",
"redis"
] | e2a56d9bb404cb0e47cc737fdc3fe1fd6c095743 | https://github.com/adjust/redismq/blob/e2a56d9bb404cb0e47cc737fdc3fe1fd6c095743/buffered_queue.go#L74-L80 |
4,085 | adjust/redismq | observer.go | NewObserver | func NewObserver(redisHost, redisPort, redisPassword string, redisDb int64) *Observer {
q := &Observer{
redisHost: redisHost,
redisPort: redisPort,
redisPassword: redisPassword,
redisDb: redisDb,
Stats: make(map[string]*QueueStat),
}
q.redisClient = redis.NewClient(&redis.Options{
Addr: redisHost + ":" + redisPort,
Password: redisPassword,
DB: redisDb,
})
return q
} | go | func NewObserver(redisHost, redisPort, redisPassword string, redisDb int64) *Observer {
q := &Observer{
redisHost: redisHost,
redisPort: redisPort,
redisPassword: redisPassword,
redisDb: redisDb,
Stats: make(map[string]*QueueStat),
}
q.redisClient = redis.NewClient(&redis.Options{
Addr: redisHost + ":" + redisPort,
Password: redisPassword,
DB: redisDb,
})
return q
} | [
"func",
"NewObserver",
"(",
"redisHost",
",",
"redisPort",
",",
"redisPassword",
"string",
",",
"redisDb",
"int64",
")",
"*",
"Observer",
"{",
"q",
":=",
"&",
"Observer",
"{",
"redisHost",
":",
"redisHost",
",",
"redisPort",
":",
"redisPort",
",",
"redisPassword",
":",
"redisPassword",
",",
"redisDb",
":",
"redisDb",
",",
"Stats",
":",
"make",
"(",
"map",
"[",
"string",
"]",
"*",
"QueueStat",
")",
",",
"}",
"\n",
"q",
".",
"redisClient",
"=",
"redis",
".",
"NewClient",
"(",
"&",
"redis",
".",
"Options",
"{",
"Addr",
":",
"redisHost",
"+",
"\"",
"\"",
"+",
"redisPort",
",",
"Password",
":",
"redisPassword",
",",
"DB",
":",
"redisDb",
",",
"}",
")",
"\n",
"return",
"q",
"\n",
"}"
] | // NewObserver returns an Oberserver to monitor different statistics from redis | [
"NewObserver",
"returns",
"an",
"Oberserver",
"to",
"monitor",
"different",
"statistics",
"from",
"redis"
] | e2a56d9bb404cb0e47cc737fdc3fe1fd6c095743 | https://github.com/adjust/redismq/blob/e2a56d9bb404cb0e47cc737fdc3fe1fd6c095743/observer.go#L55-L69 |
4,086 | adjust/redismq | observer.go | UpdateAllStats | func (observer *Observer) UpdateAllStats() {
queues, err := observer.GetAllQueues()
if err != nil {
log.Fatalf("ERROR FETCHING QUEUES %s", err.Error())
}
for _, queue := range queues {
observer.UpdateQueueStats(queue)
}
} | go | func (observer *Observer) UpdateAllStats() {
queues, err := observer.GetAllQueues()
if err != nil {
log.Fatalf("ERROR FETCHING QUEUES %s", err.Error())
}
for _, queue := range queues {
observer.UpdateQueueStats(queue)
}
} | [
"func",
"(",
"observer",
"*",
"Observer",
")",
"UpdateAllStats",
"(",
")",
"{",
"queues",
",",
"err",
":=",
"observer",
".",
"GetAllQueues",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"log",
".",
"Fatalf",
"(",
"\"",
"\"",
",",
"err",
".",
"Error",
"(",
")",
")",
"\n",
"}",
"\n\n",
"for",
"_",
",",
"queue",
":=",
"range",
"queues",
"{",
"observer",
".",
"UpdateQueueStats",
"(",
"queue",
")",
"\n",
"}",
"\n",
"}"
] | // UpdateAllStats fetches stats for all queues and all their consumers | [
"UpdateAllStats",
"fetches",
"stats",
"for",
"all",
"queues",
"and",
"all",
"their",
"consumers"
] | e2a56d9bb404cb0e47cc737fdc3fe1fd6c095743 | https://github.com/adjust/redismq/blob/e2a56d9bb404cb0e47cc737fdc3fe1fd6c095743/observer.go#L72-L81 |
4,087 | adjust/redismq | observer.go | GetAllQueues | func (observer *Observer) GetAllQueues() (queues []string, err error) {
return observer.redisClient.SMembers(masterQueueKey()).Result()
} | go | func (observer *Observer) GetAllQueues() (queues []string, err error) {
return observer.redisClient.SMembers(masterQueueKey()).Result()
} | [
"func",
"(",
"observer",
"*",
"Observer",
")",
"GetAllQueues",
"(",
")",
"(",
"queues",
"[",
"]",
"string",
",",
"err",
"error",
")",
"{",
"return",
"observer",
".",
"redisClient",
".",
"SMembers",
"(",
"masterQueueKey",
"(",
")",
")",
".",
"Result",
"(",
")",
"\n",
"}"
] | // GetAllQueues returns a list of all registed queues | [
"GetAllQueues",
"returns",
"a",
"list",
"of",
"all",
"registed",
"queues"
] | e2a56d9bb404cb0e47cc737fdc3fe1fd6c095743 | https://github.com/adjust/redismq/blob/e2a56d9bb404cb0e47cc737fdc3fe1fd6c095743/observer.go#L84-L86 |
4,088 | adjust/redismq | observer.go | UpdateQueueStats | func (observer *Observer) UpdateQueueStats(queue string) {
queueStats := &QueueStat{ConsumerStats: make(map[string]*ConsumerStat)}
queueStats.InputRateSecond = observer.fetchStat(queueInputRateKey(queue), 1)
queueStats.InputSizeSecond = observer.fetchStat(queueInputSizeKey(queue), 1)
queueStats.FailSizeSecond = observer.fetchStat(queueFailedSizeKey(queue), 1)
queueStats.InputRateMinute = observer.fetchStat(queueInputRateKey(queue), 60)
queueStats.InputSizeMinute = observer.fetchStat(queueInputSizeKey(queue), 60)
queueStats.FailSizeMinute = observer.fetchStat(queueFailedSizeKey(queue), 60)
queueStats.InputRateHour = observer.fetchStat(queueInputRateKey(queue), 3600)
queueStats.InputSizeHour = observer.fetchStat(queueInputSizeKey(queue), 3600)
queueStats.FailSizeHour = observer.fetchStat(queueFailedSizeKey(queue), 3600)
queueStats.WorkRateSecond = 0
queueStats.WorkRateMinute = 0
queueStats.WorkRateHour = 0
consumers, err := observer.getConsumers(queue)
if err != nil {
log.Fatalf("ERROR FETCHING CONSUMERS for %s %s", queue, err.Error())
return
}
for _, consumer := range consumers {
stat := &ConsumerStat{}
stat.WorkRateSecond = observer.fetchStat(consumerWorkingRateKey(queue, consumer), 1)
stat.WorkRateMinute = observer.fetchStat(consumerWorkingRateKey(queue, consumer), 60)
stat.WorkRateHour = observer.fetchStat(consumerWorkingRateKey(queue, consumer), 3600)
queueStats.WorkRateSecond += stat.WorkRateSecond
queueStats.WorkRateMinute += stat.WorkRateMinute
queueStats.WorkRateHour += stat.WorkRateHour
queueStats.ConsumerStats[consumer] = stat
}
observer.Stats[queue] = queueStats
} | go | func (observer *Observer) UpdateQueueStats(queue string) {
queueStats := &QueueStat{ConsumerStats: make(map[string]*ConsumerStat)}
queueStats.InputRateSecond = observer.fetchStat(queueInputRateKey(queue), 1)
queueStats.InputSizeSecond = observer.fetchStat(queueInputSizeKey(queue), 1)
queueStats.FailSizeSecond = observer.fetchStat(queueFailedSizeKey(queue), 1)
queueStats.InputRateMinute = observer.fetchStat(queueInputRateKey(queue), 60)
queueStats.InputSizeMinute = observer.fetchStat(queueInputSizeKey(queue), 60)
queueStats.FailSizeMinute = observer.fetchStat(queueFailedSizeKey(queue), 60)
queueStats.InputRateHour = observer.fetchStat(queueInputRateKey(queue), 3600)
queueStats.InputSizeHour = observer.fetchStat(queueInputSizeKey(queue), 3600)
queueStats.FailSizeHour = observer.fetchStat(queueFailedSizeKey(queue), 3600)
queueStats.WorkRateSecond = 0
queueStats.WorkRateMinute = 0
queueStats.WorkRateHour = 0
consumers, err := observer.getConsumers(queue)
if err != nil {
log.Fatalf("ERROR FETCHING CONSUMERS for %s %s", queue, err.Error())
return
}
for _, consumer := range consumers {
stat := &ConsumerStat{}
stat.WorkRateSecond = observer.fetchStat(consumerWorkingRateKey(queue, consumer), 1)
stat.WorkRateMinute = observer.fetchStat(consumerWorkingRateKey(queue, consumer), 60)
stat.WorkRateHour = observer.fetchStat(consumerWorkingRateKey(queue, consumer), 3600)
queueStats.WorkRateSecond += stat.WorkRateSecond
queueStats.WorkRateMinute += stat.WorkRateMinute
queueStats.WorkRateHour += stat.WorkRateHour
queueStats.ConsumerStats[consumer] = stat
}
observer.Stats[queue] = queueStats
} | [
"func",
"(",
"observer",
"*",
"Observer",
")",
"UpdateQueueStats",
"(",
"queue",
"string",
")",
"{",
"queueStats",
":=",
"&",
"QueueStat",
"{",
"ConsumerStats",
":",
"make",
"(",
"map",
"[",
"string",
"]",
"*",
"ConsumerStat",
")",
"}",
"\n\n",
"queueStats",
".",
"InputRateSecond",
"=",
"observer",
".",
"fetchStat",
"(",
"queueInputRateKey",
"(",
"queue",
")",
",",
"1",
")",
"\n",
"queueStats",
".",
"InputSizeSecond",
"=",
"observer",
".",
"fetchStat",
"(",
"queueInputSizeKey",
"(",
"queue",
")",
",",
"1",
")",
"\n",
"queueStats",
".",
"FailSizeSecond",
"=",
"observer",
".",
"fetchStat",
"(",
"queueFailedSizeKey",
"(",
"queue",
")",
",",
"1",
")",
"\n\n",
"queueStats",
".",
"InputRateMinute",
"=",
"observer",
".",
"fetchStat",
"(",
"queueInputRateKey",
"(",
"queue",
")",
",",
"60",
")",
"\n",
"queueStats",
".",
"InputSizeMinute",
"=",
"observer",
".",
"fetchStat",
"(",
"queueInputSizeKey",
"(",
"queue",
")",
",",
"60",
")",
"\n",
"queueStats",
".",
"FailSizeMinute",
"=",
"observer",
".",
"fetchStat",
"(",
"queueFailedSizeKey",
"(",
"queue",
")",
",",
"60",
")",
"\n\n",
"queueStats",
".",
"InputRateHour",
"=",
"observer",
".",
"fetchStat",
"(",
"queueInputRateKey",
"(",
"queue",
")",
",",
"3600",
")",
"\n",
"queueStats",
".",
"InputSizeHour",
"=",
"observer",
".",
"fetchStat",
"(",
"queueInputSizeKey",
"(",
"queue",
")",
",",
"3600",
")",
"\n",
"queueStats",
".",
"FailSizeHour",
"=",
"observer",
".",
"fetchStat",
"(",
"queueFailedSizeKey",
"(",
"queue",
")",
",",
"3600",
")",
"\n\n",
"queueStats",
".",
"WorkRateSecond",
"=",
"0",
"\n",
"queueStats",
".",
"WorkRateMinute",
"=",
"0",
"\n",
"queueStats",
".",
"WorkRateHour",
"=",
"0",
"\n\n",
"consumers",
",",
"err",
":=",
"observer",
".",
"getConsumers",
"(",
"queue",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"log",
".",
"Fatalf",
"(",
"\"",
"\"",
",",
"queue",
",",
"err",
".",
"Error",
"(",
")",
")",
"\n",
"return",
"\n",
"}",
"\n\n",
"for",
"_",
",",
"consumer",
":=",
"range",
"consumers",
"{",
"stat",
":=",
"&",
"ConsumerStat",
"{",
"}",
"\n\n",
"stat",
".",
"WorkRateSecond",
"=",
"observer",
".",
"fetchStat",
"(",
"consumerWorkingRateKey",
"(",
"queue",
",",
"consumer",
")",
",",
"1",
")",
"\n",
"stat",
".",
"WorkRateMinute",
"=",
"observer",
".",
"fetchStat",
"(",
"consumerWorkingRateKey",
"(",
"queue",
",",
"consumer",
")",
",",
"60",
")",
"\n",
"stat",
".",
"WorkRateHour",
"=",
"observer",
".",
"fetchStat",
"(",
"consumerWorkingRateKey",
"(",
"queue",
",",
"consumer",
")",
",",
"3600",
")",
"\n\n",
"queueStats",
".",
"WorkRateSecond",
"+=",
"stat",
".",
"WorkRateSecond",
"\n",
"queueStats",
".",
"WorkRateMinute",
"+=",
"stat",
".",
"WorkRateMinute",
"\n",
"queueStats",
".",
"WorkRateHour",
"+=",
"stat",
".",
"WorkRateHour",
"\n\n",
"queueStats",
".",
"ConsumerStats",
"[",
"consumer",
"]",
"=",
"stat",
"\n",
"}",
"\n\n",
"observer",
".",
"Stats",
"[",
"queue",
"]",
"=",
"queueStats",
"\n",
"}"
] | // UpdateQueueStats fetches stats for one specific queue and its consumers | [
"UpdateQueueStats",
"fetches",
"stats",
"for",
"one",
"specific",
"queue",
"and",
"its",
"consumers"
] | e2a56d9bb404cb0e47cc737fdc3fe1fd6c095743 | https://github.com/adjust/redismq/blob/e2a56d9bb404cb0e47cc737fdc3fe1fd6c095743/observer.go#L93-L133 |
4,089 | adjust/redismq | observer.go | ToJSON | func (observer *Observer) ToJSON() string {
json, err := json.Marshal(observer)
if err != nil {
log.Fatalf("ERROR MARSHALLING OVERSEER %s", err.Error())
}
return string(json)
} | go | func (observer *Observer) ToJSON() string {
json, err := json.Marshal(observer)
if err != nil {
log.Fatalf("ERROR MARSHALLING OVERSEER %s", err.Error())
}
return string(json)
} | [
"func",
"(",
"observer",
"*",
"Observer",
")",
"ToJSON",
"(",
")",
"string",
"{",
"json",
",",
"err",
":=",
"json",
".",
"Marshal",
"(",
"observer",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"log",
".",
"Fatalf",
"(",
"\"",
"\"",
",",
"err",
".",
"Error",
"(",
")",
")",
"\n",
"}",
"\n",
"return",
"string",
"(",
"json",
")",
"\n",
"}"
] | // ToJSON renders the whole observer as a JSON string | [
"ToJSON",
"renders",
"the",
"whole",
"observer",
"as",
"a",
"JSON",
"string"
] | e2a56d9bb404cb0e47cc737fdc3fe1fd6c095743 | https://github.com/adjust/redismq/blob/e2a56d9bb404cb0e47cc737fdc3fe1fd6c095743/observer.go#L164-L170 |
4,090 | adjust/redismq | package.go | MultiAck | func (pack *Package) MultiAck() (err error) {
if pack.Collection == nil {
return fmt.Errorf("cannot MultiAck single package")
}
// TODO write in lua
for i := 0; i <= pack.index(); i++ {
var p *Package
p = (*pack.Collection)[i]
// if the package has already been acked just skip
if p.Acked == true {
continue
}
err = pack.Consumer.ackPackage(p)
if err != nil {
break
}
p.Acked = true
}
return
} | go | func (pack *Package) MultiAck() (err error) {
if pack.Collection == nil {
return fmt.Errorf("cannot MultiAck single package")
}
// TODO write in lua
for i := 0; i <= pack.index(); i++ {
var p *Package
p = (*pack.Collection)[i]
// if the package has already been acked just skip
if p.Acked == true {
continue
}
err = pack.Consumer.ackPackage(p)
if err != nil {
break
}
p.Acked = true
}
return
} | [
"func",
"(",
"pack",
"*",
"Package",
")",
"MultiAck",
"(",
")",
"(",
"err",
"error",
")",
"{",
"if",
"pack",
".",
"Collection",
"==",
"nil",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"// TODO write in lua",
"for",
"i",
":=",
"0",
";",
"i",
"<=",
"pack",
".",
"index",
"(",
")",
";",
"i",
"++",
"{",
"var",
"p",
"*",
"Package",
"\n",
"p",
"=",
"(",
"*",
"pack",
".",
"Collection",
")",
"[",
"i",
"]",
"\n",
"// if the package has already been acked just skip",
"if",
"p",
".",
"Acked",
"==",
"true",
"{",
"continue",
"\n",
"}",
"\n\n",
"err",
"=",
"pack",
".",
"Consumer",
".",
"ackPackage",
"(",
"p",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"break",
"\n",
"}",
"\n",
"p",
".",
"Acked",
"=",
"true",
"\n",
"}",
"\n",
"return",
"\n",
"}"
] | // MultiAck removes all packaes from the fetched array up to and including this package | [
"MultiAck",
"removes",
"all",
"packaes",
"from",
"the",
"fetched",
"array",
"up",
"to",
"and",
"including",
"this",
"package"
] | e2a56d9bb404cb0e47cc737fdc3fe1fd6c095743 | https://github.com/adjust/redismq/blob/e2a56d9bb404cb0e47cc737fdc3fe1fd6c095743/package.go#L55-L75 |
4,091 | adjust/redismq | package.go | Ack | func (pack *Package) Ack() error {
if pack.Collection != nil {
return fmt.Errorf("cannot Ack package in multi package answer")
}
err := pack.Consumer.ackPackage(pack)
return err
} | go | func (pack *Package) Ack() error {
if pack.Collection != nil {
return fmt.Errorf("cannot Ack package in multi package answer")
}
err := pack.Consumer.ackPackage(pack)
return err
} | [
"func",
"(",
"pack",
"*",
"Package",
")",
"Ack",
"(",
")",
"error",
"{",
"if",
"pack",
".",
"Collection",
"!=",
"nil",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"err",
":=",
"pack",
".",
"Consumer",
".",
"ackPackage",
"(",
"pack",
")",
"\n",
"return",
"err",
"\n",
"}"
] | // Ack removes the packages from the queue | [
"Ack",
"removes",
"the",
"packages",
"from",
"the",
"queue"
] | e2a56d9bb404cb0e47cc737fdc3fe1fd6c095743 | https://github.com/adjust/redismq/blob/e2a56d9bb404cb0e47cc737fdc3fe1fd6c095743/package.go#L78-L84 |
4,092 | adjust/redismq | server.go | Start | func (server *Server) Start() {
go func() {
server.setUpRoutes()
log.Printf("STARTING REDISMQ SERVER ON PORT %s", server.port)
err := http.ListenAndServe(":"+server.port, nil)
if err != nil {
log.Fatalf("REDISMQ SERVER SHUTTING DOWN [%s]\n\n", err.Error())
}
}()
} | go | func (server *Server) Start() {
go func() {
server.setUpRoutes()
log.Printf("STARTING REDISMQ SERVER ON PORT %s", server.port)
err := http.ListenAndServe(":"+server.port, nil)
if err != nil {
log.Fatalf("REDISMQ SERVER SHUTTING DOWN [%s]\n\n", err.Error())
}
}()
} | [
"func",
"(",
"server",
"*",
"Server",
")",
"Start",
"(",
")",
"{",
"go",
"func",
"(",
")",
"{",
"server",
".",
"setUpRoutes",
"(",
")",
"\n",
"log",
".",
"Printf",
"(",
"\"",
"\"",
",",
"server",
".",
"port",
")",
"\n",
"err",
":=",
"http",
".",
"ListenAndServe",
"(",
"\"",
"\"",
"+",
"server",
".",
"port",
",",
"nil",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"log",
".",
"Fatalf",
"(",
"\"",
"\\n",
"\\n",
"\"",
",",
"err",
".",
"Error",
"(",
")",
")",
"\n",
"}",
"\n",
"}",
"(",
")",
"\n",
"}"
] | // Start enables the Server to listen on his port | [
"Start",
"enables",
"the",
"Server",
"to",
"listen",
"on",
"his",
"port"
] | e2a56d9bb404cb0e47cc737fdc3fe1fd6c095743 | https://github.com/adjust/redismq/blob/e2a56d9bb404cb0e47cc737fdc3fe1fd6c095743/server.go#L30-L39 |
4,093 | adjust/redismq | consumer.go | MultiGet | func (consumer *Consumer) MultiGet(length int) ([]*Package, error) {
var collection []*Package
if consumer.HasUnacked() {
return nil, fmt.Errorf("unacked Packages found")
}
// TODO maybe use transactions for rollback in case of errors?
reqs, err := consumer.Queue.redisClient.Pipelined(func(c *redis.Pipeline) error {
c.BRPopLPush(
queueInputKey(consumer.Queue.Name),
consumerWorkingQueueKey(consumer.Queue.Name, consumer.Name),
0,
)
for i := 1; i < length; i++ {
c.RPopLPush(
queueInputKey(consumer.Queue.Name),
consumerWorkingQueueKey(consumer.Queue.Name, consumer.Name),
)
}
return nil
})
if err != nil && err != redis.Nil {
return nil, err
}
for _, answer := range reqs {
switch answer := answer.(type) {
case *redis.StringCmd:
if answer.Val() == "" {
continue
}
p, err := consumer.parseRedisAnswer(answer)
if err != nil {
return nil, err
}
p.Collection = &collection
collection = append(collection, p)
default:
return nil, err
}
}
consumer.Queue.incrRate(
consumerWorkingRateKey(consumer.Queue.Name, consumer.Name),
int64(length),
)
return collection, nil
} | go | func (consumer *Consumer) MultiGet(length int) ([]*Package, error) {
var collection []*Package
if consumer.HasUnacked() {
return nil, fmt.Errorf("unacked Packages found")
}
// TODO maybe use transactions for rollback in case of errors?
reqs, err := consumer.Queue.redisClient.Pipelined(func(c *redis.Pipeline) error {
c.BRPopLPush(
queueInputKey(consumer.Queue.Name),
consumerWorkingQueueKey(consumer.Queue.Name, consumer.Name),
0,
)
for i := 1; i < length; i++ {
c.RPopLPush(
queueInputKey(consumer.Queue.Name),
consumerWorkingQueueKey(consumer.Queue.Name, consumer.Name),
)
}
return nil
})
if err != nil && err != redis.Nil {
return nil, err
}
for _, answer := range reqs {
switch answer := answer.(type) {
case *redis.StringCmd:
if answer.Val() == "" {
continue
}
p, err := consumer.parseRedisAnswer(answer)
if err != nil {
return nil, err
}
p.Collection = &collection
collection = append(collection, p)
default:
return nil, err
}
}
consumer.Queue.incrRate(
consumerWorkingRateKey(consumer.Queue.Name, consumer.Name),
int64(length),
)
return collection, nil
} | [
"func",
"(",
"consumer",
"*",
"Consumer",
")",
"MultiGet",
"(",
"length",
"int",
")",
"(",
"[",
"]",
"*",
"Package",
",",
"error",
")",
"{",
"var",
"collection",
"[",
"]",
"*",
"Package",
"\n",
"if",
"consumer",
".",
"HasUnacked",
"(",
")",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"// TODO maybe use transactions for rollback in case of errors?",
"reqs",
",",
"err",
":=",
"consumer",
".",
"Queue",
".",
"redisClient",
".",
"Pipelined",
"(",
"func",
"(",
"c",
"*",
"redis",
".",
"Pipeline",
")",
"error",
"{",
"c",
".",
"BRPopLPush",
"(",
"queueInputKey",
"(",
"consumer",
".",
"Queue",
".",
"Name",
")",
",",
"consumerWorkingQueueKey",
"(",
"consumer",
".",
"Queue",
".",
"Name",
",",
"consumer",
".",
"Name",
")",
",",
"0",
",",
")",
"\n",
"for",
"i",
":=",
"1",
";",
"i",
"<",
"length",
";",
"i",
"++",
"{",
"c",
".",
"RPopLPush",
"(",
"queueInputKey",
"(",
"consumer",
".",
"Queue",
".",
"Name",
")",
",",
"consumerWorkingQueueKey",
"(",
"consumer",
".",
"Queue",
".",
"Name",
",",
"consumer",
".",
"Name",
")",
",",
")",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}",
")",
"\n",
"if",
"err",
"!=",
"nil",
"&&",
"err",
"!=",
"redis",
".",
"Nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"for",
"_",
",",
"answer",
":=",
"range",
"reqs",
"{",
"switch",
"answer",
":=",
"answer",
".",
"(",
"type",
")",
"{",
"case",
"*",
"redis",
".",
"StringCmd",
":",
"if",
"answer",
".",
"Val",
"(",
")",
"==",
"\"",
"\"",
"{",
"continue",
"\n",
"}",
"\n",
"p",
",",
"err",
":=",
"consumer",
".",
"parseRedisAnswer",
"(",
"answer",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"p",
".",
"Collection",
"=",
"&",
"collection",
"\n",
"collection",
"=",
"append",
"(",
"collection",
",",
"p",
")",
"\n",
"default",
":",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"}",
"\n",
"consumer",
".",
"Queue",
".",
"incrRate",
"(",
"consumerWorkingRateKey",
"(",
"consumer",
".",
"Queue",
".",
"Name",
",",
"consumer",
".",
"Name",
")",
",",
"int64",
"(",
"length",
")",
",",
")",
"\n\n",
"return",
"collection",
",",
"nil",
"\n",
"}"
] | // MultiGet returns an array of packages from the queue | [
"MultiGet",
"returns",
"an",
"array",
"of",
"packages",
"from",
"the",
"queue"
] | e2a56d9bb404cb0e47cc737fdc3fe1fd6c095743 | https://github.com/adjust/redismq/blob/e2a56d9bb404cb0e47cc737fdc3fe1fd6c095743/consumer.go#L48-L95 |
4,094 | adjust/redismq | consumer.go | GetUnacked | func (consumer *Consumer) GetUnacked() (*Package, error) {
if !consumer.HasUnacked() {
return nil, fmt.Errorf("no unacked Packages found")
}
answer := consumer.Queue.redisClient.LIndex(
consumerWorkingQueueKey(consumer.Queue.Name, consumer.Name),
-1,
)
return consumer.parseRedisAnswer(answer)
} | go | func (consumer *Consumer) GetUnacked() (*Package, error) {
if !consumer.HasUnacked() {
return nil, fmt.Errorf("no unacked Packages found")
}
answer := consumer.Queue.redisClient.LIndex(
consumerWorkingQueueKey(consumer.Queue.Name, consumer.Name),
-1,
)
return consumer.parseRedisAnswer(answer)
} | [
"func",
"(",
"consumer",
"*",
"Consumer",
")",
"GetUnacked",
"(",
")",
"(",
"*",
"Package",
",",
"error",
")",
"{",
"if",
"!",
"consumer",
".",
"HasUnacked",
"(",
")",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"answer",
":=",
"consumer",
".",
"Queue",
".",
"redisClient",
".",
"LIndex",
"(",
"consumerWorkingQueueKey",
"(",
"consumer",
".",
"Queue",
".",
"Name",
",",
"consumer",
".",
"Name",
")",
",",
"-",
"1",
",",
")",
"\n",
"return",
"consumer",
".",
"parseRedisAnswer",
"(",
"answer",
")",
"\n",
"}"
] | // GetUnacked returns a single packages from the working queue of this consumer | [
"GetUnacked",
"returns",
"a",
"single",
"packages",
"from",
"the",
"working",
"queue",
"of",
"this",
"consumer"
] | e2a56d9bb404cb0e47cc737fdc3fe1fd6c095743 | https://github.com/adjust/redismq/blob/e2a56d9bb404cb0e47cc737fdc3fe1fd6c095743/consumer.go#L98-L107 |
4,095 | adjust/redismq | consumer.go | GetUnackedLength | func (consumer *Consumer) GetUnackedLength() int64 {
return consumer.Queue.redisClient.LLen(consumerWorkingQueueKey(consumer.Queue.Name, consumer.Name)).Val()
} | go | func (consumer *Consumer) GetUnackedLength() int64 {
return consumer.Queue.redisClient.LLen(consumerWorkingQueueKey(consumer.Queue.Name, consumer.Name)).Val()
} | [
"func",
"(",
"consumer",
"*",
"Consumer",
")",
"GetUnackedLength",
"(",
")",
"int64",
"{",
"return",
"consumer",
".",
"Queue",
".",
"redisClient",
".",
"LLen",
"(",
"consumerWorkingQueueKey",
"(",
"consumer",
".",
"Queue",
".",
"Name",
",",
"consumer",
".",
"Name",
")",
")",
".",
"Val",
"(",
")",
"\n",
"}"
] | // GetUnackedLength returns the number of packages in the unacked queue | [
"GetUnackedLength",
"returns",
"the",
"number",
"of",
"packages",
"in",
"the",
"unacked",
"queue"
] | e2a56d9bb404cb0e47cc737fdc3fe1fd6c095743 | https://github.com/adjust/redismq/blob/e2a56d9bb404cb0e47cc737fdc3fe1fd6c095743/consumer.go#L118-L120 |
4,096 | adjust/redismq | consumer.go | GetFailed | func (consumer *Consumer) GetFailed() (*Package, error) {
answer := consumer.Queue.redisClient.RPopLPush(
queueFailedKey(consumer.Queue.Name),
consumerWorkingQueueKey(consumer.Queue.Name, consumer.Name),
)
consumer.Queue.incrRate(
consumerWorkingRateKey(consumer.Queue.Name, consumer.Name),
1,
)
return consumer.parseRedisAnswer(answer)
} | go | func (consumer *Consumer) GetFailed() (*Package, error) {
answer := consumer.Queue.redisClient.RPopLPush(
queueFailedKey(consumer.Queue.Name),
consumerWorkingQueueKey(consumer.Queue.Name, consumer.Name),
)
consumer.Queue.incrRate(
consumerWorkingRateKey(consumer.Queue.Name, consumer.Name),
1,
)
return consumer.parseRedisAnswer(answer)
} | [
"func",
"(",
"consumer",
"*",
"Consumer",
")",
"GetFailed",
"(",
")",
"(",
"*",
"Package",
",",
"error",
")",
"{",
"answer",
":=",
"consumer",
".",
"Queue",
".",
"redisClient",
".",
"RPopLPush",
"(",
"queueFailedKey",
"(",
"consumer",
".",
"Queue",
".",
"Name",
")",
",",
"consumerWorkingQueueKey",
"(",
"consumer",
".",
"Queue",
".",
"Name",
",",
"consumer",
".",
"Name",
")",
",",
")",
"\n",
"consumer",
".",
"Queue",
".",
"incrRate",
"(",
"consumerWorkingRateKey",
"(",
"consumer",
".",
"Queue",
".",
"Name",
",",
"consumer",
".",
"Name",
")",
",",
"1",
",",
")",
"\n",
"return",
"consumer",
".",
"parseRedisAnswer",
"(",
"answer",
")",
"\n",
"}"
] | // GetFailed returns a single packages from the failed queue of this consumer | [
"GetFailed",
"returns",
"a",
"single",
"packages",
"from",
"the",
"failed",
"queue",
"of",
"this",
"consumer"
] | e2a56d9bb404cb0e47cc737fdc3fe1fd6c095743 | https://github.com/adjust/redismq/blob/e2a56d9bb404cb0e47cc737fdc3fe1fd6c095743/consumer.go#L123-L133 |
4,097 | adjust/redismq | consumer.go | ResetWorking | func (consumer *Consumer) ResetWorking() error {
return consumer.Queue.redisClient.Del(consumerWorkingQueueKey(consumer.Queue.Name, consumer.Name)).Err()
} | go | func (consumer *Consumer) ResetWorking() error {
return consumer.Queue.redisClient.Del(consumerWorkingQueueKey(consumer.Queue.Name, consumer.Name)).Err()
} | [
"func",
"(",
"consumer",
"*",
"Consumer",
")",
"ResetWorking",
"(",
")",
"error",
"{",
"return",
"consumer",
".",
"Queue",
".",
"redisClient",
".",
"Del",
"(",
"consumerWorkingQueueKey",
"(",
"consumer",
".",
"Queue",
".",
"Name",
",",
"consumer",
".",
"Name",
")",
")",
".",
"Err",
"(",
")",
"\n",
"}"
] | // ResetWorking deletes! all messages in the working queue of this consumer | [
"ResetWorking",
"deletes!",
"all",
"messages",
"in",
"the",
"working",
"queue",
"of",
"this",
"consumer"
] | e2a56d9bb404cb0e47cc737fdc3fe1fd6c095743 | https://github.com/adjust/redismq/blob/e2a56d9bb404cb0e47cc737fdc3fe1fd6c095743/consumer.go#L136-L138 |
4,098 | adjust/redismq | consumer.go | RequeueWorking | func (consumer *Consumer) RequeueWorking() error {
for consumer.HasUnacked() {
p, err := consumer.GetUnacked()
if err != nil {
return err
}
p.Requeue()
}
return nil
} | go | func (consumer *Consumer) RequeueWorking() error {
for consumer.HasUnacked() {
p, err := consumer.GetUnacked()
if err != nil {
return err
}
p.Requeue()
}
return nil
} | [
"func",
"(",
"consumer",
"*",
"Consumer",
")",
"RequeueWorking",
"(",
")",
"error",
"{",
"for",
"consumer",
".",
"HasUnacked",
"(",
")",
"{",
"p",
",",
"err",
":=",
"consumer",
".",
"GetUnacked",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"p",
".",
"Requeue",
"(",
")",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] | // RequeueWorking requeues all packages from working to input | [
"RequeueWorking",
"requeues",
"all",
"packages",
"from",
"working",
"to",
"input"
] | e2a56d9bb404cb0e47cc737fdc3fe1fd6c095743 | https://github.com/adjust/redismq/blob/e2a56d9bb404cb0e47cc737fdc3fe1fd6c095743/consumer.go#L141-L150 |
4,099 | kennygrant/sanitize | sanitize.go | HTMLAllowing | func HTMLAllowing(s string, args ...[]string) (string, error) {
allowedTags := defaultTags
if len(args) > 0 {
allowedTags = args[0]
}
allowedAttributes := defaultAttributes
if len(args) > 1 {
allowedAttributes = args[1]
}
// Parse the html
tokenizer := parser.NewTokenizer(strings.NewReader(s))
buffer := bytes.NewBufferString("")
ignore := ""
for {
tokenType := tokenizer.Next()
token := tokenizer.Token()
switch tokenType {
case parser.ErrorToken:
err := tokenizer.Err()
if err == io.EOF {
return buffer.String(), nil
}
return "", err
case parser.StartTagToken:
if len(ignore) == 0 && includes(allowedTags, token.Data) {
token.Attr = cleanAttributes(token.Attr, allowedAttributes)
buffer.WriteString(token.String())
} else if includes(ignoreTags, token.Data) {
ignore = token.Data
}
case parser.SelfClosingTagToken:
if len(ignore) == 0 && includes(allowedTags, token.Data) {
token.Attr = cleanAttributes(token.Attr, allowedAttributes)
buffer.WriteString(token.String())
} else if token.Data == ignore {
ignore = ""
}
case parser.EndTagToken:
if len(ignore) == 0 && includes(allowedTags, token.Data) {
token.Attr = []parser.Attribute{}
buffer.WriteString(token.String())
} else if token.Data == ignore {
ignore = ""
}
case parser.TextToken:
// We allow text content through, unless ignoring this entire tag and its contents (including other tags)
if ignore == "" {
buffer.WriteString(token.String())
}
case parser.CommentToken:
// We ignore comments by default
case parser.DoctypeToken:
// We ignore doctypes by default - html5 does not require them and this is intended for sanitizing snippets of text
default:
// We ignore unknown token types by default
}
}
} | go | func HTMLAllowing(s string, args ...[]string) (string, error) {
allowedTags := defaultTags
if len(args) > 0 {
allowedTags = args[0]
}
allowedAttributes := defaultAttributes
if len(args) > 1 {
allowedAttributes = args[1]
}
// Parse the html
tokenizer := parser.NewTokenizer(strings.NewReader(s))
buffer := bytes.NewBufferString("")
ignore := ""
for {
tokenType := tokenizer.Next()
token := tokenizer.Token()
switch tokenType {
case parser.ErrorToken:
err := tokenizer.Err()
if err == io.EOF {
return buffer.String(), nil
}
return "", err
case parser.StartTagToken:
if len(ignore) == 0 && includes(allowedTags, token.Data) {
token.Attr = cleanAttributes(token.Attr, allowedAttributes)
buffer.WriteString(token.String())
} else if includes(ignoreTags, token.Data) {
ignore = token.Data
}
case parser.SelfClosingTagToken:
if len(ignore) == 0 && includes(allowedTags, token.Data) {
token.Attr = cleanAttributes(token.Attr, allowedAttributes)
buffer.WriteString(token.String())
} else if token.Data == ignore {
ignore = ""
}
case parser.EndTagToken:
if len(ignore) == 0 && includes(allowedTags, token.Data) {
token.Attr = []parser.Attribute{}
buffer.WriteString(token.String())
} else if token.Data == ignore {
ignore = ""
}
case parser.TextToken:
// We allow text content through, unless ignoring this entire tag and its contents (including other tags)
if ignore == "" {
buffer.WriteString(token.String())
}
case parser.CommentToken:
// We ignore comments by default
case parser.DoctypeToken:
// We ignore doctypes by default - html5 does not require them and this is intended for sanitizing snippets of text
default:
// We ignore unknown token types by default
}
}
} | [
"func",
"HTMLAllowing",
"(",
"s",
"string",
",",
"args",
"...",
"[",
"]",
"string",
")",
"(",
"string",
",",
"error",
")",
"{",
"allowedTags",
":=",
"defaultTags",
"\n",
"if",
"len",
"(",
"args",
")",
">",
"0",
"{",
"allowedTags",
"=",
"args",
"[",
"0",
"]",
"\n",
"}",
"\n",
"allowedAttributes",
":=",
"defaultAttributes",
"\n",
"if",
"len",
"(",
"args",
")",
">",
"1",
"{",
"allowedAttributes",
"=",
"args",
"[",
"1",
"]",
"\n",
"}",
"\n\n",
"// Parse the html",
"tokenizer",
":=",
"parser",
".",
"NewTokenizer",
"(",
"strings",
".",
"NewReader",
"(",
"s",
")",
")",
"\n\n",
"buffer",
":=",
"bytes",
".",
"NewBufferString",
"(",
"\"",
"\"",
")",
"\n",
"ignore",
":=",
"\"",
"\"",
"\n\n",
"for",
"{",
"tokenType",
":=",
"tokenizer",
".",
"Next",
"(",
")",
"\n",
"token",
":=",
"tokenizer",
".",
"Token",
"(",
")",
"\n\n",
"switch",
"tokenType",
"{",
"case",
"parser",
".",
"ErrorToken",
":",
"err",
":=",
"tokenizer",
".",
"Err",
"(",
")",
"\n",
"if",
"err",
"==",
"io",
".",
"EOF",
"{",
"return",
"buffer",
".",
"String",
"(",
")",
",",
"nil",
"\n",
"}",
"\n",
"return",
"\"",
"\"",
",",
"err",
"\n\n",
"case",
"parser",
".",
"StartTagToken",
":",
"if",
"len",
"(",
"ignore",
")",
"==",
"0",
"&&",
"includes",
"(",
"allowedTags",
",",
"token",
".",
"Data",
")",
"{",
"token",
".",
"Attr",
"=",
"cleanAttributes",
"(",
"token",
".",
"Attr",
",",
"allowedAttributes",
")",
"\n",
"buffer",
".",
"WriteString",
"(",
"token",
".",
"String",
"(",
")",
")",
"\n",
"}",
"else",
"if",
"includes",
"(",
"ignoreTags",
",",
"token",
".",
"Data",
")",
"{",
"ignore",
"=",
"token",
".",
"Data",
"\n",
"}",
"\n\n",
"case",
"parser",
".",
"SelfClosingTagToken",
":",
"if",
"len",
"(",
"ignore",
")",
"==",
"0",
"&&",
"includes",
"(",
"allowedTags",
",",
"token",
".",
"Data",
")",
"{",
"token",
".",
"Attr",
"=",
"cleanAttributes",
"(",
"token",
".",
"Attr",
",",
"allowedAttributes",
")",
"\n",
"buffer",
".",
"WriteString",
"(",
"token",
".",
"String",
"(",
")",
")",
"\n",
"}",
"else",
"if",
"token",
".",
"Data",
"==",
"ignore",
"{",
"ignore",
"=",
"\"",
"\"",
"\n",
"}",
"\n\n",
"case",
"parser",
".",
"EndTagToken",
":",
"if",
"len",
"(",
"ignore",
")",
"==",
"0",
"&&",
"includes",
"(",
"allowedTags",
",",
"token",
".",
"Data",
")",
"{",
"token",
".",
"Attr",
"=",
"[",
"]",
"parser",
".",
"Attribute",
"{",
"}",
"\n",
"buffer",
".",
"WriteString",
"(",
"token",
".",
"String",
"(",
")",
")",
"\n",
"}",
"else",
"if",
"token",
".",
"Data",
"==",
"ignore",
"{",
"ignore",
"=",
"\"",
"\"",
"\n",
"}",
"\n\n",
"case",
"parser",
".",
"TextToken",
":",
"// We allow text content through, unless ignoring this entire tag and its contents (including other tags)",
"if",
"ignore",
"==",
"\"",
"\"",
"{",
"buffer",
".",
"WriteString",
"(",
"token",
".",
"String",
"(",
")",
")",
"\n",
"}",
"\n",
"case",
"parser",
".",
"CommentToken",
":",
"// We ignore comments by default",
"case",
"parser",
".",
"DoctypeToken",
":",
"// We ignore doctypes by default - html5 does not require them and this is intended for sanitizing snippets of text",
"default",
":",
"// We ignore unknown token types by default",
"}",
"\n\n",
"}",
"\n\n",
"}"
] | // HTMLAllowing sanitizes html, allowing some tags.
// Arrays of allowed tags and allowed attributes may optionally be passed as the second and third arguments. | [
"HTMLAllowing",
"sanitizes",
"html",
"allowing",
"some",
"tags",
".",
"Arrays",
"of",
"allowed",
"tags",
"and",
"allowed",
"attributes",
"may",
"optionally",
"be",
"passed",
"as",
"the",
"second",
"and",
"third",
"arguments",
"."
] | 06ec0d0dbcd497d01e5189b16f5263f712e61a8e | https://github.com/kennygrant/sanitize/blob/06ec0d0dbcd497d01e5189b16f5263f712e61a8e/sanitize.go#L26-L98 |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.