id
int32 0
167k
| repo
stringlengths 5
54
| path
stringlengths 4
155
| func_name
stringlengths 1
118
| original_string
stringlengths 52
85.5k
| language
stringclasses 1
value | code
stringlengths 52
85.5k
| code_tokens
listlengths 21
1.41k
| docstring
stringlengths 6
2.61k
| docstring_tokens
listlengths 3
215
| sha
stringlengths 40
40
| url
stringlengths 85
252
|
---|---|---|---|---|---|---|---|---|---|---|---|
17,700 |
thriftrw/thriftrw-go
|
internal/semver/semver.go
|
preCmp
|
func preCmp(a, b string) int {
auint, auinterr := parseUint(a)
buint, buinterr := parseUint(b)
switch {
case auinterr == nil && buinterr == nil:
return uintCmp(auint, buint)
case auinterr == nil && buinterr != nil:
return -1
case auinterr != nil && buinterr == nil:
return +1
}
return strings.Compare(a, b)
}
|
go
|
func preCmp(a, b string) int {
auint, auinterr := parseUint(a)
buint, buinterr := parseUint(b)
switch {
case auinterr == nil && buinterr == nil:
return uintCmp(auint, buint)
case auinterr == nil && buinterr != nil:
return -1
case auinterr != nil && buinterr == nil:
return +1
}
return strings.Compare(a, b)
}
|
[
"func",
"preCmp",
"(",
"a",
",",
"b",
"string",
")",
"int",
"{",
"auint",
",",
"auinterr",
":=",
"parseUint",
"(",
"a",
")",
"\n",
"buint",
",",
"buinterr",
":=",
"parseUint",
"(",
"b",
")",
"\n",
"switch",
"{",
"case",
"auinterr",
"==",
"nil",
"&&",
"buinterr",
"==",
"nil",
":",
"return",
"uintCmp",
"(",
"auint",
",",
"buint",
")",
"\n",
"case",
"auinterr",
"==",
"nil",
"&&",
"buinterr",
"!=",
"nil",
":",
"return",
"-",
"1",
"\n",
"case",
"auinterr",
"!=",
"nil",
"&&",
"buinterr",
"==",
"nil",
":",
"return",
"+",
"1",
"\n",
"}",
"\n",
"return",
"strings",
".",
"Compare",
"(",
"a",
",",
"b",
")",
"\n",
"}"
] |
// preCmp compares the pre release items `a` and `b` following semver rules.
|
[
"preCmp",
"compares",
"the",
"pre",
"release",
"items",
"a",
"and",
"b",
"following",
"semver",
"rules",
"."
] |
a9a6ad793beab07cc3385954d2e8af8abfaa83e2
|
https://github.com/thriftrw/thriftrw-go/blob/a9a6ad793beab07cc3385954d2e8af8abfaa83e2/internal/semver/semver.go#L136-L148
|
17,701 |
thriftrw/thriftrw-go
|
plugin/api/plugin_handshake.go
|
MarshalLogObject
|
func (v *Plugin_Handshake_Result) MarshalLogObject(enc zapcore.ObjectEncoder) (err error) {
if v == nil {
return nil
}
if v.Success != nil {
err = multierr.Append(err, enc.AddObject("success", v.Success))
}
return err
}
|
go
|
func (v *Plugin_Handshake_Result) MarshalLogObject(enc zapcore.ObjectEncoder) (err error) {
if v == nil {
return nil
}
if v.Success != nil {
err = multierr.Append(err, enc.AddObject("success", v.Success))
}
return err
}
|
[
"func",
"(",
"v",
"*",
"Plugin_Handshake_Result",
")",
"MarshalLogObject",
"(",
"enc",
"zapcore",
".",
"ObjectEncoder",
")",
"(",
"err",
"error",
")",
"{",
"if",
"v",
"==",
"nil",
"{",
"return",
"nil",
"\n",
"}",
"\n",
"if",
"v",
".",
"Success",
"!=",
"nil",
"{",
"err",
"=",
"multierr",
".",
"Append",
"(",
"err",
",",
"enc",
".",
"AddObject",
"(",
"\"",
"\"",
",",
"v",
".",
"Success",
")",
")",
"\n",
"}",
"\n",
"return",
"err",
"\n",
"}"
] |
// MarshalLogObject implements zapcore.ObjectMarshaler, enabling
// fast logging of Plugin_Handshake_Result.
|
[
"MarshalLogObject",
"implements",
"zapcore",
".",
"ObjectMarshaler",
"enabling",
"fast",
"logging",
"of",
"Plugin_Handshake_Result",
"."
] |
a9a6ad793beab07cc3385954d2e8af8abfaa83e2
|
https://github.com/thriftrw/thriftrw-go/blob/a9a6ad793beab07cc3385954d2e8af8abfaa83e2/plugin/api/plugin_handshake.go#L411-L419
|
17,702 |
thriftrw/thriftrw-go
|
plugin/api/servicegenerator_generate.go
|
String
|
func (v *ServiceGenerator_Generate_Args) String() string {
if v == nil {
return "<nil>"
}
var fields [1]string
i := 0
if v.Request != nil {
fields[i] = fmt.Sprintf("Request: %v", v.Request)
i++
}
return fmt.Sprintf("ServiceGenerator_Generate_Args{%v}", strings.Join(fields[:i], ", "))
}
|
go
|
func (v *ServiceGenerator_Generate_Args) String() string {
if v == nil {
return "<nil>"
}
var fields [1]string
i := 0
if v.Request != nil {
fields[i] = fmt.Sprintf("Request: %v", v.Request)
i++
}
return fmt.Sprintf("ServiceGenerator_Generate_Args{%v}", strings.Join(fields[:i], ", "))
}
|
[
"func",
"(",
"v",
"*",
"ServiceGenerator_Generate_Args",
")",
"String",
"(",
")",
"string",
"{",
"if",
"v",
"==",
"nil",
"{",
"return",
"\"",
"\"",
"\n",
"}",
"\n\n",
"var",
"fields",
"[",
"1",
"]",
"string",
"\n",
"i",
":=",
"0",
"\n",
"if",
"v",
".",
"Request",
"!=",
"nil",
"{",
"fields",
"[",
"i",
"]",
"=",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"v",
".",
"Request",
")",
"\n",
"i",
"++",
"\n",
"}",
"\n\n",
"return",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"strings",
".",
"Join",
"(",
"fields",
"[",
":",
"i",
"]",
",",
"\"",
"\"",
")",
")",
"\n",
"}"
] |
// String returns a readable string representation of a ServiceGenerator_Generate_Args
// struct.
|
[
"String",
"returns",
"a",
"readable",
"string",
"representation",
"of",
"a",
"ServiceGenerator_Generate_Args",
"struct",
"."
] |
a9a6ad793beab07cc3385954d2e8af8abfaa83e2
|
https://github.com/thriftrw/thriftrw-go/blob/a9a6ad793beab07cc3385954d2e8af8abfaa83e2/plugin/api/servicegenerator_generate.go#L121-L134
|
17,703 |
thriftrw/thriftrw-go
|
plugin/api/servicegenerator_generate.go
|
Equals
|
func (v *ServiceGenerator_Generate_Args) Equals(rhs *ServiceGenerator_Generate_Args) bool {
if v == nil {
return rhs == nil
} else if rhs == nil {
return false
}
if !((v.Request == nil && rhs.Request == nil) || (v.Request != nil && rhs.Request != nil && v.Request.Equals(rhs.Request))) {
return false
}
return true
}
|
go
|
func (v *ServiceGenerator_Generate_Args) Equals(rhs *ServiceGenerator_Generate_Args) bool {
if v == nil {
return rhs == nil
} else if rhs == nil {
return false
}
if !((v.Request == nil && rhs.Request == nil) || (v.Request != nil && rhs.Request != nil && v.Request.Equals(rhs.Request))) {
return false
}
return true
}
|
[
"func",
"(",
"v",
"*",
"ServiceGenerator_Generate_Args",
")",
"Equals",
"(",
"rhs",
"*",
"ServiceGenerator_Generate_Args",
")",
"bool",
"{",
"if",
"v",
"==",
"nil",
"{",
"return",
"rhs",
"==",
"nil",
"\n",
"}",
"else",
"if",
"rhs",
"==",
"nil",
"{",
"return",
"false",
"\n",
"}",
"\n",
"if",
"!",
"(",
"(",
"v",
".",
"Request",
"==",
"nil",
"&&",
"rhs",
".",
"Request",
"==",
"nil",
")",
"||",
"(",
"v",
".",
"Request",
"!=",
"nil",
"&&",
"rhs",
".",
"Request",
"!=",
"nil",
"&&",
"v",
".",
"Request",
".",
"Equals",
"(",
"rhs",
".",
"Request",
")",
")",
")",
"{",
"return",
"false",
"\n",
"}",
"\n\n",
"return",
"true",
"\n",
"}"
] |
// Equals returns true if all the fields of this ServiceGenerator_Generate_Args match the
// provided ServiceGenerator_Generate_Args.
//
// This function performs a deep comparison.
|
[
"Equals",
"returns",
"true",
"if",
"all",
"the",
"fields",
"of",
"this",
"ServiceGenerator_Generate_Args",
"match",
"the",
"provided",
"ServiceGenerator_Generate_Args",
".",
"This",
"function",
"performs",
"a",
"deep",
"comparison",
"."
] |
a9a6ad793beab07cc3385954d2e8af8abfaa83e2
|
https://github.com/thriftrw/thriftrw-go/blob/a9a6ad793beab07cc3385954d2e8af8abfaa83e2/plugin/api/servicegenerator_generate.go#L140-L151
|
17,704 |
thriftrw/thriftrw-go
|
plugin/api/servicegenerator_generate.go
|
MarshalLogObject
|
func (v *ServiceGenerator_Generate_Args) MarshalLogObject(enc zapcore.ObjectEncoder) (err error) {
if v == nil {
return nil
}
if v.Request != nil {
err = multierr.Append(err, enc.AddObject("request", v.Request))
}
return err
}
|
go
|
func (v *ServiceGenerator_Generate_Args) MarshalLogObject(enc zapcore.ObjectEncoder) (err error) {
if v == nil {
return nil
}
if v.Request != nil {
err = multierr.Append(err, enc.AddObject("request", v.Request))
}
return err
}
|
[
"func",
"(",
"v",
"*",
"ServiceGenerator_Generate_Args",
")",
"MarshalLogObject",
"(",
"enc",
"zapcore",
".",
"ObjectEncoder",
")",
"(",
"err",
"error",
")",
"{",
"if",
"v",
"==",
"nil",
"{",
"return",
"nil",
"\n",
"}",
"\n",
"if",
"v",
".",
"Request",
"!=",
"nil",
"{",
"err",
"=",
"multierr",
".",
"Append",
"(",
"err",
",",
"enc",
".",
"AddObject",
"(",
"\"",
"\"",
",",
"v",
".",
"Request",
")",
")",
"\n",
"}",
"\n",
"return",
"err",
"\n",
"}"
] |
// MarshalLogObject implements zapcore.ObjectMarshaler, enabling
// fast logging of ServiceGenerator_Generate_Args.
|
[
"MarshalLogObject",
"implements",
"zapcore",
".",
"ObjectMarshaler",
"enabling",
"fast",
"logging",
"of",
"ServiceGenerator_Generate_Args",
"."
] |
a9a6ad793beab07cc3385954d2e8af8abfaa83e2
|
https://github.com/thriftrw/thriftrw-go/blob/a9a6ad793beab07cc3385954d2e8af8abfaa83e2/plugin/api/servicegenerator_generate.go#L155-L163
|
17,705 |
thriftrw/thriftrw-go
|
plugin/api/servicegenerator_generate.go
|
Equals
|
func (v *ServiceGenerator_Generate_Result) Equals(rhs *ServiceGenerator_Generate_Result) bool {
if v == nil {
return rhs == nil
} else if rhs == nil {
return false
}
if !((v.Success == nil && rhs.Success == nil) || (v.Success != nil && rhs.Success != nil && v.Success.Equals(rhs.Success))) {
return false
}
return true
}
|
go
|
func (v *ServiceGenerator_Generate_Result) Equals(rhs *ServiceGenerator_Generate_Result) bool {
if v == nil {
return rhs == nil
} else if rhs == nil {
return false
}
if !((v.Success == nil && rhs.Success == nil) || (v.Success != nil && rhs.Success != nil && v.Success.Equals(rhs.Success))) {
return false
}
return true
}
|
[
"func",
"(",
"v",
"*",
"ServiceGenerator_Generate_Result",
")",
"Equals",
"(",
"rhs",
"*",
"ServiceGenerator_Generate_Result",
")",
"bool",
"{",
"if",
"v",
"==",
"nil",
"{",
"return",
"rhs",
"==",
"nil",
"\n",
"}",
"else",
"if",
"rhs",
"==",
"nil",
"{",
"return",
"false",
"\n",
"}",
"\n",
"if",
"!",
"(",
"(",
"v",
".",
"Success",
"==",
"nil",
"&&",
"rhs",
".",
"Success",
"==",
"nil",
")",
"||",
"(",
"v",
".",
"Success",
"!=",
"nil",
"&&",
"rhs",
".",
"Success",
"!=",
"nil",
"&&",
"v",
".",
"Success",
".",
"Equals",
"(",
"rhs",
".",
"Success",
")",
")",
")",
"{",
"return",
"false",
"\n",
"}",
"\n\n",
"return",
"true",
"\n",
"}"
] |
// Equals returns true if all the fields of this ServiceGenerator_Generate_Result match the
// provided ServiceGenerator_Generate_Result.
//
// This function performs a deep comparison.
|
[
"Equals",
"returns",
"true",
"if",
"all",
"the",
"fields",
"of",
"this",
"ServiceGenerator_Generate_Result",
"match",
"the",
"provided",
"ServiceGenerator_Generate_Result",
".",
"This",
"function",
"performs",
"a",
"deep",
"comparison",
"."
] |
a9a6ad793beab07cc3385954d2e8af8abfaa83e2
|
https://github.com/thriftrw/thriftrw-go/blob/a9a6ad793beab07cc3385954d2e8af8abfaa83e2/plugin/api/servicegenerator_generate.go#L396-L407
|
17,706 |
thriftrw/thriftrw-go
|
ast/annotation.go
|
FormatAnnotations
|
func FormatAnnotations(anns []*Annotation) string {
if len(anns) == 0 {
return ""
}
as := make([]string, len(anns))
for i, ann := range anns {
as[i] = ann.String()
}
return "(" + strings.Join(as, ", ") + ")"
}
|
go
|
func FormatAnnotations(anns []*Annotation) string {
if len(anns) == 0 {
return ""
}
as := make([]string, len(anns))
for i, ann := range anns {
as[i] = ann.String()
}
return "(" + strings.Join(as, ", ") + ")"
}
|
[
"func",
"FormatAnnotations",
"(",
"anns",
"[",
"]",
"*",
"Annotation",
")",
"string",
"{",
"if",
"len",
"(",
"anns",
")",
"==",
"0",
"{",
"return",
"\"",
"\"",
"\n",
"}",
"\n\n",
"as",
":=",
"make",
"(",
"[",
"]",
"string",
",",
"len",
"(",
"anns",
")",
")",
"\n",
"for",
"i",
",",
"ann",
":=",
"range",
"anns",
"{",
"as",
"[",
"i",
"]",
"=",
"ann",
".",
"String",
"(",
")",
"\n",
"}",
"\n\n",
"return",
"\"",
"\"",
"+",
"strings",
".",
"Join",
"(",
"as",
",",
"\"",
"\"",
")",
"+",
"\"",
"\"",
"\n",
"}"
] |
// FormatAnnotations formats a collection of annotations into a string.
|
[
"FormatAnnotations",
"formats",
"a",
"collection",
"of",
"annotations",
"into",
"a",
"string",
"."
] |
a9a6ad793beab07cc3385954d2e8af8abfaa83e2
|
https://github.com/thriftrw/thriftrw-go/blob/a9a6ad793beab07cc3385954d2e8af8abfaa83e2/ast/annotation.go#L52-L63
|
17,707 |
thriftrw/thriftrw-go
|
gen/field.go
|
generateTags
|
func generateTags(f *compile.FieldSpec) (string, error) {
tags, err := structtag.Parse("") // no tags
if err != nil {
return "", fmt.Errorf("failed to parse tag: %v", err)
}
// Default to the field name or label as the name used in the JSON
// representation.
if err := tags.Set(compileJSONTag(f, entityLabel(f))); err != nil {
return "", fmt.Errorf("failed to set tag: %v", err)
}
// Process go.tags and overwrite JSON tag if specified in Thrift
// annotation.
if goAnnotation := f.Annotations[goTagKey]; goAnnotation != "" {
goTags, err := structtag.Parse(goAnnotation)
if err != nil {
return "", fmt.Errorf("failed to parse tags %q: %v", goAnnotation, err)
}
for _, t := range goTags.Tags() {
if t.Key == jsonTagKey {
t = compileJSONTag(f, t.Name, t.Options...)
}
if err := tags.Set(t); err != nil {
return "", fmt.Errorf("failed to set tag: %v", err)
}
}
}
return fmt.Sprintf("`%s`", tags.String()), nil
}
|
go
|
func generateTags(f *compile.FieldSpec) (string, error) {
tags, err := structtag.Parse("") // no tags
if err != nil {
return "", fmt.Errorf("failed to parse tag: %v", err)
}
// Default to the field name or label as the name used in the JSON
// representation.
if err := tags.Set(compileJSONTag(f, entityLabel(f))); err != nil {
return "", fmt.Errorf("failed to set tag: %v", err)
}
// Process go.tags and overwrite JSON tag if specified in Thrift
// annotation.
if goAnnotation := f.Annotations[goTagKey]; goAnnotation != "" {
goTags, err := structtag.Parse(goAnnotation)
if err != nil {
return "", fmt.Errorf("failed to parse tags %q: %v", goAnnotation, err)
}
for _, t := range goTags.Tags() {
if t.Key == jsonTagKey {
t = compileJSONTag(f, t.Name, t.Options...)
}
if err := tags.Set(t); err != nil {
return "", fmt.Errorf("failed to set tag: %v", err)
}
}
}
return fmt.Sprintf("`%s`", tags.String()), nil
}
|
[
"func",
"generateTags",
"(",
"f",
"*",
"compile",
".",
"FieldSpec",
")",
"(",
"string",
",",
"error",
")",
"{",
"tags",
",",
"err",
":=",
"structtag",
".",
"Parse",
"(",
"\"",
"\"",
")",
"// no tags",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\"",
"\"",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n\n",
"// Default to the field name or label as the name used in the JSON",
"// representation.",
"if",
"err",
":=",
"tags",
".",
"Set",
"(",
"compileJSONTag",
"(",
"f",
",",
"entityLabel",
"(",
"f",
")",
")",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"\"",
"\"",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n\n",
"// Process go.tags and overwrite JSON tag if specified in Thrift",
"// annotation.",
"if",
"goAnnotation",
":=",
"f",
".",
"Annotations",
"[",
"goTagKey",
"]",
";",
"goAnnotation",
"!=",
"\"",
"\"",
"{",
"goTags",
",",
"err",
":=",
"structtag",
".",
"Parse",
"(",
"goAnnotation",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\"",
"\"",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"goAnnotation",
",",
"err",
")",
"\n",
"}",
"\n\n",
"for",
"_",
",",
"t",
":=",
"range",
"goTags",
".",
"Tags",
"(",
")",
"{",
"if",
"t",
".",
"Key",
"==",
"jsonTagKey",
"{",
"t",
"=",
"compileJSONTag",
"(",
"f",
",",
"t",
".",
"Name",
",",
"t",
".",
"Options",
"...",
")",
"\n",
"}",
"\n",
"if",
"err",
":=",
"tags",
".",
"Set",
"(",
"t",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"\"",
"\"",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n\n",
"return",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"tags",
".",
"String",
"(",
")",
")",
",",
"nil",
"\n",
"}"
] |
// generateTags parses the annotation on the thrift field and creates the resulting go tag
|
[
"generateTags",
"parses",
"the",
"annotation",
"on",
"the",
"thrift",
"field",
"and",
"creates",
"the",
"resulting",
"go",
"tag"
] |
a9a6ad793beab07cc3385954d2e8af8abfaa83e2
|
https://github.com/thriftrw/thriftrw-go/blob/a9a6ad793beab07cc3385954d2e8af8abfaa83e2/gen/field.go#L125-L156
|
17,708 |
thriftrw/thriftrw-go
|
compile/scope.go
|
getIncludedScope
|
func getIncludedScope(scope Scope, name string) (Scope, error) {
included, err := scope.LookupInclude(name)
if err != nil {
return nil, unrecognizedModuleError{Name: name, Reason: err}
}
return included, nil
}
|
go
|
func getIncludedScope(scope Scope, name string) (Scope, error) {
included, err := scope.LookupInclude(name)
if err != nil {
return nil, unrecognizedModuleError{Name: name, Reason: err}
}
return included, nil
}
|
[
"func",
"getIncludedScope",
"(",
"scope",
"Scope",
",",
"name",
"string",
")",
"(",
"Scope",
",",
"error",
")",
"{",
"included",
",",
"err",
":=",
"scope",
".",
"LookupInclude",
"(",
"name",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"unrecognizedModuleError",
"{",
"Name",
":",
"name",
",",
"Reason",
":",
"err",
"}",
"\n",
"}",
"\n",
"return",
"included",
",",
"nil",
"\n",
"}"
] |
// getIncludedScope retrieves an included scope from the given scope.
|
[
"getIncludedScope",
"retrieves",
"an",
"included",
"scope",
"from",
"the",
"given",
"scope",
"."
] |
a9a6ad793beab07cc3385954d2e8af8abfaa83e2
|
https://github.com/thriftrw/thriftrw-go/blob/a9a6ad793beab07cc3385954d2e8af8abfaa83e2/compile/scope.go#L47-L53
|
17,709 |
thriftrw/thriftrw-go
|
gen/plugin.go
|
AddRootService
|
func (g *generateServiceBuilder) AddRootService(spec *compile.ServiceSpec) (api.ServiceID, error) {
id, err := g.addService(spec)
if err != nil {
return id, err
}
if _, alreadyAdded := g.rootServices[id]; !alreadyAdded {
g.RootServices = append(g.RootServices, id)
g.rootServices[id] = struct{}{}
}
return id, err
}
|
go
|
func (g *generateServiceBuilder) AddRootService(spec *compile.ServiceSpec) (api.ServiceID, error) {
id, err := g.addService(spec)
if err != nil {
return id, err
}
if _, alreadyAdded := g.rootServices[id]; !alreadyAdded {
g.RootServices = append(g.RootServices, id)
g.rootServices[id] = struct{}{}
}
return id, err
}
|
[
"func",
"(",
"g",
"*",
"generateServiceBuilder",
")",
"AddRootService",
"(",
"spec",
"*",
"compile",
".",
"ServiceSpec",
")",
"(",
"api",
".",
"ServiceID",
",",
"error",
")",
"{",
"id",
",",
"err",
":=",
"g",
".",
"addService",
"(",
"spec",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"id",
",",
"err",
"\n",
"}",
"\n\n",
"if",
"_",
",",
"alreadyAdded",
":=",
"g",
".",
"rootServices",
"[",
"id",
"]",
";",
"!",
"alreadyAdded",
"{",
"g",
".",
"RootServices",
"=",
"append",
"(",
"g",
".",
"RootServices",
",",
"id",
")",
"\n",
"g",
".",
"rootServices",
"[",
"id",
"]",
"=",
"struct",
"{",
"}",
"{",
"}",
"\n",
"}",
"\n\n",
"return",
"id",
",",
"err",
"\n",
"}"
] |
// AddRootService adds a service as a root service to this request.
|
[
"AddRootService",
"adds",
"a",
"service",
"as",
"a",
"root",
"service",
"to",
"this",
"request",
"."
] |
a9a6ad793beab07cc3385954d2e8af8abfaa83e2
|
https://github.com/thriftrw/thriftrw-go/blob/a9a6ad793beab07cc3385954d2e8af8abfaa83e2/gen/plugin.go#L74-L86
|
17,710 |
thriftrw/thriftrw-go
|
gen/plugin.go
|
addModule
|
func (g *generateServiceBuilder) addModule(thriftPath string) (api.ModuleID, error) {
if id, ok := g.moduleIDs[thriftPath]; ok {
return id, nil
}
id := g.nextModuleID
g.nextModuleID++
g.moduleIDs[thriftPath] = id
importPath, err := g.importer.Package(thriftPath)
if err != nil {
return 0, err
}
dir, err := g.importer.RelativePackage(thriftPath)
if err != nil {
return 0, err
}
g.Modules[id] = &api.Module{
ImportPath: importPath,
Directory: dir,
ThriftFilePath: thriftPath,
}
return id, nil
}
|
go
|
func (g *generateServiceBuilder) addModule(thriftPath string) (api.ModuleID, error) {
if id, ok := g.moduleIDs[thriftPath]; ok {
return id, nil
}
id := g.nextModuleID
g.nextModuleID++
g.moduleIDs[thriftPath] = id
importPath, err := g.importer.Package(thriftPath)
if err != nil {
return 0, err
}
dir, err := g.importer.RelativePackage(thriftPath)
if err != nil {
return 0, err
}
g.Modules[id] = &api.Module{
ImportPath: importPath,
Directory: dir,
ThriftFilePath: thriftPath,
}
return id, nil
}
|
[
"func",
"(",
"g",
"*",
"generateServiceBuilder",
")",
"addModule",
"(",
"thriftPath",
"string",
")",
"(",
"api",
".",
"ModuleID",
",",
"error",
")",
"{",
"if",
"id",
",",
"ok",
":=",
"g",
".",
"moduleIDs",
"[",
"thriftPath",
"]",
";",
"ok",
"{",
"return",
"id",
",",
"nil",
"\n",
"}",
"\n\n",
"id",
":=",
"g",
".",
"nextModuleID",
"\n",
"g",
".",
"nextModuleID",
"++",
"\n",
"g",
".",
"moduleIDs",
"[",
"thriftPath",
"]",
"=",
"id",
"\n\n",
"importPath",
",",
"err",
":=",
"g",
".",
"importer",
".",
"Package",
"(",
"thriftPath",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"0",
",",
"err",
"\n",
"}",
"\n\n",
"dir",
",",
"err",
":=",
"g",
".",
"importer",
".",
"RelativePackage",
"(",
"thriftPath",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"0",
",",
"err",
"\n",
"}",
"\n\n",
"g",
".",
"Modules",
"[",
"id",
"]",
"=",
"&",
"api",
".",
"Module",
"{",
"ImportPath",
":",
"importPath",
",",
"Directory",
":",
"dir",
",",
"ThriftFilePath",
":",
"thriftPath",
",",
"}",
"\n",
"return",
"id",
",",
"nil",
"\n",
"}"
] |
// addModule adds the module for the given Thrift file to the request.
|
[
"addModule",
"adds",
"the",
"module",
"for",
"the",
"given",
"Thrift",
"file",
"to",
"the",
"request",
"."
] |
a9a6ad793beab07cc3385954d2e8af8abfaa83e2
|
https://github.com/thriftrw/thriftrw-go/blob/a9a6ad793beab07cc3385954d2e8af8abfaa83e2/gen/plugin.go#L89-L114
|
17,711 |
thriftrw/thriftrw-go
|
internal/multiplex/client.go
|
NewClient
|
func NewClient(name string, c envelope.Client) envelope.Client {
return client{name: name, c: c}
}
|
go
|
func NewClient(name string, c envelope.Client) envelope.Client {
return client{name: name, c: c}
}
|
[
"func",
"NewClient",
"(",
"name",
"string",
",",
"c",
"envelope",
".",
"Client",
")",
"envelope",
".",
"Client",
"{",
"return",
"client",
"{",
"name",
":",
"name",
",",
"c",
":",
"c",
"}",
"\n",
"}"
] |
// NewClient builds a new multiplexing client.
//
// name is the name of the service for which requests are being sent through
// this client.
|
[
"NewClient",
"builds",
"a",
"new",
"multiplexing",
"client",
".",
"name",
"is",
"the",
"name",
"of",
"the",
"service",
"for",
"which",
"requests",
"are",
"being",
"sent",
"through",
"this",
"client",
"."
] |
a9a6ad793beab07cc3385954d2e8af8abfaa83e2
|
https://github.com/thriftrw/thriftrw-go/blob/a9a6ad793beab07cc3385954d2e8af8abfaa83e2/internal/multiplex/client.go#L32-L34
|
17,712 |
thriftrw/thriftrw-go
|
gen/namespace.go
|
NewNamespace
|
func NewNamespace() Namespace {
return &namespace{
taken: make(map[string]struct{}),
gave: make(map[string][]string),
}
}
|
go
|
func NewNamespace() Namespace {
return &namespace{
taken: make(map[string]struct{}),
gave: make(map[string][]string),
}
}
|
[
"func",
"NewNamespace",
"(",
")",
"Namespace",
"{",
"return",
"&",
"namespace",
"{",
"taken",
":",
"make",
"(",
"map",
"[",
"string",
"]",
"struct",
"{",
"}",
")",
",",
"gave",
":",
"make",
"(",
"map",
"[",
"string",
"]",
"[",
"]",
"string",
")",
",",
"}",
"\n",
"}"
] |
// NewNamespace creates a new namespace.
|
[
"NewNamespace",
"creates",
"a",
"new",
"namespace",
"."
] |
a9a6ad793beab07cc3385954d2e8af8abfaa83e2
|
https://github.com/thriftrw/thriftrw-go/blob/a9a6ad793beab07cc3385954d2e8af8abfaa83e2/gen/namespace.go#L74-L79
|
17,713 |
thriftrw/thriftrw-go
|
protocol/binary/reader.go
|
fixedWidth
|
func fixedWidth(t wire.Type) int64 {
switch t {
case wire.TBool:
return 1
case wire.TI8:
return 1
case wire.TDouble:
return 8
case wire.TI16:
return 2
case wire.TI32:
return 4
case wire.TI64:
return 8
default:
return -1
}
}
|
go
|
func fixedWidth(t wire.Type) int64 {
switch t {
case wire.TBool:
return 1
case wire.TI8:
return 1
case wire.TDouble:
return 8
case wire.TI16:
return 2
case wire.TI32:
return 4
case wire.TI64:
return 8
default:
return -1
}
}
|
[
"func",
"fixedWidth",
"(",
"t",
"wire",
".",
"Type",
")",
"int64",
"{",
"switch",
"t",
"{",
"case",
"wire",
".",
"TBool",
":",
"return",
"1",
"\n",
"case",
"wire",
".",
"TI8",
":",
"return",
"1",
"\n",
"case",
"wire",
".",
"TDouble",
":",
"return",
"8",
"\n",
"case",
"wire",
".",
"TI16",
":",
"return",
"2",
"\n",
"case",
"wire",
".",
"TI32",
":",
"return",
"4",
"\n",
"case",
"wire",
".",
"TI64",
":",
"return",
"8",
"\n",
"default",
":",
"return",
"-",
"1",
"\n",
"}",
"\n",
"}"
] |
// For the reader, we keep track of the read offset manually everywhere so
// that we can implement lazy collections without extra allocations
// fixedWidth returns the encoded size of a value of the given type. If the
// type's width depends on the value, -1 is returned.
|
[
"For",
"the",
"reader",
"we",
"keep",
"track",
"of",
"the",
"read",
"offset",
"manually",
"everywhere",
"so",
"that",
"we",
"can",
"implement",
"lazy",
"collections",
"without",
"extra",
"allocations",
"fixedWidth",
"returns",
"the",
"encoded",
"size",
"of",
"a",
"value",
"of",
"the",
"given",
"type",
".",
"If",
"the",
"type",
"s",
"width",
"depends",
"on",
"the",
"value",
"-",
"1",
"is",
"returned",
"."
] |
a9a6ad793beab07cc3385954d2e8af8abfaa83e2
|
https://github.com/thriftrw/thriftrw-go/blob/a9a6ad793beab07cc3385954d2e8af8abfaa83e2/protocol/binary/reader.go#L54-L71
|
17,714 |
thriftrw/thriftrw-go
|
protocol/binary/reader.go
|
copyN
|
func (br *Reader) copyN(w io.Writer, off int64, n int64) (int64, error) {
src := io.NewSectionReader(br.reader, off, n)
copied, err := io.CopyN(w, src, n)
off += copied
if err == io.EOF {
// All EOFs are unexpected for the decoder
err = io.ErrUnexpectedEOF
}
return off, err
}
|
go
|
func (br *Reader) copyN(w io.Writer, off int64, n int64) (int64, error) {
src := io.NewSectionReader(br.reader, off, n)
copied, err := io.CopyN(w, src, n)
off += copied
if err == io.EOF {
// All EOFs are unexpected for the decoder
err = io.ErrUnexpectedEOF
}
return off, err
}
|
[
"func",
"(",
"br",
"*",
"Reader",
")",
"copyN",
"(",
"w",
"io",
".",
"Writer",
",",
"off",
"int64",
",",
"n",
"int64",
")",
"(",
"int64",
",",
"error",
")",
"{",
"src",
":=",
"io",
".",
"NewSectionReader",
"(",
"br",
".",
"reader",
",",
"off",
",",
"n",
")",
"\n",
"copied",
",",
"err",
":=",
"io",
".",
"CopyN",
"(",
"w",
",",
"src",
",",
"n",
")",
"\n",
"off",
"+=",
"copied",
"\n",
"if",
"err",
"==",
"io",
".",
"EOF",
"{",
"// All EOFs are unexpected for the decoder",
"err",
"=",
"io",
".",
"ErrUnexpectedEOF",
"\n",
"}",
"\n",
"return",
"off",
",",
"err",
"\n",
"}"
] |
// copyN copies n bytes starting at offset off into the given Writer.
|
[
"copyN",
"copies",
"n",
"bytes",
"starting",
"at",
"offset",
"off",
"into",
"the",
"given",
"Writer",
"."
] |
a9a6ad793beab07cc3385954d2e8af8abfaa83e2
|
https://github.com/thriftrw/thriftrw-go/blob/a9a6ad793beab07cc3385954d2e8af8abfaa83e2/protocol/binary/reader.go#L211-L220
|
17,715 |
thriftrw/thriftrw-go
|
protocol/binary/reader.go
|
ReadValue
|
func (br *Reader) ReadValue(t wire.Type, off int64) (wire.Value, int64, error) {
switch t {
case wire.TBool:
b, off, err := br.readByte(off)
if err != nil {
return wire.Value{}, off, err
}
if b != 0 && b != 1 {
return wire.Value{}, off, decodeErrorf(
"invalid value %q for bool field", b,
)
}
return wire.NewValueBool(b == 1), off, nil
case wire.TI8:
b, off, err := br.readByte(off)
return wire.NewValueI8(int8(b)), off, err
case wire.TDouble:
value, off, err := br.readInt64(off)
d := math.Float64frombits(uint64(value))
return wire.NewValueDouble(d), off, err
case wire.TI16:
n, off, err := br.readInt16(off)
return wire.NewValueI16(n), off, err
case wire.TI32:
n, off, err := br.readInt32(off)
return wire.NewValueI32(n), off, err
case wire.TI64:
n, off, err := br.readInt64(off)
return wire.NewValueI64(n), off, err
case wire.TBinary:
v, off, err := br.readBytes(off)
return wire.NewValueBinary(v), off, err
case wire.TStruct:
s, off, err := br.readStruct(off)
return wire.NewValueStruct(s), off, err
case wire.TMap:
m, off, err := br.readMap(off)
return wire.NewValueMap(m), off, err
case wire.TSet:
s, off, err := br.readSet(off)
return wire.NewValueSet(s), off, err
case wire.TList:
l, off, err := br.readList(off)
return wire.NewValueList(l), off, err
default:
return wire.Value{}, off, decodeErrorf("unknown ttype %v", t)
}
}
|
go
|
func (br *Reader) ReadValue(t wire.Type, off int64) (wire.Value, int64, error) {
switch t {
case wire.TBool:
b, off, err := br.readByte(off)
if err != nil {
return wire.Value{}, off, err
}
if b != 0 && b != 1 {
return wire.Value{}, off, decodeErrorf(
"invalid value %q for bool field", b,
)
}
return wire.NewValueBool(b == 1), off, nil
case wire.TI8:
b, off, err := br.readByte(off)
return wire.NewValueI8(int8(b)), off, err
case wire.TDouble:
value, off, err := br.readInt64(off)
d := math.Float64frombits(uint64(value))
return wire.NewValueDouble(d), off, err
case wire.TI16:
n, off, err := br.readInt16(off)
return wire.NewValueI16(n), off, err
case wire.TI32:
n, off, err := br.readInt32(off)
return wire.NewValueI32(n), off, err
case wire.TI64:
n, off, err := br.readInt64(off)
return wire.NewValueI64(n), off, err
case wire.TBinary:
v, off, err := br.readBytes(off)
return wire.NewValueBinary(v), off, err
case wire.TStruct:
s, off, err := br.readStruct(off)
return wire.NewValueStruct(s), off, err
case wire.TMap:
m, off, err := br.readMap(off)
return wire.NewValueMap(m), off, err
case wire.TSet:
s, off, err := br.readSet(off)
return wire.NewValueSet(s), off, err
case wire.TList:
l, off, err := br.readList(off)
return wire.NewValueList(l), off, err
default:
return wire.Value{}, off, decodeErrorf("unknown ttype %v", t)
}
}
|
[
"func",
"(",
"br",
"*",
"Reader",
")",
"ReadValue",
"(",
"t",
"wire",
".",
"Type",
",",
"off",
"int64",
")",
"(",
"wire",
".",
"Value",
",",
"int64",
",",
"error",
")",
"{",
"switch",
"t",
"{",
"case",
"wire",
".",
"TBool",
":",
"b",
",",
"off",
",",
"err",
":=",
"br",
".",
"readByte",
"(",
"off",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"wire",
".",
"Value",
"{",
"}",
",",
"off",
",",
"err",
"\n",
"}",
"\n\n",
"if",
"b",
"!=",
"0",
"&&",
"b",
"!=",
"1",
"{",
"return",
"wire",
".",
"Value",
"{",
"}",
",",
"off",
",",
"decodeErrorf",
"(",
"\"",
"\"",
",",
"b",
",",
")",
"\n",
"}",
"\n\n",
"return",
"wire",
".",
"NewValueBool",
"(",
"b",
"==",
"1",
")",
",",
"off",
",",
"nil",
"\n\n",
"case",
"wire",
".",
"TI8",
":",
"b",
",",
"off",
",",
"err",
":=",
"br",
".",
"readByte",
"(",
"off",
")",
"\n",
"return",
"wire",
".",
"NewValueI8",
"(",
"int8",
"(",
"b",
")",
")",
",",
"off",
",",
"err",
"\n\n",
"case",
"wire",
".",
"TDouble",
":",
"value",
",",
"off",
",",
"err",
":=",
"br",
".",
"readInt64",
"(",
"off",
")",
"\n",
"d",
":=",
"math",
".",
"Float64frombits",
"(",
"uint64",
"(",
"value",
")",
")",
"\n",
"return",
"wire",
".",
"NewValueDouble",
"(",
"d",
")",
",",
"off",
",",
"err",
"\n\n",
"case",
"wire",
".",
"TI16",
":",
"n",
",",
"off",
",",
"err",
":=",
"br",
".",
"readInt16",
"(",
"off",
")",
"\n",
"return",
"wire",
".",
"NewValueI16",
"(",
"n",
")",
",",
"off",
",",
"err",
"\n\n",
"case",
"wire",
".",
"TI32",
":",
"n",
",",
"off",
",",
"err",
":=",
"br",
".",
"readInt32",
"(",
"off",
")",
"\n",
"return",
"wire",
".",
"NewValueI32",
"(",
"n",
")",
",",
"off",
",",
"err",
"\n\n",
"case",
"wire",
".",
"TI64",
":",
"n",
",",
"off",
",",
"err",
":=",
"br",
".",
"readInt64",
"(",
"off",
")",
"\n",
"return",
"wire",
".",
"NewValueI64",
"(",
"n",
")",
",",
"off",
",",
"err",
"\n\n",
"case",
"wire",
".",
"TBinary",
":",
"v",
",",
"off",
",",
"err",
":=",
"br",
".",
"readBytes",
"(",
"off",
")",
"\n",
"return",
"wire",
".",
"NewValueBinary",
"(",
"v",
")",
",",
"off",
",",
"err",
"\n\n",
"case",
"wire",
".",
"TStruct",
":",
"s",
",",
"off",
",",
"err",
":=",
"br",
".",
"readStruct",
"(",
"off",
")",
"\n",
"return",
"wire",
".",
"NewValueStruct",
"(",
"s",
")",
",",
"off",
",",
"err",
"\n\n",
"case",
"wire",
".",
"TMap",
":",
"m",
",",
"off",
",",
"err",
":=",
"br",
".",
"readMap",
"(",
"off",
")",
"\n",
"return",
"wire",
".",
"NewValueMap",
"(",
"m",
")",
",",
"off",
",",
"err",
"\n\n",
"case",
"wire",
".",
"TSet",
":",
"s",
",",
"off",
",",
"err",
":=",
"br",
".",
"readSet",
"(",
"off",
")",
"\n",
"return",
"wire",
".",
"NewValueSet",
"(",
"s",
")",
",",
"off",
",",
"err",
"\n\n",
"case",
"wire",
".",
"TList",
":",
"l",
",",
"off",
",",
"err",
":=",
"br",
".",
"readList",
"(",
"off",
")",
"\n",
"return",
"wire",
".",
"NewValueList",
"(",
"l",
")",
",",
"off",
",",
"err",
"\n\n",
"default",
":",
"return",
"wire",
".",
"Value",
"{",
"}",
",",
"off",
",",
"decodeErrorf",
"(",
"\"",
"\"",
",",
"t",
")",
"\n",
"}",
"\n",
"}"
] |
// ReadValue reads a value off the given type off the wire starting at the
// given offset.
//
// Returns the Value, the new offset, and an error if there was a decode error.
|
[
"ReadValue",
"reads",
"a",
"value",
"off",
"the",
"given",
"type",
"off",
"the",
"wire",
"starting",
"at",
"the",
"given",
"offset",
".",
"Returns",
"the",
"Value",
"the",
"new",
"offset",
"and",
"an",
"error",
"if",
"there",
"was",
"a",
"decode",
"error",
"."
] |
a9a6ad793beab07cc3385954d2e8af8abfaa83e2
|
https://github.com/thriftrw/thriftrw-go/blob/a9a6ad793beab07cc3385954d2e8af8abfaa83e2/protocol/binary/reader.go#L425-L485
|
17,716 |
thriftrw/thriftrw-go
|
internal/goast/package.go
|
DeterminePackageName
|
func DeterminePackageName(importPath string) string {
packageName := filepath.Base(importPath)
if strings.HasSuffix(packageName, "-go") {
packageName = packageName[:len(packageName)-3]
}
return strings.Map(func(c rune) rune {
switch {
case unicode.IsLetter(c), unicode.IsDigit(c):
return c
default:
return '_'
}
}, packageName)
}
|
go
|
func DeterminePackageName(importPath string) string {
packageName := filepath.Base(importPath)
if strings.HasSuffix(packageName, "-go") {
packageName = packageName[:len(packageName)-3]
}
return strings.Map(func(c rune) rune {
switch {
case unicode.IsLetter(c), unicode.IsDigit(c):
return c
default:
return '_'
}
}, packageName)
}
|
[
"func",
"DeterminePackageName",
"(",
"importPath",
"string",
")",
"string",
"{",
"packageName",
":=",
"filepath",
".",
"Base",
"(",
"importPath",
")",
"\n",
"if",
"strings",
".",
"HasSuffix",
"(",
"packageName",
",",
"\"",
"\"",
")",
"{",
"packageName",
"=",
"packageName",
"[",
":",
"len",
"(",
"packageName",
")",
"-",
"3",
"]",
"\n",
"}",
"\n\n",
"return",
"strings",
".",
"Map",
"(",
"func",
"(",
"c",
"rune",
")",
"rune",
"{",
"switch",
"{",
"case",
"unicode",
".",
"IsLetter",
"(",
"c",
")",
",",
"unicode",
".",
"IsDigit",
"(",
"c",
")",
":",
"return",
"c",
"\n",
"default",
":",
"return",
"'_'",
"\n",
"}",
"\n",
"}",
",",
"packageName",
")",
"\n",
"}"
] |
// DeterminePackageName determines the name of the package at the given import
// path.
|
[
"DeterminePackageName",
"determines",
"the",
"name",
"of",
"the",
"package",
"at",
"the",
"given",
"import",
"path",
"."
] |
a9a6ad793beab07cc3385954d2e8af8abfaa83e2
|
https://github.com/thriftrw/thriftrw-go/blob/a9a6ad793beab07cc3385954d2e8af8abfaa83e2/internal/goast/package.go#L31-L45
|
17,717 |
thriftrw/thriftrw-go
|
compile/enum.go
|
compileEnum
|
func compileEnum(file string, src *ast.Enum) (*EnumSpec, error) {
enumNS := newNamespace(caseInsensitive)
prev := -1
var items []EnumItem
for _, astItem := range src.Items {
if err := enumNS.claim(astItem.Name, astItem.Line); err != nil {
return nil, compileError{
Target: src.Name + "." + astItem.Name,
Line: astItem.Line,
Reason: err,
}
}
value := prev + 1
if astItem.Value != nil {
value = *astItem.Value
}
prev = value
itemAnnotations, err := compileAnnotations(astItem.Annotations)
if err != nil {
return nil, compileError{
Target: src.Name + "." + astItem.Name,
Line: astItem.Line,
Reason: err,
}
}
// TODO bounds check for value
item := EnumItem{
Name: astItem.Name,
Value: int32(value),
Doc: astItem.Doc,
Annotations: itemAnnotations,
}
items = append(items, item)
}
annotations, err := compileAnnotations(src.Annotations)
if err != nil {
return nil, compileError{
Target: src.Name,
Line: src.Line,
Reason: err,
}
}
return &EnumSpec{
Name: src.Name,
File: file,
Doc: src.Doc,
Items: items,
Annotations: annotations,
}, nil
}
|
go
|
func compileEnum(file string, src *ast.Enum) (*EnumSpec, error) {
enumNS := newNamespace(caseInsensitive)
prev := -1
var items []EnumItem
for _, astItem := range src.Items {
if err := enumNS.claim(astItem.Name, astItem.Line); err != nil {
return nil, compileError{
Target: src.Name + "." + astItem.Name,
Line: astItem.Line,
Reason: err,
}
}
value := prev + 1
if astItem.Value != nil {
value = *astItem.Value
}
prev = value
itemAnnotations, err := compileAnnotations(astItem.Annotations)
if err != nil {
return nil, compileError{
Target: src.Name + "." + astItem.Name,
Line: astItem.Line,
Reason: err,
}
}
// TODO bounds check for value
item := EnumItem{
Name: astItem.Name,
Value: int32(value),
Doc: astItem.Doc,
Annotations: itemAnnotations,
}
items = append(items, item)
}
annotations, err := compileAnnotations(src.Annotations)
if err != nil {
return nil, compileError{
Target: src.Name,
Line: src.Line,
Reason: err,
}
}
return &EnumSpec{
Name: src.Name,
File: file,
Doc: src.Doc,
Items: items,
Annotations: annotations,
}, nil
}
|
[
"func",
"compileEnum",
"(",
"file",
"string",
",",
"src",
"*",
"ast",
".",
"Enum",
")",
"(",
"*",
"EnumSpec",
",",
"error",
")",
"{",
"enumNS",
":=",
"newNamespace",
"(",
"caseInsensitive",
")",
"\n",
"prev",
":=",
"-",
"1",
"\n\n",
"var",
"items",
"[",
"]",
"EnumItem",
"\n",
"for",
"_",
",",
"astItem",
":=",
"range",
"src",
".",
"Items",
"{",
"if",
"err",
":=",
"enumNS",
".",
"claim",
"(",
"astItem",
".",
"Name",
",",
"astItem",
".",
"Line",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"compileError",
"{",
"Target",
":",
"src",
".",
"Name",
"+",
"\"",
"\"",
"+",
"astItem",
".",
"Name",
",",
"Line",
":",
"astItem",
".",
"Line",
",",
"Reason",
":",
"err",
",",
"}",
"\n",
"}",
"\n",
"value",
":=",
"prev",
"+",
"1",
"\n",
"if",
"astItem",
".",
"Value",
"!=",
"nil",
"{",
"value",
"=",
"*",
"astItem",
".",
"Value",
"\n",
"}",
"\n",
"prev",
"=",
"value",
"\n\n",
"itemAnnotations",
",",
"err",
":=",
"compileAnnotations",
"(",
"astItem",
".",
"Annotations",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"compileError",
"{",
"Target",
":",
"src",
".",
"Name",
"+",
"\"",
"\"",
"+",
"astItem",
".",
"Name",
",",
"Line",
":",
"astItem",
".",
"Line",
",",
"Reason",
":",
"err",
",",
"}",
"\n",
"}",
"\n",
"// TODO bounds check for value",
"item",
":=",
"EnumItem",
"{",
"Name",
":",
"astItem",
".",
"Name",
",",
"Value",
":",
"int32",
"(",
"value",
")",
",",
"Doc",
":",
"astItem",
".",
"Doc",
",",
"Annotations",
":",
"itemAnnotations",
",",
"}",
"\n",
"items",
"=",
"append",
"(",
"items",
",",
"item",
")",
"\n",
"}",
"\n\n",
"annotations",
",",
"err",
":=",
"compileAnnotations",
"(",
"src",
".",
"Annotations",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"compileError",
"{",
"Target",
":",
"src",
".",
"Name",
",",
"Line",
":",
"src",
".",
"Line",
",",
"Reason",
":",
"err",
",",
"}",
"\n",
"}",
"\n",
"return",
"&",
"EnumSpec",
"{",
"Name",
":",
"src",
".",
"Name",
",",
"File",
":",
"file",
",",
"Doc",
":",
"src",
".",
"Doc",
",",
"Items",
":",
"items",
",",
"Annotations",
":",
"annotations",
",",
"}",
",",
"nil",
"\n",
"}"
] |
// compileEnum compiles the given Enum AST into an EnumSpec.
|
[
"compileEnum",
"compiles",
"the",
"given",
"Enum",
"AST",
"into",
"an",
"EnumSpec",
"."
] |
a9a6ad793beab07cc3385954d2e8af8abfaa83e2
|
https://github.com/thriftrw/thriftrw-go/blob/a9a6ad793beab07cc3385954d2e8af8abfaa83e2/compile/enum.go#L46-L98
|
17,718 |
thriftrw/thriftrw-go
|
compile/enum.go
|
LookupItem
|
func (e *EnumSpec) LookupItem(name string) (*EnumItem, bool) {
for _, item := range e.Items {
if item.Name == name {
return &item, true
}
}
return nil, false
}
|
go
|
func (e *EnumSpec) LookupItem(name string) (*EnumItem, bool) {
for _, item := range e.Items {
if item.Name == name {
return &item, true
}
}
return nil, false
}
|
[
"func",
"(",
"e",
"*",
"EnumSpec",
")",
"LookupItem",
"(",
"name",
"string",
")",
"(",
"*",
"EnumItem",
",",
"bool",
")",
"{",
"for",
"_",
",",
"item",
":=",
"range",
"e",
".",
"Items",
"{",
"if",
"item",
".",
"Name",
"==",
"name",
"{",
"return",
"&",
"item",
",",
"true",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"nil",
",",
"false",
"\n",
"}"
] |
// LookupItem retrieves the item with the given name from the enum.
//
// Returns true or false indicating whether the result is valid or not.
|
[
"LookupItem",
"retrieves",
"the",
"item",
"with",
"the",
"given",
"name",
"from",
"the",
"enum",
".",
"Returns",
"true",
"or",
"false",
"indicating",
"whether",
"the",
"result",
"is",
"valid",
"or",
"not",
"."
] |
a9a6ad793beab07cc3385954d2e8af8abfaa83e2
|
https://github.com/thriftrw/thriftrw-go/blob/a9a6ad793beab07cc3385954d2e8af8abfaa83e2/compile/enum.go#L103-L110
|
17,719 |
thriftrw/thriftrw-go
|
compile/primitive.go
|
compileBaseType
|
func compileBaseType(t ast.BaseType) (TypeSpec, error) {
annots, err := compileAnnotations(t.Annotations)
if err != nil {
return nil, err
}
switch t.ID {
case ast.BoolTypeID:
return &BoolSpec{Annotations: annots}, nil
case ast.I8TypeID:
return &I8Spec{Annotations: annots}, nil
case ast.I16TypeID:
return &I16Spec{Annotations: annots}, nil
case ast.I32TypeID:
return &I32Spec{Annotations: annots}, nil
case ast.I64TypeID:
return &I64Spec{Annotations: annots}, nil
case ast.DoubleTypeID:
return &DoubleSpec{Annotations: annots}, nil
case ast.StringTypeID:
return &StringSpec{Annotations: annots}, nil
case ast.BinaryTypeID:
return &BinarySpec{Annotations: annots}, nil
default:
panic(fmt.Sprintf("unknown base type %v", t))
}
}
|
go
|
func compileBaseType(t ast.BaseType) (TypeSpec, error) {
annots, err := compileAnnotations(t.Annotations)
if err != nil {
return nil, err
}
switch t.ID {
case ast.BoolTypeID:
return &BoolSpec{Annotations: annots}, nil
case ast.I8TypeID:
return &I8Spec{Annotations: annots}, nil
case ast.I16TypeID:
return &I16Spec{Annotations: annots}, nil
case ast.I32TypeID:
return &I32Spec{Annotations: annots}, nil
case ast.I64TypeID:
return &I64Spec{Annotations: annots}, nil
case ast.DoubleTypeID:
return &DoubleSpec{Annotations: annots}, nil
case ast.StringTypeID:
return &StringSpec{Annotations: annots}, nil
case ast.BinaryTypeID:
return &BinarySpec{Annotations: annots}, nil
default:
panic(fmt.Sprintf("unknown base type %v", t))
}
}
|
[
"func",
"compileBaseType",
"(",
"t",
"ast",
".",
"BaseType",
")",
"(",
"TypeSpec",
",",
"error",
")",
"{",
"annots",
",",
"err",
":=",
"compileAnnotations",
"(",
"t",
".",
"Annotations",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"switch",
"t",
".",
"ID",
"{",
"case",
"ast",
".",
"BoolTypeID",
":",
"return",
"&",
"BoolSpec",
"{",
"Annotations",
":",
"annots",
"}",
",",
"nil",
"\n",
"case",
"ast",
".",
"I8TypeID",
":",
"return",
"&",
"I8Spec",
"{",
"Annotations",
":",
"annots",
"}",
",",
"nil",
"\n",
"case",
"ast",
".",
"I16TypeID",
":",
"return",
"&",
"I16Spec",
"{",
"Annotations",
":",
"annots",
"}",
",",
"nil",
"\n",
"case",
"ast",
".",
"I32TypeID",
":",
"return",
"&",
"I32Spec",
"{",
"Annotations",
":",
"annots",
"}",
",",
"nil",
"\n",
"case",
"ast",
".",
"I64TypeID",
":",
"return",
"&",
"I64Spec",
"{",
"Annotations",
":",
"annots",
"}",
",",
"nil",
"\n",
"case",
"ast",
".",
"DoubleTypeID",
":",
"return",
"&",
"DoubleSpec",
"{",
"Annotations",
":",
"annots",
"}",
",",
"nil",
"\n",
"case",
"ast",
".",
"StringTypeID",
":",
"return",
"&",
"StringSpec",
"{",
"Annotations",
":",
"annots",
"}",
",",
"nil",
"\n",
"case",
"ast",
".",
"BinaryTypeID",
":",
"return",
"&",
"BinarySpec",
"{",
"Annotations",
":",
"annots",
"}",
",",
"nil",
"\n",
"default",
":",
"panic",
"(",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"t",
")",
")",
"\n",
"}",
"\n",
"}"
] |
// compileBaseType compiles a base type reference in the AST to a primitive
// TypeSpec.
|
[
"compileBaseType",
"compiles",
"a",
"base",
"type",
"reference",
"in",
"the",
"AST",
"to",
"a",
"primitive",
"TypeSpec",
"."
] |
a9a6ad793beab07cc3385954d2e8af8abfaa83e2
|
https://github.com/thriftrw/thriftrw-go/blob/a9a6ad793beab07cc3385954d2e8af8abfaa83e2/compile/primitive.go#L127-L153
|
17,720 |
thriftrw/thriftrw-go
|
internal/multiplex/handler.go
|
Put
|
func (h Handler) Put(name string, service envelope.Handler) {
h.services[name] = service
}
|
go
|
func (h Handler) Put(name string, service envelope.Handler) {
h.services[name] = service
}
|
[
"func",
"(",
"h",
"Handler",
")",
"Put",
"(",
"name",
"string",
",",
"service",
"envelope",
".",
"Handler",
")",
"{",
"h",
".",
"services",
"[",
"name",
"]",
"=",
"service",
"\n",
"}"
] |
// Put adds the given service to the multiplexer.
|
[
"Put",
"adds",
"the",
"given",
"service",
"to",
"the",
"multiplexer",
"."
] |
a9a6ad793beab07cc3385954d2e8af8abfaa83e2
|
https://github.com/thriftrw/thriftrw-go/blob/a9a6ad793beab07cc3385954d2e8af8abfaa83e2/internal/multiplex/handler.go#L41-L43
|
17,721 |
thriftrw/thriftrw-go
|
internal/multiplex/handler.go
|
Handle
|
func (h Handler) Handle(name string, req wire.Value) (wire.Value, error) {
parts := strings.SplitN(name, ":", 2)
if len(parts) < 2 {
return wire.Value{}, envelope.ErrUnknownMethod(name)
}
service, ok := h.services[parts[0]]
if !ok {
return wire.Value{}, envelope.ErrUnknownMethod(name)
}
name = parts[1]
return service.Handle(name, req)
}
|
go
|
func (h Handler) Handle(name string, req wire.Value) (wire.Value, error) {
parts := strings.SplitN(name, ":", 2)
if len(parts) < 2 {
return wire.Value{}, envelope.ErrUnknownMethod(name)
}
service, ok := h.services[parts[0]]
if !ok {
return wire.Value{}, envelope.ErrUnknownMethod(name)
}
name = parts[1]
return service.Handle(name, req)
}
|
[
"func",
"(",
"h",
"Handler",
")",
"Handle",
"(",
"name",
"string",
",",
"req",
"wire",
".",
"Value",
")",
"(",
"wire",
".",
"Value",
",",
"error",
")",
"{",
"parts",
":=",
"strings",
".",
"SplitN",
"(",
"name",
",",
"\"",
"\"",
",",
"2",
")",
"\n",
"if",
"len",
"(",
"parts",
")",
"<",
"2",
"{",
"return",
"wire",
".",
"Value",
"{",
"}",
",",
"envelope",
".",
"ErrUnknownMethod",
"(",
"name",
")",
"\n",
"}",
"\n\n",
"service",
",",
"ok",
":=",
"h",
".",
"services",
"[",
"parts",
"[",
"0",
"]",
"]",
"\n",
"if",
"!",
"ok",
"{",
"return",
"wire",
".",
"Value",
"{",
"}",
",",
"envelope",
".",
"ErrUnknownMethod",
"(",
"name",
")",
"\n",
"}",
"\n\n",
"name",
"=",
"parts",
"[",
"1",
"]",
"\n",
"return",
"service",
".",
"Handle",
"(",
"name",
",",
"req",
")",
"\n",
"}"
] |
// Handle handles the given request, dispatching to one of the
// registered services.
|
[
"Handle",
"handles",
"the",
"given",
"request",
"dispatching",
"to",
"one",
"of",
"the",
"registered",
"services",
"."
] |
a9a6ad793beab07cc3385954d2e8af8abfaa83e2
|
https://github.com/thriftrw/thriftrw-go/blob/a9a6ad793beab07cc3385954d2e8af8abfaa83e2/internal/multiplex/handler.go#L47-L60
|
17,722 |
thriftrw/thriftrw-go
|
plugin/api/plugin_handler.go
|
Handle
|
func (h PluginHandler) Handle(name string, reqValue wire.Value) (wire.Value, error) {
switch name {
case "goodbye":
var args Plugin_Goodbye_Args
if err := args.FromWire(reqValue); err != nil {
return wire.Value{}, err
}
result, err := Plugin_Goodbye_Helper.WrapResponse(
h.impl.Goodbye(),
)
if err != nil {
return wire.Value{}, err
}
return result.ToWire()
case "handshake":
var args Plugin_Handshake_Args
if err := args.FromWire(reqValue); err != nil {
return wire.Value{}, err
}
result, err := Plugin_Handshake_Helper.WrapResponse(
h.impl.Handshake(args.Request),
)
if err != nil {
return wire.Value{}, err
}
return result.ToWire()
default:
return wire.Value{}, envelope.ErrUnknownMethod(name)
}
}
|
go
|
func (h PluginHandler) Handle(name string, reqValue wire.Value) (wire.Value, error) {
switch name {
case "goodbye":
var args Plugin_Goodbye_Args
if err := args.FromWire(reqValue); err != nil {
return wire.Value{}, err
}
result, err := Plugin_Goodbye_Helper.WrapResponse(
h.impl.Goodbye(),
)
if err != nil {
return wire.Value{}, err
}
return result.ToWire()
case "handshake":
var args Plugin_Handshake_Args
if err := args.FromWire(reqValue); err != nil {
return wire.Value{}, err
}
result, err := Plugin_Handshake_Helper.WrapResponse(
h.impl.Handshake(args.Request),
)
if err != nil {
return wire.Value{}, err
}
return result.ToWire()
default:
return wire.Value{}, envelope.ErrUnknownMethod(name)
}
}
|
[
"func",
"(",
"h",
"PluginHandler",
")",
"Handle",
"(",
"name",
"string",
",",
"reqValue",
"wire",
".",
"Value",
")",
"(",
"wire",
".",
"Value",
",",
"error",
")",
"{",
"switch",
"name",
"{",
"case",
"\"",
"\"",
":",
"var",
"args",
"Plugin_Goodbye_Args",
"\n",
"if",
"err",
":=",
"args",
".",
"FromWire",
"(",
"reqValue",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"wire",
".",
"Value",
"{",
"}",
",",
"err",
"\n",
"}",
"\n\n",
"result",
",",
"err",
":=",
"Plugin_Goodbye_Helper",
".",
"WrapResponse",
"(",
"h",
".",
"impl",
".",
"Goodbye",
"(",
")",
",",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"wire",
".",
"Value",
"{",
"}",
",",
"err",
"\n",
"}",
"\n\n",
"return",
"result",
".",
"ToWire",
"(",
")",
"\n\n",
"case",
"\"",
"\"",
":",
"var",
"args",
"Plugin_Handshake_Args",
"\n",
"if",
"err",
":=",
"args",
".",
"FromWire",
"(",
"reqValue",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"wire",
".",
"Value",
"{",
"}",
",",
"err",
"\n",
"}",
"\n\n",
"result",
",",
"err",
":=",
"Plugin_Handshake_Helper",
".",
"WrapResponse",
"(",
"h",
".",
"impl",
".",
"Handshake",
"(",
"args",
".",
"Request",
")",
",",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"wire",
".",
"Value",
"{",
"}",
",",
"err",
"\n",
"}",
"\n\n",
"return",
"result",
".",
"ToWire",
"(",
")",
"\n\n",
"default",
":",
"return",
"wire",
".",
"Value",
"{",
"}",
",",
"envelope",
".",
"ErrUnknownMethod",
"(",
"name",
")",
"\n\n",
"}",
"\n",
"}"
] |
// Handle receives and handles a request for the Plugin service.
|
[
"Handle",
"receives",
"and",
"handles",
"a",
"request",
"for",
"the",
"Plugin",
"service",
"."
] |
a9a6ad793beab07cc3385954d2e8af8abfaa83e2
|
https://github.com/thriftrw/thriftrw-go/blob/a9a6ad793beab07cc3385954d2e8af8abfaa83e2/plugin/api/plugin_handler.go#L44-L84
|
17,723 |
thriftrw/thriftrw-go
|
idl/internal/quote.go
|
swapQuotes
|
func swapQuotes(in []byte) []byte {
// s/'/"/g, s/"/'/g
out := make([]byte, len(in))
for i, c := range in {
if c == '"' {
c = '\''
} else if c == '\'' {
c = '"'
}
out[i] = c
}
return out
}
|
go
|
func swapQuotes(in []byte) []byte {
// s/'/"/g, s/"/'/g
out := make([]byte, len(in))
for i, c := range in {
if c == '"' {
c = '\''
} else if c == '\'' {
c = '"'
}
out[i] = c
}
return out
}
|
[
"func",
"swapQuotes",
"(",
"in",
"[",
"]",
"byte",
")",
"[",
"]",
"byte",
"{",
"// s/'/\"/g, s/\"/'/g",
"out",
":=",
"make",
"(",
"[",
"]",
"byte",
",",
"len",
"(",
"in",
")",
")",
"\n",
"for",
"i",
",",
"c",
":=",
"range",
"in",
"{",
"if",
"c",
"==",
"'\"'",
"{",
"c",
"=",
"'\\''",
"\n",
"}",
"else",
"if",
"c",
"==",
"'\\''",
"{",
"c",
"=",
"'\"'",
"\n",
"}",
"\n",
"out",
"[",
"i",
"]",
"=",
"c",
"\n",
"}",
"\n",
"return",
"out",
"\n",
"}"
] |
// swapQuotes replaces all single quotes with double quotes and all double
// quotes with single quotes.
|
[
"swapQuotes",
"replaces",
"all",
"single",
"quotes",
"with",
"double",
"quotes",
"and",
"all",
"double",
"quotes",
"with",
"single",
"quotes",
"."
] |
a9a6ad793beab07cc3385954d2e8af8abfaa83e2
|
https://github.com/thriftrw/thriftrw-go/blob/a9a6ad793beab07cc3385954d2e8af8abfaa83e2/idl/internal/quote.go#L43-L55
|
17,724 |
thriftrw/thriftrw-go
|
wire/evaluate.go
|
EvaluateValue
|
func EvaluateValue(v Value) error {
switch v.Type() {
case TBool, TI8, TDouble, TI16, TI32, TI64, TBinary:
return nil
case TStruct:
for _, f := range v.GetStruct().Fields {
if err := EvaluateValue(f.Value); err != nil {
return err
}
}
return nil
case TMap:
m := v.GetMap()
defer m.Close()
return m.ForEach(func(item MapItem) error {
if err := EvaluateValue(item.Key); err != nil {
return err
}
return EvaluateValue(item.Value)
})
case TSet:
s := v.GetSet()
defer s.Close()
return s.ForEach(EvaluateValue)
case TList:
l := v.GetList()
defer l.Close()
return l.ForEach(EvaluateValue)
default:
return fmt.Errorf("unknown type %s", v.Type())
}
}
|
go
|
func EvaluateValue(v Value) error {
switch v.Type() {
case TBool, TI8, TDouble, TI16, TI32, TI64, TBinary:
return nil
case TStruct:
for _, f := range v.GetStruct().Fields {
if err := EvaluateValue(f.Value); err != nil {
return err
}
}
return nil
case TMap:
m := v.GetMap()
defer m.Close()
return m.ForEach(func(item MapItem) error {
if err := EvaluateValue(item.Key); err != nil {
return err
}
return EvaluateValue(item.Value)
})
case TSet:
s := v.GetSet()
defer s.Close()
return s.ForEach(EvaluateValue)
case TList:
l := v.GetList()
defer l.Close()
return l.ForEach(EvaluateValue)
default:
return fmt.Errorf("unknown type %s", v.Type())
}
}
|
[
"func",
"EvaluateValue",
"(",
"v",
"Value",
")",
"error",
"{",
"switch",
"v",
".",
"Type",
"(",
")",
"{",
"case",
"TBool",
",",
"TI8",
",",
"TDouble",
",",
"TI16",
",",
"TI32",
",",
"TI64",
",",
"TBinary",
":",
"return",
"nil",
"\n",
"case",
"TStruct",
":",
"for",
"_",
",",
"f",
":=",
"range",
"v",
".",
"GetStruct",
"(",
")",
".",
"Fields",
"{",
"if",
"err",
":=",
"EvaluateValue",
"(",
"f",
".",
"Value",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"case",
"TMap",
":",
"m",
":=",
"v",
".",
"GetMap",
"(",
")",
"\n",
"defer",
"m",
".",
"Close",
"(",
")",
"\n",
"return",
"m",
".",
"ForEach",
"(",
"func",
"(",
"item",
"MapItem",
")",
"error",
"{",
"if",
"err",
":=",
"EvaluateValue",
"(",
"item",
".",
"Key",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"return",
"EvaluateValue",
"(",
"item",
".",
"Value",
")",
"\n",
"}",
")",
"\n",
"case",
"TSet",
":",
"s",
":=",
"v",
".",
"GetSet",
"(",
")",
"\n",
"defer",
"s",
".",
"Close",
"(",
")",
"\n",
"return",
"s",
".",
"ForEach",
"(",
"EvaluateValue",
")",
"\n",
"case",
"TList",
":",
"l",
":=",
"v",
".",
"GetList",
"(",
")",
"\n",
"defer",
"l",
".",
"Close",
"(",
")",
"\n",
"return",
"l",
".",
"ForEach",
"(",
"EvaluateValue",
")",
"\n",
"default",
":",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"v",
".",
"Type",
"(",
")",
")",
"\n",
"}",
"\n",
"}"
] |
// EvaluateValue ensures that the given Value is fully evaluated. Lazy lists
// are spinned and any errors raised by them are returned.
|
[
"EvaluateValue",
"ensures",
"that",
"the",
"given",
"Value",
"is",
"fully",
"evaluated",
".",
"Lazy",
"lists",
"are",
"spinned",
"and",
"any",
"errors",
"raised",
"by",
"them",
"are",
"returned",
"."
] |
a9a6ad793beab07cc3385954d2e8af8abfaa83e2
|
https://github.com/thriftrw/thriftrw-go/blob/a9a6ad793beab07cc3385954d2e8af8abfaa83e2/wire/evaluate.go#L27-L58
|
17,725 |
thriftrw/thriftrw-go
|
plugin/template.go
|
Import
|
func (g *goFileGenerator) Import(path string) string {
if name, ok := g.imports[path]; ok {
return name
}
name := goast.DeterminePackageName(path)
// Find an import name that does not conflict with any known globals.
importedName := name
for i := 2; ; i++ {
if !g.isGlobalTaken(importedName) {
break
}
importedName = fmt.Sprintf("%s%d", name, i)
}
g.imports[path] = importedName
g.globals[importedName] = struct{}{}
return importedName
}
|
go
|
func (g *goFileGenerator) Import(path string) string {
if name, ok := g.imports[path]; ok {
return name
}
name := goast.DeterminePackageName(path)
// Find an import name that does not conflict with any known globals.
importedName := name
for i := 2; ; i++ {
if !g.isGlobalTaken(importedName) {
break
}
importedName = fmt.Sprintf("%s%d", name, i)
}
g.imports[path] = importedName
g.globals[importedName] = struct{}{}
return importedName
}
|
[
"func",
"(",
"g",
"*",
"goFileGenerator",
")",
"Import",
"(",
"path",
"string",
")",
"string",
"{",
"if",
"name",
",",
"ok",
":=",
"g",
".",
"imports",
"[",
"path",
"]",
";",
"ok",
"{",
"return",
"name",
"\n",
"}",
"\n\n",
"name",
":=",
"goast",
".",
"DeterminePackageName",
"(",
"path",
")",
"\n\n",
"// Find an import name that does not conflict with any known globals.",
"importedName",
":=",
"name",
"\n",
"for",
"i",
":=",
"2",
";",
";",
"i",
"++",
"{",
"if",
"!",
"g",
".",
"isGlobalTaken",
"(",
"importedName",
")",
"{",
"break",
"\n",
"}",
"\n",
"importedName",
"=",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"name",
",",
"i",
")",
"\n",
"}",
"\n\n",
"g",
".",
"imports",
"[",
"path",
"]",
"=",
"importedName",
"\n",
"g",
".",
"globals",
"[",
"importedName",
"]",
"=",
"struct",
"{",
"}",
"{",
"}",
"\n",
"return",
"importedName",
"\n",
"}"
] |
// Import the given import path and return the imported name for this package.
|
[
"Import",
"the",
"given",
"import",
"path",
"and",
"return",
"the",
"imported",
"name",
"for",
"this",
"package",
"."
] |
a9a6ad793beab07cc3385954d2e8af8abfaa83e2
|
https://github.com/thriftrw/thriftrw-go/blob/a9a6ad793beab07cc3385954d2e8af8abfaa83e2/plugin/template.go#L107-L126
|
17,726 |
thriftrw/thriftrw-go
|
plugin/template.go
|
FormatType
|
func (g *goFileGenerator) FormatType(t *api.Type) (string, error) {
switch {
case t.SimpleType != nil:
switch *t.SimpleType {
case api.SimpleTypeBool:
return "bool", nil
case api.SimpleTypeByte:
return "byte", nil
case api.SimpleTypeInt8:
return "int8", nil
case api.SimpleTypeInt16:
return "int16", nil
case api.SimpleTypeInt32:
return "int32", nil
case api.SimpleTypeInt64:
return "int64", nil
case api.SimpleTypeFloat64:
return "float64", nil
case api.SimpleTypeString:
return "string", nil
case api.SimpleTypeStructEmpty:
return "struct{}", nil
default:
return "", fmt.Errorf("unknown simple type: %v", *t.SimpleType)
}
case t.SliceType != nil:
v, err := g.FormatType(t.SliceType)
return "[]" + v, err
case t.KeyValueSliceType != nil:
k, err := g.FormatType(t.KeyValueSliceType.Left)
if err != nil {
return "", err
}
v, err := g.FormatType(t.KeyValueSliceType.Right)
return fmt.Sprintf("[]struct{Key %v; Value %v}", k, v), err
case t.MapType != nil:
k, err := g.FormatType(t.MapType.Left)
if err != nil {
return "", err
}
v, err := g.FormatType(t.MapType.Right)
return fmt.Sprintf("map[%v]%v", k, v), err
case t.ReferenceType != nil:
if g.importPath == t.ReferenceType.ImportPath {
// Target is in the same package. No need to import.
return t.ReferenceType.Name, nil
}
importName := g.Import(t.ReferenceType.ImportPath)
return importName + "." + t.ReferenceType.Name, nil
case t.PointerType != nil:
v, err := g.FormatType(t.PointerType)
return "*" + v, err
default:
return "", fmt.Errorf("unknown type: %v", t)
}
}
|
go
|
func (g *goFileGenerator) FormatType(t *api.Type) (string, error) {
switch {
case t.SimpleType != nil:
switch *t.SimpleType {
case api.SimpleTypeBool:
return "bool", nil
case api.SimpleTypeByte:
return "byte", nil
case api.SimpleTypeInt8:
return "int8", nil
case api.SimpleTypeInt16:
return "int16", nil
case api.SimpleTypeInt32:
return "int32", nil
case api.SimpleTypeInt64:
return "int64", nil
case api.SimpleTypeFloat64:
return "float64", nil
case api.SimpleTypeString:
return "string", nil
case api.SimpleTypeStructEmpty:
return "struct{}", nil
default:
return "", fmt.Errorf("unknown simple type: %v", *t.SimpleType)
}
case t.SliceType != nil:
v, err := g.FormatType(t.SliceType)
return "[]" + v, err
case t.KeyValueSliceType != nil:
k, err := g.FormatType(t.KeyValueSliceType.Left)
if err != nil {
return "", err
}
v, err := g.FormatType(t.KeyValueSliceType.Right)
return fmt.Sprintf("[]struct{Key %v; Value %v}", k, v), err
case t.MapType != nil:
k, err := g.FormatType(t.MapType.Left)
if err != nil {
return "", err
}
v, err := g.FormatType(t.MapType.Right)
return fmt.Sprintf("map[%v]%v", k, v), err
case t.ReferenceType != nil:
if g.importPath == t.ReferenceType.ImportPath {
// Target is in the same package. No need to import.
return t.ReferenceType.Name, nil
}
importName := g.Import(t.ReferenceType.ImportPath)
return importName + "." + t.ReferenceType.Name, nil
case t.PointerType != nil:
v, err := g.FormatType(t.PointerType)
return "*" + v, err
default:
return "", fmt.Errorf("unknown type: %v", t)
}
}
|
[
"func",
"(",
"g",
"*",
"goFileGenerator",
")",
"FormatType",
"(",
"t",
"*",
"api",
".",
"Type",
")",
"(",
"string",
",",
"error",
")",
"{",
"switch",
"{",
"case",
"t",
".",
"SimpleType",
"!=",
"nil",
":",
"switch",
"*",
"t",
".",
"SimpleType",
"{",
"case",
"api",
".",
"SimpleTypeBool",
":",
"return",
"\"",
"\"",
",",
"nil",
"\n",
"case",
"api",
".",
"SimpleTypeByte",
":",
"return",
"\"",
"\"",
",",
"nil",
"\n",
"case",
"api",
".",
"SimpleTypeInt8",
":",
"return",
"\"",
"\"",
",",
"nil",
"\n",
"case",
"api",
".",
"SimpleTypeInt16",
":",
"return",
"\"",
"\"",
",",
"nil",
"\n",
"case",
"api",
".",
"SimpleTypeInt32",
":",
"return",
"\"",
"\"",
",",
"nil",
"\n",
"case",
"api",
".",
"SimpleTypeInt64",
":",
"return",
"\"",
"\"",
",",
"nil",
"\n",
"case",
"api",
".",
"SimpleTypeFloat64",
":",
"return",
"\"",
"\"",
",",
"nil",
"\n",
"case",
"api",
".",
"SimpleTypeString",
":",
"return",
"\"",
"\"",
",",
"nil",
"\n",
"case",
"api",
".",
"SimpleTypeStructEmpty",
":",
"return",
"\"",
"\"",
",",
"nil",
"\n",
"default",
":",
"return",
"\"",
"\"",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"*",
"t",
".",
"SimpleType",
")",
"\n",
"}",
"\n",
"case",
"t",
".",
"SliceType",
"!=",
"nil",
":",
"v",
",",
"err",
":=",
"g",
".",
"FormatType",
"(",
"t",
".",
"SliceType",
")",
"\n",
"return",
"\"",
"\"",
"+",
"v",
",",
"err",
"\n",
"case",
"t",
".",
"KeyValueSliceType",
"!=",
"nil",
":",
"k",
",",
"err",
":=",
"g",
".",
"FormatType",
"(",
"t",
".",
"KeyValueSliceType",
".",
"Left",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\"",
"\"",
",",
"err",
"\n",
"}",
"\n\n",
"v",
",",
"err",
":=",
"g",
".",
"FormatType",
"(",
"t",
".",
"KeyValueSliceType",
".",
"Right",
")",
"\n",
"return",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"k",
",",
"v",
")",
",",
"err",
"\n",
"case",
"t",
".",
"MapType",
"!=",
"nil",
":",
"k",
",",
"err",
":=",
"g",
".",
"FormatType",
"(",
"t",
".",
"MapType",
".",
"Left",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\"",
"\"",
",",
"err",
"\n",
"}",
"\n\n",
"v",
",",
"err",
":=",
"g",
".",
"FormatType",
"(",
"t",
".",
"MapType",
".",
"Right",
")",
"\n",
"return",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"k",
",",
"v",
")",
",",
"err",
"\n",
"case",
"t",
".",
"ReferenceType",
"!=",
"nil",
":",
"if",
"g",
".",
"importPath",
"==",
"t",
".",
"ReferenceType",
".",
"ImportPath",
"{",
"// Target is in the same package. No need to import.",
"return",
"t",
".",
"ReferenceType",
".",
"Name",
",",
"nil",
"\n",
"}",
"\n\n",
"importName",
":=",
"g",
".",
"Import",
"(",
"t",
".",
"ReferenceType",
".",
"ImportPath",
")",
"\n",
"return",
"importName",
"+",
"\"",
"\"",
"+",
"t",
".",
"ReferenceType",
".",
"Name",
",",
"nil",
"\n",
"case",
"t",
".",
"PointerType",
"!=",
"nil",
":",
"v",
",",
"err",
":=",
"g",
".",
"FormatType",
"(",
"t",
".",
"PointerType",
")",
"\n",
"return",
"\"",
"\"",
"+",
"v",
",",
"err",
"\n",
"default",
":",
"return",
"\"",
"\"",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"t",
")",
"\n",
"}",
"\n",
"}"
] |
// FormatType formats the given api.Type into a Go type, importing packages
// necessary to reference this type.
|
[
"FormatType",
"formats",
"the",
"given",
"api",
".",
"Type",
"into",
"a",
"Go",
"type",
"importing",
"packages",
"necessary",
"to",
"reference",
"this",
"type",
"."
] |
a9a6ad793beab07cc3385954d2e8af8abfaa83e2
|
https://github.com/thriftrw/thriftrw-go/blob/a9a6ad793beab07cc3385954d2e8af8abfaa83e2/plugin/template.go#L130-L188
|
17,727 |
thriftrw/thriftrw-go
|
plugin/template.go
|
Generate
|
func (g *goFileGenerator) Generate(filename, tmpl string, data interface{}) ([]byte, error) {
funcs := template.FuncMap{
"import": g.Import,
"formatType": g.FormatType,
}
for k, v := range g.templateFuncs {
funcs[k] = v
}
t, err := template.New(filename).Delims("<", ">").Funcs(funcs).Parse(tmpl)
if err != nil {
return nil, fmt.Errorf("failed to parse template %q: %v", filename, err)
}
var buff bytes.Buffer
if err := t.Execute(&buff, data); err != nil {
return nil, err
}
fset := token.NewFileSet()
f, err := parser.ParseFile(fset, filename, buff.Bytes(), parser.ParseComments)
if err != nil {
return nil, fmt.Errorf("failed to parse generated code: %v:\n%s", err, buff.String())
}
if len(f.Imports) > 0 {
return nil, fmt.Errorf(
"plain imports are not allowed with GoFileFromTemplate: use the import function")
}
importPaths := make([]string, 0, len(g.imports))
for path := range g.imports {
importPaths = append(importPaths, path)
}
sort.Strings(importPaths)
for _, path := range importPaths {
astutil.AddNamedImport(fset, f, g.imports[path], path)
}
buff = bytes.Buffer{}
if err := format.Node(&buff, fset, f); err != nil {
return nil, err // TODO wrap error
}
return buff.Bytes(), nil
}
|
go
|
func (g *goFileGenerator) Generate(filename, tmpl string, data interface{}) ([]byte, error) {
funcs := template.FuncMap{
"import": g.Import,
"formatType": g.FormatType,
}
for k, v := range g.templateFuncs {
funcs[k] = v
}
t, err := template.New(filename).Delims("<", ">").Funcs(funcs).Parse(tmpl)
if err != nil {
return nil, fmt.Errorf("failed to parse template %q: %v", filename, err)
}
var buff bytes.Buffer
if err := t.Execute(&buff, data); err != nil {
return nil, err
}
fset := token.NewFileSet()
f, err := parser.ParseFile(fset, filename, buff.Bytes(), parser.ParseComments)
if err != nil {
return nil, fmt.Errorf("failed to parse generated code: %v:\n%s", err, buff.String())
}
if len(f.Imports) > 0 {
return nil, fmt.Errorf(
"plain imports are not allowed with GoFileFromTemplate: use the import function")
}
importPaths := make([]string, 0, len(g.imports))
for path := range g.imports {
importPaths = append(importPaths, path)
}
sort.Strings(importPaths)
for _, path := range importPaths {
astutil.AddNamedImport(fset, f, g.imports[path], path)
}
buff = bytes.Buffer{}
if err := format.Node(&buff, fset, f); err != nil {
return nil, err // TODO wrap error
}
return buff.Bytes(), nil
}
|
[
"func",
"(",
"g",
"*",
"goFileGenerator",
")",
"Generate",
"(",
"filename",
",",
"tmpl",
"string",
",",
"data",
"interface",
"{",
"}",
")",
"(",
"[",
"]",
"byte",
",",
"error",
")",
"{",
"funcs",
":=",
"template",
".",
"FuncMap",
"{",
"\"",
"\"",
":",
"g",
".",
"Import",
",",
"\"",
"\"",
":",
"g",
".",
"FormatType",
",",
"}",
"\n",
"for",
"k",
",",
"v",
":=",
"range",
"g",
".",
"templateFuncs",
"{",
"funcs",
"[",
"k",
"]",
"=",
"v",
"\n",
"}",
"\n\n",
"t",
",",
"err",
":=",
"template",
".",
"New",
"(",
"filename",
")",
".",
"Delims",
"(",
"\"",
"\"",
",",
"\"",
"\"",
")",
".",
"Funcs",
"(",
"funcs",
")",
".",
"Parse",
"(",
"tmpl",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"filename",
",",
"err",
")",
"\n",
"}",
"\n\n",
"var",
"buff",
"bytes",
".",
"Buffer",
"\n",
"if",
"err",
":=",
"t",
".",
"Execute",
"(",
"&",
"buff",
",",
"data",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"fset",
":=",
"token",
".",
"NewFileSet",
"(",
")",
"\n",
"f",
",",
"err",
":=",
"parser",
".",
"ParseFile",
"(",
"fset",
",",
"filename",
",",
"buff",
".",
"Bytes",
"(",
")",
",",
"parser",
".",
"ParseComments",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\\n",
"\"",
",",
"err",
",",
"buff",
".",
"String",
"(",
")",
")",
"\n",
"}",
"\n\n",
"if",
"len",
"(",
"f",
".",
"Imports",
")",
">",
"0",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"importPaths",
":=",
"make",
"(",
"[",
"]",
"string",
",",
"0",
",",
"len",
"(",
"g",
".",
"imports",
")",
")",
"\n",
"for",
"path",
":=",
"range",
"g",
".",
"imports",
"{",
"importPaths",
"=",
"append",
"(",
"importPaths",
",",
"path",
")",
"\n",
"}",
"\n",
"sort",
".",
"Strings",
"(",
"importPaths",
")",
"\n",
"for",
"_",
",",
"path",
":=",
"range",
"importPaths",
"{",
"astutil",
".",
"AddNamedImport",
"(",
"fset",
",",
"f",
",",
"g",
".",
"imports",
"[",
"path",
"]",
",",
"path",
")",
"\n",
"}",
"\n\n",
"buff",
"=",
"bytes",
".",
"Buffer",
"{",
"}",
"\n",
"if",
"err",
":=",
"format",
".",
"Node",
"(",
"&",
"buff",
",",
"fset",
",",
"f",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"// TODO wrap error",
"\n",
"}",
"\n\n",
"return",
"buff",
".",
"Bytes",
"(",
")",
",",
"nil",
"\n",
"}"
] |
// Generates a Go file with the given name using the provided template and
// template data.
|
[
"Generates",
"a",
"Go",
"file",
"with",
"the",
"given",
"name",
"using",
"the",
"provided",
"template",
"and",
"template",
"data",
"."
] |
a9a6ad793beab07cc3385954d2e8af8abfaa83e2
|
https://github.com/thriftrw/thriftrw-go/blob/a9a6ad793beab07cc3385954d2e8af8abfaa83e2/plugin/template.go#L192-L237
|
17,728 |
thriftrw/thriftrw-go
|
wire/value.go
|
Get
|
func (v *Value) Get() interface{} {
switch v.typ {
case TBool:
return v.GetBool()
case TI8:
return v.GetI8()
case TDouble:
return v.GetDouble()
case TI16:
return v.GetI16()
case TI32:
return v.GetI32()
case TI64:
return v.GetI64()
case TBinary:
return v.GetBinary()
case TStruct:
return v.GetStruct()
case TMap:
return v.GetMap()
case TSet, TList:
return v.GetList()
default:
panic(fmt.Sprintf("Unknown value type %v", v.typ))
}
}
|
go
|
func (v *Value) Get() interface{} {
switch v.typ {
case TBool:
return v.GetBool()
case TI8:
return v.GetI8()
case TDouble:
return v.GetDouble()
case TI16:
return v.GetI16()
case TI32:
return v.GetI32()
case TI64:
return v.GetI64()
case TBinary:
return v.GetBinary()
case TStruct:
return v.GetStruct()
case TMap:
return v.GetMap()
case TSet, TList:
return v.GetList()
default:
panic(fmt.Sprintf("Unknown value type %v", v.typ))
}
}
|
[
"func",
"(",
"v",
"*",
"Value",
")",
"Get",
"(",
")",
"interface",
"{",
"}",
"{",
"switch",
"v",
".",
"typ",
"{",
"case",
"TBool",
":",
"return",
"v",
".",
"GetBool",
"(",
")",
"\n",
"case",
"TI8",
":",
"return",
"v",
".",
"GetI8",
"(",
")",
"\n",
"case",
"TDouble",
":",
"return",
"v",
".",
"GetDouble",
"(",
")",
"\n",
"case",
"TI16",
":",
"return",
"v",
".",
"GetI16",
"(",
")",
"\n",
"case",
"TI32",
":",
"return",
"v",
".",
"GetI32",
"(",
")",
"\n",
"case",
"TI64",
":",
"return",
"v",
".",
"GetI64",
"(",
")",
"\n",
"case",
"TBinary",
":",
"return",
"v",
".",
"GetBinary",
"(",
")",
"\n",
"case",
"TStruct",
":",
"return",
"v",
".",
"GetStruct",
"(",
")",
"\n",
"case",
"TMap",
":",
"return",
"v",
".",
"GetMap",
"(",
")",
"\n",
"case",
"TSet",
",",
"TList",
":",
"return",
"v",
".",
"GetList",
"(",
")",
"\n",
"default",
":",
"panic",
"(",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"v",
".",
"typ",
")",
")",
"\n",
"}",
"\n",
"}"
] |
// Get retrieves whatever value the given Value contains.
|
[
"Get",
"retrieves",
"whatever",
"value",
"the",
"given",
"Value",
"contains",
"."
] |
a9a6ad793beab07cc3385954d2e8af8abfaa83e2
|
https://github.com/thriftrw/thriftrw-go/blob/a9a6ad793beab07cc3385954d2e8af8abfaa83e2/wire/value.go#L51-L76
|
17,729 |
thriftrw/thriftrw-go
|
wire/value.go
|
NewValueBool
|
func NewValueBool(v bool) Value {
n := uint64(0)
if v {
n = 1
}
return Value{
typ: TBool,
tnumber: n,
}
}
|
go
|
func NewValueBool(v bool) Value {
n := uint64(0)
if v {
n = 1
}
return Value{
typ: TBool,
tnumber: n,
}
}
|
[
"func",
"NewValueBool",
"(",
"v",
"bool",
")",
"Value",
"{",
"n",
":=",
"uint64",
"(",
"0",
")",
"\n",
"if",
"v",
"{",
"n",
"=",
"1",
"\n",
"}",
"\n",
"return",
"Value",
"{",
"typ",
":",
"TBool",
",",
"tnumber",
":",
"n",
",",
"}",
"\n",
"}"
] |
// NewValueBool constructs a new Value that contains a boolean.
|
[
"NewValueBool",
"constructs",
"a",
"new",
"Value",
"that",
"contains",
"a",
"boolean",
"."
] |
a9a6ad793beab07cc3385954d2e8af8abfaa83e2
|
https://github.com/thriftrw/thriftrw-go/blob/a9a6ad793beab07cc3385954d2e8af8abfaa83e2/wire/value.go#L79-L88
|
17,730 |
thriftrw/thriftrw-go
|
wire/value.go
|
NewValueI8
|
func NewValueI8(v int8) Value {
return Value{
typ: TI8,
tnumber: uint64(v),
}
}
|
go
|
func NewValueI8(v int8) Value {
return Value{
typ: TI8,
tnumber: uint64(v),
}
}
|
[
"func",
"NewValueI8",
"(",
"v",
"int8",
")",
"Value",
"{",
"return",
"Value",
"{",
"typ",
":",
"TI8",
",",
"tnumber",
":",
"uint64",
"(",
"v",
")",
",",
"}",
"\n",
"}"
] |
// NewValueI8 constructs a new Value that contains a byte
|
[
"NewValueI8",
"constructs",
"a",
"new",
"Value",
"that",
"contains",
"a",
"byte"
] |
a9a6ad793beab07cc3385954d2e8af8abfaa83e2
|
https://github.com/thriftrw/thriftrw-go/blob/a9a6ad793beab07cc3385954d2e8af8abfaa83e2/wire/value.go#L96-L101
|
17,731 |
thriftrw/thriftrw-go
|
wire/value.go
|
NewValueDouble
|
func NewValueDouble(v float64) Value {
return Value{
typ: TDouble,
tnumber: math.Float64bits(v),
}
}
|
go
|
func NewValueDouble(v float64) Value {
return Value{
typ: TDouble,
tnumber: math.Float64bits(v),
}
}
|
[
"func",
"NewValueDouble",
"(",
"v",
"float64",
")",
"Value",
"{",
"return",
"Value",
"{",
"typ",
":",
"TDouble",
",",
"tnumber",
":",
"math",
".",
"Float64bits",
"(",
"v",
")",
",",
"}",
"\n",
"}"
] |
// NewValueDouble constructs a new Value that contains a double.
|
[
"NewValueDouble",
"constructs",
"a",
"new",
"Value",
"that",
"contains",
"a",
"double",
"."
] |
a9a6ad793beab07cc3385954d2e8af8abfaa83e2
|
https://github.com/thriftrw/thriftrw-go/blob/a9a6ad793beab07cc3385954d2e8af8abfaa83e2/wire/value.go#L109-L114
|
17,732 |
thriftrw/thriftrw-go
|
wire/value.go
|
NewValueI16
|
func NewValueI16(v int16) Value {
return Value{
typ: TI16,
tnumber: uint64(v),
}
}
|
go
|
func NewValueI16(v int16) Value {
return Value{
typ: TI16,
tnumber: uint64(v),
}
}
|
[
"func",
"NewValueI16",
"(",
"v",
"int16",
")",
"Value",
"{",
"return",
"Value",
"{",
"typ",
":",
"TI16",
",",
"tnumber",
":",
"uint64",
"(",
"v",
")",
",",
"}",
"\n",
"}"
] |
// NewValueI16 constructs a new Value that contains a 16-bit integer.
|
[
"NewValueI16",
"constructs",
"a",
"new",
"Value",
"that",
"contains",
"a",
"16",
"-",
"bit",
"integer",
"."
] |
a9a6ad793beab07cc3385954d2e8af8abfaa83e2
|
https://github.com/thriftrw/thriftrw-go/blob/a9a6ad793beab07cc3385954d2e8af8abfaa83e2/wire/value.go#L122-L127
|
17,733 |
thriftrw/thriftrw-go
|
wire/value.go
|
NewValueI32
|
func NewValueI32(v int32) Value {
return Value{
typ: TI32,
tnumber: uint64(v),
}
}
|
go
|
func NewValueI32(v int32) Value {
return Value{
typ: TI32,
tnumber: uint64(v),
}
}
|
[
"func",
"NewValueI32",
"(",
"v",
"int32",
")",
"Value",
"{",
"return",
"Value",
"{",
"typ",
":",
"TI32",
",",
"tnumber",
":",
"uint64",
"(",
"v",
")",
",",
"}",
"\n",
"}"
] |
// NewValueI32 constructs a new Value that contains a 32-bit integer.
|
[
"NewValueI32",
"constructs",
"a",
"new",
"Value",
"that",
"contains",
"a",
"32",
"-",
"bit",
"integer",
"."
] |
a9a6ad793beab07cc3385954d2e8af8abfaa83e2
|
https://github.com/thriftrw/thriftrw-go/blob/a9a6ad793beab07cc3385954d2e8af8abfaa83e2/wire/value.go#L135-L140
|
17,734 |
thriftrw/thriftrw-go
|
wire/value.go
|
NewValueI64
|
func NewValueI64(v int64) Value {
return Value{
typ: TI64,
tnumber: uint64(v),
}
}
|
go
|
func NewValueI64(v int64) Value {
return Value{
typ: TI64,
tnumber: uint64(v),
}
}
|
[
"func",
"NewValueI64",
"(",
"v",
"int64",
")",
"Value",
"{",
"return",
"Value",
"{",
"typ",
":",
"TI64",
",",
"tnumber",
":",
"uint64",
"(",
"v",
")",
",",
"}",
"\n",
"}"
] |
// NewValueI64 constructs a new Value that contains a 64-bit integer.
|
[
"NewValueI64",
"constructs",
"a",
"new",
"Value",
"that",
"contains",
"a",
"64",
"-",
"bit",
"integer",
"."
] |
a9a6ad793beab07cc3385954d2e8af8abfaa83e2
|
https://github.com/thriftrw/thriftrw-go/blob/a9a6ad793beab07cc3385954d2e8af8abfaa83e2/wire/value.go#L148-L153
|
17,735 |
thriftrw/thriftrw-go
|
wire/value.go
|
NewValueBinary
|
func NewValueBinary(v []byte) Value {
if v == nil {
v = _emptyByteSlice
}
return Value{
typ: TBinary,
tbinary: v,
}
}
|
go
|
func NewValueBinary(v []byte) Value {
if v == nil {
v = _emptyByteSlice
}
return Value{
typ: TBinary,
tbinary: v,
}
}
|
[
"func",
"NewValueBinary",
"(",
"v",
"[",
"]",
"byte",
")",
"Value",
"{",
"if",
"v",
"==",
"nil",
"{",
"v",
"=",
"_emptyByteSlice",
"\n",
"}",
"\n",
"return",
"Value",
"{",
"typ",
":",
"TBinary",
",",
"tbinary",
":",
"v",
",",
"}",
"\n",
"}"
] |
// NewValueBinary constructs a new Value that contains a binary string.
|
[
"NewValueBinary",
"constructs",
"a",
"new",
"Value",
"that",
"contains",
"a",
"binary",
"string",
"."
] |
a9a6ad793beab07cc3385954d2e8af8abfaa83e2
|
https://github.com/thriftrw/thriftrw-go/blob/a9a6ad793beab07cc3385954d2e8af8abfaa83e2/wire/value.go#L161-L169
|
17,736 |
thriftrw/thriftrw-go
|
wire/value.go
|
NewValueString
|
func NewValueString(v string) Value {
return Value{
typ: TBinary,
tbinary: unsafeStringToBytes(v),
}
}
|
go
|
func NewValueString(v string) Value {
return Value{
typ: TBinary,
tbinary: unsafeStringToBytes(v),
}
}
|
[
"func",
"NewValueString",
"(",
"v",
"string",
")",
"Value",
"{",
"return",
"Value",
"{",
"typ",
":",
"TBinary",
",",
"tbinary",
":",
"unsafeStringToBytes",
"(",
"v",
")",
",",
"}",
"\n",
"}"
] |
// NewValueString constructs a new Value that contains a string.
|
[
"NewValueString",
"constructs",
"a",
"new",
"Value",
"that",
"contains",
"a",
"string",
"."
] |
a9a6ad793beab07cc3385954d2e8af8abfaa83e2
|
https://github.com/thriftrw/thriftrw-go/blob/a9a6ad793beab07cc3385954d2e8af8abfaa83e2/wire/value.go#L172-L177
|
17,737 |
thriftrw/thriftrw-go
|
internal/frame/writer.go
|
Write
|
func (w *Writer) Write(b []byte) error {
w.Lock()
defer w.Unlock()
// TODO(abg): Bounds check?
binary.BigEndian.PutUint32(w.buff[:], uint32(len(b)))
if _, err := w.w.Write(w.buff[:]); err != nil {
return err
}
if len(b) == 0 {
return nil
}
_, err := w.w.Write(b)
return err
}
|
go
|
func (w *Writer) Write(b []byte) error {
w.Lock()
defer w.Unlock()
// TODO(abg): Bounds check?
binary.BigEndian.PutUint32(w.buff[:], uint32(len(b)))
if _, err := w.w.Write(w.buff[:]); err != nil {
return err
}
if len(b) == 0 {
return nil
}
_, err := w.w.Write(b)
return err
}
|
[
"func",
"(",
"w",
"*",
"Writer",
")",
"Write",
"(",
"b",
"[",
"]",
"byte",
")",
"error",
"{",
"w",
".",
"Lock",
"(",
")",
"\n",
"defer",
"w",
".",
"Unlock",
"(",
")",
"\n\n",
"// TODO(abg): Bounds check?",
"binary",
".",
"BigEndian",
".",
"PutUint32",
"(",
"w",
".",
"buff",
"[",
":",
"]",
",",
"uint32",
"(",
"len",
"(",
"b",
")",
")",
")",
"\n",
"if",
"_",
",",
"err",
":=",
"w",
".",
"w",
".",
"Write",
"(",
"w",
".",
"buff",
"[",
":",
"]",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"if",
"len",
"(",
"b",
")",
"==",
"0",
"{",
"return",
"nil",
"\n",
"}",
"\n\n",
"_",
",",
"err",
":=",
"w",
".",
"w",
".",
"Write",
"(",
"b",
")",
"\n",
"return",
"err",
"\n",
"}"
] |
// Write writes the given frame to the Writer.
|
[
"Write",
"writes",
"the",
"given",
"frame",
"to",
"the",
"Writer",
"."
] |
a9a6ad793beab07cc3385954d2e8af8abfaa83e2
|
https://github.com/thriftrw/thriftrw-go/blob/a9a6ad793beab07cc3385954d2e8af8abfaa83e2/internal/frame/writer.go#L49-L65
|
17,738 |
thriftrw/thriftrw-go
|
internal/frame/writer.go
|
Close
|
func (w *Writer) Close() error {
if w.closed.Swap(true) {
return nil // already closed
}
if c, ok := w.w.(io.Closer); ok {
return c.Close()
}
return nil
}
|
go
|
func (w *Writer) Close() error {
if w.closed.Swap(true) {
return nil // already closed
}
if c, ok := w.w.(io.Closer); ok {
return c.Close()
}
return nil
}
|
[
"func",
"(",
"w",
"*",
"Writer",
")",
"Close",
"(",
")",
"error",
"{",
"if",
"w",
".",
"closed",
".",
"Swap",
"(",
"true",
")",
"{",
"return",
"nil",
"// already closed",
"\n",
"}",
"\n",
"if",
"c",
",",
"ok",
":=",
"w",
".",
"w",
".",
"(",
"io",
".",
"Closer",
")",
";",
"ok",
"{",
"return",
"c",
".",
"Close",
"(",
")",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] |
// Close closes the given Writeer.
|
[
"Close",
"closes",
"the",
"given",
"Writeer",
"."
] |
a9a6ad793beab07cc3385954d2e8af8abfaa83e2
|
https://github.com/thriftrw/thriftrw-go/blob/a9a6ad793beab07cc3385954d2e8af8abfaa83e2/internal/frame/writer.go#L68-L76
|
17,739 |
go-chassis/paas-lager
|
lager.go
|
RegisterWriter
|
func RegisterWriter(name string, writer io.Writer) {
m.Lock()
Writers[name] = writer
m.Unlock()
}
|
go
|
func RegisterWriter(name string, writer io.Writer) {
m.Lock()
Writers[name] = writer
m.Unlock()
}
|
[
"func",
"RegisterWriter",
"(",
"name",
"string",
",",
"writer",
"io",
".",
"Writer",
")",
"{",
"m",
".",
"Lock",
"(",
")",
"\n",
"Writers",
"[",
"name",
"]",
"=",
"writer",
"\n",
"m",
".",
"Unlock",
"(",
")",
"\n",
"}"
] |
//RegisterWriter is used to register a io writer
|
[
"RegisterWriter",
"is",
"used",
"to",
"register",
"a",
"io",
"writer"
] |
718a854dce30120d437b6b3918790d1c6a843678
|
https://github.com/go-chassis/paas-lager/blob/718a854dce30120d437b6b3918790d1c6a843678/lager.go#L44-L48
|
17,740 |
go-chassis/paas-lager
|
lager.go
|
DefaultConfig
|
func DefaultConfig() *Config {
return &Config{
LoggerLevel: INFO,
LoggerFile: "",
EnableRsyslog: false,
RsyslogNetwork: "udp",
RsyslogAddr: "127.0.0.1:5140",
LogFormatText: false,
}
}
|
go
|
func DefaultConfig() *Config {
return &Config{
LoggerLevel: INFO,
LoggerFile: "",
EnableRsyslog: false,
RsyslogNetwork: "udp",
RsyslogAddr: "127.0.0.1:5140",
LogFormatText: false,
}
}
|
[
"func",
"DefaultConfig",
"(",
")",
"*",
"Config",
"{",
"return",
"&",
"Config",
"{",
"LoggerLevel",
":",
"INFO",
",",
"LoggerFile",
":",
"\"",
"\"",
",",
"EnableRsyslog",
":",
"false",
",",
"RsyslogNetwork",
":",
"\"",
"\"",
",",
"RsyslogAddr",
":",
"\"",
"\"",
",",
"LogFormatText",
":",
"false",
",",
"}",
"\n",
"}"
] |
//DefaultConfig is a function which retuns config object with default configuration
|
[
"DefaultConfig",
"is",
"a",
"function",
"which",
"retuns",
"config",
"object",
"with",
"default",
"configuration"
] |
718a854dce30120d437b6b3918790d1c6a843678
|
https://github.com/go-chassis/paas-lager/blob/718a854dce30120d437b6b3918790d1c6a843678/lager.go#L51-L60
|
17,741 |
go-chassis/paas-lager
|
lager.go
|
Init
|
func Init(c Config) {
if c.LoggerLevel != "" {
config.LoggerLevel = c.LoggerLevel
}
if c.LoggerFile != "" {
config.LoggerFile = c.LoggerFile
config.Writers = append(config.Writers, "file")
}
if c.EnableRsyslog {
config.EnableRsyslog = c.EnableRsyslog
}
if c.RsyslogNetwork != "" {
config.RsyslogNetwork = c.RsyslogNetwork
}
if c.RsyslogAddr != "" {
config.RsyslogAddr = c.RsyslogAddr
}
if len(c.Writers) == 0 {
config.Writers = append(config.Writers, "stdout")
} else {
config.Writers = c.Writers
}
config.LogFormatText = c.LogFormatText
RegisterWriter("stdout", os.Stdout)
var file io.Writer
var err error
if config.LoggerFile != "" {
file, err = os.OpenFile(config.LoggerFile, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0666)
if err != nil {
panic(err)
}
}
for _, sink := range config.Writers {
if sink == "file" {
if file == nil {
log.Panic("Must set file path")
}
RegisterWriter("file", file)
}
}
}
|
go
|
func Init(c Config) {
if c.LoggerLevel != "" {
config.LoggerLevel = c.LoggerLevel
}
if c.LoggerFile != "" {
config.LoggerFile = c.LoggerFile
config.Writers = append(config.Writers, "file")
}
if c.EnableRsyslog {
config.EnableRsyslog = c.EnableRsyslog
}
if c.RsyslogNetwork != "" {
config.RsyslogNetwork = c.RsyslogNetwork
}
if c.RsyslogAddr != "" {
config.RsyslogAddr = c.RsyslogAddr
}
if len(c.Writers) == 0 {
config.Writers = append(config.Writers, "stdout")
} else {
config.Writers = c.Writers
}
config.LogFormatText = c.LogFormatText
RegisterWriter("stdout", os.Stdout)
var file io.Writer
var err error
if config.LoggerFile != "" {
file, err = os.OpenFile(config.LoggerFile, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0666)
if err != nil {
panic(err)
}
}
for _, sink := range config.Writers {
if sink == "file" {
if file == nil {
log.Panic("Must set file path")
}
RegisterWriter("file", file)
}
}
}
|
[
"func",
"Init",
"(",
"c",
"Config",
")",
"{",
"if",
"c",
".",
"LoggerLevel",
"!=",
"\"",
"\"",
"{",
"config",
".",
"LoggerLevel",
"=",
"c",
".",
"LoggerLevel",
"\n",
"}",
"\n\n",
"if",
"c",
".",
"LoggerFile",
"!=",
"\"",
"\"",
"{",
"config",
".",
"LoggerFile",
"=",
"c",
".",
"LoggerFile",
"\n",
"config",
".",
"Writers",
"=",
"append",
"(",
"config",
".",
"Writers",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"if",
"c",
".",
"EnableRsyslog",
"{",
"config",
".",
"EnableRsyslog",
"=",
"c",
".",
"EnableRsyslog",
"\n",
"}",
"\n\n",
"if",
"c",
".",
"RsyslogNetwork",
"!=",
"\"",
"\"",
"{",
"config",
".",
"RsyslogNetwork",
"=",
"c",
".",
"RsyslogNetwork",
"\n",
"}",
"\n\n",
"if",
"c",
".",
"RsyslogAddr",
"!=",
"\"",
"\"",
"{",
"config",
".",
"RsyslogAddr",
"=",
"c",
".",
"RsyslogAddr",
"\n",
"}",
"\n",
"if",
"len",
"(",
"c",
".",
"Writers",
")",
"==",
"0",
"{",
"config",
".",
"Writers",
"=",
"append",
"(",
"config",
".",
"Writers",
",",
"\"",
"\"",
")",
"\n\n",
"}",
"else",
"{",
"config",
".",
"Writers",
"=",
"c",
".",
"Writers",
"\n",
"}",
"\n",
"config",
".",
"LogFormatText",
"=",
"c",
".",
"LogFormatText",
"\n",
"RegisterWriter",
"(",
"\"",
"\"",
",",
"os",
".",
"Stdout",
")",
"\n",
"var",
"file",
"io",
".",
"Writer",
"\n",
"var",
"err",
"error",
"\n",
"if",
"config",
".",
"LoggerFile",
"!=",
"\"",
"\"",
"{",
"file",
",",
"err",
"=",
"os",
".",
"OpenFile",
"(",
"config",
".",
"LoggerFile",
",",
"os",
".",
"O_APPEND",
"|",
"os",
".",
"O_CREATE",
"|",
"os",
".",
"O_WRONLY",
",",
"0666",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"panic",
"(",
"err",
")",
"\n",
"}",
"\n\n",
"}",
"\n",
"for",
"_",
",",
"sink",
":=",
"range",
"config",
".",
"Writers",
"{",
"if",
"sink",
"==",
"\"",
"\"",
"{",
"if",
"file",
"==",
"nil",
"{",
"log",
".",
"Panic",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"RegisterWriter",
"(",
"\"",
"\"",
",",
"file",
")",
"\n",
"}",
"\n",
"}",
"\n",
"}"
] |
//Init is a function which initializes all config struct variables
|
[
"Init",
"is",
"a",
"function",
"which",
"initializes",
"all",
"config",
"struct",
"variables"
] |
718a854dce30120d437b6b3918790d1c6a843678
|
https://github.com/go-chassis/paas-lager/blob/718a854dce30120d437b6b3918790d1c6a843678/lager.go#L63-L109
|
17,742 |
go-chassis/paas-lager
|
lager.go
|
NewLoggerExt
|
func NewLoggerExt(component string, appGUID string) lager.Logger {
var lagerLogLevel lager.LogLevel
switch strings.ToUpper(config.LoggerLevel) {
case DEBUG:
lagerLogLevel = lager.DEBUG
case INFO:
lagerLogLevel = lager.INFO
case WARN:
lagerLogLevel = lager.WARN
case ERROR:
lagerLogLevel = lager.ERROR
case FATAL:
lagerLogLevel = lager.FATAL
default:
panic(fmt.Errorf("unknown logger level: %s", config.LoggerLevel))
}
logger := lager.NewLoggerExt(component, config.LogFormatText)
for _, sink := range config.Writers {
writer, ok := Writers[sink]
if !ok {
log.Panic("Unknow writer: ", sink)
}
sink := lager.NewReconfigurableSink(lager.NewWriterSink(sink, writer, lager.DEBUG), lagerLogLevel)
logger.RegisterSink(sink)
}
return logger
}
|
go
|
func NewLoggerExt(component string, appGUID string) lager.Logger {
var lagerLogLevel lager.LogLevel
switch strings.ToUpper(config.LoggerLevel) {
case DEBUG:
lagerLogLevel = lager.DEBUG
case INFO:
lagerLogLevel = lager.INFO
case WARN:
lagerLogLevel = lager.WARN
case ERROR:
lagerLogLevel = lager.ERROR
case FATAL:
lagerLogLevel = lager.FATAL
default:
panic(fmt.Errorf("unknown logger level: %s", config.LoggerLevel))
}
logger := lager.NewLoggerExt(component, config.LogFormatText)
for _, sink := range config.Writers {
writer, ok := Writers[sink]
if !ok {
log.Panic("Unknow writer: ", sink)
}
sink := lager.NewReconfigurableSink(lager.NewWriterSink(sink, writer, lager.DEBUG), lagerLogLevel)
logger.RegisterSink(sink)
}
return logger
}
|
[
"func",
"NewLoggerExt",
"(",
"component",
"string",
",",
"appGUID",
"string",
")",
"lager",
".",
"Logger",
"{",
"var",
"lagerLogLevel",
"lager",
".",
"LogLevel",
"\n",
"switch",
"strings",
".",
"ToUpper",
"(",
"config",
".",
"LoggerLevel",
")",
"{",
"case",
"DEBUG",
":",
"lagerLogLevel",
"=",
"lager",
".",
"DEBUG",
"\n",
"case",
"INFO",
":",
"lagerLogLevel",
"=",
"lager",
".",
"INFO",
"\n",
"case",
"WARN",
":",
"lagerLogLevel",
"=",
"lager",
".",
"WARN",
"\n",
"case",
"ERROR",
":",
"lagerLogLevel",
"=",
"lager",
".",
"ERROR",
"\n",
"case",
"FATAL",
":",
"lagerLogLevel",
"=",
"lager",
".",
"FATAL",
"\n",
"default",
":",
"panic",
"(",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"config",
".",
"LoggerLevel",
")",
")",
"\n",
"}",
"\n",
"logger",
":=",
"lager",
".",
"NewLoggerExt",
"(",
"component",
",",
"config",
".",
"LogFormatText",
")",
"\n",
"for",
"_",
",",
"sink",
":=",
"range",
"config",
".",
"Writers",
"{",
"writer",
",",
"ok",
":=",
"Writers",
"[",
"sink",
"]",
"\n",
"if",
"!",
"ok",
"{",
"log",
".",
"Panic",
"(",
"\"",
"\"",
",",
"sink",
")",
"\n",
"}",
"\n",
"sink",
":=",
"lager",
".",
"NewReconfigurableSink",
"(",
"lager",
".",
"NewWriterSink",
"(",
"sink",
",",
"writer",
",",
"lager",
".",
"DEBUG",
")",
",",
"lagerLogLevel",
")",
"\n",
"logger",
".",
"RegisterSink",
"(",
"sink",
")",
"\n",
"}",
"\n\n",
"return",
"logger",
"\n",
"}"
] |
//NewLoggerExt is a function which is used to write new logs
|
[
"NewLoggerExt",
"is",
"a",
"function",
"which",
"is",
"used",
"to",
"write",
"new",
"logs"
] |
718a854dce30120d437b6b3918790d1c6a843678
|
https://github.com/go-chassis/paas-lager/blob/718a854dce30120d437b6b3918790d1c6a843678/lager.go#L117-L145
|
17,743 |
go-chassis/paas-lager
|
syslog/syslog.go
|
Dial
|
func Dial(component, appguid, network, raddr string) (*Writer, error) {
hostname, _ := os.Hostname()
// construct syslog header the same to rsyslog's,
// origin, node_id, app_guid, instance_id, loglevel
syslogHeader = fmt.Sprintf("%s %s %s %s %s", component, component, appguid, hostname, "all")
var conn net.Conn
var err error
if network == "" {
conn, err = unixSyslog()
} else {
conn, err = net.Dial(network, raddr)
}
return &Writer{
conn: conn,
}, err
}
|
go
|
func Dial(component, appguid, network, raddr string) (*Writer, error) {
hostname, _ := os.Hostname()
// construct syslog header the same to rsyslog's,
// origin, node_id, app_guid, instance_id, loglevel
syslogHeader = fmt.Sprintf("%s %s %s %s %s", component, component, appguid, hostname, "all")
var conn net.Conn
var err error
if network == "" {
conn, err = unixSyslog()
} else {
conn, err = net.Dial(network, raddr)
}
return &Writer{
conn: conn,
}, err
}
|
[
"func",
"Dial",
"(",
"component",
",",
"appguid",
",",
"network",
",",
"raddr",
"string",
")",
"(",
"*",
"Writer",
",",
"error",
")",
"{",
"hostname",
",",
"_",
":=",
"os",
".",
"Hostname",
"(",
")",
"\n",
"// construct syslog header the same to rsyslog's,",
"// origin, node_id, app_guid, instance_id, loglevel",
"syslogHeader",
"=",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"component",
",",
"component",
",",
"appguid",
",",
"hostname",
",",
"\"",
"\"",
")",
"\n\n",
"var",
"conn",
"net",
".",
"Conn",
"\n",
"var",
"err",
"error",
"\n",
"if",
"network",
"==",
"\"",
"\"",
"{",
"conn",
",",
"err",
"=",
"unixSyslog",
"(",
")",
"\n",
"}",
"else",
"{",
"conn",
",",
"err",
"=",
"net",
".",
"Dial",
"(",
"network",
",",
"raddr",
")",
"\n",
"}",
"\n",
"return",
"&",
"Writer",
"{",
"conn",
":",
"conn",
",",
"}",
",",
"err",
"\n",
"}"
] |
//Dial is a function
|
[
"Dial",
"is",
"a",
"function"
] |
718a854dce30120d437b6b3918790d1c6a843678
|
https://github.com/go-chassis/paas-lager/blob/718a854dce30120d437b6b3918790d1c6a843678/syslog/syslog.go#L24-L41
|
17,744 |
go-chassis/paas-lager
|
syslog/syslog.go
|
Write
|
func (r *Writer) Write(b []byte) (int, error) {
nl := ""
if len(b) == 0 || b[len(b)-1] != '\n' {
nl = "\n"
}
r.conn.SetWriteDeadline(time.Now().Add(1 * time.Second))
_, err := fmt.Fprintf(r.conn, " %s %s%s", syslogHeader, b, nl)
if err != nil {
return 0, err
}
return len(b), nil
}
|
go
|
func (r *Writer) Write(b []byte) (int, error) {
nl := ""
if len(b) == 0 || b[len(b)-1] != '\n' {
nl = "\n"
}
r.conn.SetWriteDeadline(time.Now().Add(1 * time.Second))
_, err := fmt.Fprintf(r.conn, " %s %s%s", syslogHeader, b, nl)
if err != nil {
return 0, err
}
return len(b), nil
}
|
[
"func",
"(",
"r",
"*",
"Writer",
")",
"Write",
"(",
"b",
"[",
"]",
"byte",
")",
"(",
"int",
",",
"error",
")",
"{",
"nl",
":=",
"\"",
"\"",
"\n",
"if",
"len",
"(",
"b",
")",
"==",
"0",
"||",
"b",
"[",
"len",
"(",
"b",
")",
"-",
"1",
"]",
"!=",
"'\\n'",
"{",
"nl",
"=",
"\"",
"\\n",
"\"",
"\n",
"}",
"\n\n",
"r",
".",
"conn",
".",
"SetWriteDeadline",
"(",
"time",
".",
"Now",
"(",
")",
".",
"Add",
"(",
"1",
"*",
"time",
".",
"Second",
")",
")",
"\n\n",
"_",
",",
"err",
":=",
"fmt",
".",
"Fprintf",
"(",
"r",
".",
"conn",
",",
"\"",
"\"",
",",
"syslogHeader",
",",
"b",
",",
"nl",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"0",
",",
"err",
"\n",
"}",
"\n\n",
"return",
"len",
"(",
"b",
")",
",",
"nil",
"\n",
"}"
] |
//Write is a function used to write
|
[
"Write",
"is",
"a",
"function",
"used",
"to",
"write"
] |
718a854dce30120d437b6b3918790d1c6a843678
|
https://github.com/go-chassis/paas-lager/blob/718a854dce30120d437b6b3918790d1c6a843678/syslog/syslog.go#L44-L58
|
17,745 |
go-chassis/paas-lager
|
syslog/syslog.go
|
unixSyslog
|
func unixSyslog() (net.Conn, error) {
networks := []string{"unixgram", "unix"}
logPaths := []string{"/dev/log", "/var/run/syslog"}
var addr string
for _, n := range networks {
for _, p := range logPaths {
addr = p
if conn, err := net.Dial(n, addr); err == nil {
return conn, nil
}
}
}
return nil, errors.New("Could not connect to local syslog socket")
}
|
go
|
func unixSyslog() (net.Conn, error) {
networks := []string{"unixgram", "unix"}
logPaths := []string{"/dev/log", "/var/run/syslog"}
var addr string
for _, n := range networks {
for _, p := range logPaths {
addr = p
if conn, err := net.Dial(n, addr); err == nil {
return conn, nil
}
}
}
return nil, errors.New("Could not connect to local syslog socket")
}
|
[
"func",
"unixSyslog",
"(",
")",
"(",
"net",
".",
"Conn",
",",
"error",
")",
"{",
"networks",
":=",
"[",
"]",
"string",
"{",
"\"",
"\"",
",",
"\"",
"\"",
"}",
"\n",
"logPaths",
":=",
"[",
"]",
"string",
"{",
"\"",
"\"",
",",
"\"",
"\"",
"}",
"\n",
"var",
"addr",
"string",
"\n",
"for",
"_",
",",
"n",
":=",
"range",
"networks",
"{",
"for",
"_",
",",
"p",
":=",
"range",
"logPaths",
"{",
"addr",
"=",
"p",
"\n",
"if",
"conn",
",",
"err",
":=",
"net",
".",
"Dial",
"(",
"n",
",",
"addr",
")",
";",
"err",
"==",
"nil",
"{",
"return",
"conn",
",",
"nil",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"nil",
",",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"}"
] |
//unixSyslog is a function
|
[
"unixSyslog",
"is",
"a",
"function"
] |
718a854dce30120d437b6b3918790d1c6a843678
|
https://github.com/go-chassis/paas-lager/blob/718a854dce30120d437b6b3918790d1c6a843678/syslog/syslog.go#L66-L79
|
17,746 |
go-chassis/paas-lager
|
third_party/forked/cloudfoundry/lager/logger.go
|
NewLoggerExt
|
func NewLoggerExt(component string, isFormatText bool) Logger {
return &logger{
component: component,
task: component,
sinks: []Sink{},
data: openlogging.Tags{},
logFormatText: isFormatText,
}
}
|
go
|
func NewLoggerExt(component string, isFormatText bool) Logger {
return &logger{
component: component,
task: component,
sinks: []Sink{},
data: openlogging.Tags{},
logFormatText: isFormatText,
}
}
|
[
"func",
"NewLoggerExt",
"(",
"component",
"string",
",",
"isFormatText",
"bool",
")",
"Logger",
"{",
"return",
"&",
"logger",
"{",
"component",
":",
"component",
",",
"task",
":",
"component",
",",
"sinks",
":",
"[",
"]",
"Sink",
"{",
"}",
",",
"data",
":",
"openlogging",
".",
"Tags",
"{",
"}",
",",
"logFormatText",
":",
"isFormatText",
",",
"}",
"\n",
"}"
] |
//NewLoggerExt is a function which returns logger struct object
|
[
"NewLoggerExt",
"is",
"a",
"function",
"which",
"returns",
"logger",
"struct",
"object"
] |
718a854dce30120d437b6b3918790d1c6a843678
|
https://github.com/go-chassis/paas-lager/blob/718a854dce30120d437b6b3918790d1c6a843678/third_party/forked/cloudfoundry/lager/logger.go#L47-L55
|
17,747 |
go-chassis/paas-lager
|
third_party/forked/cloudfoundry/lager/logger.go
|
Session
|
func (l *logger) Session(task string, opts ...openlogging.Option) Logger {
opt := &openlogging.Options{}
for _, o := range opts {
o(opt)
}
sid := atomic.AddUint64(&l.nextSession, 1)
var sessionIDstr string
if l.sessionID != "" {
sessionIDstr = fmt.Sprintf("%s.%d", l.sessionID, sid)
} else {
sessionIDstr = fmt.Sprintf("%d", sid)
}
return &logger{
component: l.component,
task: fmt.Sprintf("%s.%s", l.task, task),
sinks: l.sinks,
sessionID: sessionIDstr,
data: l.baseData(opt.Tags),
}
}
|
go
|
func (l *logger) Session(task string, opts ...openlogging.Option) Logger {
opt := &openlogging.Options{}
for _, o := range opts {
o(opt)
}
sid := atomic.AddUint64(&l.nextSession, 1)
var sessionIDstr string
if l.sessionID != "" {
sessionIDstr = fmt.Sprintf("%s.%d", l.sessionID, sid)
} else {
sessionIDstr = fmt.Sprintf("%d", sid)
}
return &logger{
component: l.component,
task: fmt.Sprintf("%s.%s", l.task, task),
sinks: l.sinks,
sessionID: sessionIDstr,
data: l.baseData(opt.Tags),
}
}
|
[
"func",
"(",
"l",
"*",
"logger",
")",
"Session",
"(",
"task",
"string",
",",
"opts",
"...",
"openlogging",
".",
"Option",
")",
"Logger",
"{",
"opt",
":=",
"&",
"openlogging",
".",
"Options",
"{",
"}",
"\n",
"for",
"_",
",",
"o",
":=",
"range",
"opts",
"{",
"o",
"(",
"opt",
")",
"\n",
"}",
"\n",
"sid",
":=",
"atomic",
".",
"AddUint64",
"(",
"&",
"l",
".",
"nextSession",
",",
"1",
")",
"\n\n",
"var",
"sessionIDstr",
"string",
"\n\n",
"if",
"l",
".",
"sessionID",
"!=",
"\"",
"\"",
"{",
"sessionIDstr",
"=",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"l",
".",
"sessionID",
",",
"sid",
")",
"\n",
"}",
"else",
"{",
"sessionIDstr",
"=",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"sid",
")",
"\n",
"}",
"\n\n",
"return",
"&",
"logger",
"{",
"component",
":",
"l",
".",
"component",
",",
"task",
":",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"l",
".",
"task",
",",
"task",
")",
",",
"sinks",
":",
"l",
".",
"sinks",
",",
"sessionID",
":",
"sessionIDstr",
",",
"data",
":",
"l",
".",
"baseData",
"(",
"opt",
".",
"Tags",
")",
",",
"}",
"\n",
"}"
] |
//Session is a function which returns logger details for that session
|
[
"Session",
"is",
"a",
"function",
"which",
"returns",
"logger",
"details",
"for",
"that",
"session"
] |
718a854dce30120d437b6b3918790d1c6a843678
|
https://github.com/go-chassis/paas-lager/blob/718a854dce30120d437b6b3918790d1c6a843678/third_party/forked/cloudfoundry/lager/logger.go#L73-L95
|
17,748 |
go-chassis/paas-lager
|
third_party/forked/cloudfoundry/lager/logger.go
|
WithData
|
func (l *logger) WithData(data openlogging.Tags) Logger {
return &logger{
component: l.component,
task: l.task,
sinks: l.sinks,
sessionID: l.sessionID,
data: l.baseData(data),
}
}
|
go
|
func (l *logger) WithData(data openlogging.Tags) Logger {
return &logger{
component: l.component,
task: l.task,
sinks: l.sinks,
sessionID: l.sessionID,
data: l.baseData(data),
}
}
|
[
"func",
"(",
"l",
"*",
"logger",
")",
"WithData",
"(",
"data",
"openlogging",
".",
"Tags",
")",
"Logger",
"{",
"return",
"&",
"logger",
"{",
"component",
":",
"l",
".",
"component",
",",
"task",
":",
"l",
".",
"task",
",",
"sinks",
":",
"l",
".",
"sinks",
",",
"sessionID",
":",
"l",
".",
"sessionID",
",",
"data",
":",
"l",
".",
"baseData",
"(",
"data",
")",
",",
"}",
"\n",
"}"
] |
//WithData which adds data to the logger object
|
[
"WithData",
"which",
"adds",
"data",
"to",
"the",
"logger",
"object"
] |
718a854dce30120d437b6b3918790d1c6a843678
|
https://github.com/go-chassis/paas-lager/blob/718a854dce30120d437b6b3918790d1c6a843678/third_party/forked/cloudfoundry/lager/logger.go#L98-L106
|
17,749 |
go-chassis/paas-lager
|
third_party/forked/cloudfoundry/lager/logger.go
|
SetLogLevel
|
func (l *logger) SetLogLevel(level LogLevel) {
for _, itf := range l.sinks {
if s, ok := itf.(*writerSink); ok && s.name != "file" {
continue
}
if s, ok := itf.(*ReconfigurableSink); ok {
s.SetMinLevel(level)
}
}
}
|
go
|
func (l *logger) SetLogLevel(level LogLevel) {
for _, itf := range l.sinks {
if s, ok := itf.(*writerSink); ok && s.name != "file" {
continue
}
if s, ok := itf.(*ReconfigurableSink); ok {
s.SetMinLevel(level)
}
}
}
|
[
"func",
"(",
"l",
"*",
"logger",
")",
"SetLogLevel",
"(",
"level",
"LogLevel",
")",
"{",
"for",
"_",
",",
"itf",
":=",
"range",
"l",
".",
"sinks",
"{",
"if",
"s",
",",
"ok",
":=",
"itf",
".",
"(",
"*",
"writerSink",
")",
";",
"ok",
"&&",
"s",
".",
"name",
"!=",
"\"",
"\"",
"{",
"continue",
"\n",
"}",
"\n",
"if",
"s",
",",
"ok",
":=",
"itf",
".",
"(",
"*",
"ReconfigurableSink",
")",
";",
"ok",
"{",
"s",
".",
"SetMinLevel",
"(",
"level",
")",
"\n",
"}",
"\n",
"}",
"\n",
"}"
] |
// SetLogLevel set logger level, current just support file output
|
[
"SetLogLevel",
"set",
"logger",
"level",
"current",
"just",
"support",
"file",
"output"
] |
718a854dce30120d437b6b3918790d1c6a843678
|
https://github.com/go-chassis/paas-lager/blob/718a854dce30120d437b6b3918790d1c6a843678/third_party/forked/cloudfoundry/lager/logger.go#L109-L118
|
17,750 |
go-chassis/paas-lager
|
third_party/forked/cloudfoundry/lager/logger.go
|
activeSinks
|
func (l *logger) activeSinks(loglevel LogLevel) []Sink {
ss := make([]Sink, len(l.sinks))
idx := 0
for _, itf := range l.sinks {
if s, ok := itf.(*writerSink); ok && loglevel < s.minLogLevel {
continue
}
if s, ok := itf.(*ReconfigurableSink); ok && loglevel < LogLevel(s.minLogLevel) {
continue
}
ss[idx] = itf
idx++
}
return ss[:idx]
}
|
go
|
func (l *logger) activeSinks(loglevel LogLevel) []Sink {
ss := make([]Sink, len(l.sinks))
idx := 0
for _, itf := range l.sinks {
if s, ok := itf.(*writerSink); ok && loglevel < s.minLogLevel {
continue
}
if s, ok := itf.(*ReconfigurableSink); ok && loglevel < LogLevel(s.minLogLevel) {
continue
}
ss[idx] = itf
idx++
}
return ss[:idx]
}
|
[
"func",
"(",
"l",
"*",
"logger",
")",
"activeSinks",
"(",
"loglevel",
"LogLevel",
")",
"[",
"]",
"Sink",
"{",
"ss",
":=",
"make",
"(",
"[",
"]",
"Sink",
",",
"len",
"(",
"l",
".",
"sinks",
")",
")",
"\n",
"idx",
":=",
"0",
"\n",
"for",
"_",
",",
"itf",
":=",
"range",
"l",
".",
"sinks",
"{",
"if",
"s",
",",
"ok",
":=",
"itf",
".",
"(",
"*",
"writerSink",
")",
";",
"ok",
"&&",
"loglevel",
"<",
"s",
".",
"minLogLevel",
"{",
"continue",
"\n",
"}",
"\n",
"if",
"s",
",",
"ok",
":=",
"itf",
".",
"(",
"*",
"ReconfigurableSink",
")",
";",
"ok",
"&&",
"loglevel",
"<",
"LogLevel",
"(",
"s",
".",
"minLogLevel",
")",
"{",
"continue",
"\n",
"}",
"\n",
"ss",
"[",
"idx",
"]",
"=",
"itf",
"\n",
"idx",
"++",
"\n",
"}",
"\n",
"return",
"ss",
"[",
":",
"idx",
"]",
"\n",
"}"
] |
// Find the sink need to log
|
[
"Find",
"the",
"sink",
"need",
"to",
"log"
] |
718a854dce30120d437b6b3918790d1c6a843678
|
https://github.com/go-chassis/paas-lager/blob/718a854dce30120d437b6b3918790d1c6a843678/third_party/forked/cloudfoundry/lager/logger.go#L122-L136
|
17,751 |
go-chassis/paas-lager
|
third_party/forked/cloudfoundry/lager/models.go
|
FormatLogLevel
|
func FormatLogLevel(x LogLevel) string {
var level string
switch x {
case DEBUG:
level = "DEBUG"
case INFO:
level = "INFO"
case WARN:
level = "WARN"
case ERROR:
level = "ERROR"
case FATAL:
level = "FATAL"
}
return level
}
|
go
|
func FormatLogLevel(x LogLevel) string {
var level string
switch x {
case DEBUG:
level = "DEBUG"
case INFO:
level = "INFO"
case WARN:
level = "WARN"
case ERROR:
level = "ERROR"
case FATAL:
level = "FATAL"
}
return level
}
|
[
"func",
"FormatLogLevel",
"(",
"x",
"LogLevel",
")",
"string",
"{",
"var",
"level",
"string",
"\n",
"switch",
"x",
"{",
"case",
"DEBUG",
":",
"level",
"=",
"\"",
"\"",
"\n",
"case",
"INFO",
":",
"level",
"=",
"\"",
"\"",
"\n",
"case",
"WARN",
":",
"level",
"=",
"\"",
"\"",
"\n",
"case",
"ERROR",
":",
"level",
"=",
"\"",
"\"",
"\n",
"case",
"FATAL",
":",
"level",
"=",
"\"",
"\"",
"\n",
"}",
"\n",
"return",
"level",
"\n",
"}"
] |
//FormatLogLevel is a function which returns string format of log level
|
[
"FormatLogLevel",
"is",
"a",
"function",
"which",
"returns",
"string",
"format",
"of",
"log",
"level"
] |
718a854dce30120d437b6b3918790d1c6a843678
|
https://github.com/go-chassis/paas-lager/blob/718a854dce30120d437b6b3918790d1c6a843678/third_party/forked/cloudfoundry/lager/models.go#L21-L36
|
17,752 |
go-chassis/paas-lager
|
third_party/forked/cloudfoundry/lager/models.go
|
MarshalJSON
|
func (x LogLevel) MarshalJSON() ([]byte, error) {
// var level string
var level = FormatLogLevel(x)
return json.Marshal(level)
}
|
go
|
func (x LogLevel) MarshalJSON() ([]byte, error) {
// var level string
var level = FormatLogLevel(x)
return json.Marshal(level)
}
|
[
"func",
"(",
"x",
"LogLevel",
")",
"MarshalJSON",
"(",
")",
"(",
"[",
"]",
"byte",
",",
"error",
")",
"{",
"// var level string",
"var",
"level",
"=",
"FormatLogLevel",
"(",
"x",
")",
"\n",
"return",
"json",
".",
"Marshal",
"(",
"level",
")",
"\n",
"}"
] |
//MarshalJSON is a function which returns data in JSON format
|
[
"MarshalJSON",
"is",
"a",
"function",
"which",
"returns",
"data",
"in",
"JSON",
"format"
] |
718a854dce30120d437b6b3918790d1c6a843678
|
https://github.com/go-chassis/paas-lager/blob/718a854dce30120d437b6b3918790d1c6a843678/third_party/forked/cloudfoundry/lager/models.go#L39-L43
|
17,753 |
go-chassis/paas-lager
|
third_party/forked/cloudfoundry/lager/reconfigurable_sink.go
|
Log
|
func (sink *ReconfigurableSink) Log(level LogLevel, log []byte) {
minLogLevel := LogLevel(atomic.LoadInt32(&sink.minLogLevel))
if level < minLogLevel {
return
}
sink.sink.Log(level, log)
}
|
go
|
func (sink *ReconfigurableSink) Log(level LogLevel, log []byte) {
minLogLevel := LogLevel(atomic.LoadInt32(&sink.minLogLevel))
if level < minLogLevel {
return
}
sink.sink.Log(level, log)
}
|
[
"func",
"(",
"sink",
"*",
"ReconfigurableSink",
")",
"Log",
"(",
"level",
"LogLevel",
",",
"log",
"[",
"]",
"byte",
")",
"{",
"minLogLevel",
":=",
"LogLevel",
"(",
"atomic",
".",
"LoadInt32",
"(",
"&",
"sink",
".",
"minLogLevel",
")",
")",
"\n\n",
"if",
"level",
"<",
"minLogLevel",
"{",
"return",
"\n",
"}",
"\n\n",
"sink",
".",
"sink",
".",
"Log",
"(",
"level",
",",
"log",
")",
"\n",
"}"
] |
//Log is a method which returns log level and log
|
[
"Log",
"is",
"a",
"method",
"which",
"returns",
"log",
"level",
"and",
"log"
] |
718a854dce30120d437b6b3918790d1c6a843678
|
https://github.com/go-chassis/paas-lager/blob/718a854dce30120d437b6b3918790d1c6a843678/third_party/forked/cloudfoundry/lager/reconfigurable_sink.go#L19-L27
|
17,754 |
go-chassis/paas-lager
|
rotate/logrotate.go
|
getTimeStamp
|
func getTimeStamp() string {
now := time.Now().Format("2006.01.02.15.04.05.000")
timeSlot := strings.Replace(now, ".", "", -1)
return timeSlot
}
|
go
|
func getTimeStamp() string {
now := time.Now().Format("2006.01.02.15.04.05.000")
timeSlot := strings.Replace(now, ".", "", -1)
return timeSlot
}
|
[
"func",
"getTimeStamp",
"(",
")",
"string",
"{",
"now",
":=",
"time",
".",
"Now",
"(",
")",
".",
"Format",
"(",
"\"",
"\"",
")",
"\n",
"timeSlot",
":=",
"strings",
".",
"Replace",
"(",
"now",
",",
"\"",
"\"",
",",
"\"",
"\"",
",",
"-",
"1",
")",
"\n",
"return",
"timeSlot",
"\n",
"}"
] |
// getTimeStamp get time stamp
|
[
"getTimeStamp",
"get",
"time",
"stamp"
] |
718a854dce30120d437b6b3918790d1c6a843678
|
https://github.com/go-chassis/paas-lager/blob/718a854dce30120d437b6b3918790d1c6a843678/rotate/logrotate.go#L285-L289
|
17,755 |
go-chassis/paas-lager
|
rotate/logrotate.go
|
CopyFile
|
func CopyFile(srcFile, destFile string) error {
file, err := os.Open(srcFile)
if err != nil {
return err
}
defer file.Close()
dest, err := os.Create(destFile)
if err != nil {
return err
}
defer dest.Close()
_, err = io.Copy(dest, file)
return err
}
|
go
|
func CopyFile(srcFile, destFile string) error {
file, err := os.Open(srcFile)
if err != nil {
return err
}
defer file.Close()
dest, err := os.Create(destFile)
if err != nil {
return err
}
defer dest.Close()
_, err = io.Copy(dest, file)
return err
}
|
[
"func",
"CopyFile",
"(",
"srcFile",
",",
"destFile",
"string",
")",
"error",
"{",
"file",
",",
"err",
":=",
"os",
".",
"Open",
"(",
"srcFile",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"defer",
"file",
".",
"Close",
"(",
")",
"\n",
"dest",
",",
"err",
":=",
"os",
".",
"Create",
"(",
"destFile",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"defer",
"dest",
".",
"Close",
"(",
")",
"\n",
"_",
",",
"err",
"=",
"io",
".",
"Copy",
"(",
"dest",
",",
"file",
")",
"\n",
"return",
"err",
"\n",
"}"
] |
// CopyFile copy file
|
[
"CopyFile",
"copy",
"file"
] |
718a854dce30120d437b6b3918790d1c6a843678
|
https://github.com/go-chassis/paas-lager/blob/718a854dce30120d437b6b3918790d1c6a843678/rotate/logrotate.go#L292-L305
|
17,756 |
go-chassis/paas-lager
|
rotate/logrotate.go
|
RunLogRotate
|
func RunLogRotate(logFilePath string, c *RotateConfig, logger lager.Logger) {
Logger = logger
if logFilePath == "" {
return
}
checkConfig(c)
if c == nil {
go func() {
for {
LogRotate(filepath.Dir(logFilePath), LogRotateSize, LogBackupCount)
time.Sleep(30 * time.Second)
}
}()
} else {
if c.RollingPolicy == RollingPolicySize {
go func() {
for {
LogRotate(filepath.Dir(logFilePath), c.LogRotateSize, c.LogBackupCount)
time.Sleep(30 * time.Second)
}
}()
} else {
go func() {
for {
LogRotate(filepath.Dir(logFilePath), 0, c.LogBackupCount)
time.Sleep(24 * time.Hour * time.Duration(c.LogRotateDate))
}
}()
}
}
}
|
go
|
func RunLogRotate(logFilePath string, c *RotateConfig, logger lager.Logger) {
Logger = logger
if logFilePath == "" {
return
}
checkConfig(c)
if c == nil {
go func() {
for {
LogRotate(filepath.Dir(logFilePath), LogRotateSize, LogBackupCount)
time.Sleep(30 * time.Second)
}
}()
} else {
if c.RollingPolicy == RollingPolicySize {
go func() {
for {
LogRotate(filepath.Dir(logFilePath), c.LogRotateSize, c.LogBackupCount)
time.Sleep(30 * time.Second)
}
}()
} else {
go func() {
for {
LogRotate(filepath.Dir(logFilePath), 0, c.LogBackupCount)
time.Sleep(24 * time.Hour * time.Duration(c.LogRotateDate))
}
}()
}
}
}
|
[
"func",
"RunLogRotate",
"(",
"logFilePath",
"string",
",",
"c",
"*",
"RotateConfig",
",",
"logger",
"lager",
".",
"Logger",
")",
"{",
"Logger",
"=",
"logger",
"\n",
"if",
"logFilePath",
"==",
"\"",
"\"",
"{",
"return",
"\n",
"}",
"\n",
"checkConfig",
"(",
"c",
")",
"\n",
"if",
"c",
"==",
"nil",
"{",
"go",
"func",
"(",
")",
"{",
"for",
"{",
"LogRotate",
"(",
"filepath",
".",
"Dir",
"(",
"logFilePath",
")",
",",
"LogRotateSize",
",",
"LogBackupCount",
")",
"\n",
"time",
".",
"Sleep",
"(",
"30",
"*",
"time",
".",
"Second",
")",
"\n",
"}",
"\n",
"}",
"(",
")",
"\n",
"}",
"else",
"{",
"if",
"c",
".",
"RollingPolicy",
"==",
"RollingPolicySize",
"{",
"go",
"func",
"(",
")",
"{",
"for",
"{",
"LogRotate",
"(",
"filepath",
".",
"Dir",
"(",
"logFilePath",
")",
",",
"c",
".",
"LogRotateSize",
",",
"c",
".",
"LogBackupCount",
")",
"\n",
"time",
".",
"Sleep",
"(",
"30",
"*",
"time",
".",
"Second",
")",
"\n",
"}",
"\n",
"}",
"(",
")",
"\n",
"}",
"else",
"{",
"go",
"func",
"(",
")",
"{",
"for",
"{",
"LogRotate",
"(",
"filepath",
".",
"Dir",
"(",
"logFilePath",
")",
",",
"0",
",",
"c",
".",
"LogBackupCount",
")",
"\n",
"time",
".",
"Sleep",
"(",
"24",
"*",
"time",
".",
"Hour",
"*",
"time",
".",
"Duration",
"(",
"c",
".",
"LogRotateDate",
")",
")",
"\n",
"}",
"\n",
"}",
"(",
")",
"\n",
"}",
"\n",
"}",
"\n",
"}"
] |
// RunLogRotate initialize log rotate
|
[
"RunLogRotate",
"initialize",
"log",
"rotate"
] |
718a854dce30120d437b6b3918790d1c6a843678
|
https://github.com/go-chassis/paas-lager/blob/718a854dce30120d437b6b3918790d1c6a843678/rotate/logrotate.go#L316-L346
|
17,757 |
go-chassis/paas-lager
|
rotate/logrotate.go
|
checkConfig
|
func checkConfig(c *RotateConfig) {
if c.RollingPolicy == "" {
log.Println("RollingPolicy is empty, use default policy[size]")
c.RollingPolicy = RollingPolicySize
} else if c.RollingPolicy != "daily" && c.RollingPolicy != RollingPolicySize {
log.Printf("RollingPolicy is error, RollingPolicy=%s, use default policy[size].", c.RollingPolicy)
c.RollingPolicy = RollingPolicySize
}
if c.LogRotateDate <= 0 || c.LogRotateDate > 10 {
c.LogRotateDate = LogRotateDate
}
if c.LogRotateSize <= 0 || c.LogRotateSize > 50 {
c.LogRotateSize = LogRotateSize
}
if c.LogBackupCount < 0 || c.LogBackupCount > 100 {
c.LogBackupCount = LogBackupCount
}
}
|
go
|
func checkConfig(c *RotateConfig) {
if c.RollingPolicy == "" {
log.Println("RollingPolicy is empty, use default policy[size]")
c.RollingPolicy = RollingPolicySize
} else if c.RollingPolicy != "daily" && c.RollingPolicy != RollingPolicySize {
log.Printf("RollingPolicy is error, RollingPolicy=%s, use default policy[size].", c.RollingPolicy)
c.RollingPolicy = RollingPolicySize
}
if c.LogRotateDate <= 0 || c.LogRotateDate > 10 {
c.LogRotateDate = LogRotateDate
}
if c.LogRotateSize <= 0 || c.LogRotateSize > 50 {
c.LogRotateSize = LogRotateSize
}
if c.LogBackupCount < 0 || c.LogBackupCount > 100 {
c.LogBackupCount = LogBackupCount
}
}
|
[
"func",
"checkConfig",
"(",
"c",
"*",
"RotateConfig",
")",
"{",
"if",
"c",
".",
"RollingPolicy",
"==",
"\"",
"\"",
"{",
"log",
".",
"Println",
"(",
"\"",
"\"",
")",
"\n",
"c",
".",
"RollingPolicy",
"=",
"RollingPolicySize",
"\n",
"}",
"else",
"if",
"c",
".",
"RollingPolicy",
"!=",
"\"",
"\"",
"&&",
"c",
".",
"RollingPolicy",
"!=",
"RollingPolicySize",
"{",
"log",
".",
"Printf",
"(",
"\"",
"\"",
",",
"c",
".",
"RollingPolicy",
")",
"\n",
"c",
".",
"RollingPolicy",
"=",
"RollingPolicySize",
"\n",
"}",
"\n\n",
"if",
"c",
".",
"LogRotateDate",
"<=",
"0",
"||",
"c",
".",
"LogRotateDate",
">",
"10",
"{",
"c",
".",
"LogRotateDate",
"=",
"LogRotateDate",
"\n",
"}",
"\n\n",
"if",
"c",
".",
"LogRotateSize",
"<=",
"0",
"||",
"c",
".",
"LogRotateSize",
">",
"50",
"{",
"c",
".",
"LogRotateSize",
"=",
"LogRotateSize",
"\n",
"}",
"\n\n",
"if",
"c",
".",
"LogBackupCount",
"<",
"0",
"||",
"c",
".",
"LogBackupCount",
">",
"100",
"{",
"c",
".",
"LogBackupCount",
"=",
"LogBackupCount",
"\n",
"}",
"\n",
"}"
] |
// checkPassLagerDefinition check pass lager definition
|
[
"checkPassLagerDefinition",
"check",
"pass",
"lager",
"definition"
] |
718a854dce30120d437b6b3918790d1c6a843678
|
https://github.com/go-chassis/paas-lager/blob/718a854dce30120d437b6b3918790d1c6a843678/rotate/logrotate.go#L349-L369
|
17,758 |
rainycape/dl
|
dl.go
|
Close
|
func (d *DL) Close() error {
if d.handle != nil {
d.mu.Lock()
defer d.mu.Unlock()
if d.handle != nil {
mu.Lock()
defer mu.Unlock()
if C.dlclose(d.handle) != 0 {
return dlerror()
}
d.handle = nil
}
}
return nil
}
|
go
|
func (d *DL) Close() error {
if d.handle != nil {
d.mu.Lock()
defer d.mu.Unlock()
if d.handle != nil {
mu.Lock()
defer mu.Unlock()
if C.dlclose(d.handle) != 0 {
return dlerror()
}
d.handle = nil
}
}
return nil
}
|
[
"func",
"(",
"d",
"*",
"DL",
")",
"Close",
"(",
")",
"error",
"{",
"if",
"d",
".",
"handle",
"!=",
"nil",
"{",
"d",
".",
"mu",
".",
"Lock",
"(",
")",
"\n",
"defer",
"d",
".",
"mu",
".",
"Unlock",
"(",
")",
"\n",
"if",
"d",
".",
"handle",
"!=",
"nil",
"{",
"mu",
".",
"Lock",
"(",
")",
"\n",
"defer",
"mu",
".",
"Unlock",
"(",
")",
"\n",
"if",
"C",
".",
"dlclose",
"(",
"d",
".",
"handle",
")",
"!=",
"0",
"{",
"return",
"dlerror",
"(",
")",
"\n",
"}",
"\n",
"d",
".",
"handle",
"=",
"nil",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] |
// Close closes the shared library handle. All symbols
// loaded from the library will become invalid.
|
[
"Close",
"closes",
"the",
"shared",
"library",
"handle",
".",
"All",
"symbols",
"loaded",
"from",
"the",
"library",
"will",
"become",
"invalid",
"."
] |
1b01514224a1a60a6bcbb0b6b9d3a00ec14ae17f
|
https://github.com/rainycape/dl/blob/1b01514224a1a60a6bcbb0b6b9d3a00ec14ae17f/dl.go#L155-L169
|
17,759 |
containous/staert
|
staert.go
|
AddSource
|
func (s *Staert) AddSource(src Source) {
s.sources = append(s.sources, src)
}
|
go
|
func (s *Staert) AddSource(src Source) {
s.sources = append(s.sources, src)
}
|
[
"func",
"(",
"s",
"*",
"Staert",
")",
"AddSource",
"(",
"src",
"Source",
")",
"{",
"s",
".",
"sources",
"=",
"append",
"(",
"s",
".",
"sources",
",",
"src",
")",
"\n",
"}"
] |
// AddSource adds new Source to Staert, give it by reference
|
[
"AddSource",
"adds",
"new",
"Source",
"to",
"Staert",
"give",
"it",
"by",
"reference"
] |
f987d01c3d97d01fffb73a57fa35a659c944396a
|
https://github.com/containous/staert/blob/f987d01c3d97d01fffb73a57fa35a659c944396a/staert.go#L27-L29
|
17,760 |
containous/staert
|
staert.go
|
LoadConfig
|
func (s *Staert) LoadConfig() (interface{}, error) {
for _, src := range s.sources {
// Type assertion
if flg, ok := src.(*flaeg.Flaeg); ok {
fCmd, err := flg.GetCommand()
if err != nil {
return nil, err
}
// if fleag sub-command
if s.command != fCmd {
// if parseAllSources
if fCmd.Metadata["parseAllSources"] == "true" {
fCmdConfigType := reflect.TypeOf(fCmd.Config)
sCmdConfigType := reflect.TypeOf(s.command.Config)
if fCmdConfigType != sCmdConfigType {
return nil, fmt.Errorf("command %s : Config type doesn't match with root command config type. Expected %s got %s",
fCmd.Name, sCmdConfigType.Name(), fCmdConfigType.Name())
}
s.command = fCmd
} else {
// (not parseAllSources)
s.command, err = flg.Parse(fCmd)
return s.command.Config, err
}
}
}
}
err := s.parseConfigAllSources(s.command)
return s.command.Config, err
}
|
go
|
func (s *Staert) LoadConfig() (interface{}, error) {
for _, src := range s.sources {
// Type assertion
if flg, ok := src.(*flaeg.Flaeg); ok {
fCmd, err := flg.GetCommand()
if err != nil {
return nil, err
}
// if fleag sub-command
if s.command != fCmd {
// if parseAllSources
if fCmd.Metadata["parseAllSources"] == "true" {
fCmdConfigType := reflect.TypeOf(fCmd.Config)
sCmdConfigType := reflect.TypeOf(s.command.Config)
if fCmdConfigType != sCmdConfigType {
return nil, fmt.Errorf("command %s : Config type doesn't match with root command config type. Expected %s got %s",
fCmd.Name, sCmdConfigType.Name(), fCmdConfigType.Name())
}
s.command = fCmd
} else {
// (not parseAllSources)
s.command, err = flg.Parse(fCmd)
return s.command.Config, err
}
}
}
}
err := s.parseConfigAllSources(s.command)
return s.command.Config, err
}
|
[
"func",
"(",
"s",
"*",
"Staert",
")",
"LoadConfig",
"(",
")",
"(",
"interface",
"{",
"}",
",",
"error",
")",
"{",
"for",
"_",
",",
"src",
":=",
"range",
"s",
".",
"sources",
"{",
"// Type assertion",
"if",
"flg",
",",
"ok",
":=",
"src",
".",
"(",
"*",
"flaeg",
".",
"Flaeg",
")",
";",
"ok",
"{",
"fCmd",
",",
"err",
":=",
"flg",
".",
"GetCommand",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"// if fleag sub-command",
"if",
"s",
".",
"command",
"!=",
"fCmd",
"{",
"// if parseAllSources",
"if",
"fCmd",
".",
"Metadata",
"[",
"\"",
"\"",
"]",
"==",
"\"",
"\"",
"{",
"fCmdConfigType",
":=",
"reflect",
".",
"TypeOf",
"(",
"fCmd",
".",
"Config",
")",
"\n",
"sCmdConfigType",
":=",
"reflect",
".",
"TypeOf",
"(",
"s",
".",
"command",
".",
"Config",
")",
"\n",
"if",
"fCmdConfigType",
"!=",
"sCmdConfigType",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"fCmd",
".",
"Name",
",",
"sCmdConfigType",
".",
"Name",
"(",
")",
",",
"fCmdConfigType",
".",
"Name",
"(",
")",
")",
"\n",
"}",
"\n",
"s",
".",
"command",
"=",
"fCmd",
"\n",
"}",
"else",
"{",
"// (not parseAllSources)",
"s",
".",
"command",
",",
"err",
"=",
"flg",
".",
"Parse",
"(",
"fCmd",
")",
"\n",
"return",
"s",
".",
"command",
".",
"Config",
",",
"err",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n",
"err",
":=",
"s",
".",
"parseConfigAllSources",
"(",
"s",
".",
"command",
")",
"\n",
"return",
"s",
".",
"command",
".",
"Config",
",",
"err",
"\n",
"}"
] |
// LoadConfig check which command is called and parses config
// It returns the the parsed config or an error if it fails
|
[
"LoadConfig",
"check",
"which",
"command",
"is",
"called",
"and",
"parses",
"config",
"It",
"returns",
"the",
"the",
"parsed",
"config",
"or",
"an",
"error",
"if",
"it",
"fails"
] |
f987d01c3d97d01fffb73a57fa35a659c944396a
|
https://github.com/containous/staert/blob/f987d01c3d97d01fffb73a57fa35a659c944396a/staert.go#L33-L63
|
17,761 |
containous/staert
|
staert.go
|
parseConfigAllSources
|
func (s *Staert) parseConfigAllSources(cmd *flaeg.Command) error {
for _, src := range s.sources {
_, err := src.Parse(cmd)
if err != nil {
return err
}
}
return nil
}
|
go
|
func (s *Staert) parseConfigAllSources(cmd *flaeg.Command) error {
for _, src := range s.sources {
_, err := src.Parse(cmd)
if err != nil {
return err
}
}
return nil
}
|
[
"func",
"(",
"s",
"*",
"Staert",
")",
"parseConfigAllSources",
"(",
"cmd",
"*",
"flaeg",
".",
"Command",
")",
"error",
"{",
"for",
"_",
",",
"src",
":=",
"range",
"s",
".",
"sources",
"{",
"_",
",",
"err",
":=",
"src",
".",
"Parse",
"(",
"cmd",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] |
// parseConfigAllSources getConfig for a flaeg.Command run sources Parse func in the raw
|
[
"parseConfigAllSources",
"getConfig",
"for",
"a",
"flaeg",
".",
"Command",
"run",
"sources",
"Parse",
"func",
"in",
"the",
"raw"
] |
f987d01c3d97d01fffb73a57fa35a659c944396a
|
https://github.com/containous/staert/blob/f987d01c3d97d01fffb73a57fa35a659c944396a/staert.go#L66-L74
|
17,762 |
containous/staert
|
kv.go
|
NewKvSource
|
func NewKvSource(backend store.Backend, addrs []string, options *store.Config, prefix string) (*KvSource, error) {
kvStore, err := valkeyrie.NewStore(backend, addrs, options)
return &KvSource{Store: kvStore, Prefix: prefix}, err
}
|
go
|
func NewKvSource(backend store.Backend, addrs []string, options *store.Config, prefix string) (*KvSource, error) {
kvStore, err := valkeyrie.NewStore(backend, addrs, options)
return &KvSource{Store: kvStore, Prefix: prefix}, err
}
|
[
"func",
"NewKvSource",
"(",
"backend",
"store",
".",
"Backend",
",",
"addrs",
"[",
"]",
"string",
",",
"options",
"*",
"store",
".",
"Config",
",",
"prefix",
"string",
")",
"(",
"*",
"KvSource",
",",
"error",
")",
"{",
"kvStore",
",",
"err",
":=",
"valkeyrie",
".",
"NewStore",
"(",
"backend",
",",
"addrs",
",",
"options",
")",
"\n",
"return",
"&",
"KvSource",
"{",
"Store",
":",
"kvStore",
",",
"Prefix",
":",
"prefix",
"}",
",",
"err",
"\n",
"}"
] |
// NewKvSource creates a new KvSource
|
[
"NewKvSource",
"creates",
"a",
"new",
"KvSource"
] |
f987d01c3d97d01fffb73a57fa35a659c944396a
|
https://github.com/containous/staert/blob/f987d01c3d97d01fffb73a57fa35a659c944396a/kv.go#L33-L36
|
17,763 |
containous/staert
|
kv.go
|
Parse
|
func (kv *KvSource) Parse(cmd *flaeg.Command) (*flaeg.Command, error) {
err := kv.LoadConfig(cmd.Config)
if err != nil {
return nil, err
}
return cmd, nil
}
|
go
|
func (kv *KvSource) Parse(cmd *flaeg.Command) (*flaeg.Command, error) {
err := kv.LoadConfig(cmd.Config)
if err != nil {
return nil, err
}
return cmd, nil
}
|
[
"func",
"(",
"kv",
"*",
"KvSource",
")",
"Parse",
"(",
"cmd",
"*",
"flaeg",
".",
"Command",
")",
"(",
"*",
"flaeg",
".",
"Command",
",",
"error",
")",
"{",
"err",
":=",
"kv",
".",
"LoadConfig",
"(",
"cmd",
".",
"Config",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"return",
"cmd",
",",
"nil",
"\n",
"}"
] |
// Parse uses valkeyrie and mapstructure to fill the structure
|
[
"Parse",
"uses",
"valkeyrie",
"and",
"mapstructure",
"to",
"fill",
"the",
"structure"
] |
f987d01c3d97d01fffb73a57fa35a659c944396a
|
https://github.com/containous/staert/blob/f987d01c3d97d01fffb73a57fa35a659c944396a/kv.go#L39-L45
|
17,764 |
containous/staert
|
kv.go
|
StoreConfig
|
func (kv *KvSource) StoreConfig(config interface{}) error {
kvMap := map[string]string{}
if err := collateKvRecursive(reflect.ValueOf(config), kvMap, kv.Prefix); err != nil {
return err
}
var keys []string
for key := range kvMap {
keys = append(keys, key)
}
sort.Strings(keys)
for _, k := range keys {
var writeOptions *store.WriteOptions
// is it a directory ?
if strings.HasSuffix(k, "/") {
writeOptions = &store.WriteOptions{
IsDir: true,
}
}
if err := kv.Put(k, []byte(kvMap[k]), writeOptions); err != nil {
return err
}
}
return nil
}
|
go
|
func (kv *KvSource) StoreConfig(config interface{}) error {
kvMap := map[string]string{}
if err := collateKvRecursive(reflect.ValueOf(config), kvMap, kv.Prefix); err != nil {
return err
}
var keys []string
for key := range kvMap {
keys = append(keys, key)
}
sort.Strings(keys)
for _, k := range keys {
var writeOptions *store.WriteOptions
// is it a directory ?
if strings.HasSuffix(k, "/") {
writeOptions = &store.WriteOptions{
IsDir: true,
}
}
if err := kv.Put(k, []byte(kvMap[k]), writeOptions); err != nil {
return err
}
}
return nil
}
|
[
"func",
"(",
"kv",
"*",
"KvSource",
")",
"StoreConfig",
"(",
"config",
"interface",
"{",
"}",
")",
"error",
"{",
"kvMap",
":=",
"map",
"[",
"string",
"]",
"string",
"{",
"}",
"\n",
"if",
"err",
":=",
"collateKvRecursive",
"(",
"reflect",
".",
"ValueOf",
"(",
"config",
")",
",",
"kvMap",
",",
"kv",
".",
"Prefix",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"var",
"keys",
"[",
"]",
"string",
"\n",
"for",
"key",
":=",
"range",
"kvMap",
"{",
"keys",
"=",
"append",
"(",
"keys",
",",
"key",
")",
"\n",
"}",
"\n",
"sort",
".",
"Strings",
"(",
"keys",
")",
"\n",
"for",
"_",
",",
"k",
":=",
"range",
"keys",
"{",
"var",
"writeOptions",
"*",
"store",
".",
"WriteOptions",
"\n",
"// is it a directory ?",
"if",
"strings",
".",
"HasSuffix",
"(",
"k",
",",
"\"",
"\"",
")",
"{",
"writeOptions",
"=",
"&",
"store",
".",
"WriteOptions",
"{",
"IsDir",
":",
"true",
",",
"}",
"\n",
"}",
"\n",
"if",
"err",
":=",
"kv",
".",
"Put",
"(",
"k",
",",
"[",
"]",
"byte",
"(",
"kvMap",
"[",
"k",
"]",
")",
",",
"writeOptions",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] |
// StoreConfig stores the config into the KV Store
|
[
"StoreConfig",
"stores",
"the",
"config",
"into",
"the",
"KV",
"Store"
] |
f987d01c3d97d01fffb73a57fa35a659c944396a
|
https://github.com/containous/staert/blob/f987d01c3d97d01fffb73a57fa35a659c944396a/kv.go#L189-L212
|
17,765 |
containous/staert
|
kv.go
|
ListRecursive
|
func (kv *KvSource) ListRecursive(key string, pairs map[string][]byte) error {
pairsN1, err := kv.List(key, nil)
if err == store.ErrKeyNotFound {
return nil
}
if err != nil {
return err
}
if len(pairsN1) == 0 {
pairLeaf, err := kv.Get(key, nil)
if err != nil {
return err
}
if pairLeaf == nil {
return nil
}
pairs[pairLeaf.Key] = pairLeaf.Value
return nil
}
for _, p := range pairsN1 {
if p.Key != key {
err := kv.ListRecursive(p.Key, pairs)
if err != nil {
return err
}
}
}
return nil
}
|
go
|
func (kv *KvSource) ListRecursive(key string, pairs map[string][]byte) error {
pairsN1, err := kv.List(key, nil)
if err == store.ErrKeyNotFound {
return nil
}
if err != nil {
return err
}
if len(pairsN1) == 0 {
pairLeaf, err := kv.Get(key, nil)
if err != nil {
return err
}
if pairLeaf == nil {
return nil
}
pairs[pairLeaf.Key] = pairLeaf.Value
return nil
}
for _, p := range pairsN1 {
if p.Key != key {
err := kv.ListRecursive(p.Key, pairs)
if err != nil {
return err
}
}
}
return nil
}
|
[
"func",
"(",
"kv",
"*",
"KvSource",
")",
"ListRecursive",
"(",
"key",
"string",
",",
"pairs",
"map",
"[",
"string",
"]",
"[",
"]",
"byte",
")",
"error",
"{",
"pairsN1",
",",
"err",
":=",
"kv",
".",
"List",
"(",
"key",
",",
"nil",
")",
"\n",
"if",
"err",
"==",
"store",
".",
"ErrKeyNotFound",
"{",
"return",
"nil",
"\n",
"}",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"if",
"len",
"(",
"pairsN1",
")",
"==",
"0",
"{",
"pairLeaf",
",",
"err",
":=",
"kv",
".",
"Get",
"(",
"key",
",",
"nil",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"if",
"pairLeaf",
"==",
"nil",
"{",
"return",
"nil",
"\n",
"}",
"\n",
"pairs",
"[",
"pairLeaf",
".",
"Key",
"]",
"=",
"pairLeaf",
".",
"Value",
"\n",
"return",
"nil",
"\n",
"}",
"\n",
"for",
"_",
",",
"p",
":=",
"range",
"pairsN1",
"{",
"if",
"p",
".",
"Key",
"!=",
"key",
"{",
"err",
":=",
"kv",
".",
"ListRecursive",
"(",
"p",
".",
"Key",
",",
"pairs",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] |
// ListRecursive lists all key value children under key
// Replaced by ListValuedPairWithPrefix
// Deprecated
|
[
"ListRecursive",
"lists",
"all",
"key",
"value",
"children",
"under",
"key",
"Replaced",
"by",
"ListValuedPairWithPrefix",
"Deprecated"
] |
f987d01c3d97d01fffb73a57fa35a659c944396a
|
https://github.com/containous/staert/blob/f987d01c3d97d01fffb73a57fa35a659c944396a/kv.go#L333-L361
|
17,766 |
containous/staert
|
kv.go
|
ListValuedPairWithPrefix
|
func (kv *KvSource) ListValuedPairWithPrefix(key string) (map[string][]byte, error) {
pairs := make(map[string][]byte)
pairsN1, err := kv.List(key, nil)
if err == store.ErrKeyNotFound {
return pairs, nil
}
if err != nil {
return pairs, err
}
for _, p := range pairsN1 {
if len(p.Value) > 0 {
pairs[p.Key] = p.Value
}
}
return pairs, nil
}
|
go
|
func (kv *KvSource) ListValuedPairWithPrefix(key string) (map[string][]byte, error) {
pairs := make(map[string][]byte)
pairsN1, err := kv.List(key, nil)
if err == store.ErrKeyNotFound {
return pairs, nil
}
if err != nil {
return pairs, err
}
for _, p := range pairsN1 {
if len(p.Value) > 0 {
pairs[p.Key] = p.Value
}
}
return pairs, nil
}
|
[
"func",
"(",
"kv",
"*",
"KvSource",
")",
"ListValuedPairWithPrefix",
"(",
"key",
"string",
")",
"(",
"map",
"[",
"string",
"]",
"[",
"]",
"byte",
",",
"error",
")",
"{",
"pairs",
":=",
"make",
"(",
"map",
"[",
"string",
"]",
"[",
"]",
"byte",
")",
"\n\n",
"pairsN1",
",",
"err",
":=",
"kv",
".",
"List",
"(",
"key",
",",
"nil",
")",
"\n",
"if",
"err",
"==",
"store",
".",
"ErrKeyNotFound",
"{",
"return",
"pairs",
",",
"nil",
"\n",
"}",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"pairs",
",",
"err",
"\n",
"}",
"\n\n",
"for",
"_",
",",
"p",
":=",
"range",
"pairsN1",
"{",
"if",
"len",
"(",
"p",
".",
"Value",
")",
">",
"0",
"{",
"pairs",
"[",
"p",
".",
"Key",
"]",
"=",
"p",
".",
"Value",
"\n",
"}",
"\n",
"}",
"\n\n",
"return",
"pairs",
",",
"nil",
"\n",
"}"
] |
// ListValuedPairWithPrefix lists all key value children under key
|
[
"ListValuedPairWithPrefix",
"lists",
"all",
"key",
"value",
"children",
"under",
"key"
] |
f987d01c3d97d01fffb73a57fa35a659c944396a
|
https://github.com/containous/staert/blob/f987d01c3d97d01fffb73a57fa35a659c944396a/kv.go#L364-L382
|
17,767 |
powerman/rpc-codec
|
jsonrpc2/server.go
|
NewServerCodecContext
|
func NewServerCodecContext(ctx context.Context, conn io.ReadWriteCloser, srv *rpc.Server) rpc.ServerCodec {
codec := NewServerCodec(conn, srv)
codec.(*serverCodec).ctx = ctx
return codec
}
|
go
|
func NewServerCodecContext(ctx context.Context, conn io.ReadWriteCloser, srv *rpc.Server) rpc.ServerCodec {
codec := NewServerCodec(conn, srv)
codec.(*serverCodec).ctx = ctx
return codec
}
|
[
"func",
"NewServerCodecContext",
"(",
"ctx",
"context",
".",
"Context",
",",
"conn",
"io",
".",
"ReadWriteCloser",
",",
"srv",
"*",
"rpc",
".",
"Server",
")",
"rpc",
".",
"ServerCodec",
"{",
"codec",
":=",
"NewServerCodec",
"(",
"conn",
",",
"srv",
")",
"\n",
"codec",
".",
"(",
"*",
"serverCodec",
")",
".",
"ctx",
"=",
"ctx",
"\n",
"return",
"codec",
"\n",
"}"
] |
// NewServerCodecContext is NewServerCodec with given context provided
// within parameters for compatible RPC methods.
|
[
"NewServerCodecContext",
"is",
"NewServerCodec",
"with",
"given",
"context",
"provided",
"within",
"parameters",
"for",
"compatible",
"RPC",
"methods",
"."
] |
af7f4ca4cb4a72587df9f428a9226393eff61107
|
https://github.com/powerman/rpc-codec/blob/af7f4ca4cb4a72587df9f428a9226393eff61107/jsonrpc2/server.go#L71-L75
|
17,768 |
powerman/rpc-codec
|
jsonrpc2/server.go
|
ServeConnContext
|
func ServeConnContext(ctx context.Context, conn io.ReadWriteCloser) {
rpc.ServeCodec(NewServerCodecContext(ctx, conn, nil))
}
|
go
|
func ServeConnContext(ctx context.Context, conn io.ReadWriteCloser) {
rpc.ServeCodec(NewServerCodecContext(ctx, conn, nil))
}
|
[
"func",
"ServeConnContext",
"(",
"ctx",
"context",
".",
"Context",
",",
"conn",
"io",
".",
"ReadWriteCloser",
")",
"{",
"rpc",
".",
"ServeCodec",
"(",
"NewServerCodecContext",
"(",
"ctx",
",",
"conn",
",",
"nil",
")",
")",
"\n",
"}"
] |
// ServeConnContext is ServeConn with given context provided
// within parameters for compatible RPC methods.
|
[
"ServeConnContext",
"is",
"ServeConn",
"with",
"given",
"context",
"provided",
"within",
"parameters",
"for",
"compatible",
"RPC",
"methods",
"."
] |
af7f4ca4cb4a72587df9f428a9226393eff61107
|
https://github.com/powerman/rpc-codec/blob/af7f4ca4cb4a72587df9f428a9226393eff61107/jsonrpc2/server.go#L280-L282
|
17,769 |
powerman/rpc-codec
|
jsonrpc2/batch.go
|
Batch
|
func (JSONRPC2) Batch(arg BatchArg, replies *[]*json.RawMessage) (err error) {
cli, srv := net.Pipe()
defer cli.Close()
go arg.srv.ServeCodec(NewServerCodecContext(arg.Context(), srv, arg.srv))
replyc := make(chan *json.RawMessage, len(arg.reqs))
donec := make(chan struct{}, 1)
go func() {
dec := json.NewDecoder(cli)
*replies = make([]*json.RawMessage, 0, len(arg.reqs))
for reply := range replyc {
if reply != nil {
*replies = append(*replies, reply)
} else {
*replies = append(*replies, new(json.RawMessage))
if dec.Decode((*replies)[len(*replies)-1]) != nil {
(*replies)[len(*replies)-1] = &jErrRequest
}
}
}
donec <- struct{}{}
}()
var testreq serverRequest
for _, req := range arg.reqs {
if req == nil || json.Unmarshal(*req, &testreq) != nil {
replyc <- &jErrRequest
} else {
if testreq.ID != nil {
replyc <- nil
}
if _, err = cli.Write(append(*req, '\n')); err != nil {
break
}
}
}
close(replyc)
<-donec
return err
}
|
go
|
func (JSONRPC2) Batch(arg BatchArg, replies *[]*json.RawMessage) (err error) {
cli, srv := net.Pipe()
defer cli.Close()
go arg.srv.ServeCodec(NewServerCodecContext(arg.Context(), srv, arg.srv))
replyc := make(chan *json.RawMessage, len(arg.reqs))
donec := make(chan struct{}, 1)
go func() {
dec := json.NewDecoder(cli)
*replies = make([]*json.RawMessage, 0, len(arg.reqs))
for reply := range replyc {
if reply != nil {
*replies = append(*replies, reply)
} else {
*replies = append(*replies, new(json.RawMessage))
if dec.Decode((*replies)[len(*replies)-1]) != nil {
(*replies)[len(*replies)-1] = &jErrRequest
}
}
}
donec <- struct{}{}
}()
var testreq serverRequest
for _, req := range arg.reqs {
if req == nil || json.Unmarshal(*req, &testreq) != nil {
replyc <- &jErrRequest
} else {
if testreq.ID != nil {
replyc <- nil
}
if _, err = cli.Write(append(*req, '\n')); err != nil {
break
}
}
}
close(replyc)
<-donec
return err
}
|
[
"func",
"(",
"JSONRPC2",
")",
"Batch",
"(",
"arg",
"BatchArg",
",",
"replies",
"*",
"[",
"]",
"*",
"json",
".",
"RawMessage",
")",
"(",
"err",
"error",
")",
"{",
"cli",
",",
"srv",
":=",
"net",
".",
"Pipe",
"(",
")",
"\n",
"defer",
"cli",
".",
"Close",
"(",
")",
"\n",
"go",
"arg",
".",
"srv",
".",
"ServeCodec",
"(",
"NewServerCodecContext",
"(",
"arg",
".",
"Context",
"(",
")",
",",
"srv",
",",
"arg",
".",
"srv",
")",
")",
"\n\n",
"replyc",
":=",
"make",
"(",
"chan",
"*",
"json",
".",
"RawMessage",
",",
"len",
"(",
"arg",
".",
"reqs",
")",
")",
"\n",
"donec",
":=",
"make",
"(",
"chan",
"struct",
"{",
"}",
",",
"1",
")",
"\n\n",
"go",
"func",
"(",
")",
"{",
"dec",
":=",
"json",
".",
"NewDecoder",
"(",
"cli",
")",
"\n",
"*",
"replies",
"=",
"make",
"(",
"[",
"]",
"*",
"json",
".",
"RawMessage",
",",
"0",
",",
"len",
"(",
"arg",
".",
"reqs",
")",
")",
"\n",
"for",
"reply",
":=",
"range",
"replyc",
"{",
"if",
"reply",
"!=",
"nil",
"{",
"*",
"replies",
"=",
"append",
"(",
"*",
"replies",
",",
"reply",
")",
"\n",
"}",
"else",
"{",
"*",
"replies",
"=",
"append",
"(",
"*",
"replies",
",",
"new",
"(",
"json",
".",
"RawMessage",
")",
")",
"\n",
"if",
"dec",
".",
"Decode",
"(",
"(",
"*",
"replies",
")",
"[",
"len",
"(",
"*",
"replies",
")",
"-",
"1",
"]",
")",
"!=",
"nil",
"{",
"(",
"*",
"replies",
")",
"[",
"len",
"(",
"*",
"replies",
")",
"-",
"1",
"]",
"=",
"&",
"jErrRequest",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n",
"donec",
"<-",
"struct",
"{",
"}",
"{",
"}",
"\n",
"}",
"(",
")",
"\n\n",
"var",
"testreq",
"serverRequest",
"\n",
"for",
"_",
",",
"req",
":=",
"range",
"arg",
".",
"reqs",
"{",
"if",
"req",
"==",
"nil",
"||",
"json",
".",
"Unmarshal",
"(",
"*",
"req",
",",
"&",
"testreq",
")",
"!=",
"nil",
"{",
"replyc",
"<-",
"&",
"jErrRequest",
"\n",
"}",
"else",
"{",
"if",
"testreq",
".",
"ID",
"!=",
"nil",
"{",
"replyc",
"<-",
"nil",
"\n",
"}",
"\n",
"if",
"_",
",",
"err",
"=",
"cli",
".",
"Write",
"(",
"append",
"(",
"*",
"req",
",",
"'\\n'",
")",
")",
";",
"err",
"!=",
"nil",
"{",
"break",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n\n",
"close",
"(",
"replyc",
")",
"\n",
"<-",
"donec",
"\n",
"return",
"err",
"\n",
"}"
] |
// Batch is an internal RPC method used to process batch requests.
|
[
"Batch",
"is",
"an",
"internal",
"RPC",
"method",
"used",
"to",
"process",
"batch",
"requests",
"."
] |
af7f4ca4cb4a72587df9f428a9226393eff61107
|
https://github.com/powerman/rpc-codec/blob/af7f4ca4cb4a72587df9f428a9226393eff61107/jsonrpc2/batch.go#L22-L63
|
17,770 |
powerman/rpc-codec
|
jsonrpc2/client.go
|
Notify
|
func (c Client) Notify(serviceMethod string, args interface{}) error {
req := &rpc.Request{
ServiceMethod: serviceMethod,
Seq: seqNotify,
}
return c.codec.WriteRequest(req, args)
}
|
go
|
func (c Client) Notify(serviceMethod string, args interface{}) error {
req := &rpc.Request{
ServiceMethod: serviceMethod,
Seq: seqNotify,
}
return c.codec.WriteRequest(req, args)
}
|
[
"func",
"(",
"c",
"Client",
")",
"Notify",
"(",
"serviceMethod",
"string",
",",
"args",
"interface",
"{",
"}",
")",
"error",
"{",
"req",
":=",
"&",
"rpc",
".",
"Request",
"{",
"ServiceMethod",
":",
"serviceMethod",
",",
"Seq",
":",
"seqNotify",
",",
"}",
"\n",
"return",
"c",
".",
"codec",
".",
"WriteRequest",
"(",
"req",
",",
"args",
")",
"\n",
"}"
] |
// Notify try to invoke the named function. It return error only in case
// it wasn't able to send request.
|
[
"Notify",
"try",
"to",
"invoke",
"the",
"named",
"function",
".",
"It",
"return",
"error",
"only",
"in",
"case",
"it",
"wasn",
"t",
"able",
"to",
"send",
"request",
"."
] |
af7f4ca4cb4a72587df9f428a9226393eff61107
|
https://github.com/powerman/rpc-codec/blob/af7f4ca4cb4a72587df9f428a9226393eff61107/jsonrpc2/client.go#L231-L237
|
17,771 |
powerman/rpc-codec
|
jsonrpc2/client.go
|
NewClientWithCodec
|
func NewClientWithCodec(codec rpc.ClientCodec) *Client {
client := rpc.NewClientWithCodec(codec)
return &Client{client, codec}
}
|
go
|
func NewClientWithCodec(codec rpc.ClientCodec) *Client {
client := rpc.NewClientWithCodec(codec)
return &Client{client, codec}
}
|
[
"func",
"NewClientWithCodec",
"(",
"codec",
"rpc",
".",
"ClientCodec",
")",
"*",
"Client",
"{",
"client",
":=",
"rpc",
".",
"NewClientWithCodec",
"(",
"codec",
")",
"\n",
"return",
"&",
"Client",
"{",
"client",
",",
"codec",
"}",
"\n",
"}"
] |
// NewClientWithCodec returns a new Client using the given rpc.ClientCodec.
|
[
"NewClientWithCodec",
"returns",
"a",
"new",
"Client",
"using",
"the",
"given",
"rpc",
".",
"ClientCodec",
"."
] |
af7f4ca4cb4a72587df9f428a9226393eff61107
|
https://github.com/powerman/rpc-codec/blob/af7f4ca4cb4a72587df9f428a9226393eff61107/jsonrpc2/client.go#L246-L249
|
17,772 |
mjibson/goon
|
goon.go
|
FromContext
|
func FromContext(c context.Context) *Goon {
return &Goon{
Context: c,
cache: make(map[string]interface{}),
KindNameResolver: DefaultKindName,
}
}
|
go
|
func FromContext(c context.Context) *Goon {
return &Goon{
Context: c,
cache: make(map[string]interface{}),
KindNameResolver: DefaultKindName,
}
}
|
[
"func",
"FromContext",
"(",
"c",
"context",
".",
"Context",
")",
"*",
"Goon",
"{",
"return",
"&",
"Goon",
"{",
"Context",
":",
"c",
",",
"cache",
":",
"make",
"(",
"map",
"[",
"string",
"]",
"interface",
"{",
"}",
")",
",",
"KindNameResolver",
":",
"DefaultKindName",
",",
"}",
"\n",
"}"
] |
// FromContext creates a new Goon object from the given appengine Context.
// Useful with profiling packages like appstats.
|
[
"FromContext",
"creates",
"a",
"new",
"Goon",
"object",
"from",
"the",
"given",
"appengine",
"Context",
".",
"Useful",
"with",
"profiling",
"packages",
"like",
"appstats",
"."
] |
339e0044a72ff2a4a0620cca12959496c9c8be12
|
https://github.com/mjibson/goon/blob/339e0044a72ff2a4a0620cca12959496c9c8be12/goon.go#L88-L94
|
17,773 |
mjibson/goon
|
goon.go
|
Key
|
func (g *Goon) Key(src interface{}) *datastore.Key {
if k, err := g.KeyError(src); err == nil {
return k
}
return nil
}
|
go
|
func (g *Goon) Key(src interface{}) *datastore.Key {
if k, err := g.KeyError(src); err == nil {
return k
}
return nil
}
|
[
"func",
"(",
"g",
"*",
"Goon",
")",
"Key",
"(",
"src",
"interface",
"{",
"}",
")",
"*",
"datastore",
".",
"Key",
"{",
"if",
"k",
",",
"err",
":=",
"g",
".",
"KeyError",
"(",
"src",
")",
";",
"err",
"==",
"nil",
"{",
"return",
"k",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] |
// Key is the same as KeyError, except nil is returned on error or if the key
// is incomplete.
|
[
"Key",
"is",
"the",
"same",
"as",
"KeyError",
"except",
"nil",
"is",
"returned",
"on",
"error",
"or",
"if",
"the",
"key",
"is",
"incomplete",
"."
] |
339e0044a72ff2a4a0620cca12959496c9c8be12
|
https://github.com/mjibson/goon/blob/339e0044a72ff2a4a0620cca12959496c9c8be12/goon.go#L140-L145
|
17,774 |
mjibson/goon
|
goon.go
|
Kind
|
func (g *Goon) Kind(src interface{}) string {
if k, err := g.KeyError(src); err == nil {
return k.Kind()
}
return ""
}
|
go
|
func (g *Goon) Kind(src interface{}) string {
if k, err := g.KeyError(src); err == nil {
return k.Kind()
}
return ""
}
|
[
"func",
"(",
"g",
"*",
"Goon",
")",
"Kind",
"(",
"src",
"interface",
"{",
"}",
")",
"string",
"{",
"if",
"k",
",",
"err",
":=",
"g",
".",
"KeyError",
"(",
"src",
")",
";",
"err",
"==",
"nil",
"{",
"return",
"k",
".",
"Kind",
"(",
")",
"\n",
"}",
"\n",
"return",
"\"",
"\"",
"\n",
"}"
] |
// Kind returns src's datastore Kind or "" on error.
|
[
"Kind",
"returns",
"src",
"s",
"datastore",
"Kind",
"or",
"on",
"error",
"."
] |
339e0044a72ff2a4a0620cca12959496c9c8be12
|
https://github.com/mjibson/goon/blob/339e0044a72ff2a4a0620cca12959496c9c8be12/goon.go#L148-L153
|
17,775 |
mjibson/goon
|
goon.go
|
KeyError
|
func (g *Goon) KeyError(src interface{}) (*datastore.Key, error) {
key, _, err := g.getStructKey(src)
return key, err
}
|
go
|
func (g *Goon) KeyError(src interface{}) (*datastore.Key, error) {
key, _, err := g.getStructKey(src)
return key, err
}
|
[
"func",
"(",
"g",
"*",
"Goon",
")",
"KeyError",
"(",
"src",
"interface",
"{",
"}",
")",
"(",
"*",
"datastore",
".",
"Key",
",",
"error",
")",
"{",
"key",
",",
"_",
",",
"err",
":=",
"g",
".",
"getStructKey",
"(",
"src",
")",
"\n",
"return",
"key",
",",
"err",
"\n",
"}"
] |
// KeyError returns the key of src based on its properties.
|
[
"KeyError",
"returns",
"the",
"key",
"of",
"src",
"based",
"on",
"its",
"properties",
"."
] |
339e0044a72ff2a4a0620cca12959496c9c8be12
|
https://github.com/mjibson/goon/blob/339e0044a72ff2a4a0620cca12959496c9c8be12/goon.go#L156-L159
|
17,776 |
mjibson/goon
|
goon.go
|
Put
|
func (g *Goon) Put(src interface{}) (*datastore.Key, error) {
ks, err := g.PutMulti([]interface{}{src})
if err != nil {
if me, ok := err.(appengine.MultiError); ok {
return nil, me[0]
}
return nil, err
}
return ks[0], nil
}
|
go
|
func (g *Goon) Put(src interface{}) (*datastore.Key, error) {
ks, err := g.PutMulti([]interface{}{src})
if err != nil {
if me, ok := err.(appengine.MultiError); ok {
return nil, me[0]
}
return nil, err
}
return ks[0], nil
}
|
[
"func",
"(",
"g",
"*",
"Goon",
")",
"Put",
"(",
"src",
"interface",
"{",
"}",
")",
"(",
"*",
"datastore",
".",
"Key",
",",
"error",
")",
"{",
"ks",
",",
"err",
":=",
"g",
".",
"PutMulti",
"(",
"[",
"]",
"interface",
"{",
"}",
"{",
"src",
"}",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"if",
"me",
",",
"ok",
":=",
"err",
".",
"(",
"appengine",
".",
"MultiError",
")",
";",
"ok",
"{",
"return",
"nil",
",",
"me",
"[",
"0",
"]",
"\n",
"}",
"\n",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"return",
"ks",
"[",
"0",
"]",
",",
"nil",
"\n",
"}"
] |
// Put saves the entity src into the datastore based on src's key k. If k
// is an incomplete key, the returned key will be a unique key generated by
// the datastore.
|
[
"Put",
"saves",
"the",
"entity",
"src",
"into",
"the",
"datastore",
"based",
"on",
"src",
"s",
"key",
"k",
".",
"If",
"k",
"is",
"an",
"incomplete",
"key",
"the",
"returned",
"key",
"will",
"be",
"a",
"unique",
"key",
"generated",
"by",
"the",
"datastore",
"."
] |
339e0044a72ff2a4a0620cca12959496c9c8be12
|
https://github.com/mjibson/goon/blob/339e0044a72ff2a4a0620cca12959496c9c8be12/goon.go#L205-L214
|
17,777 |
mjibson/goon
|
goon.go
|
FlushLocalCache
|
func (g *Goon) FlushLocalCache() {
g.cacheLock.Lock()
g.cache = make(map[string]interface{})
g.cacheLock.Unlock()
}
|
go
|
func (g *Goon) FlushLocalCache() {
g.cacheLock.Lock()
g.cache = make(map[string]interface{})
g.cacheLock.Unlock()
}
|
[
"func",
"(",
"g",
"*",
"Goon",
")",
"FlushLocalCache",
"(",
")",
"{",
"g",
".",
"cacheLock",
".",
"Lock",
"(",
")",
"\n",
"g",
".",
"cache",
"=",
"make",
"(",
"map",
"[",
"string",
"]",
"interface",
"{",
"}",
")",
"\n",
"g",
".",
"cacheLock",
".",
"Unlock",
"(",
")",
"\n",
"}"
] |
// FlushLocalCache clears the local memory cache.
|
[
"FlushLocalCache",
"clears",
"the",
"local",
"memory",
"cache",
"."
] |
339e0044a72ff2a4a0620cca12959496c9c8be12
|
https://github.com/mjibson/goon/blob/339e0044a72ff2a4a0620cca12959496c9c8be12/goon.go#L315-L319
|
17,778 |
mjibson/goon
|
goon.go
|
Get
|
func (g *Goon) Get(dst interface{}) error {
set := reflect.ValueOf(dst)
if set.Kind() != reflect.Ptr {
return fmt.Errorf("goon: expected pointer to a struct, got %#v", dst)
}
if !set.CanSet() {
set = set.Elem()
}
dsts := []interface{}{dst}
if err := g.GetMulti(dsts); err != nil {
// Look for an embedded error if it's multi
if me, ok := err.(appengine.MultiError); ok {
return me[0]
}
// Not multi, normal error
return err
}
set.Set(reflect.Indirect(reflect.ValueOf(dsts[0])))
return nil
}
|
go
|
func (g *Goon) Get(dst interface{}) error {
set := reflect.ValueOf(dst)
if set.Kind() != reflect.Ptr {
return fmt.Errorf("goon: expected pointer to a struct, got %#v", dst)
}
if !set.CanSet() {
set = set.Elem()
}
dsts := []interface{}{dst}
if err := g.GetMulti(dsts); err != nil {
// Look for an embedded error if it's multi
if me, ok := err.(appengine.MultiError); ok {
return me[0]
}
// Not multi, normal error
return err
}
set.Set(reflect.Indirect(reflect.ValueOf(dsts[0])))
return nil
}
|
[
"func",
"(",
"g",
"*",
"Goon",
")",
"Get",
"(",
"dst",
"interface",
"{",
"}",
")",
"error",
"{",
"set",
":=",
"reflect",
".",
"ValueOf",
"(",
"dst",
")",
"\n",
"if",
"set",
".",
"Kind",
"(",
")",
"!=",
"reflect",
".",
"Ptr",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"dst",
")",
"\n",
"}",
"\n",
"if",
"!",
"set",
".",
"CanSet",
"(",
")",
"{",
"set",
"=",
"set",
".",
"Elem",
"(",
")",
"\n",
"}",
"\n",
"dsts",
":=",
"[",
"]",
"interface",
"{",
"}",
"{",
"dst",
"}",
"\n",
"if",
"err",
":=",
"g",
".",
"GetMulti",
"(",
"dsts",
")",
";",
"err",
"!=",
"nil",
"{",
"// Look for an embedded error if it's multi",
"if",
"me",
",",
"ok",
":=",
"err",
".",
"(",
"appengine",
".",
"MultiError",
")",
";",
"ok",
"{",
"return",
"me",
"[",
"0",
"]",
"\n",
"}",
"\n",
"// Not multi, normal error",
"return",
"err",
"\n",
"}",
"\n",
"set",
".",
"Set",
"(",
"reflect",
".",
"Indirect",
"(",
"reflect",
".",
"ValueOf",
"(",
"dsts",
"[",
"0",
"]",
")",
")",
")",
"\n",
"return",
"nil",
"\n",
"}"
] |
// Get loads the entity based on dst's key into dst
// If there is no such entity for the key, Get returns
// datastore.ErrNoSuchEntity.
|
[
"Get",
"loads",
"the",
"entity",
"based",
"on",
"dst",
"s",
"key",
"into",
"dst",
"If",
"there",
"is",
"no",
"such",
"entity",
"for",
"the",
"key",
"Get",
"returns",
"datastore",
".",
"ErrNoSuchEntity",
"."
] |
339e0044a72ff2a4a0620cca12959496c9c8be12
|
https://github.com/mjibson/goon/blob/339e0044a72ff2a4a0620cca12959496c9c8be12/goon.go#L359-L378
|
17,779 |
mjibson/goon
|
goon.go
|
Delete
|
func (g *Goon) Delete(key *datastore.Key) error {
keys := []*datastore.Key{key}
err := g.DeleteMulti(keys)
if me, ok := err.(appengine.MultiError); ok {
return me[0]
}
return err
}
|
go
|
func (g *Goon) Delete(key *datastore.Key) error {
keys := []*datastore.Key{key}
err := g.DeleteMulti(keys)
if me, ok := err.(appengine.MultiError); ok {
return me[0]
}
return err
}
|
[
"func",
"(",
"g",
"*",
"Goon",
")",
"Delete",
"(",
"key",
"*",
"datastore",
".",
"Key",
")",
"error",
"{",
"keys",
":=",
"[",
"]",
"*",
"datastore",
".",
"Key",
"{",
"key",
"}",
"\n",
"err",
":=",
"g",
".",
"DeleteMulti",
"(",
"keys",
")",
"\n",
"if",
"me",
",",
"ok",
":=",
"err",
".",
"(",
"appengine",
".",
"MultiError",
")",
";",
"ok",
"{",
"return",
"me",
"[",
"0",
"]",
"\n",
"}",
"\n",
"return",
"err",
"\n",
"}"
] |
// Delete deletes the entity for the given key.
|
[
"Delete",
"deletes",
"the",
"entity",
"for",
"the",
"given",
"key",
"."
] |
339e0044a72ff2a4a0620cca12959496c9c8be12
|
https://github.com/mjibson/goon/blob/339e0044a72ff2a4a0620cca12959496c9c8be12/goon.go#L580-L587
|
17,780 |
mjibson/goon
|
goon.go
|
DeleteMulti
|
func (g *Goon) DeleteMulti(keys []*datastore.Key) error {
if len(keys) == 0 {
return nil
// not an error, and it was "successful", so return nil
}
memkeys := make([]string, len(keys))
g.cacheLock.Lock()
for i, k := range keys {
mk := MemcacheKey(k)
memkeys[i] = mk
if g.inTransaction {
g.txnCacheLock.Lock()
g.toDelete[mk] = true
g.txnCacheLock.Unlock()
} else {
delete(g.cache, mk)
}
}
g.cacheLock.Unlock()
// Memcache needs to be updated after the datastore to prevent a common race condition,
// where a concurrent request will fetch the not-yet-updated data from the datastore
// and populate memcache with it.
if g.inTransaction {
g.txnCacheLock.Lock()
for _, mk := range memkeys {
g.toDeleteMC[mk] = true
}
g.txnCacheLock.Unlock()
} else {
defer memcache.DeleteMulti(g.Context, memkeys)
}
mu := new(sync.Mutex)
multiErr, any := make(appengine.MultiError, len(keys)), false
goroutines := (len(keys)-1)/deleteMultiLimit + 1
var wg sync.WaitGroup
wg.Add(goroutines)
for i := 0; i < goroutines; i++ {
go func(i int) {
defer wg.Done()
lo := i * deleteMultiLimit
hi := (i + 1) * deleteMultiLimit
if hi > len(keys) {
hi = len(keys)
}
dmerr := datastore.DeleteMulti(g.Context, keys[lo:hi])
if dmerr != nil {
mu.Lock()
any = true // this flag tells DeleteMulti to return multiErr later
mu.Unlock()
merr, ok := dmerr.(appengine.MultiError)
if !ok {
g.error(dmerr)
for j := lo; j < hi; j++ {
multiErr[j] = dmerr
}
return
}
copy(multiErr[lo:hi], merr)
}
}(i)
}
wg.Wait()
if any {
return realError(multiErr)
}
return nil
}
|
go
|
func (g *Goon) DeleteMulti(keys []*datastore.Key) error {
if len(keys) == 0 {
return nil
// not an error, and it was "successful", so return nil
}
memkeys := make([]string, len(keys))
g.cacheLock.Lock()
for i, k := range keys {
mk := MemcacheKey(k)
memkeys[i] = mk
if g.inTransaction {
g.txnCacheLock.Lock()
g.toDelete[mk] = true
g.txnCacheLock.Unlock()
} else {
delete(g.cache, mk)
}
}
g.cacheLock.Unlock()
// Memcache needs to be updated after the datastore to prevent a common race condition,
// where a concurrent request will fetch the not-yet-updated data from the datastore
// and populate memcache with it.
if g.inTransaction {
g.txnCacheLock.Lock()
for _, mk := range memkeys {
g.toDeleteMC[mk] = true
}
g.txnCacheLock.Unlock()
} else {
defer memcache.DeleteMulti(g.Context, memkeys)
}
mu := new(sync.Mutex)
multiErr, any := make(appengine.MultiError, len(keys)), false
goroutines := (len(keys)-1)/deleteMultiLimit + 1
var wg sync.WaitGroup
wg.Add(goroutines)
for i := 0; i < goroutines; i++ {
go func(i int) {
defer wg.Done()
lo := i * deleteMultiLimit
hi := (i + 1) * deleteMultiLimit
if hi > len(keys) {
hi = len(keys)
}
dmerr := datastore.DeleteMulti(g.Context, keys[lo:hi])
if dmerr != nil {
mu.Lock()
any = true // this flag tells DeleteMulti to return multiErr later
mu.Unlock()
merr, ok := dmerr.(appengine.MultiError)
if !ok {
g.error(dmerr)
for j := lo; j < hi; j++ {
multiErr[j] = dmerr
}
return
}
copy(multiErr[lo:hi], merr)
}
}(i)
}
wg.Wait()
if any {
return realError(multiErr)
}
return nil
}
|
[
"func",
"(",
"g",
"*",
"Goon",
")",
"DeleteMulti",
"(",
"keys",
"[",
"]",
"*",
"datastore",
".",
"Key",
")",
"error",
"{",
"if",
"len",
"(",
"keys",
")",
"==",
"0",
"{",
"return",
"nil",
"\n",
"// not an error, and it was \"successful\", so return nil",
"}",
"\n",
"memkeys",
":=",
"make",
"(",
"[",
"]",
"string",
",",
"len",
"(",
"keys",
")",
")",
"\n\n",
"g",
".",
"cacheLock",
".",
"Lock",
"(",
")",
"\n",
"for",
"i",
",",
"k",
":=",
"range",
"keys",
"{",
"mk",
":=",
"MemcacheKey",
"(",
"k",
")",
"\n",
"memkeys",
"[",
"i",
"]",
"=",
"mk",
"\n\n",
"if",
"g",
".",
"inTransaction",
"{",
"g",
".",
"txnCacheLock",
".",
"Lock",
"(",
")",
"\n",
"g",
".",
"toDelete",
"[",
"mk",
"]",
"=",
"true",
"\n",
"g",
".",
"txnCacheLock",
".",
"Unlock",
"(",
")",
"\n",
"}",
"else",
"{",
"delete",
"(",
"g",
".",
"cache",
",",
"mk",
")",
"\n",
"}",
"\n",
"}",
"\n",
"g",
".",
"cacheLock",
".",
"Unlock",
"(",
")",
"\n\n",
"// Memcache needs to be updated after the datastore to prevent a common race condition,",
"// where a concurrent request will fetch the not-yet-updated data from the datastore",
"// and populate memcache with it.",
"if",
"g",
".",
"inTransaction",
"{",
"g",
".",
"txnCacheLock",
".",
"Lock",
"(",
")",
"\n",
"for",
"_",
",",
"mk",
":=",
"range",
"memkeys",
"{",
"g",
".",
"toDeleteMC",
"[",
"mk",
"]",
"=",
"true",
"\n",
"}",
"\n",
"g",
".",
"txnCacheLock",
".",
"Unlock",
"(",
")",
"\n",
"}",
"else",
"{",
"defer",
"memcache",
".",
"DeleteMulti",
"(",
"g",
".",
"Context",
",",
"memkeys",
")",
"\n",
"}",
"\n\n",
"mu",
":=",
"new",
"(",
"sync",
".",
"Mutex",
")",
"\n",
"multiErr",
",",
"any",
":=",
"make",
"(",
"appengine",
".",
"MultiError",
",",
"len",
"(",
"keys",
")",
")",
",",
"false",
"\n",
"goroutines",
":=",
"(",
"len",
"(",
"keys",
")",
"-",
"1",
")",
"/",
"deleteMultiLimit",
"+",
"1",
"\n",
"var",
"wg",
"sync",
".",
"WaitGroup",
"\n",
"wg",
".",
"Add",
"(",
"goroutines",
")",
"\n",
"for",
"i",
":=",
"0",
";",
"i",
"<",
"goroutines",
";",
"i",
"++",
"{",
"go",
"func",
"(",
"i",
"int",
")",
"{",
"defer",
"wg",
".",
"Done",
"(",
")",
"\n",
"lo",
":=",
"i",
"*",
"deleteMultiLimit",
"\n",
"hi",
":=",
"(",
"i",
"+",
"1",
")",
"*",
"deleteMultiLimit",
"\n",
"if",
"hi",
">",
"len",
"(",
"keys",
")",
"{",
"hi",
"=",
"len",
"(",
"keys",
")",
"\n",
"}",
"\n",
"dmerr",
":=",
"datastore",
".",
"DeleteMulti",
"(",
"g",
".",
"Context",
",",
"keys",
"[",
"lo",
":",
"hi",
"]",
")",
"\n",
"if",
"dmerr",
"!=",
"nil",
"{",
"mu",
".",
"Lock",
"(",
")",
"\n",
"any",
"=",
"true",
"// this flag tells DeleteMulti to return multiErr later",
"\n",
"mu",
".",
"Unlock",
"(",
")",
"\n",
"merr",
",",
"ok",
":=",
"dmerr",
".",
"(",
"appengine",
".",
"MultiError",
")",
"\n",
"if",
"!",
"ok",
"{",
"g",
".",
"error",
"(",
"dmerr",
")",
"\n",
"for",
"j",
":=",
"lo",
";",
"j",
"<",
"hi",
";",
"j",
"++",
"{",
"multiErr",
"[",
"j",
"]",
"=",
"dmerr",
"\n",
"}",
"\n",
"return",
"\n",
"}",
"\n",
"copy",
"(",
"multiErr",
"[",
"lo",
":",
"hi",
"]",
",",
"merr",
")",
"\n",
"}",
"\n",
"}",
"(",
"i",
")",
"\n",
"}",
"\n",
"wg",
".",
"Wait",
"(",
")",
"\n",
"if",
"any",
"{",
"return",
"realError",
"(",
"multiErr",
")",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] |
// DeleteMulti is a batch version of Delete.
|
[
"DeleteMulti",
"is",
"a",
"batch",
"version",
"of",
"Delete",
"."
] |
339e0044a72ff2a4a0620cca12959496c9c8be12
|
https://github.com/mjibson/goon/blob/339e0044a72ff2a4a0620cca12959496c9c8be12/goon.go#L623-L693
|
17,781 |
mjibson/goon
|
entity.go
|
serializeStruct
|
func serializeStruct(src interface{}) ([]byte, error) {
if src == nil {
return serializeProperties(nil, false)
}
if k := reflect.Indirect(reflect.ValueOf(src)).Type().Kind(); k != reflect.Struct {
return nil, fmt.Errorf("goon: Expected struct, got instead: %v", k)
}
var err error
var props []datastore.Property
if pls, ok := src.(datastore.PropertyLoadSaver); ok {
props, err = pls.Save()
} else {
props, err = datastore.SaveStruct(src)
}
if err != nil {
return nil, err
}
return serializeProperties(props, true)
}
|
go
|
func serializeStruct(src interface{}) ([]byte, error) {
if src == nil {
return serializeProperties(nil, false)
}
if k := reflect.Indirect(reflect.ValueOf(src)).Type().Kind(); k != reflect.Struct {
return nil, fmt.Errorf("goon: Expected struct, got instead: %v", k)
}
var err error
var props []datastore.Property
if pls, ok := src.(datastore.PropertyLoadSaver); ok {
props, err = pls.Save()
} else {
props, err = datastore.SaveStruct(src)
}
if err != nil {
return nil, err
}
return serializeProperties(props, true)
}
|
[
"func",
"serializeStruct",
"(",
"src",
"interface",
"{",
"}",
")",
"(",
"[",
"]",
"byte",
",",
"error",
")",
"{",
"if",
"src",
"==",
"nil",
"{",
"return",
"serializeProperties",
"(",
"nil",
",",
"false",
")",
"\n",
"}",
"\n",
"if",
"k",
":=",
"reflect",
".",
"Indirect",
"(",
"reflect",
".",
"ValueOf",
"(",
"src",
")",
")",
".",
"Type",
"(",
")",
".",
"Kind",
"(",
")",
";",
"k",
"!=",
"reflect",
".",
"Struct",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"k",
")",
"\n",
"}",
"\n\n",
"var",
"err",
"error",
"\n",
"var",
"props",
"[",
"]",
"datastore",
".",
"Property",
"\n",
"if",
"pls",
",",
"ok",
":=",
"src",
".",
"(",
"datastore",
".",
"PropertyLoadSaver",
")",
";",
"ok",
"{",
"props",
",",
"err",
"=",
"pls",
".",
"Save",
"(",
")",
"\n",
"}",
"else",
"{",
"props",
",",
"err",
"=",
"datastore",
".",
"SaveStruct",
"(",
"src",
")",
"\n",
"}",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"return",
"serializeProperties",
"(",
"props",
",",
"true",
")",
"\n",
"}"
] |
// serializeStruct takes a struct and serializes it to portable bytes.
|
[
"serializeStruct",
"takes",
"a",
"struct",
"and",
"serializes",
"it",
"to",
"portable",
"bytes",
"."
] |
339e0044a72ff2a4a0620cca12959496c9c8be12
|
https://github.com/mjibson/goon/blob/339e0044a72ff2a4a0620cca12959496c9c8be12/entity.go#L500-L520
|
17,782 |
mjibson/goon
|
entity.go
|
serializeProperties
|
func serializeProperties(props []datastore.Property, exists bool) ([]byte, error) {
// NOTE: We use a separate exists bool to support nil-props for existing structs
if !exists {
return []byte{0, 0, 0, 0}, nil
}
buf := getBuffer()
defer freeBuffer(buf)
// Serialize the entity header
header := serializeEntityHeader(len(props), entityExists)
headerBytes := make([]byte, 4)
binary.LittleEndian.PutUint32(headerBytes, header)
buf.Write(headerBytes)
// Serialize the properties
for i := range props {
if err := serializeProperty(buf, &props[i]); err != nil {
return nil, err
}
}
output := make([]byte, buf.Len())
copy(output, buf.Bytes())
return output, nil
}
|
go
|
func serializeProperties(props []datastore.Property, exists bool) ([]byte, error) {
// NOTE: We use a separate exists bool to support nil-props for existing structs
if !exists {
return []byte{0, 0, 0, 0}, nil
}
buf := getBuffer()
defer freeBuffer(buf)
// Serialize the entity header
header := serializeEntityHeader(len(props), entityExists)
headerBytes := make([]byte, 4)
binary.LittleEndian.PutUint32(headerBytes, header)
buf.Write(headerBytes)
// Serialize the properties
for i := range props {
if err := serializeProperty(buf, &props[i]); err != nil {
return nil, err
}
}
output := make([]byte, buf.Len())
copy(output, buf.Bytes())
return output, nil
}
|
[
"func",
"serializeProperties",
"(",
"props",
"[",
"]",
"datastore",
".",
"Property",
",",
"exists",
"bool",
")",
"(",
"[",
"]",
"byte",
",",
"error",
")",
"{",
"// NOTE: We use a separate exists bool to support nil-props for existing structs",
"if",
"!",
"exists",
"{",
"return",
"[",
"]",
"byte",
"{",
"0",
",",
"0",
",",
"0",
",",
"0",
"}",
",",
"nil",
"\n",
"}",
"\n\n",
"buf",
":=",
"getBuffer",
"(",
")",
"\n",
"defer",
"freeBuffer",
"(",
"buf",
")",
"\n\n",
"// Serialize the entity header",
"header",
":=",
"serializeEntityHeader",
"(",
"len",
"(",
"props",
")",
",",
"entityExists",
")",
"\n",
"headerBytes",
":=",
"make",
"(",
"[",
"]",
"byte",
",",
"4",
")",
"\n",
"binary",
".",
"LittleEndian",
".",
"PutUint32",
"(",
"headerBytes",
",",
"header",
")",
"\n",
"buf",
".",
"Write",
"(",
"headerBytes",
")",
"\n\n",
"// Serialize the properties",
"for",
"i",
":=",
"range",
"props",
"{",
"if",
"err",
":=",
"serializeProperty",
"(",
"buf",
",",
"&",
"props",
"[",
"i",
"]",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"}",
"\n\n",
"output",
":=",
"make",
"(",
"[",
"]",
"byte",
",",
"buf",
".",
"Len",
"(",
")",
")",
"\n",
"copy",
"(",
"output",
",",
"buf",
".",
"Bytes",
"(",
")",
")",
"\n",
"return",
"output",
",",
"nil",
"\n",
"}"
] |
// serializeProperties takes a slice of properties and serializes it to portable bytes.
|
[
"serializeProperties",
"takes",
"a",
"slice",
"of",
"properties",
"and",
"serializes",
"it",
"to",
"portable",
"bytes",
"."
] |
339e0044a72ff2a4a0620cca12959496c9c8be12
|
https://github.com/mjibson/goon/blob/339e0044a72ff2a4a0620cca12959496c9c8be12/entity.go#L523-L548
|
17,783 |
mjibson/goon
|
entity.go
|
deserializeStruct
|
func deserializeStruct(dst interface{}, b []byte) error {
if len(b) == 0 {
return fmt.Errorf("goon: Expected some data to deserialize, got none.")
}
if k := reflect.Indirect(reflect.ValueOf(dst)).Type().Kind(); k != reflect.Struct {
return fmt.Errorf("goon: Expected struct, got instead: %v", k)
}
// Deserialize the header
header := binary.LittleEndian.Uint32(b[:4])
propCount, flags := deserializeEntityHeader(header)
if flags&entityExists == 0 {
return datastore.ErrNoSuchEntity
}
// Deserialize the properties
buf := bytes.NewBuffer(b[4:])
props := make([]datastore.Property, propCount)
for i := 0; i < propCount; i++ {
if err := deserializeProperty(buf, &props[i]); err != nil {
return err
}
}
return deserializeProperties(dst, props)
}
|
go
|
func deserializeStruct(dst interface{}, b []byte) error {
if len(b) == 0 {
return fmt.Errorf("goon: Expected some data to deserialize, got none.")
}
if k := reflect.Indirect(reflect.ValueOf(dst)).Type().Kind(); k != reflect.Struct {
return fmt.Errorf("goon: Expected struct, got instead: %v", k)
}
// Deserialize the header
header := binary.LittleEndian.Uint32(b[:4])
propCount, flags := deserializeEntityHeader(header)
if flags&entityExists == 0 {
return datastore.ErrNoSuchEntity
}
// Deserialize the properties
buf := bytes.NewBuffer(b[4:])
props := make([]datastore.Property, propCount)
for i := 0; i < propCount; i++ {
if err := deserializeProperty(buf, &props[i]); err != nil {
return err
}
}
return deserializeProperties(dst, props)
}
|
[
"func",
"deserializeStruct",
"(",
"dst",
"interface",
"{",
"}",
",",
"b",
"[",
"]",
"byte",
")",
"error",
"{",
"if",
"len",
"(",
"b",
")",
"==",
"0",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"if",
"k",
":=",
"reflect",
".",
"Indirect",
"(",
"reflect",
".",
"ValueOf",
"(",
"dst",
")",
")",
".",
"Type",
"(",
")",
".",
"Kind",
"(",
")",
";",
"k",
"!=",
"reflect",
".",
"Struct",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"k",
")",
"\n",
"}",
"\n\n",
"// Deserialize the header",
"header",
":=",
"binary",
".",
"LittleEndian",
".",
"Uint32",
"(",
"b",
"[",
":",
"4",
"]",
")",
"\n",
"propCount",
",",
"flags",
":=",
"deserializeEntityHeader",
"(",
"header",
")",
"\n",
"if",
"flags",
"&",
"entityExists",
"==",
"0",
"{",
"return",
"datastore",
".",
"ErrNoSuchEntity",
"\n",
"}",
"\n\n",
"// Deserialize the properties",
"buf",
":=",
"bytes",
".",
"NewBuffer",
"(",
"b",
"[",
"4",
":",
"]",
")",
"\n",
"props",
":=",
"make",
"(",
"[",
"]",
"datastore",
".",
"Property",
",",
"propCount",
")",
"\n",
"for",
"i",
":=",
"0",
";",
"i",
"<",
"propCount",
";",
"i",
"++",
"{",
"if",
"err",
":=",
"deserializeProperty",
"(",
"buf",
",",
"&",
"props",
"[",
"i",
"]",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"}",
"\n\n",
"return",
"deserializeProperties",
"(",
"dst",
",",
"props",
")",
"\n",
"}"
] |
// deserializeStruct takes portable bytes b, generated by serializeStruct, and assigns correct values to struct dst.
|
[
"deserializeStruct",
"takes",
"portable",
"bytes",
"b",
"generated",
"by",
"serializeStruct",
"and",
"assigns",
"correct",
"values",
"to",
"struct",
"dst",
"."
] |
339e0044a72ff2a4a0620cca12959496c9c8be12
|
https://github.com/mjibson/goon/blob/339e0044a72ff2a4a0620cca12959496c9c8be12/entity.go#L551-L576
|
17,784 |
mjibson/goon
|
entity.go
|
deserializeProperties
|
func deserializeProperties(dst interface{}, props []datastore.Property) error {
if k := reflect.Indirect(reflect.ValueOf(dst)).Type().Kind(); k != reflect.Struct {
return fmt.Errorf("goon: Expected struct, got instead: %v", k)
}
if pls, ok := dst.(datastore.PropertyLoadSaver); ok {
return pls.Load(props)
}
return datastore.LoadStruct(dst, props)
}
|
go
|
func deserializeProperties(dst interface{}, props []datastore.Property) error {
if k := reflect.Indirect(reflect.ValueOf(dst)).Type().Kind(); k != reflect.Struct {
return fmt.Errorf("goon: Expected struct, got instead: %v", k)
}
if pls, ok := dst.(datastore.PropertyLoadSaver); ok {
return pls.Load(props)
}
return datastore.LoadStruct(dst, props)
}
|
[
"func",
"deserializeProperties",
"(",
"dst",
"interface",
"{",
"}",
",",
"props",
"[",
"]",
"datastore",
".",
"Property",
")",
"error",
"{",
"if",
"k",
":=",
"reflect",
".",
"Indirect",
"(",
"reflect",
".",
"ValueOf",
"(",
"dst",
")",
")",
".",
"Type",
"(",
")",
".",
"Kind",
"(",
")",
";",
"k",
"!=",
"reflect",
".",
"Struct",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"k",
")",
"\n",
"}",
"\n",
"if",
"pls",
",",
"ok",
":=",
"dst",
".",
"(",
"datastore",
".",
"PropertyLoadSaver",
")",
";",
"ok",
"{",
"return",
"pls",
".",
"Load",
"(",
"props",
")",
"\n",
"}",
"\n",
"return",
"datastore",
".",
"LoadStruct",
"(",
"dst",
",",
"props",
")",
"\n",
"}"
] |
// deserializeProperties takes a slice of properties and assigns correct values to struct dst.
|
[
"deserializeProperties",
"takes",
"a",
"slice",
"of",
"properties",
"and",
"assigns",
"correct",
"values",
"to",
"struct",
"dst",
"."
] |
339e0044a72ff2a4a0620cca12959496c9c8be12
|
https://github.com/mjibson/goon/blob/339e0044a72ff2a4a0620cca12959496c9c8be12/entity.go#L579-L587
|
17,785 |
mjibson/goon
|
entity.go
|
getStructKey
|
func (g *Goon) getStructKey(src interface{}) (key *datastore.Key, hasStringId bool, err error) {
v := reflect.Indirect(reflect.ValueOf(src))
t := v.Type()
k := t.Kind()
if k != reflect.Struct {
err = fmt.Errorf("goon: Expected struct, got instead: %v", k)
return
}
var parent *datastore.Key
var stringID string
var intID int64
var kind string
for i := 0; i < v.NumField(); i++ {
tf := t.Field(i)
vf := v.Field(i)
tag := tf.Tag.Get("goon")
tagValues := strings.Split(tag, ",")
if len(tagValues) > 0 {
tagValue := tagValues[0]
if tagValue == "id" {
switch vf.Kind() {
case reflect.Int64:
if intID != 0 || stringID != "" {
err = fmt.Errorf("goon: Only one field may be marked id")
return
}
intID = vf.Int()
case reflect.String:
if intID != 0 || stringID != "" {
err = fmt.Errorf("goon: Only one field may be marked id")
return
}
stringID = vf.String()
hasStringId = true
default:
err = fmt.Errorf("goon: ID field must be int64 or string in %v", t.Name())
return
}
} else if tagValue == "kind" {
if vf.Kind() == reflect.String {
if kind != "" {
err = fmt.Errorf("goon: Only one field may be marked kind")
return
}
kind = vf.String()
if kind == "" && len(tagValues) > 1 && tagValues[1] != "" {
kind = tagValues[1]
}
}
} else if tagValue == "parent" {
dskeyType := reflect.TypeOf(&datastore.Key{})
if vf.Type().ConvertibleTo(dskeyType) {
if parent != nil {
err = fmt.Errorf("goon: Only one field may be marked parent")
return
}
parent = vf.Convert(dskeyType).Interface().(*datastore.Key)
}
}
}
}
// if kind has not been manually set, fetch it from src's type
if kind == "" {
kind = g.KindNameResolver(src)
}
key = datastore.NewKey(g.Context, kind, stringID, intID, parent)
return
}
|
go
|
func (g *Goon) getStructKey(src interface{}) (key *datastore.Key, hasStringId bool, err error) {
v := reflect.Indirect(reflect.ValueOf(src))
t := v.Type()
k := t.Kind()
if k != reflect.Struct {
err = fmt.Errorf("goon: Expected struct, got instead: %v", k)
return
}
var parent *datastore.Key
var stringID string
var intID int64
var kind string
for i := 0; i < v.NumField(); i++ {
tf := t.Field(i)
vf := v.Field(i)
tag := tf.Tag.Get("goon")
tagValues := strings.Split(tag, ",")
if len(tagValues) > 0 {
tagValue := tagValues[0]
if tagValue == "id" {
switch vf.Kind() {
case reflect.Int64:
if intID != 0 || stringID != "" {
err = fmt.Errorf("goon: Only one field may be marked id")
return
}
intID = vf.Int()
case reflect.String:
if intID != 0 || stringID != "" {
err = fmt.Errorf("goon: Only one field may be marked id")
return
}
stringID = vf.String()
hasStringId = true
default:
err = fmt.Errorf("goon: ID field must be int64 or string in %v", t.Name())
return
}
} else if tagValue == "kind" {
if vf.Kind() == reflect.String {
if kind != "" {
err = fmt.Errorf("goon: Only one field may be marked kind")
return
}
kind = vf.String()
if kind == "" && len(tagValues) > 1 && tagValues[1] != "" {
kind = tagValues[1]
}
}
} else if tagValue == "parent" {
dskeyType := reflect.TypeOf(&datastore.Key{})
if vf.Type().ConvertibleTo(dskeyType) {
if parent != nil {
err = fmt.Errorf("goon: Only one field may be marked parent")
return
}
parent = vf.Convert(dskeyType).Interface().(*datastore.Key)
}
}
}
}
// if kind has not been manually set, fetch it from src's type
if kind == "" {
kind = g.KindNameResolver(src)
}
key = datastore.NewKey(g.Context, kind, stringID, intID, parent)
return
}
|
[
"func",
"(",
"g",
"*",
"Goon",
")",
"getStructKey",
"(",
"src",
"interface",
"{",
"}",
")",
"(",
"key",
"*",
"datastore",
".",
"Key",
",",
"hasStringId",
"bool",
",",
"err",
"error",
")",
"{",
"v",
":=",
"reflect",
".",
"Indirect",
"(",
"reflect",
".",
"ValueOf",
"(",
"src",
")",
")",
"\n",
"t",
":=",
"v",
".",
"Type",
"(",
")",
"\n",
"k",
":=",
"t",
".",
"Kind",
"(",
")",
"\n\n",
"if",
"k",
"!=",
"reflect",
".",
"Struct",
"{",
"err",
"=",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"k",
")",
"\n",
"return",
"\n",
"}",
"\n\n",
"var",
"parent",
"*",
"datastore",
".",
"Key",
"\n",
"var",
"stringID",
"string",
"\n",
"var",
"intID",
"int64",
"\n",
"var",
"kind",
"string",
"\n\n",
"for",
"i",
":=",
"0",
";",
"i",
"<",
"v",
".",
"NumField",
"(",
")",
";",
"i",
"++",
"{",
"tf",
":=",
"t",
".",
"Field",
"(",
"i",
")",
"\n",
"vf",
":=",
"v",
".",
"Field",
"(",
"i",
")",
"\n\n",
"tag",
":=",
"tf",
".",
"Tag",
".",
"Get",
"(",
"\"",
"\"",
")",
"\n",
"tagValues",
":=",
"strings",
".",
"Split",
"(",
"tag",
",",
"\"",
"\"",
")",
"\n",
"if",
"len",
"(",
"tagValues",
")",
">",
"0",
"{",
"tagValue",
":=",
"tagValues",
"[",
"0",
"]",
"\n",
"if",
"tagValue",
"==",
"\"",
"\"",
"{",
"switch",
"vf",
".",
"Kind",
"(",
")",
"{",
"case",
"reflect",
".",
"Int64",
":",
"if",
"intID",
"!=",
"0",
"||",
"stringID",
"!=",
"\"",
"\"",
"{",
"err",
"=",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
")",
"\n",
"return",
"\n",
"}",
"\n",
"intID",
"=",
"vf",
".",
"Int",
"(",
")",
"\n",
"case",
"reflect",
".",
"String",
":",
"if",
"intID",
"!=",
"0",
"||",
"stringID",
"!=",
"\"",
"\"",
"{",
"err",
"=",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
")",
"\n",
"return",
"\n",
"}",
"\n",
"stringID",
"=",
"vf",
".",
"String",
"(",
")",
"\n",
"hasStringId",
"=",
"true",
"\n",
"default",
":",
"err",
"=",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"t",
".",
"Name",
"(",
")",
")",
"\n",
"return",
"\n",
"}",
"\n",
"}",
"else",
"if",
"tagValue",
"==",
"\"",
"\"",
"{",
"if",
"vf",
".",
"Kind",
"(",
")",
"==",
"reflect",
".",
"String",
"{",
"if",
"kind",
"!=",
"\"",
"\"",
"{",
"err",
"=",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
")",
"\n",
"return",
"\n",
"}",
"\n",
"kind",
"=",
"vf",
".",
"String",
"(",
")",
"\n",
"if",
"kind",
"==",
"\"",
"\"",
"&&",
"len",
"(",
"tagValues",
")",
">",
"1",
"&&",
"tagValues",
"[",
"1",
"]",
"!=",
"\"",
"\"",
"{",
"kind",
"=",
"tagValues",
"[",
"1",
"]",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"else",
"if",
"tagValue",
"==",
"\"",
"\"",
"{",
"dskeyType",
":=",
"reflect",
".",
"TypeOf",
"(",
"&",
"datastore",
".",
"Key",
"{",
"}",
")",
"\n",
"if",
"vf",
".",
"Type",
"(",
")",
".",
"ConvertibleTo",
"(",
"dskeyType",
")",
"{",
"if",
"parent",
"!=",
"nil",
"{",
"err",
"=",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
")",
"\n",
"return",
"\n",
"}",
"\n",
"parent",
"=",
"vf",
".",
"Convert",
"(",
"dskeyType",
")",
".",
"Interface",
"(",
")",
".",
"(",
"*",
"datastore",
".",
"Key",
")",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n\n",
"// if kind has not been manually set, fetch it from src's type",
"if",
"kind",
"==",
"\"",
"\"",
"{",
"kind",
"=",
"g",
".",
"KindNameResolver",
"(",
"src",
")",
"\n",
"}",
"\n",
"key",
"=",
"datastore",
".",
"NewKey",
"(",
"g",
".",
"Context",
",",
"kind",
",",
"stringID",
",",
"intID",
",",
"parent",
")",
"\n",
"return",
"\n",
"}"
] |
// getStructKey returns the key of the struct based in its reflected or
// specified kind and id. The second return parameter is true if src has a
// string id.
|
[
"getStructKey",
"returns",
"the",
"key",
"of",
"the",
"struct",
"based",
"in",
"its",
"reflected",
"or",
"specified",
"kind",
"and",
"id",
".",
"The",
"second",
"return",
"parameter",
"is",
"true",
"if",
"src",
"has",
"a",
"string",
"id",
"."
] |
339e0044a72ff2a4a0620cca12959496c9c8be12
|
https://github.com/mjibson/goon/blob/339e0044a72ff2a4a0620cca12959496c9c8be12/entity.go#L592-L664
|
17,786 |
mjibson/goon
|
query.go
|
Count
|
func (g *Goon) Count(q *datastore.Query) (int, error) {
return q.Count(g.Context)
}
|
go
|
func (g *Goon) Count(q *datastore.Query) (int, error) {
return q.Count(g.Context)
}
|
[
"func",
"(",
"g",
"*",
"Goon",
")",
"Count",
"(",
"q",
"*",
"datastore",
".",
"Query",
")",
"(",
"int",
",",
"error",
")",
"{",
"return",
"q",
".",
"Count",
"(",
"g",
".",
"Context",
")",
"\n",
"}"
] |
// Count returns the number of results for the query.
|
[
"Count",
"returns",
"the",
"number",
"of",
"results",
"for",
"the",
"query",
"."
] |
339e0044a72ff2a4a0620cca12959496c9c8be12
|
https://github.com/mjibson/goon/blob/339e0044a72ff2a4a0620cca12959496c9c8be12/query.go#L27-L29
|
17,787 |
mjibson/goon
|
query.go
|
Run
|
func (g *Goon) Run(q *datastore.Query) *Iterator {
return &Iterator{
g: g,
i: q.Run(g.Context),
}
}
|
go
|
func (g *Goon) Run(q *datastore.Query) *Iterator {
return &Iterator{
g: g,
i: q.Run(g.Context),
}
}
|
[
"func",
"(",
"g",
"*",
"Goon",
")",
"Run",
"(",
"q",
"*",
"datastore",
".",
"Query",
")",
"*",
"Iterator",
"{",
"return",
"&",
"Iterator",
"{",
"g",
":",
"g",
",",
"i",
":",
"q",
".",
"Run",
"(",
"g",
".",
"Context",
")",
",",
"}",
"\n",
"}"
] |
// Run runs the query.
|
[
"Run",
"runs",
"the",
"query",
"."
] |
339e0044a72ff2a4a0620cca12959496c9c8be12
|
https://github.com/mjibson/goon/blob/339e0044a72ff2a4a0620cca12959496c9c8be12/query.go#L126-L131
|
17,788 |
holys/initials-avatar
|
draw.go
|
Draw
|
func (g *drawer) Draw(s string, size int, bg *color.RGBA) image.Image {
// draw the background
dst := image.NewRGBA(image.Rect(0, 0, size, size))
draw.Draw(dst, dst.Bounds(), &image.Uniform{bg}, image.ZP, draw.Src)
// draw the text
drawer := &font.Drawer{
Dst: dst,
Src: image.White,
Face: g.face,
}
// font index
fi := g.font.Index([]rune(s)[0])
// glyph example: http://www.freetype.org/freetype2/docs/tutorial/metrics.png
var gbuf truetype.GlyphBuf
var err error
fsize := fixed.Int26_6(g.fontSize * g.dpi * (64.0 / 72.0))
err = gbuf.Load(g.font, fsize, fi, font.HintingFull)
if err != nil {
// fixme
drawer.DrawString("")
return dst
}
// center
dY := int((size - int(gbuf.Bounds.Max.Y-gbuf.Bounds.Min.Y)>>6) / 2)
dX := int((size - int(gbuf.Bounds.Max.X-gbuf.Bounds.Min.X)>>6) / 2)
y := int(gbuf.Bounds.Max.Y>>6) + dY
x := 0 - int(gbuf.Bounds.Min.X>>6) + dX
drawer.Dot = fixed.Point26_6{
X: fixed.I(x),
Y: fixed.I(y),
}
drawer.DrawString(s)
return dst
}
|
go
|
func (g *drawer) Draw(s string, size int, bg *color.RGBA) image.Image {
// draw the background
dst := image.NewRGBA(image.Rect(0, 0, size, size))
draw.Draw(dst, dst.Bounds(), &image.Uniform{bg}, image.ZP, draw.Src)
// draw the text
drawer := &font.Drawer{
Dst: dst,
Src: image.White,
Face: g.face,
}
// font index
fi := g.font.Index([]rune(s)[0])
// glyph example: http://www.freetype.org/freetype2/docs/tutorial/metrics.png
var gbuf truetype.GlyphBuf
var err error
fsize := fixed.Int26_6(g.fontSize * g.dpi * (64.0 / 72.0))
err = gbuf.Load(g.font, fsize, fi, font.HintingFull)
if err != nil {
// fixme
drawer.DrawString("")
return dst
}
// center
dY := int((size - int(gbuf.Bounds.Max.Y-gbuf.Bounds.Min.Y)>>6) / 2)
dX := int((size - int(gbuf.Bounds.Max.X-gbuf.Bounds.Min.X)>>6) / 2)
y := int(gbuf.Bounds.Max.Y>>6) + dY
x := 0 - int(gbuf.Bounds.Min.X>>6) + dX
drawer.Dot = fixed.Point26_6{
X: fixed.I(x),
Y: fixed.I(y),
}
drawer.DrawString(s)
return dst
}
|
[
"func",
"(",
"g",
"*",
"drawer",
")",
"Draw",
"(",
"s",
"string",
",",
"size",
"int",
",",
"bg",
"*",
"color",
".",
"RGBA",
")",
"image",
".",
"Image",
"{",
"// draw the background",
"dst",
":=",
"image",
".",
"NewRGBA",
"(",
"image",
".",
"Rect",
"(",
"0",
",",
"0",
",",
"size",
",",
"size",
")",
")",
"\n",
"draw",
".",
"Draw",
"(",
"dst",
",",
"dst",
".",
"Bounds",
"(",
")",
",",
"&",
"image",
".",
"Uniform",
"{",
"bg",
"}",
",",
"image",
".",
"ZP",
",",
"draw",
".",
"Src",
")",
"\n\n",
"// draw the text",
"drawer",
":=",
"&",
"font",
".",
"Drawer",
"{",
"Dst",
":",
"dst",
",",
"Src",
":",
"image",
".",
"White",
",",
"Face",
":",
"g",
".",
"face",
",",
"}",
"\n\n",
"// font index",
"fi",
":=",
"g",
".",
"font",
".",
"Index",
"(",
"[",
"]",
"rune",
"(",
"s",
")",
"[",
"0",
"]",
")",
"\n\n",
"// glyph example: http://www.freetype.org/freetype2/docs/tutorial/metrics.png",
"var",
"gbuf",
"truetype",
".",
"GlyphBuf",
"\n",
"var",
"err",
"error",
"\n",
"fsize",
":=",
"fixed",
".",
"Int26_6",
"(",
"g",
".",
"fontSize",
"*",
"g",
".",
"dpi",
"*",
"(",
"64.0",
"/",
"72.0",
")",
")",
"\n",
"err",
"=",
"gbuf",
".",
"Load",
"(",
"g",
".",
"font",
",",
"fsize",
",",
"fi",
",",
"font",
".",
"HintingFull",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"// fixme",
"drawer",
".",
"DrawString",
"(",
"\"",
"\"",
")",
"\n",
"return",
"dst",
"\n",
"}",
"\n\n",
"// center",
"dY",
":=",
"int",
"(",
"(",
"size",
"-",
"int",
"(",
"gbuf",
".",
"Bounds",
".",
"Max",
".",
"Y",
"-",
"gbuf",
".",
"Bounds",
".",
"Min",
".",
"Y",
")",
">>",
"6",
")",
"/",
"2",
")",
"\n",
"dX",
":=",
"int",
"(",
"(",
"size",
"-",
"int",
"(",
"gbuf",
".",
"Bounds",
".",
"Max",
".",
"X",
"-",
"gbuf",
".",
"Bounds",
".",
"Min",
".",
"X",
")",
">>",
"6",
")",
"/",
"2",
")",
"\n",
"y",
":=",
"int",
"(",
"gbuf",
".",
"Bounds",
".",
"Max",
".",
"Y",
">>",
"6",
")",
"+",
"dY",
"\n",
"x",
":=",
"0",
"-",
"int",
"(",
"gbuf",
".",
"Bounds",
".",
"Min",
".",
"X",
">>",
"6",
")",
"+",
"dX",
"\n\n",
"drawer",
".",
"Dot",
"=",
"fixed",
".",
"Point26_6",
"{",
"X",
":",
"fixed",
".",
"I",
"(",
"x",
")",
",",
"Y",
":",
"fixed",
".",
"I",
"(",
"y",
")",
",",
"}",
"\n",
"drawer",
".",
"DrawString",
"(",
"s",
")",
"\n\n",
"return",
"dst",
"\n",
"}"
] |
// our avatar image is square
|
[
"our",
"avatar",
"image",
"is",
"square"
] |
a82edcad34088ad546ba1763d42c83c26e98fa7d
|
https://github.com/holys/initials-avatar/blob/a82edcad34088ad546ba1763d42c83c26e98fa7d/draw.go#L53-L92
|
17,789 |
holys/initials-avatar
|
avatar.go
|
New
|
func New(fontFile string) *InitialsAvatar {
avatar := NewWithConfig(Config{
MaxItems: 1024, // default to 1024 items.
FontFile: fontFile,
})
return avatar
}
|
go
|
func New(fontFile string) *InitialsAvatar {
avatar := NewWithConfig(Config{
MaxItems: 1024, // default to 1024 items.
FontFile: fontFile,
})
return avatar
}
|
[
"func",
"New",
"(",
"fontFile",
"string",
")",
"*",
"InitialsAvatar",
"{",
"avatar",
":=",
"NewWithConfig",
"(",
"Config",
"{",
"MaxItems",
":",
"1024",
",",
"// default to 1024 items.",
"FontFile",
":",
"fontFile",
",",
"}",
")",
"\n",
"return",
"avatar",
"\n",
"}"
] |
// New creates an instance of InitialsAvatar
|
[
"New",
"creates",
"an",
"instance",
"of",
"InitialsAvatar"
] |
a82edcad34088ad546ba1763d42c83c26e98fa7d
|
https://github.com/holys/initials-avatar/blob/a82edcad34088ad546ba1763d42c83c26e98fa7d/avatar.go#L46-L52
|
17,790 |
holys/initials-avatar
|
avatar.go
|
NewWithConfig
|
func NewWithConfig(cfg Config) *InitialsAvatar {
var err error
avatar := new(InitialsAvatar)
avatar.drawer, err = newDrawer(cfg.FontFile, cfg.FontSize)
if err != nil {
panic(err.Error())
}
avatar.cache = lru.New(lru.Config{
MaxItems: cfg.MaxItems,
MaxBytes: cfg.MaxBytes,
})
return avatar
}
|
go
|
func NewWithConfig(cfg Config) *InitialsAvatar {
var err error
avatar := new(InitialsAvatar)
avatar.drawer, err = newDrawer(cfg.FontFile, cfg.FontSize)
if err != nil {
panic(err.Error())
}
avatar.cache = lru.New(lru.Config{
MaxItems: cfg.MaxItems,
MaxBytes: cfg.MaxBytes,
})
return avatar
}
|
[
"func",
"NewWithConfig",
"(",
"cfg",
"Config",
")",
"*",
"InitialsAvatar",
"{",
"var",
"err",
"error",
"\n\n",
"avatar",
":=",
"new",
"(",
"InitialsAvatar",
")",
"\n",
"avatar",
".",
"drawer",
",",
"err",
"=",
"newDrawer",
"(",
"cfg",
".",
"FontFile",
",",
"cfg",
".",
"FontSize",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"panic",
"(",
"err",
".",
"Error",
"(",
")",
")",
"\n",
"}",
"\n",
"avatar",
".",
"cache",
"=",
"lru",
".",
"New",
"(",
"lru",
".",
"Config",
"{",
"MaxItems",
":",
"cfg",
".",
"MaxItems",
",",
"MaxBytes",
":",
"cfg",
".",
"MaxBytes",
",",
"}",
")",
"\n\n",
"return",
"avatar",
"\n",
"}"
] |
// NewWithConfig provides config for LRU Cache.
|
[
"NewWithConfig",
"provides",
"config",
"for",
"LRU",
"Cache",
"."
] |
a82edcad34088ad546ba1763d42c83c26e98fa7d
|
https://github.com/holys/initials-avatar/blob/a82edcad34088ad546ba1763d42c83c26e98fa7d/avatar.go#L71-L85
|
17,791 |
holys/initials-avatar
|
avatar.go
|
DrawToBytes
|
func (a *InitialsAvatar) DrawToBytes(name string, size int, encoding ...string) ([]byte, error) {
if size <= 0 {
size = 48 // default size
}
name = strings.TrimSpace(name)
firstRune := []rune(name)[0]
if !isHan(firstRune) && !unicode.IsLetter(firstRune) {
return nil, ErrUnsupportChar
}
initials := getInitials(name)
bgcolor := getColorByName(name)
// get from cache
v, ok := a.cache.GetBytes(lru.Key(initials))
if ok {
return v, nil
}
m := a.drawer.Draw(initials, size, bgcolor)
// encode the image
var buf bytes.Buffer
enc := "png"
if len(encoding) > 0 {
enc = encoding[0]
}
switch enc {
case "jpeg":
err := jpeg.Encode(&buf, m, nil)
if err != nil {
return nil, err
}
case "png":
err := png.Encode(&buf, m)
if err != nil {
return nil, err
}
default:
return nil, ErrUnsupportedEncoding
}
// set cache
a.cache.SetBytes(lru.Key(initials), buf.Bytes())
return buf.Bytes(), nil
}
|
go
|
func (a *InitialsAvatar) DrawToBytes(name string, size int, encoding ...string) ([]byte, error) {
if size <= 0 {
size = 48 // default size
}
name = strings.TrimSpace(name)
firstRune := []rune(name)[0]
if !isHan(firstRune) && !unicode.IsLetter(firstRune) {
return nil, ErrUnsupportChar
}
initials := getInitials(name)
bgcolor := getColorByName(name)
// get from cache
v, ok := a.cache.GetBytes(lru.Key(initials))
if ok {
return v, nil
}
m := a.drawer.Draw(initials, size, bgcolor)
// encode the image
var buf bytes.Buffer
enc := "png"
if len(encoding) > 0 {
enc = encoding[0]
}
switch enc {
case "jpeg":
err := jpeg.Encode(&buf, m, nil)
if err != nil {
return nil, err
}
case "png":
err := png.Encode(&buf, m)
if err != nil {
return nil, err
}
default:
return nil, ErrUnsupportedEncoding
}
// set cache
a.cache.SetBytes(lru.Key(initials), buf.Bytes())
return buf.Bytes(), nil
}
|
[
"func",
"(",
"a",
"*",
"InitialsAvatar",
")",
"DrawToBytes",
"(",
"name",
"string",
",",
"size",
"int",
",",
"encoding",
"...",
"string",
")",
"(",
"[",
"]",
"byte",
",",
"error",
")",
"{",
"if",
"size",
"<=",
"0",
"{",
"size",
"=",
"48",
"// default size",
"\n",
"}",
"\n",
"name",
"=",
"strings",
".",
"TrimSpace",
"(",
"name",
")",
"\n",
"firstRune",
":=",
"[",
"]",
"rune",
"(",
"name",
")",
"[",
"0",
"]",
"\n",
"if",
"!",
"isHan",
"(",
"firstRune",
")",
"&&",
"!",
"unicode",
".",
"IsLetter",
"(",
"firstRune",
")",
"{",
"return",
"nil",
",",
"ErrUnsupportChar",
"\n",
"}",
"\n",
"initials",
":=",
"getInitials",
"(",
"name",
")",
"\n",
"bgcolor",
":=",
"getColorByName",
"(",
"name",
")",
"\n\n",
"// get from cache",
"v",
",",
"ok",
":=",
"a",
".",
"cache",
".",
"GetBytes",
"(",
"lru",
".",
"Key",
"(",
"initials",
")",
")",
"\n",
"if",
"ok",
"{",
"return",
"v",
",",
"nil",
"\n",
"}",
"\n\n",
"m",
":=",
"a",
".",
"drawer",
".",
"Draw",
"(",
"initials",
",",
"size",
",",
"bgcolor",
")",
"\n\n",
"// encode the image",
"var",
"buf",
"bytes",
".",
"Buffer",
"\n",
"enc",
":=",
"\"",
"\"",
"\n",
"if",
"len",
"(",
"encoding",
")",
">",
"0",
"{",
"enc",
"=",
"encoding",
"[",
"0",
"]",
"\n",
"}",
"\n",
"switch",
"enc",
"{",
"case",
"\"",
"\"",
":",
"err",
":=",
"jpeg",
".",
"Encode",
"(",
"&",
"buf",
",",
"m",
",",
"nil",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"case",
"\"",
"\"",
":",
"err",
":=",
"png",
".",
"Encode",
"(",
"&",
"buf",
",",
"m",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"default",
":",
"return",
"nil",
",",
"ErrUnsupportedEncoding",
"\n",
"}",
"\n\n",
"// set cache",
"a",
".",
"cache",
".",
"SetBytes",
"(",
"lru",
".",
"Key",
"(",
"initials",
")",
",",
"buf",
".",
"Bytes",
"(",
")",
")",
"\n\n",
"return",
"buf",
".",
"Bytes",
"(",
")",
",",
"nil",
"\n",
"}"
] |
// DrawToBytes draws an image base on the name and size.
// Only initials of name will be draw.
// The size is the side length of the square image. Image is encoded to bytes.
//
// You can optionaly specify the encoding of the file. the supported values are png and jpeg for
// png images and jpeg images respectively. if no encoding is specified then png is used.
|
[
"DrawToBytes",
"draws",
"an",
"image",
"base",
"on",
"the",
"name",
"and",
"size",
".",
"Only",
"initials",
"of",
"name",
"will",
"be",
"draw",
".",
"The",
"size",
"is",
"the",
"side",
"length",
"of",
"the",
"square",
"image",
".",
"Image",
"is",
"encoded",
"to",
"bytes",
".",
"You",
"can",
"optionaly",
"specify",
"the",
"encoding",
"of",
"the",
"file",
".",
"the",
"supported",
"values",
"are",
"png",
"and",
"jpeg",
"for",
"png",
"images",
"and",
"jpeg",
"images",
"respectively",
".",
"if",
"no",
"encoding",
"is",
"specified",
"then",
"png",
"is",
"used",
"."
] |
a82edcad34088ad546ba1763d42c83c26e98fa7d
|
https://github.com/holys/initials-avatar/blob/a82edcad34088ad546ba1763d42c83c26e98fa7d/avatar.go#L93-L138
|
17,792 |
holys/initials-avatar
|
avatar.go
|
isHan
|
func isHan(r rune) bool {
if unicode.Is(unicode.Scripts["Han"], r) {
return true
}
return false
}
|
go
|
func isHan(r rune) bool {
if unicode.Is(unicode.Scripts["Han"], r) {
return true
}
return false
}
|
[
"func",
"isHan",
"(",
"r",
"rune",
")",
"bool",
"{",
"if",
"unicode",
".",
"Is",
"(",
"unicode",
".",
"Scripts",
"[",
"\"",
"\"",
"]",
",",
"r",
")",
"{",
"return",
"true",
"\n",
"}",
"\n",
"return",
"false",
"\n",
"}"
] |
// Is it Chinese characters?
|
[
"Is",
"it",
"Chinese",
"characters?"
] |
a82edcad34088ad546ba1763d42c83c26e98fa7d
|
https://github.com/holys/initials-avatar/blob/a82edcad34088ad546ba1763d42c83c26e98fa7d/avatar.go#L141-L146
|
17,793 |
likexian/whois-parser-go
|
parser.go
|
parseRegistrant
|
func parseRegistrant(registrant Registrant, name, value string) Registrant {
keyName := FindKeyName(name)
switch keyName {
case "registrant_id":
registrant.ID = value
case "registrant_name":
registrant.Name = value
case "registrant_organization":
registrant.Organization = value
case "registrant_street":
registrant.Street = value
case "registrant_city":
registrant.City = value
case "registrant_state_province":
registrant.Province = value
case "registrant_postal_code":
registrant.PostalCode = value
case "registrant_country":
registrant.Country = value
case "registrant_phone":
registrant.Phone = value
case "registrant_phone_ext":
registrant.PhoneExt = value
case "registrant_fax":
registrant.Fax = value
case "registrant_fax_ext":
registrant.FaxExt = value
case "registrant_email":
registrant.Email = strings.ToLower(value)
}
return registrant
}
|
go
|
func parseRegistrant(registrant Registrant, name, value string) Registrant {
keyName := FindKeyName(name)
switch keyName {
case "registrant_id":
registrant.ID = value
case "registrant_name":
registrant.Name = value
case "registrant_organization":
registrant.Organization = value
case "registrant_street":
registrant.Street = value
case "registrant_city":
registrant.City = value
case "registrant_state_province":
registrant.Province = value
case "registrant_postal_code":
registrant.PostalCode = value
case "registrant_country":
registrant.Country = value
case "registrant_phone":
registrant.Phone = value
case "registrant_phone_ext":
registrant.PhoneExt = value
case "registrant_fax":
registrant.Fax = value
case "registrant_fax_ext":
registrant.FaxExt = value
case "registrant_email":
registrant.Email = strings.ToLower(value)
}
return registrant
}
|
[
"func",
"parseRegistrant",
"(",
"registrant",
"Registrant",
",",
"name",
",",
"value",
"string",
")",
"Registrant",
"{",
"keyName",
":=",
"FindKeyName",
"(",
"name",
")",
"\n",
"switch",
"keyName",
"{",
"case",
"\"",
"\"",
":",
"registrant",
".",
"ID",
"=",
"value",
"\n",
"case",
"\"",
"\"",
":",
"registrant",
".",
"Name",
"=",
"value",
"\n",
"case",
"\"",
"\"",
":",
"registrant",
".",
"Organization",
"=",
"value",
"\n",
"case",
"\"",
"\"",
":",
"registrant",
".",
"Street",
"=",
"value",
"\n",
"case",
"\"",
"\"",
":",
"registrant",
".",
"City",
"=",
"value",
"\n",
"case",
"\"",
"\"",
":",
"registrant",
".",
"Province",
"=",
"value",
"\n",
"case",
"\"",
"\"",
":",
"registrant",
".",
"PostalCode",
"=",
"value",
"\n",
"case",
"\"",
"\"",
":",
"registrant",
".",
"Country",
"=",
"value",
"\n",
"case",
"\"",
"\"",
":",
"registrant",
".",
"Phone",
"=",
"value",
"\n",
"case",
"\"",
"\"",
":",
"registrant",
".",
"PhoneExt",
"=",
"value",
"\n",
"case",
"\"",
"\"",
":",
"registrant",
".",
"Fax",
"=",
"value",
"\n",
"case",
"\"",
"\"",
":",
"registrant",
".",
"FaxExt",
"=",
"value",
"\n",
"case",
"\"",
"\"",
":",
"registrant",
".",
"Email",
"=",
"strings",
".",
"ToLower",
"(",
"value",
")",
"\n",
"}",
"\n\n",
"return",
"registrant",
"\n",
"}"
] |
// parseRegistrant do parse registrant info
|
[
"parseRegistrant",
"do",
"parse",
"registrant",
"info"
] |
0aa0498833b2f39c0a4f0ac0f6b5ddcf605fcf87
|
https://github.com/likexian/whois-parser-go/blob/0aa0498833b2f39c0a4f0ac0f6b5ddcf605fcf87/parser.go#L190-L222
|
17,794 |
likexian/whois-parser-go
|
utils.go
|
IsNotFound
|
func IsNotFound(data string) bool {
notExistsKeys := []string{
"no found",
"no match",
"not found",
"not match",
"no entries found",
"no data found",
"not registered",
"not been registered",
"is free",
"not available for registration",
"object does not exist",
}
data = strings.ToLower(data)
for _, v := range notExistsKeys {
if strings.Contains(data, v) {
return true
}
}
return false
}
|
go
|
func IsNotFound(data string) bool {
notExistsKeys := []string{
"no found",
"no match",
"not found",
"not match",
"no entries found",
"no data found",
"not registered",
"not been registered",
"is free",
"not available for registration",
"object does not exist",
}
data = strings.ToLower(data)
for _, v := range notExistsKeys {
if strings.Contains(data, v) {
return true
}
}
return false
}
|
[
"func",
"IsNotFound",
"(",
"data",
"string",
")",
"bool",
"{",
"notExistsKeys",
":=",
"[",
"]",
"string",
"{",
"\"",
"\"",
",",
"\"",
"\"",
",",
"\"",
"\"",
",",
"\"",
"\"",
",",
"\"",
"\"",
",",
"\"",
"\"",
",",
"\"",
"\"",
",",
"\"",
"\"",
",",
"\"",
"\"",
",",
"\"",
"\"",
",",
"\"",
"\"",
",",
"}",
"\n\n",
"data",
"=",
"strings",
".",
"ToLower",
"(",
"data",
")",
"\n",
"for",
"_",
",",
"v",
":=",
"range",
"notExistsKeys",
"{",
"if",
"strings",
".",
"Contains",
"(",
"data",
",",
"v",
")",
"{",
"return",
"true",
"\n",
"}",
"\n",
"}",
"\n\n",
"return",
"false",
"\n",
"}"
] |
// IsNotFound returns domain is not found
|
[
"IsNotFound",
"returns",
"domain",
"is",
"not",
"found"
] |
0aa0498833b2f39c0a4f0ac0f6b5ddcf605fcf87
|
https://github.com/likexian/whois-parser-go/blob/0aa0498833b2f39c0a4f0ac0f6b5ddcf605fcf87/utils.go#L28-L51
|
17,795 |
likexian/whois-parser-go
|
utils.go
|
IsLimitExceeded
|
func IsLimitExceeded(data string) bool {
data = strings.ToLower(data)
return strings.Contains(data, "limit exceeded")
}
|
go
|
func IsLimitExceeded(data string) bool {
data = strings.ToLower(data)
return strings.Contains(data, "limit exceeded")
}
|
[
"func",
"IsLimitExceeded",
"(",
"data",
"string",
")",
"bool",
"{",
"data",
"=",
"strings",
".",
"ToLower",
"(",
"data",
")",
"\n",
"return",
"strings",
".",
"Contains",
"(",
"data",
",",
"\"",
"\"",
")",
"\n",
"}"
] |
// IsLimitExceeded returns is query limit
|
[
"IsLimitExceeded",
"returns",
"is",
"query",
"limit"
] |
0aa0498833b2f39c0a4f0ac0f6b5ddcf605fcf87
|
https://github.com/likexian/whois-parser-go/blob/0aa0498833b2f39c0a4f0ac0f6b5ddcf605fcf87/utils.go#L54-L57
|
17,796 |
likexian/whois-parser-go
|
utils.go
|
ClearName
|
func ClearName(key string) string {
if strings.Contains(key, "(") {
key = strings.Split(key, "(")[0]
}
key = strings.Replace(key, "-", " ", -1)
key = strings.Replace(key, "_", " ", -1)
key = strings.Replace(key, "/", " ", -1)
key = strings.Replace(key, "\\", " ", -1)
key = strings.Replace(key, "'", " ", -1)
key = strings.Replace(key, ".", " ", -1)
key = strings.TrimSpace(key)
key = strings.ToLower(key)
return key
}
|
go
|
func ClearName(key string) string {
if strings.Contains(key, "(") {
key = strings.Split(key, "(")[0]
}
key = strings.Replace(key, "-", " ", -1)
key = strings.Replace(key, "_", " ", -1)
key = strings.Replace(key, "/", " ", -1)
key = strings.Replace(key, "\\", " ", -1)
key = strings.Replace(key, "'", " ", -1)
key = strings.Replace(key, ".", " ", -1)
key = strings.TrimSpace(key)
key = strings.ToLower(key)
return key
}
|
[
"func",
"ClearName",
"(",
"key",
"string",
")",
"string",
"{",
"if",
"strings",
".",
"Contains",
"(",
"key",
",",
"\"",
"\"",
")",
"{",
"key",
"=",
"strings",
".",
"Split",
"(",
"key",
",",
"\"",
"\"",
")",
"[",
"0",
"]",
"\n",
"}",
"\n\n",
"key",
"=",
"strings",
".",
"Replace",
"(",
"key",
",",
"\"",
"\"",
",",
"\"",
"\"",
",",
"-",
"1",
")",
"\n",
"key",
"=",
"strings",
".",
"Replace",
"(",
"key",
",",
"\"",
"\"",
",",
"\"",
"\"",
",",
"-",
"1",
")",
"\n",
"key",
"=",
"strings",
".",
"Replace",
"(",
"key",
",",
"\"",
"\"",
",",
"\"",
"\"",
",",
"-",
"1",
")",
"\n",
"key",
"=",
"strings",
".",
"Replace",
"(",
"key",
",",
"\"",
"\\\\",
"\"",
",",
"\"",
"\"",
",",
"-",
"1",
")",
"\n",
"key",
"=",
"strings",
".",
"Replace",
"(",
"key",
",",
"\"",
"\"",
",",
"\"",
"\"",
",",
"-",
"1",
")",
"\n",
"key",
"=",
"strings",
".",
"Replace",
"(",
"key",
",",
"\"",
"\"",
",",
"\"",
"\"",
",",
"-",
"1",
")",
"\n\n",
"key",
"=",
"strings",
".",
"TrimSpace",
"(",
"key",
")",
"\n",
"key",
"=",
"strings",
".",
"ToLower",
"(",
"key",
")",
"\n\n",
"return",
"key",
"\n",
"}"
] |
// ClearName returns cleared key name
|
[
"ClearName",
"returns",
"cleared",
"key",
"name"
] |
0aa0498833b2f39c0a4f0ac0f6b5ddcf605fcf87
|
https://github.com/likexian/whois-parser-go/blob/0aa0498833b2f39c0a4f0ac0f6b5ddcf605fcf87/utils.go#L60-L76
|
17,797 |
likexian/whois-parser-go
|
utils.go
|
FindKeyName
|
func FindKeyName(key string) string {
key = ClearName(key)
if v, ok := keyRule[key]; ok {
return v
}
return ""
}
|
go
|
func FindKeyName(key string) string {
key = ClearName(key)
if v, ok := keyRule[key]; ok {
return v
}
return ""
}
|
[
"func",
"FindKeyName",
"(",
"key",
"string",
")",
"string",
"{",
"key",
"=",
"ClearName",
"(",
"key",
")",
"\n",
"if",
"v",
",",
"ok",
":=",
"keyRule",
"[",
"key",
"]",
";",
"ok",
"{",
"return",
"v",
"\n",
"}",
"\n\n",
"return",
"\"",
"\"",
"\n",
"}"
] |
// FindKeyName returns the mapper value by key
|
[
"FindKeyName",
"returns",
"the",
"mapper",
"value",
"by",
"key"
] |
0aa0498833b2f39c0a4f0ac0f6b5ddcf605fcf87
|
https://github.com/likexian/whois-parser-go/blob/0aa0498833b2f39c0a4f0ac0f6b5ddcf605fcf87/utils.go#L79-L86
|
17,798 |
likexian/whois-parser-go
|
utils.go
|
RemoveDuplicateField
|
func RemoveDuplicateField(data string) string {
fs := []string{}
for _, v := range strings.Split(data, ",") {
if strings.TrimSpace(v) != "" {
fs = append(fs, v)
}
}
fields := xslice.Unique(fs)
result := strings.Join(fields.([]string), ",")
return result
}
|
go
|
func RemoveDuplicateField(data string) string {
fs := []string{}
for _, v := range strings.Split(data, ",") {
if strings.TrimSpace(v) != "" {
fs = append(fs, v)
}
}
fields := xslice.Unique(fs)
result := strings.Join(fields.([]string), ",")
return result
}
|
[
"func",
"RemoveDuplicateField",
"(",
"data",
"string",
")",
"string",
"{",
"fs",
":=",
"[",
"]",
"string",
"{",
"}",
"\n\n",
"for",
"_",
",",
"v",
":=",
"range",
"strings",
".",
"Split",
"(",
"data",
",",
"\"",
"\"",
")",
"{",
"if",
"strings",
".",
"TrimSpace",
"(",
"v",
")",
"!=",
"\"",
"\"",
"{",
"fs",
"=",
"append",
"(",
"fs",
",",
"v",
")",
"\n",
"}",
"\n",
"}",
"\n\n",
"fields",
":=",
"xslice",
".",
"Unique",
"(",
"fs",
")",
"\n",
"result",
":=",
"strings",
".",
"Join",
"(",
"fields",
".",
"(",
"[",
"]",
"string",
")",
",",
"\"",
"\"",
")",
"\n\n",
"return",
"result",
"\n",
"}"
] |
// RemoveDuplicateField remove the duplicate field
|
[
"RemoveDuplicateField",
"remove",
"the",
"duplicate",
"field"
] |
0aa0498833b2f39c0a4f0ac0f6b5ddcf605fcf87
|
https://github.com/likexian/whois-parser-go/blob/0aa0498833b2f39c0a4f0ac0f6b5ddcf605fcf87/utils.go#L89-L102
|
17,799 |
likexian/whois-parser-go
|
utils.go
|
FixDomainStatus
|
func FixDomainStatus(state string) string {
states := strings.Split(state, ",")
for k, v := range states {
names := strings.Split(strings.TrimSpace(v), " ")
states[k] = names[0]
}
return strings.Join(states, ",")
}
|
go
|
func FixDomainStatus(state string) string {
states := strings.Split(state, ",")
for k, v := range states {
names := strings.Split(strings.TrimSpace(v), " ")
states[k] = names[0]
}
return strings.Join(states, ",")
}
|
[
"func",
"FixDomainStatus",
"(",
"state",
"string",
")",
"string",
"{",
"states",
":=",
"strings",
".",
"Split",
"(",
"state",
",",
"\"",
"\"",
")",
"\n",
"for",
"k",
",",
"v",
":=",
"range",
"states",
"{",
"names",
":=",
"strings",
".",
"Split",
"(",
"strings",
".",
"TrimSpace",
"(",
"v",
")",
",",
"\"",
"\"",
")",
"\n",
"states",
"[",
"k",
"]",
"=",
"names",
"[",
"0",
"]",
"\n",
"}",
"\n\n",
"return",
"strings",
".",
"Join",
"(",
"states",
",",
"\"",
"\"",
")",
"\n",
"}"
] |
// FixDomainStatus returns fixed domain status
|
[
"FixDomainStatus",
"returns",
"fixed",
"domain",
"status"
] |
0aa0498833b2f39c0a4f0ac0f6b5ddcf605fcf87
|
https://github.com/likexian/whois-parser-go/blob/0aa0498833b2f39c0a4f0ac0f6b5ddcf605fcf87/utils.go#L105-L113
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.