id
int32
0
167k
repo
stringlengths
5
54
path
stringlengths
4
155
func_name
stringlengths
1
118
original_string
stringlengths
52
85.5k
language
stringclasses
1 value
code
stringlengths
52
85.5k
code_tokens
sequencelengths
21
1.41k
docstring
stringlengths
6
2.61k
docstring_tokens
sequencelengths
3
215
sha
stringlengths
40
40
url
stringlengths
85
252
152,700
rogpeppe/godef
go/printer/printer.go
Fprint
func Fprint(output io.Writer, fset *token.FileSet, node interface{}) error { _, err := (&Config{Tabwidth: 8}).Fprint(output, fset, node) // don't care about number of bytes written return err }
go
func Fprint(output io.Writer, fset *token.FileSet, node interface{}) error { _, err := (&Config{Tabwidth: 8}).Fprint(output, fset, node) // don't care about number of bytes written return err }
[ "func", "Fprint", "(", "output", "io", ".", "Writer", ",", "fset", "*", "token", ".", "FileSet", ",", "node", "interface", "{", "}", ")", "error", "{", "_", ",", "err", ":=", "(", "&", "Config", "{", "Tabwidth", ":", "8", "}", ")", ".", "Fprint", "(", "output", ",", "fset", ",", "node", ")", "// don't care about number of bytes written", "\n", "return", "err", "\n", "}" ]
// Fprint "pretty-prints" an AST node to output. // It calls Config.Fprint with default settings. //
[ "Fprint", "pretty", "-", "prints", "an", "AST", "node", "to", "output", ".", "It", "calls", "Config", ".", "Fprint", "with", "default", "settings", "." ]
5784335da72394c8f53d9036c26fcc876718879b
https://github.com/rogpeppe/godef/blob/5784335da72394c8f53d9036c26fcc876718879b/go/printer/printer.go#L1010-L1013
152,701
rogpeppe/godef
go/scanner/scanner.go
next
func (S *Scanner) next() { if S.rdOffset < len(S.src) { S.offset = S.rdOffset if S.ch == '\n' { S.lineOffset = S.offset S.file.AddLine(S.offset) } r, w := rune(S.src[S.rdOffset]), 1 switch { case r == 0: S.error(S.offset, "illegal character NUL") case r >= 0x80: // not ASCII r, w = utf8.DecodeRune(S.src[S.rdOffset:]) if r == utf8.RuneError && w == 1 { S.error(S.offset, "illegal UTF-8 encoding") } } S.rdOffset += w S.ch = r } else { S.offset = len(S.src) if S.ch == '\n' { S.lineOffset = S.offset S.file.AddLine(S.offset) } S.ch = -1 // eof } }
go
func (S *Scanner) next() { if S.rdOffset < len(S.src) { S.offset = S.rdOffset if S.ch == '\n' { S.lineOffset = S.offset S.file.AddLine(S.offset) } r, w := rune(S.src[S.rdOffset]), 1 switch { case r == 0: S.error(S.offset, "illegal character NUL") case r >= 0x80: // not ASCII r, w = utf8.DecodeRune(S.src[S.rdOffset:]) if r == utf8.RuneError && w == 1 { S.error(S.offset, "illegal UTF-8 encoding") } } S.rdOffset += w S.ch = r } else { S.offset = len(S.src) if S.ch == '\n' { S.lineOffset = S.offset S.file.AddLine(S.offset) } S.ch = -1 // eof } }
[ "func", "(", "S", "*", "Scanner", ")", "next", "(", ")", "{", "if", "S", ".", "rdOffset", "<", "len", "(", "S", ".", "src", ")", "{", "S", ".", "offset", "=", "S", ".", "rdOffset", "\n", "if", "S", ".", "ch", "==", "'\\n'", "{", "S", ".", "lineOffset", "=", "S", ".", "offset", "\n", "S", ".", "file", ".", "AddLine", "(", "S", ".", "offset", ")", "\n", "}", "\n", "r", ",", "w", ":=", "rune", "(", "S", ".", "src", "[", "S", ".", "rdOffset", "]", ")", ",", "1", "\n", "switch", "{", "case", "r", "==", "0", ":", "S", ".", "error", "(", "S", ".", "offset", ",", "\"", "\"", ")", "\n", "case", "r", ">=", "0x80", ":", "// not ASCII", "r", ",", "w", "=", "utf8", ".", "DecodeRune", "(", "S", ".", "src", "[", "S", ".", "rdOffset", ":", "]", ")", "\n", "if", "r", "==", "utf8", ".", "RuneError", "&&", "w", "==", "1", "{", "S", ".", "error", "(", "S", ".", "offset", ",", "\"", "\"", ")", "\n", "}", "\n", "}", "\n", "S", ".", "rdOffset", "+=", "w", "\n", "S", ".", "ch", "=", "r", "\n", "}", "else", "{", "S", ".", "offset", "=", "len", "(", "S", ".", "src", ")", "\n", "if", "S", ".", "ch", "==", "'\\n'", "{", "S", ".", "lineOffset", "=", "S", ".", "offset", "\n", "S", ".", "file", ".", "AddLine", "(", "S", ".", "offset", ")", "\n", "}", "\n", "S", ".", "ch", "=", "-", "1", "// eof", "\n", "}", "\n", "}" ]
// Read the next Unicode char into S.ch. // S.ch < 0 means end-of-file. //
[ "Read", "the", "next", "Unicode", "char", "into", "S", ".", "ch", ".", "S", ".", "ch", "<", "0", "means", "end", "-", "of", "-", "file", "." ]
5784335da72394c8f53d9036c26fcc876718879b
https://github.com/rogpeppe/godef/blob/5784335da72394c8f53d9036c26fcc876718879b/go/scanner/scanner.go#L60-L88
152,702
rogpeppe/godef
go/scanner/scanner.go
Init
func (S *Scanner) Init(file *token.File, src []byte, err ErrorHandler, mode uint) { // Explicitly initialize all fields since a scanner may be reused. if file.Size() != len(src) { panic("file size does not match src len") } S.file = file S.dir, _ = filepath.Split(file.Name()) S.src = src S.err = err S.mode = mode S.ch = ' ' S.offset = 0 S.rdOffset = 0 S.lineOffset = 0 S.insertSemi = false S.ErrorCount = 0 S.next() }
go
func (S *Scanner) Init(file *token.File, src []byte, err ErrorHandler, mode uint) { // Explicitly initialize all fields since a scanner may be reused. if file.Size() != len(src) { panic("file size does not match src len") } S.file = file S.dir, _ = filepath.Split(file.Name()) S.src = src S.err = err S.mode = mode S.ch = ' ' S.offset = 0 S.rdOffset = 0 S.lineOffset = 0 S.insertSemi = false S.ErrorCount = 0 S.next() }
[ "func", "(", "S", "*", "Scanner", ")", "Init", "(", "file", "*", "token", ".", "File", ",", "src", "[", "]", "byte", ",", "err", "ErrorHandler", ",", "mode", "uint", ")", "{", "// Explicitly initialize all fields since a scanner may be reused.", "if", "file", ".", "Size", "(", ")", "!=", "len", "(", "src", ")", "{", "panic", "(", "\"", "\"", ")", "\n", "}", "\n", "S", ".", "file", "=", "file", "\n", "S", ".", "dir", ",", "_", "=", "filepath", ".", "Split", "(", "file", ".", "Name", "(", ")", ")", "\n", "S", ".", "src", "=", "src", "\n", "S", ".", "err", "=", "err", "\n", "S", ".", "mode", "=", "mode", "\n\n", "S", ".", "ch", "=", "' '", "\n", "S", ".", "offset", "=", "0", "\n", "S", ".", "rdOffset", "=", "0", "\n", "S", ".", "lineOffset", "=", "0", "\n", "S", ".", "insertSemi", "=", "false", "\n", "S", ".", "ErrorCount", "=", "0", "\n\n", "S", ".", "next", "(", ")", "\n", "}" ]
// Init prepares the scanner S to tokenize the text src by setting the // scanner at the beginning of src. The scanner uses the file set file // for position information and it adds line information for each line. // It is ok to re-use the same file when re-scanning the same file as // line information which is already present is ignored. Init causes a // panic if the file size does not match the src size. // // Calls to Scan will use the error handler err if they encounter a // syntax error and err is not nil. Also, for each error encountered, // the Scanner field ErrorCount is incremented by one. The mode parameter // determines how comments, illegal characters, and semicolons are handled. // // Note that Init may call err if there is an error in the first character // of the file. //
[ "Init", "prepares", "the", "scanner", "S", "to", "tokenize", "the", "text", "src", "by", "setting", "the", "scanner", "at", "the", "beginning", "of", "src", ".", "The", "scanner", "uses", "the", "file", "set", "file", "for", "position", "information", "and", "it", "adds", "line", "information", "for", "each", "line", ".", "It", "is", "ok", "to", "re", "-", "use", "the", "same", "file", "when", "re", "-", "scanning", "the", "same", "file", "as", "line", "information", "which", "is", "already", "present", "is", "ignored", ".", "Init", "causes", "a", "panic", "if", "the", "file", "size", "does", "not", "match", "the", "src", "size", ".", "Calls", "to", "Scan", "will", "use", "the", "error", "handler", "err", "if", "they", "encounter", "a", "syntax", "error", "and", "err", "is", "not", "nil", ".", "Also", "for", "each", "error", "encountered", "the", "Scanner", "field", "ErrorCount", "is", "incremented", "by", "one", ".", "The", "mode", "parameter", "determines", "how", "comments", "illegal", "characters", "and", "semicolons", "are", "handled", ".", "Note", "that", "Init", "may", "call", "err", "if", "there", "is", "an", "error", "in", "the", "first", "character", "of", "the", "file", "." ]
5784335da72394c8f53d9036c26fcc876718879b
https://github.com/rogpeppe/godef/blob/5784335da72394c8f53d9036c26fcc876718879b/go/scanner/scanner.go#L114-L133
152,703
rogpeppe/godef
go/scanner/scanner.go
switch2
func (S *Scanner) switch2(tok0, tok1 token.Token) token.Token { if S.ch == '=' { S.next() return tok1 } return tok0 }
go
func (S *Scanner) switch2(tok0, tok1 token.Token) token.Token { if S.ch == '=' { S.next() return tok1 } return tok0 }
[ "func", "(", "S", "*", "Scanner", ")", "switch2", "(", "tok0", ",", "tok1", "token", ".", "Token", ")", "token", ".", "Token", "{", "if", "S", ".", "ch", "==", "'='", "{", "S", ".", "next", "(", ")", "\n", "return", "tok1", "\n", "}", "\n", "return", "tok0", "\n", "}" ]
// Helper functions for scanning multi-byte tokens such as >> += >>= . // Different routines recognize different length tok_i based on matches // of ch_i. If a token ends in '=', the result is tok1 or tok3 // respectively. Otherwise, the result is tok0 if there was no other // matching character, or tok2 if the matching character was ch2.
[ "Helper", "functions", "for", "scanning", "multi", "-", "byte", "tokens", "such", "as", ">>", "+", "=", ">>", "=", ".", "Different", "routines", "recognize", "different", "length", "tok_i", "based", "on", "matches", "of", "ch_i", ".", "If", "a", "token", "ends", "in", "=", "the", "result", "is", "tok1", "or", "tok3", "respectively", ".", "Otherwise", "the", "result", "is", "tok0", "if", "there", "was", "no", "other", "matching", "character", "or", "tok2", "if", "the", "matching", "character", "was", "ch2", "." ]
5784335da72394c8f53d9036c26fcc876718879b
https://github.com/rogpeppe/godef/blob/5784335da72394c8f53d9036c26fcc876718879b/go/scanner/scanner.go#L459-L465
152,704
rogpeppe/godef
go/sym/sym.go
Import
func (ctxt *Context) Import(path, srcDir string) *ast.Package { // TODO return error. return ctxt.importer(path, srcDir) }
go
func (ctxt *Context) Import(path, srcDir string) *ast.Package { // TODO return error. return ctxt.importer(path, srcDir) }
[ "func", "(", "ctxt", "*", "Context", ")", "Import", "(", "path", ",", "srcDir", "string", ")", "*", "ast", ".", "Package", "{", "// TODO return error.", "return", "ctxt", ".", "importer", "(", "path", ",", "srcDir", ")", "\n", "}" ]
// Import imports and parses the package with the given path. // It returns nil if it fails.
[ "Import", "imports", "and", "parses", "the", "package", "with", "the", "given", "path", ".", "It", "returns", "nil", "if", "it", "fails", "." ]
5784335da72394c8f53d9036c26fcc876718879b
https://github.com/rogpeppe/godef/blob/5784335da72394c8f53d9036c26fcc876718879b/go/sym/sym.go#L61-L64
152,705
rogpeppe/godef
go/sym/sym.go
IterateSyms
func (ctxt *Context) IterateSyms(f *ast.File, visitf func(info *Info) bool) { var visit astVisitor ok := true local := false // TODO set to true inside function body visit = func(n ast.Node) bool { if !ok { return false } switch n := n.(type) { case *ast.ImportSpec: // If the file imports a package to ".", abort // because we don't support that (yet). if n.Name != nil && n.Name.Name == "." { ctxt.logf(n.Pos(), "import to . not supported") ok = false return false } return true case *ast.FuncDecl: // add object for init functions if n.Recv == nil && n.Name.Name == "init" { n.Name.Obj = ast.NewObj(ast.Fun, "init") } if n.Recv != nil { ast.Walk(visit, n.Recv) } var e ast.Expr = n.Name if n.Recv != nil { // It's a method, so we need to synthesise a // selector expression so that visitExpr doesn't // just see a blank name. if len(n.Recv.List) != 1 { ctxt.logf(n.Pos(), "expected one receiver only!") return true } e = &ast.SelectorExpr{ X: n.Recv.List[0].Type, Sel: n.Name, } } ok = ctxt.visitExpr(f, e, false, visitf) local = true ast.Walk(visit, n.Type) if n.Body != nil { ast.Walk(visit, n.Body) } local = false return false case *ast.Ident: ok = ctxt.visitExpr(f, n, local, visitf) return false case *ast.KeyValueExpr: // don't try to resolve the key part of a key-value // because it might be a map key which doesn't // need resolving, and we can't tell without being // complicated with types. ast.Walk(visit, n.Value) return false case *ast.SelectorExpr: ast.Walk(visit, n.X) ok = ctxt.visitExpr(f, n, local, visitf) return false case *ast.File: for _, d := range n.Decls { ast.Walk(visit, d) } return false } return true } ast.Walk(visit, f) }
go
func (ctxt *Context) IterateSyms(f *ast.File, visitf func(info *Info) bool) { var visit astVisitor ok := true local := false // TODO set to true inside function body visit = func(n ast.Node) bool { if !ok { return false } switch n := n.(type) { case *ast.ImportSpec: // If the file imports a package to ".", abort // because we don't support that (yet). if n.Name != nil && n.Name.Name == "." { ctxt.logf(n.Pos(), "import to . not supported") ok = false return false } return true case *ast.FuncDecl: // add object for init functions if n.Recv == nil && n.Name.Name == "init" { n.Name.Obj = ast.NewObj(ast.Fun, "init") } if n.Recv != nil { ast.Walk(visit, n.Recv) } var e ast.Expr = n.Name if n.Recv != nil { // It's a method, so we need to synthesise a // selector expression so that visitExpr doesn't // just see a blank name. if len(n.Recv.List) != 1 { ctxt.logf(n.Pos(), "expected one receiver only!") return true } e = &ast.SelectorExpr{ X: n.Recv.List[0].Type, Sel: n.Name, } } ok = ctxt.visitExpr(f, e, false, visitf) local = true ast.Walk(visit, n.Type) if n.Body != nil { ast.Walk(visit, n.Body) } local = false return false case *ast.Ident: ok = ctxt.visitExpr(f, n, local, visitf) return false case *ast.KeyValueExpr: // don't try to resolve the key part of a key-value // because it might be a map key which doesn't // need resolving, and we can't tell without being // complicated with types. ast.Walk(visit, n.Value) return false case *ast.SelectorExpr: ast.Walk(visit, n.X) ok = ctxt.visitExpr(f, n, local, visitf) return false case *ast.File: for _, d := range n.Decls { ast.Walk(visit, d) } return false } return true } ast.Walk(visit, f) }
[ "func", "(", "ctxt", "*", "Context", ")", "IterateSyms", "(", "f", "*", "ast", ".", "File", ",", "visitf", "func", "(", "info", "*", "Info", ")", "bool", ")", "{", "var", "visit", "astVisitor", "\n", "ok", ":=", "true", "\n", "local", ":=", "false", "// TODO set to true inside function body", "\n", "visit", "=", "func", "(", "n", "ast", ".", "Node", ")", "bool", "{", "if", "!", "ok", "{", "return", "false", "\n", "}", "\n", "switch", "n", ":=", "n", ".", "(", "type", ")", "{", "case", "*", "ast", ".", "ImportSpec", ":", "// If the file imports a package to \".\", abort", "// because we don't support that (yet).", "if", "n", ".", "Name", "!=", "nil", "&&", "n", ".", "Name", ".", "Name", "==", "\"", "\"", "{", "ctxt", ".", "logf", "(", "n", ".", "Pos", "(", ")", ",", "\"", "\"", ")", "\n", "ok", "=", "false", "\n", "return", "false", "\n", "}", "\n", "return", "true", "\n\n", "case", "*", "ast", ".", "FuncDecl", ":", "// add object for init functions", "if", "n", ".", "Recv", "==", "nil", "&&", "n", ".", "Name", ".", "Name", "==", "\"", "\"", "{", "n", ".", "Name", ".", "Obj", "=", "ast", ".", "NewObj", "(", "ast", ".", "Fun", ",", "\"", "\"", ")", "\n", "}", "\n", "if", "n", ".", "Recv", "!=", "nil", "{", "ast", ".", "Walk", "(", "visit", ",", "n", ".", "Recv", ")", "\n", "}", "\n", "var", "e", "ast", ".", "Expr", "=", "n", ".", "Name", "\n", "if", "n", ".", "Recv", "!=", "nil", "{", "// It's a method, so we need to synthesise a", "// selector expression so that visitExpr doesn't", "// just see a blank name.", "if", "len", "(", "n", ".", "Recv", ".", "List", ")", "!=", "1", "{", "ctxt", ".", "logf", "(", "n", ".", "Pos", "(", ")", ",", "\"", "\"", ")", "\n", "return", "true", "\n", "}", "\n", "e", "=", "&", "ast", ".", "SelectorExpr", "{", "X", ":", "n", ".", "Recv", ".", "List", "[", "0", "]", ".", "Type", ",", "Sel", ":", "n", ".", "Name", ",", "}", "\n", "}", "\n", "ok", "=", "ctxt", ".", "visitExpr", "(", "f", ",", "e", ",", "false", ",", "visitf", ")", "\n", "local", "=", "true", "\n", "ast", ".", "Walk", "(", "visit", ",", "n", ".", "Type", ")", "\n", "if", "n", ".", "Body", "!=", "nil", "{", "ast", ".", "Walk", "(", "visit", ",", "n", ".", "Body", ")", "\n", "}", "\n", "local", "=", "false", "\n", "return", "false", "\n\n", "case", "*", "ast", ".", "Ident", ":", "ok", "=", "ctxt", ".", "visitExpr", "(", "f", ",", "n", ",", "local", ",", "visitf", ")", "\n", "return", "false", "\n\n", "case", "*", "ast", ".", "KeyValueExpr", ":", "// don't try to resolve the key part of a key-value", "// because it might be a map key which doesn't", "// need resolving, and we can't tell without being", "// complicated with types.", "ast", ".", "Walk", "(", "visit", ",", "n", ".", "Value", ")", "\n", "return", "false", "\n\n", "case", "*", "ast", ".", "SelectorExpr", ":", "ast", ".", "Walk", "(", "visit", ",", "n", ".", "X", ")", "\n", "ok", "=", "ctxt", ".", "visitExpr", "(", "f", ",", "n", ",", "local", ",", "visitf", ")", "\n", "return", "false", "\n\n", "case", "*", "ast", ".", "File", ":", "for", "_", ",", "d", ":=", "range", "n", ".", "Decls", "{", "ast", ".", "Walk", "(", "visit", ",", "d", ")", "\n", "}", "\n", "return", "false", "\n", "}", "\n\n", "return", "true", "\n", "}", "\n", "ast", ".", "Walk", "(", "visit", ",", "f", ")", "\n", "}" ]
// IterateSyms calls visitf for each identifier in the given file. If // visitf returns false, the iteration stops. If visitf changes // info.Ident.Name, the file is added to ctxt.ChangedFiles.
[ "IterateSyms", "calls", "visitf", "for", "each", "identifier", "in", "the", "given", "file", ".", "If", "visitf", "returns", "false", "the", "iteration", "stops", ".", "If", "visitf", "changes", "info", ".", "Ident", ".", "Name", "the", "file", "is", "added", "to", "ctxt", ".", "ChangedFiles", "." ]
5784335da72394c8f53d9036c26fcc876718879b
https://github.com/rogpeppe/godef/blob/5784335da72394c8f53d9036c26fcc876718879b/go/sym/sym.go#L123-L200
152,706
rogpeppe/godef
go/sym/sym.go
WriteFiles
func (ctxt *Context) WriteFiles(files map[string]*ast.File) error { // TODO should we try to continue changing files even after an error? for _, f := range files { name := ctxt.filename(f) newSrc, err := ctxt.gofmtFile(f) if err != nil { return fmt.Errorf("cannot format %q: %v", name, err) } err = ioutil.WriteFile(name, newSrc, 0666) if err != nil { return fmt.Errorf("cannot write %q: %v", name, err) } } return nil }
go
func (ctxt *Context) WriteFiles(files map[string]*ast.File) error { // TODO should we try to continue changing files even after an error? for _, f := range files { name := ctxt.filename(f) newSrc, err := ctxt.gofmtFile(f) if err != nil { return fmt.Errorf("cannot format %q: %v", name, err) } err = ioutil.WriteFile(name, newSrc, 0666) if err != nil { return fmt.Errorf("cannot write %q: %v", name, err) } } return nil }
[ "func", "(", "ctxt", "*", "Context", ")", "WriteFiles", "(", "files", "map", "[", "string", "]", "*", "ast", ".", "File", ")", "error", "{", "// TODO should we try to continue changing files even after an error?", "for", "_", ",", "f", ":=", "range", "files", "{", "name", ":=", "ctxt", ".", "filename", "(", "f", ")", "\n", "newSrc", ",", "err", ":=", "ctxt", ".", "gofmtFile", "(", "f", ")", "\n", "if", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "name", ",", "err", ")", "\n", "}", "\n", "err", "=", "ioutil", ".", "WriteFile", "(", "name", ",", "newSrc", ",", "0666", ")", "\n", "if", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "name", ",", "err", ")", "\n", "}", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// WriteFiles writes the given files, formatted as with gofmt.
[ "WriteFiles", "writes", "the", "given", "files", "formatted", "as", "with", "gofmt", "." ]
5784335da72394c8f53d9036c26fcc876718879b
https://github.com/rogpeppe/godef/blob/5784335da72394c8f53d9036c26fcc876718879b/go/sym/sym.go#L249-L263
152,707
rogpeppe/godef
go/ast/scope.go
NewScope
func NewScope(outer *Scope) *Scope { const n = 4 // initial scope capacity return &Scope{outer, make(map[string]*Object, n)} }
go
func NewScope(outer *Scope) *Scope { const n = 4 // initial scope capacity return &Scope{outer, make(map[string]*Object, n)} }
[ "func", "NewScope", "(", "outer", "*", "Scope", ")", "*", "Scope", "{", "const", "n", "=", "4", "// initial scope capacity", "\n", "return", "&", "Scope", "{", "outer", ",", "make", "(", "map", "[", "string", "]", "*", "Object", ",", "n", ")", "}", "\n", "}" ]
// NewScope creates a new scope nested in the outer scope.
[ "NewScope", "creates", "a", "new", "scope", "nested", "in", "the", "outer", "scope", "." ]
5784335da72394c8f53d9036c26fcc876718879b
https://github.com/rogpeppe/godef/blob/5784335da72394c8f53d9036c26fcc876718879b/go/ast/scope.go#L26-L29
152,708
rogpeppe/godef
go/ast/scope.go
Insert
func (s *Scope) Insert(obj *Object) (alt *Object) { if alt = s.Objects[obj.Name]; alt == nil { s.Objects[obj.Name] = obj } return }
go
func (s *Scope) Insert(obj *Object) (alt *Object) { if alt = s.Objects[obj.Name]; alt == nil { s.Objects[obj.Name] = obj } return }
[ "func", "(", "s", "*", "Scope", ")", "Insert", "(", "obj", "*", "Object", ")", "(", "alt", "*", "Object", ")", "{", "if", "alt", "=", "s", ".", "Objects", "[", "obj", ".", "Name", "]", ";", "alt", "==", "nil", "{", "s", ".", "Objects", "[", "obj", ".", "Name", "]", "=", "obj", "\n", "}", "\n", "return", "\n", "}" ]
// Insert attempts to insert a named object obj into the scope s. // If the scope already contains an object alt with the same name, // Insert leaves the scope unchanged and returns alt. Otherwise // it inserts obj and returns nil." //
[ "Insert", "attempts", "to", "insert", "a", "named", "object", "obj", "into", "the", "scope", "s", ".", "If", "the", "scope", "already", "contains", "an", "object", "alt", "with", "the", "same", "name", "Insert", "leaves", "the", "scope", "unchanged", "and", "returns", "alt", ".", "Otherwise", "it", "inserts", "obj", "and", "returns", "nil", "." ]
5784335da72394c8f53d9036c26fcc876718879b
https://github.com/rogpeppe/godef/blob/5784335da72394c8f53d9036c26fcc876718879b/go/ast/scope.go#L44-L49
152,709
rogpeppe/godef
go/ast/scope.go
NewObj
func NewObj(kind ObjKind, name string) *Object { return &Object{Kind: kind, Name: name} }
go
func NewObj(kind ObjKind, name string) *Object { return &Object{Kind: kind, Name: name} }
[ "func", "NewObj", "(", "kind", "ObjKind", ",", "name", "string", ")", "*", "Object", "{", "return", "&", "Object", "{", "Kind", ":", "kind", ",", "Name", ":", "name", "}", "\n", "}" ]
// NewObj creates a new object of a given kind and name.
[ "NewObj", "creates", "a", "new", "object", "of", "a", "given", "kind", "and", "name", "." ]
5784335da72394c8f53d9036c26fcc876718879b
https://github.com/rogpeppe/godef/blob/5784335da72394c8f53d9036c26fcc876718879b/go/ast/scope.go#L90-L92
152,710
rogpeppe/godef
go/ast/ast.go
Pos
func (s *ImportSpec) Pos() token.Pos { if s.Name != nil { return s.Name.Pos() } return s.Path.Pos() }
go
func (s *ImportSpec) Pos() token.Pos { if s.Name != nil { return s.Name.Pos() } return s.Path.Pos() }
[ "func", "(", "s", "*", "ImportSpec", ")", "Pos", "(", ")", "token", ".", "Pos", "{", "if", "s", ".", "Name", "!=", "nil", "{", "return", "s", ".", "Name", ".", "Pos", "(", ")", "\n", "}", "\n", "return", "s", ".", "Path", ".", "Pos", "(", ")", "\n", "}" ]
// Pos and End implementations for spec nodes. //
[ "Pos", "and", "End", "implementations", "for", "spec", "nodes", "." ]
5784335da72394c8f53d9036c26fcc876718879b
https://github.com/rogpeppe/godef/blob/5784335da72394c8f53d9036c26fcc876718879b/go/ast/ast.go#L783-L788
152,711
rogpeppe/godef
go/token/token.go
Precedence
func (op Token) Precedence() int { switch op { case LOR: return 1 case LAND: return 2 case EQL, NEQ, LSS, LEQ, GTR, GEQ: return 3 case ADD, SUB, OR, XOR: return 4 case MUL, QUO, REM, SHL, SHR, AND, AND_NOT: return 5 } return LowestPrec }
go
func (op Token) Precedence() int { switch op { case LOR: return 1 case LAND: return 2 case EQL, NEQ, LSS, LEQ, GTR, GEQ: return 3 case ADD, SUB, OR, XOR: return 4 case MUL, QUO, REM, SHL, SHR, AND, AND_NOT: return 5 } return LowestPrec }
[ "func", "(", "op", "Token", ")", "Precedence", "(", ")", "int", "{", "switch", "op", "{", "case", "LOR", ":", "return", "1", "\n", "case", "LAND", ":", "return", "2", "\n", "case", "EQL", ",", "NEQ", ",", "LSS", ",", "LEQ", ",", "GTR", ",", "GEQ", ":", "return", "3", "\n", "case", "ADD", ",", "SUB", ",", "OR", ",", "XOR", ":", "return", "4", "\n", "case", "MUL", ",", "QUO", ",", "REM", ",", "SHL", ",", "SHR", ",", "AND", ",", "AND_NOT", ":", "return", "5", "\n", "}", "\n", "return", "LowestPrec", "\n", "}" ]
// Precedence returns the operator precedence of the binary // operator op. If op is not a binary operator, the result // is LowestPrecedence. //
[ "Precedence", "returns", "the", "operator", "precedence", "of", "the", "binary", "operator", "op", ".", "If", "op", "is", "not", "a", "binary", "operator", "the", "result", "is", "LowestPrecedence", "." ]
5784335da72394c8f53d9036c26fcc876718879b
https://github.com/rogpeppe/godef/blob/5784335da72394c8f53d9036c26fcc876718879b/go/token/token.go#L260-L274
152,712
rogpeppe/godef
go/types/types.go
DefaultImporter
func DefaultImporter(path string, srcDir string) *ast.Package { bpkg, err := build.Default.Import(path, srcDir, 0) if err != nil { return nil } goFiles := make(map[string]bool) for _, f := range bpkg.GoFiles { goFiles[f] = true } for _, f := range bpkg.CgoFiles { goFiles[f] = true } shouldInclude := func(d os.FileInfo) bool { return goFiles[d.Name()] } pkgs, err := parser.ParseDir(FileSet, bpkg.Dir, shouldInclude, 0, DefaultImportPathToName) if err != nil { if Debug { switch err := err.(type) { case scanner.ErrorList: for _, e := range err { debugp("\t%v: %s", e.Pos, e.Msg) } default: debugp("\terror parsing %s: %v", bpkg.Dir, err) } } return nil } if pkg := pkgs[bpkg.Name]; pkg != nil { return pkg } if Debug { debugp("package not found by ParseDir!") } return nil }
go
func DefaultImporter(path string, srcDir string) *ast.Package { bpkg, err := build.Default.Import(path, srcDir, 0) if err != nil { return nil } goFiles := make(map[string]bool) for _, f := range bpkg.GoFiles { goFiles[f] = true } for _, f := range bpkg.CgoFiles { goFiles[f] = true } shouldInclude := func(d os.FileInfo) bool { return goFiles[d.Name()] } pkgs, err := parser.ParseDir(FileSet, bpkg.Dir, shouldInclude, 0, DefaultImportPathToName) if err != nil { if Debug { switch err := err.(type) { case scanner.ErrorList: for _, e := range err { debugp("\t%v: %s", e.Pos, e.Msg) } default: debugp("\terror parsing %s: %v", bpkg.Dir, err) } } return nil } if pkg := pkgs[bpkg.Name]; pkg != nil { return pkg } if Debug { debugp("package not found by ParseDir!") } return nil }
[ "func", "DefaultImporter", "(", "path", "string", ",", "srcDir", "string", ")", "*", "ast", ".", "Package", "{", "bpkg", ",", "err", ":=", "build", ".", "Default", ".", "Import", "(", "path", ",", "srcDir", ",", "0", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", "\n", "}", "\n", "goFiles", ":=", "make", "(", "map", "[", "string", "]", "bool", ")", "\n", "for", "_", ",", "f", ":=", "range", "bpkg", ".", "GoFiles", "{", "goFiles", "[", "f", "]", "=", "true", "\n", "}", "\n", "for", "_", ",", "f", ":=", "range", "bpkg", ".", "CgoFiles", "{", "goFiles", "[", "f", "]", "=", "true", "\n", "}", "\n", "shouldInclude", ":=", "func", "(", "d", "os", ".", "FileInfo", ")", "bool", "{", "return", "goFiles", "[", "d", ".", "Name", "(", ")", "]", "\n", "}", "\n", "pkgs", ",", "err", ":=", "parser", ".", "ParseDir", "(", "FileSet", ",", "bpkg", ".", "Dir", ",", "shouldInclude", ",", "0", ",", "DefaultImportPathToName", ")", "\n", "if", "err", "!=", "nil", "{", "if", "Debug", "{", "switch", "err", ":=", "err", ".", "(", "type", ")", "{", "case", "scanner", ".", "ErrorList", ":", "for", "_", ",", "e", ":=", "range", "err", "{", "debugp", "(", "\"", "\\t", "\"", ",", "e", ".", "Pos", ",", "e", ".", "Msg", ")", "\n", "}", "\n", "default", ":", "debugp", "(", "\"", "\\t", "\"", ",", "bpkg", ".", "Dir", ",", "err", ")", "\n", "}", "\n", "}", "\n", "return", "nil", "\n", "}", "\n", "if", "pkg", ":=", "pkgs", "[", "bpkg", ".", "Name", "]", ";", "pkg", "!=", "nil", "{", "return", "pkg", "\n", "}", "\n", "if", "Debug", "{", "debugp", "(", "\"", "\"", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// DefaultImporter looks for the package; if it finds it, // it parses and returns it. If no package was found, it returns nil.
[ "DefaultImporter", "looks", "for", "the", "package", ";", "if", "it", "finds", "it", "it", "parses", "and", "returns", "it", ".", "If", "no", "package", "was", "found", "it", "returns", "nil", "." ]
5784335da72394c8f53d9036c26fcc876718879b
https://github.com/rogpeppe/godef/blob/5784335da72394c8f53d9036c26fcc876718879b/go/types/types.go#L80-L116
152,713
rogpeppe/godef
go/types/types.go
String
func (t Type) String() string { return fmt.Sprintf("Type{%v %q %T %v}", t.Kind, t.Pkg, t.Node, pretty{t.Node}) }
go
func (t Type) String() string { return fmt.Sprintf("Type{%v %q %T %v}", t.Kind, t.Pkg, t.Node, pretty{t.Node}) }
[ "func", "(", "t", "Type", ")", "String", "(", ")", "string", "{", "return", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "t", ".", "Kind", ",", "t", ".", "Pkg", ",", "t", ".", "Node", ",", "pretty", "{", "t", ".", "Node", "}", ")", "\n", "}" ]
// String is for debugging purposes.
[ "String", "is", "for", "debugging", "purposes", "." ]
5784335da72394c8f53d9036c26fcc876718879b
https://github.com/rogpeppe/godef/blob/5784335da72394c8f53d9036c26fcc876718879b/go/types/types.go#L144-L146
152,714
rogpeppe/godef
go/printer/nodes.go
setComment
func (p *printer) setComment(g *ast.CommentGroup) { if g == nil || !p.useNodeComments { return } if p.comments == nil { // initialize p.comments lazily p.comments = make([]*ast.CommentGroup, 1) } else if p.cindex < len(p.comments) { // for some reason there are pending comments; this // should never happen - handle gracefully and flush // all comments up to g, ignore anything after that p.flush(p.fset.Position(g.List[0].Pos()), token.ILLEGAL) } p.comments[0] = g p.cindex = 0 }
go
func (p *printer) setComment(g *ast.CommentGroup) { if g == nil || !p.useNodeComments { return } if p.comments == nil { // initialize p.comments lazily p.comments = make([]*ast.CommentGroup, 1) } else if p.cindex < len(p.comments) { // for some reason there are pending comments; this // should never happen - handle gracefully and flush // all comments up to g, ignore anything after that p.flush(p.fset.Position(g.List[0].Pos()), token.ILLEGAL) } p.comments[0] = g p.cindex = 0 }
[ "func", "(", "p", "*", "printer", ")", "setComment", "(", "g", "*", "ast", ".", "CommentGroup", ")", "{", "if", "g", "==", "nil", "||", "!", "p", ".", "useNodeComments", "{", "return", "\n", "}", "\n", "if", "p", ".", "comments", "==", "nil", "{", "// initialize p.comments lazily", "p", ".", "comments", "=", "make", "(", "[", "]", "*", "ast", ".", "CommentGroup", ",", "1", ")", "\n", "}", "else", "if", "p", ".", "cindex", "<", "len", "(", "p", ".", "comments", ")", "{", "// for some reason there are pending comments; this", "// should never happen - handle gracefully and flush", "// all comments up to g, ignore anything after that", "p", ".", "flush", "(", "p", ".", "fset", ".", "Position", "(", "g", ".", "List", "[", "0", "]", ".", "Pos", "(", ")", ")", ",", "token", ".", "ILLEGAL", ")", "\n", "}", "\n", "p", ".", "comments", "[", "0", "]", "=", "g", "\n", "p", ".", "cindex", "=", "0", "\n", "}" ]
// setComment sets g as the next comment if g != nil and if node comments // are enabled - this mode is used when printing source code fragments such // as exports only. It assumes that there are no other pending comments to // intersperse.
[ "setComment", "sets", "g", "as", "the", "next", "comment", "if", "g", "!", "=", "nil", "and", "if", "node", "comments", "are", "enabled", "-", "this", "mode", "is", "used", "when", "printing", "source", "code", "fragments", "such", "as", "exports", "only", ".", "It", "assumes", "that", "there", "are", "no", "other", "pending", "comments", "to", "intersperse", "." ]
5784335da72394c8f53d9036c26fcc876718879b
https://github.com/rogpeppe/godef/blob/5784335da72394c8f53d9036c26fcc876718879b/go/printer/nodes.go#L62-L77
152,715
rogpeppe/godef
go/printer/nodes.go
identList
func (p *printer) identList(list []*ast.Ident, indent bool, multiLine *bool) { // convert into an expression list so we can re-use exprList formatting xlist := make([]ast.Expr, len(list)) for i, x := range list { xlist[i] = x } mode := commaSep if !indent { mode |= noIndent } p.exprList(token.NoPos, xlist, 1, mode, multiLine, token.NoPos) }
go
func (p *printer) identList(list []*ast.Ident, indent bool, multiLine *bool) { // convert into an expression list so we can re-use exprList formatting xlist := make([]ast.Expr, len(list)) for i, x := range list { xlist[i] = x } mode := commaSep if !indent { mode |= noIndent } p.exprList(token.NoPos, xlist, 1, mode, multiLine, token.NoPos) }
[ "func", "(", "p", "*", "printer", ")", "identList", "(", "list", "[", "]", "*", "ast", ".", "Ident", ",", "indent", "bool", ",", "multiLine", "*", "bool", ")", "{", "// convert into an expression list so we can re-use exprList formatting", "xlist", ":=", "make", "(", "[", "]", "ast", ".", "Expr", ",", "len", "(", "list", ")", ")", "\n", "for", "i", ",", "x", ":=", "range", "list", "{", "xlist", "[", "i", "]", "=", "x", "\n", "}", "\n", "mode", ":=", "commaSep", "\n", "if", "!", "indent", "{", "mode", "|=", "noIndent", "\n", "}", "\n", "p", ".", "exprList", "(", "token", ".", "NoPos", ",", "xlist", ",", "1", ",", "mode", ",", "multiLine", ",", "token", ".", "NoPos", ")", "\n", "}" ]
// Sets multiLine to true if the identifier list spans multiple lines. // If indent is set, a multi-line identifier list is indented after the // first linebreak encountered.
[ "Sets", "multiLine", "to", "true", "if", "the", "identifier", "list", "spans", "multiple", "lines", ".", "If", "indent", "is", "set", "a", "multi", "-", "line", "identifier", "list", "is", "indented", "after", "the", "first", "linebreak", "encountered", "." ]
5784335da72394c8f53d9036c26fcc876718879b
https://github.com/rogpeppe/godef/blob/5784335da72394c8f53d9036c26fcc876718879b/go/printer/nodes.go#L93-L104
152,716
rogpeppe/godef
go/printer/nodes.go
parameters
func (p *printer) parameters(fields *ast.FieldList, multiLine *bool) { p.print(fields.Opening, token.LPAREN) if len(fields.List) > 0 { var prevLine, line int for i, par := range fields.List { if i > 0 { p.print(token.COMMA) if len(par.Names) > 0 { line = p.fset.Position(par.Names[0].Pos()).Line } else { line = p.fset.Position(par.Type.Pos()).Line } if 0 < prevLine && prevLine < line && p.linebreak(line, 0, ignore, true) { *multiLine = true } else { p.print(blank) } } if len(par.Names) > 0 { p.identList(par.Names, false, multiLine) p.print(blank) } p.expr(par.Type, multiLine) prevLine = p.fset.Position(par.Type.Pos()).Line } } p.print(fields.Closing, token.RPAREN) }
go
func (p *printer) parameters(fields *ast.FieldList, multiLine *bool) { p.print(fields.Opening, token.LPAREN) if len(fields.List) > 0 { var prevLine, line int for i, par := range fields.List { if i > 0 { p.print(token.COMMA) if len(par.Names) > 0 { line = p.fset.Position(par.Names[0].Pos()).Line } else { line = p.fset.Position(par.Type.Pos()).Line } if 0 < prevLine && prevLine < line && p.linebreak(line, 0, ignore, true) { *multiLine = true } else { p.print(blank) } } if len(par.Names) > 0 { p.identList(par.Names, false, multiLine) p.print(blank) } p.expr(par.Type, multiLine) prevLine = p.fset.Position(par.Type.Pos()).Line } } p.print(fields.Closing, token.RPAREN) }
[ "func", "(", "p", "*", "printer", ")", "parameters", "(", "fields", "*", "ast", ".", "FieldList", ",", "multiLine", "*", "bool", ")", "{", "p", ".", "print", "(", "fields", ".", "Opening", ",", "token", ".", "LPAREN", ")", "\n", "if", "len", "(", "fields", ".", "List", ")", ">", "0", "{", "var", "prevLine", ",", "line", "int", "\n", "for", "i", ",", "par", ":=", "range", "fields", ".", "List", "{", "if", "i", ">", "0", "{", "p", ".", "print", "(", "token", ".", "COMMA", ")", "\n", "if", "len", "(", "par", ".", "Names", ")", ">", "0", "{", "line", "=", "p", ".", "fset", ".", "Position", "(", "par", ".", "Names", "[", "0", "]", ".", "Pos", "(", ")", ")", ".", "Line", "\n", "}", "else", "{", "line", "=", "p", ".", "fset", ".", "Position", "(", "par", ".", "Type", ".", "Pos", "(", ")", ")", ".", "Line", "\n", "}", "\n", "if", "0", "<", "prevLine", "&&", "prevLine", "<", "line", "&&", "p", ".", "linebreak", "(", "line", ",", "0", ",", "ignore", ",", "true", ")", "{", "*", "multiLine", "=", "true", "\n", "}", "else", "{", "p", ".", "print", "(", "blank", ")", "\n", "}", "\n", "}", "\n", "if", "len", "(", "par", ".", "Names", ")", ">", "0", "{", "p", ".", "identList", "(", "par", ".", "Names", ",", "false", ",", "multiLine", ")", "\n", "p", ".", "print", "(", "blank", ")", "\n", "}", "\n", "p", ".", "expr", "(", "par", ".", "Type", ",", "multiLine", ")", "\n", "prevLine", "=", "p", ".", "fset", ".", "Position", "(", "par", ".", "Type", ".", "Pos", "(", ")", ")", ".", "Line", "\n", "}", "\n", "}", "\n", "p", ".", "print", "(", "fields", ".", "Closing", ",", "token", ".", "RPAREN", ")", "\n", "}" ]
// Sets multiLine to true if the the parameter list spans multiple lines.
[ "Sets", "multiLine", "to", "true", "if", "the", "the", "parameter", "list", "spans", "multiple", "lines", "." ]
5784335da72394c8f53d9036c26fcc876718879b
https://github.com/rogpeppe/godef/blob/5784335da72394c8f53d9036c26fcc876718879b/go/printer/nodes.go#L270-L297
152,717
rogpeppe/godef
go/printer/nodes.go
signature
func (p *printer) signature(params, result *ast.FieldList, multiLine *bool) { p.parameters(params, multiLine) n := result.NumFields() if n > 0 { p.print(blank) if n == 1 && result.List[0].Names == nil { // single anonymous result; no ()'s p.expr(result.List[0].Type, multiLine) return } p.parameters(result, multiLine) } }
go
func (p *printer) signature(params, result *ast.FieldList, multiLine *bool) { p.parameters(params, multiLine) n := result.NumFields() if n > 0 { p.print(blank) if n == 1 && result.List[0].Names == nil { // single anonymous result; no ()'s p.expr(result.List[0].Type, multiLine) return } p.parameters(result, multiLine) } }
[ "func", "(", "p", "*", "printer", ")", "signature", "(", "params", ",", "result", "*", "ast", ".", "FieldList", ",", "multiLine", "*", "bool", ")", "{", "p", ".", "parameters", "(", "params", ",", "multiLine", ")", "\n", "n", ":=", "result", ".", "NumFields", "(", ")", "\n", "if", "n", ">", "0", "{", "p", ".", "print", "(", "blank", ")", "\n", "if", "n", "==", "1", "&&", "result", ".", "List", "[", "0", "]", ".", "Names", "==", "nil", "{", "// single anonymous result; no ()'s", "p", ".", "expr", "(", "result", ".", "List", "[", "0", "]", ".", "Type", ",", "multiLine", ")", "\n", "return", "\n", "}", "\n", "p", ".", "parameters", "(", "result", ",", "multiLine", ")", "\n", "}", "\n", "}" ]
// Sets multiLine to true if the signature spans multiple lines.
[ "Sets", "multiLine", "to", "true", "if", "the", "signature", "spans", "multiple", "lines", "." ]
5784335da72394c8f53d9036c26fcc876718879b
https://github.com/rogpeppe/godef/blob/5784335da72394c8f53d9036c26fcc876718879b/go/printer/nodes.go#L300-L312
152,718
rogpeppe/godef
go/printer/nodes.go
splitSelector
func splitSelector(expr ast.Expr) (body, suffix ast.Expr) { switch x := expr.(type) { case *ast.SelectorExpr: body, suffix = x.X, x.Sel return case *ast.CallExpr: body, suffix = splitSelector(x.Fun) if body != nil { suffix = &ast.CallExpr{suffix, x.Lparen, x.Args, x.Ellipsis, x.Rparen} return } case *ast.IndexExpr: body, suffix = splitSelector(x.X) if body != nil { suffix = &ast.IndexExpr{suffix, x.Lbrack, x.Index, x.Rbrack} return } case *ast.SliceExpr: body, suffix = splitSelector(x.X) if body != nil { suffix = &ast.SliceExpr{X: suffix, Lbrack: x.Lbrack, Low: x.Low, High: x.High, Rbrack: x.Rbrack, Slice3: false} return } case *ast.TypeAssertExpr: body, suffix = splitSelector(x.X) if body != nil { suffix = &ast.TypeAssertExpr{suffix, x.Type} return } } suffix = expr return }
go
func splitSelector(expr ast.Expr) (body, suffix ast.Expr) { switch x := expr.(type) { case *ast.SelectorExpr: body, suffix = x.X, x.Sel return case *ast.CallExpr: body, suffix = splitSelector(x.Fun) if body != nil { suffix = &ast.CallExpr{suffix, x.Lparen, x.Args, x.Ellipsis, x.Rparen} return } case *ast.IndexExpr: body, suffix = splitSelector(x.X) if body != nil { suffix = &ast.IndexExpr{suffix, x.Lbrack, x.Index, x.Rbrack} return } case *ast.SliceExpr: body, suffix = splitSelector(x.X) if body != nil { suffix = &ast.SliceExpr{X: suffix, Lbrack: x.Lbrack, Low: x.Low, High: x.High, Rbrack: x.Rbrack, Slice3: false} return } case *ast.TypeAssertExpr: body, suffix = splitSelector(x.X) if body != nil { suffix = &ast.TypeAssertExpr{suffix, x.Type} return } } suffix = expr return }
[ "func", "splitSelector", "(", "expr", "ast", ".", "Expr", ")", "(", "body", ",", "suffix", "ast", ".", "Expr", ")", "{", "switch", "x", ":=", "expr", ".", "(", "type", ")", "{", "case", "*", "ast", ".", "SelectorExpr", ":", "body", ",", "suffix", "=", "x", ".", "X", ",", "x", ".", "Sel", "\n", "return", "\n", "case", "*", "ast", ".", "CallExpr", ":", "body", ",", "suffix", "=", "splitSelector", "(", "x", ".", "Fun", ")", "\n", "if", "body", "!=", "nil", "{", "suffix", "=", "&", "ast", ".", "CallExpr", "{", "suffix", ",", "x", ".", "Lparen", ",", "x", ".", "Args", ",", "x", ".", "Ellipsis", ",", "x", ".", "Rparen", "}", "\n", "return", "\n", "}", "\n", "case", "*", "ast", ".", "IndexExpr", ":", "body", ",", "suffix", "=", "splitSelector", "(", "x", ".", "X", ")", "\n", "if", "body", "!=", "nil", "{", "suffix", "=", "&", "ast", ".", "IndexExpr", "{", "suffix", ",", "x", ".", "Lbrack", ",", "x", ".", "Index", ",", "x", ".", "Rbrack", "}", "\n", "return", "\n", "}", "\n", "case", "*", "ast", ".", "SliceExpr", ":", "body", ",", "suffix", "=", "splitSelector", "(", "x", ".", "X", ")", "\n", "if", "body", "!=", "nil", "{", "suffix", "=", "&", "ast", ".", "SliceExpr", "{", "X", ":", "suffix", ",", "Lbrack", ":", "x", ".", "Lbrack", ",", "Low", ":", "x", ".", "Low", ",", "High", ":", "x", ".", "High", ",", "Rbrack", ":", "x", ".", "Rbrack", ",", "Slice3", ":", "false", "}", "\n", "return", "\n", "}", "\n", "case", "*", "ast", ".", "TypeAssertExpr", ":", "body", ",", "suffix", "=", "splitSelector", "(", "x", ".", "X", ")", "\n", "if", "body", "!=", "nil", "{", "suffix", "=", "&", "ast", ".", "TypeAssertExpr", "{", "suffix", ",", "x", ".", "Type", "}", "\n", "return", "\n", "}", "\n", "}", "\n", "suffix", "=", "expr", "\n", "return", "\n", "}" ]
// If the expression contains one or more selector expressions, splits it into // two expressions at the rightmost period. Writes entire expr to suffix when // selector isn't found. Rewrites AST nodes for calls, index expressions and // type assertions, all of which may be found in selector chains, to make them // parts of the chain.
[ "If", "the", "expression", "contains", "one", "or", "more", "selector", "expressions", "splits", "it", "into", "two", "expressions", "at", "the", "rightmost", "period", ".", "Writes", "entire", "expr", "to", "suffix", "when", "selector", "isn", "t", "found", ".", "Rewrites", "AST", "nodes", "for", "calls", "index", "expressions", "and", "type", "assertions", "all", "of", "which", "may", "be", "found", "in", "selector", "chains", "to", "make", "them", "parts", "of", "the", "chain", "." ]
5784335da72394c8f53d9036c26fcc876718879b
https://github.com/rogpeppe/godef/blob/5784335da72394c8f53d9036c26fcc876718879b/go/printer/nodes.go#L640-L672
152,719
rogpeppe/godef
go/printer/nodes.go
selectorExprList
func selectorExprList(expr ast.Expr) (list []ast.Expr) { // split expression for expr != nil { var suffix ast.Expr expr, suffix = splitSelector(expr) list = append(list, suffix) } // reverse list for i, j := 0, len(list)-1; i < j; i, j = i+1, j-1 { list[i], list[j] = list[j], list[i] } return }
go
func selectorExprList(expr ast.Expr) (list []ast.Expr) { // split expression for expr != nil { var suffix ast.Expr expr, suffix = splitSelector(expr) list = append(list, suffix) } // reverse list for i, j := 0, len(list)-1; i < j; i, j = i+1, j-1 { list[i], list[j] = list[j], list[i] } return }
[ "func", "selectorExprList", "(", "expr", "ast", ".", "Expr", ")", "(", "list", "[", "]", "ast", ".", "Expr", ")", "{", "// split expression", "for", "expr", "!=", "nil", "{", "var", "suffix", "ast", ".", "Expr", "\n", "expr", ",", "suffix", "=", "splitSelector", "(", "expr", ")", "\n", "list", "=", "append", "(", "list", ",", "suffix", ")", "\n", "}", "\n\n", "// reverse list", "for", "i", ",", "j", ":=", "0", ",", "len", "(", "list", ")", "-", "1", ";", "i", "<", "j", ";", "i", ",", "j", "=", "i", "+", "1", ",", "j", "-", "1", "{", "list", "[", "i", "]", ",", "list", "[", "j", "]", "=", "list", "[", "j", "]", ",", "list", "[", "i", "]", "\n", "}", "\n\n", "return", "\n", "}" ]
// Convert an expression into an expression list split at the periods of // selector expressions.
[ "Convert", "an", "expression", "into", "an", "expression", "list", "split", "at", "the", "periods", "of", "selector", "expressions", "." ]
5784335da72394c8f53d9036c26fcc876718879b
https://github.com/rogpeppe/godef/blob/5784335da72394c8f53d9036c26fcc876718879b/go/printer/nodes.go#L676-L690
152,720
rogpeppe/godef
go/printer/nodes.go
spec
func (p *printer) spec(spec ast.Spec, n int, doIndent bool, multiLine *bool) { switch s := spec.(type) { case *ast.ImportSpec: p.setComment(s.Doc) if s.Name != nil { p.expr(s.Name, multiLine) p.print(blank) } p.expr(s.Path, multiLine) p.setComment(s.Comment) case *ast.ValueSpec: if n != 1 { p.internalError("expected n = 1; got", n) } p.setComment(s.Doc) p.identList(s.Names, doIndent, multiLine) // always present if s.Type != nil { p.print(blank) p.expr(s.Type, multiLine) } if s.Values != nil { p.print(blank, token.ASSIGN) p.exprList(token.NoPos, s.Values, 1, blankStart|commaSep, multiLine, token.NoPos) } p.setComment(s.Comment) case *ast.TypeSpec: p.setComment(s.Doc) p.expr(s.Name, multiLine) if n == 1 { p.print(blank) } else { p.print(vtab) } p.expr(s.Type, multiLine) p.setComment(s.Comment) default: panic("unreachable") } }
go
func (p *printer) spec(spec ast.Spec, n int, doIndent bool, multiLine *bool) { switch s := spec.(type) { case *ast.ImportSpec: p.setComment(s.Doc) if s.Name != nil { p.expr(s.Name, multiLine) p.print(blank) } p.expr(s.Path, multiLine) p.setComment(s.Comment) case *ast.ValueSpec: if n != 1 { p.internalError("expected n = 1; got", n) } p.setComment(s.Doc) p.identList(s.Names, doIndent, multiLine) // always present if s.Type != nil { p.print(blank) p.expr(s.Type, multiLine) } if s.Values != nil { p.print(blank, token.ASSIGN) p.exprList(token.NoPos, s.Values, 1, blankStart|commaSep, multiLine, token.NoPos) } p.setComment(s.Comment) case *ast.TypeSpec: p.setComment(s.Doc) p.expr(s.Name, multiLine) if n == 1 { p.print(blank) } else { p.print(vtab) } p.expr(s.Type, multiLine) p.setComment(s.Comment) default: panic("unreachable") } }
[ "func", "(", "p", "*", "printer", ")", "spec", "(", "spec", "ast", ".", "Spec", ",", "n", "int", ",", "doIndent", "bool", ",", "multiLine", "*", "bool", ")", "{", "switch", "s", ":=", "spec", ".", "(", "type", ")", "{", "case", "*", "ast", ".", "ImportSpec", ":", "p", ".", "setComment", "(", "s", ".", "Doc", ")", "\n", "if", "s", ".", "Name", "!=", "nil", "{", "p", ".", "expr", "(", "s", ".", "Name", ",", "multiLine", ")", "\n", "p", ".", "print", "(", "blank", ")", "\n", "}", "\n", "p", ".", "expr", "(", "s", ".", "Path", ",", "multiLine", ")", "\n", "p", ".", "setComment", "(", "s", ".", "Comment", ")", "\n\n", "case", "*", "ast", ".", "ValueSpec", ":", "if", "n", "!=", "1", "{", "p", ".", "internalError", "(", "\"", "\"", ",", "n", ")", "\n", "}", "\n", "p", ".", "setComment", "(", "s", ".", "Doc", ")", "\n", "p", ".", "identList", "(", "s", ".", "Names", ",", "doIndent", ",", "multiLine", ")", "// always present", "\n", "if", "s", ".", "Type", "!=", "nil", "{", "p", ".", "print", "(", "blank", ")", "\n", "p", ".", "expr", "(", "s", ".", "Type", ",", "multiLine", ")", "\n", "}", "\n", "if", "s", ".", "Values", "!=", "nil", "{", "p", ".", "print", "(", "blank", ",", "token", ".", "ASSIGN", ")", "\n", "p", ".", "exprList", "(", "token", ".", "NoPos", ",", "s", ".", "Values", ",", "1", ",", "blankStart", "|", "commaSep", ",", "multiLine", ",", "token", ".", "NoPos", ")", "\n", "}", "\n", "p", ".", "setComment", "(", "s", ".", "Comment", ")", "\n\n", "case", "*", "ast", ".", "TypeSpec", ":", "p", ".", "setComment", "(", "s", ".", "Doc", ")", "\n", "p", ".", "expr", "(", "s", ".", "Name", ",", "multiLine", ")", "\n", "if", "n", "==", "1", "{", "p", ".", "print", "(", "blank", ")", "\n", "}", "else", "{", "p", ".", "print", "(", "vtab", ")", "\n", "}", "\n", "p", ".", "expr", "(", "s", ".", "Type", ",", "multiLine", ")", "\n", "p", ".", "setComment", "(", "s", ".", "Comment", ")", "\n\n", "default", ":", "panic", "(", "\"", "\"", ")", "\n", "}", "\n", "}" ]
// The parameter n is the number of specs in the group. If doIndent is set, // multi-line identifier lists in the spec are indented when the first // linebreak is encountered. // Sets multiLine to true if the spec spans multiple lines. //
[ "The", "parameter", "n", "is", "the", "number", "of", "specs", "in", "the", "group", ".", "If", "doIndent", "is", "set", "multi", "-", "line", "identifier", "lists", "in", "the", "spec", "are", "indented", "when", "the", "first", "linebreak", "is", "encountered", ".", "Sets", "multiLine", "to", "true", "if", "the", "spec", "spans", "multiple", "lines", "." ]
5784335da72394c8f53d9036c26fcc876718879b
https://github.com/rogpeppe/godef/blob/5784335da72394c8f53d9036c26fcc876718879b/go/printer/nodes.go#L1265-L1306
152,721
rogpeppe/godef
go/printer/nodes.go
funcBody
func (p *printer) funcBody(b *ast.BlockStmt, headerSize int, isLit bool, multiLine *bool) { if b == nil { return } if p.isOneLineFunc(b, headerSize) { sep := vtab if isLit { sep = blank } p.print(sep, b.Lbrace, token.LBRACE) if len(b.List) > 0 { p.print(blank) for i, s := range b.List { if i > 0 { p.print(token.SEMICOLON, blank) } p.stmt(s, i == len(b.List)-1, ignoreMultiLine) } p.print(blank) } p.print(b.Rbrace, token.RBRACE) return } p.print(blank) p.block(b, 1) *multiLine = true }
go
func (p *printer) funcBody(b *ast.BlockStmt, headerSize int, isLit bool, multiLine *bool) { if b == nil { return } if p.isOneLineFunc(b, headerSize) { sep := vtab if isLit { sep = blank } p.print(sep, b.Lbrace, token.LBRACE) if len(b.List) > 0 { p.print(blank) for i, s := range b.List { if i > 0 { p.print(token.SEMICOLON, blank) } p.stmt(s, i == len(b.List)-1, ignoreMultiLine) } p.print(blank) } p.print(b.Rbrace, token.RBRACE) return } p.print(blank) p.block(b, 1) *multiLine = true }
[ "func", "(", "p", "*", "printer", ")", "funcBody", "(", "b", "*", "ast", ".", "BlockStmt", ",", "headerSize", "int", ",", "isLit", "bool", ",", "multiLine", "*", "bool", ")", "{", "if", "b", "==", "nil", "{", "return", "\n", "}", "\n\n", "if", "p", ".", "isOneLineFunc", "(", "b", ",", "headerSize", ")", "{", "sep", ":=", "vtab", "\n", "if", "isLit", "{", "sep", "=", "blank", "\n", "}", "\n", "p", ".", "print", "(", "sep", ",", "b", ".", "Lbrace", ",", "token", ".", "LBRACE", ")", "\n", "if", "len", "(", "b", ".", "List", ")", ">", "0", "{", "p", ".", "print", "(", "blank", ")", "\n", "for", "i", ",", "s", ":=", "range", "b", ".", "List", "{", "if", "i", ">", "0", "{", "p", ".", "print", "(", "token", ".", "SEMICOLON", ",", "blank", ")", "\n", "}", "\n", "p", ".", "stmt", "(", "s", ",", "i", "==", "len", "(", "b", ".", "List", ")", "-", "1", ",", "ignoreMultiLine", ")", "\n", "}", "\n", "p", ".", "print", "(", "blank", ")", "\n", "}", "\n", "p", ".", "print", "(", "b", ".", "Rbrace", ",", "token", ".", "RBRACE", ")", "\n", "return", "\n", "}", "\n\n", "p", ".", "print", "(", "blank", ")", "\n", "p", ".", "block", "(", "b", ",", "1", ")", "\n", "*", "multiLine", "=", "true", "\n", "}" ]
// Sets multiLine to true if the function body spans multiple lines.
[ "Sets", "multiLine", "to", "true", "if", "the", "function", "body", "spans", "multiple", "lines", "." ]
5784335da72394c8f53d9036c26fcc876718879b
https://github.com/rogpeppe/godef/blob/5784335da72394c8f53d9036c26fcc876718879b/go/printer/nodes.go#L1412-L1440
152,722
rogpeppe/godef
go/ast/print.go
NotNilFilter
func NotNilFilter(_ string, v reflect.Value) bool { switch v.Kind() { case reflect.Chan, reflect.Func, reflect.Interface, reflect.Map, reflect.Ptr, reflect.Slice: return !v.IsNil() } return true }
go
func NotNilFilter(_ string, v reflect.Value) bool { switch v.Kind() { case reflect.Chan, reflect.Func, reflect.Interface, reflect.Map, reflect.Ptr, reflect.Slice: return !v.IsNil() } return true }
[ "func", "NotNilFilter", "(", "_", "string", ",", "v", "reflect", ".", "Value", ")", "bool", "{", "switch", "v", ".", "Kind", "(", ")", "{", "case", "reflect", ".", "Chan", ",", "reflect", ".", "Func", ",", "reflect", ".", "Interface", ",", "reflect", ".", "Map", ",", "reflect", ".", "Ptr", ",", "reflect", ".", "Slice", ":", "return", "!", "v", ".", "IsNil", "(", ")", "\n", "}", "\n", "return", "true", "\n", "}" ]
// NotNilFilter returns true for field values that are not nil; // it returns false otherwise.
[ "NotNilFilter", "returns", "true", "for", "field", "values", "that", "are", "not", "nil", ";", "it", "returns", "false", "otherwise", "." ]
5784335da72394c8f53d9036c26fcc876718879b
https://github.com/rogpeppe/godef/blob/5784335da72394c8f53d9036c26fcc876718879b/go/ast/print.go#L23-L29
152,723
rogpeppe/godef
go/ast/print.go
printf
func (p *printer) printf(format string, args ...interface{}) { n, err := fmt.Fprintf(p, format, args...) p.written += n if err != nil { panic(localError{err}) } }
go
func (p *printer) printf(format string, args ...interface{}) { n, err := fmt.Fprintf(p, format, args...) p.written += n if err != nil { panic(localError{err}) } }
[ "func", "(", "p", "*", "printer", ")", "printf", "(", "format", "string", ",", "args", "...", "interface", "{", "}", ")", "{", "n", ",", "err", ":=", "fmt", ".", "Fprintf", "(", "p", ",", "format", ",", "args", "...", ")", "\n", "p", ".", "written", "+=", "n", "\n", "if", "err", "!=", "nil", "{", "panic", "(", "localError", "{", "err", "}", ")", "\n", "}", "\n", "}" ]
// printf is a convenience wrapper that takes care of print errors.
[ "printf", "is", "a", "convenience", "wrapper", "that", "takes", "care", "of", "print", "errors", "." ]
5784335da72394c8f53d9036c26fcc876718879b
https://github.com/rogpeppe/godef/blob/5784335da72394c8f53d9036c26fcc876718879b/go/ast/print.go#L129-L135
152,724
rogpeppe/godef
go/scanner/errors.go
GetErrorList
func (h *ErrorVector) GetErrorList(mode int) ErrorList { if len(h.errors) == 0 { return nil } list := make(ErrorList, len(h.errors)) copy(list, h.errors) if mode >= Sorted { sort.Sort(list) } if mode >= NoMultiples { var last token.Position // initial last.Line is != any legal error line i := 0 for _, e := range list { if e.Pos.Filename != last.Filename || e.Pos.Line != last.Line { last = e.Pos list[i] = e i++ } } list = list[0:i] } return list }
go
func (h *ErrorVector) GetErrorList(mode int) ErrorList { if len(h.errors) == 0 { return nil } list := make(ErrorList, len(h.errors)) copy(list, h.errors) if mode >= Sorted { sort.Sort(list) } if mode >= NoMultiples { var last token.Position // initial last.Line is != any legal error line i := 0 for _, e := range list { if e.Pos.Filename != last.Filename || e.Pos.Line != last.Line { last = e.Pos list[i] = e i++ } } list = list[0:i] } return list }
[ "func", "(", "h", "*", "ErrorVector", ")", "GetErrorList", "(", "mode", "int", ")", "ErrorList", "{", "if", "len", "(", "h", ".", "errors", ")", "==", "0", "{", "return", "nil", "\n", "}", "\n\n", "list", ":=", "make", "(", "ErrorList", ",", "len", "(", "h", ".", "errors", ")", ")", "\n", "copy", "(", "list", ",", "h", ".", "errors", ")", "\n\n", "if", "mode", ">=", "Sorted", "{", "sort", ".", "Sort", "(", "list", ")", "\n", "}", "\n\n", "if", "mode", ">=", "NoMultiples", "{", "var", "last", "token", ".", "Position", "// initial last.Line is != any legal error line", "\n", "i", ":=", "0", "\n", "for", "_", ",", "e", ":=", "range", "list", "{", "if", "e", ".", "Pos", ".", "Filename", "!=", "last", ".", "Filename", "||", "e", ".", "Pos", ".", "Line", "!=", "last", ".", "Line", "{", "last", "=", "e", ".", "Pos", "\n", "list", "[", "i", "]", "=", "e", "\n", "i", "++", "\n", "}", "\n", "}", "\n", "list", "=", "list", "[", "0", ":", "i", "]", "\n", "}", "\n\n", "return", "list", "\n", "}" ]
// GetErrorList returns the list of errors collected by an ErrorVector. // The construction of the ErrorList returned is controlled by the mode // parameter. If there are no errors, the result is nil. //
[ "GetErrorList", "returns", "the", "list", "of", "errors", "collected", "by", "an", "ErrorVector", ".", "The", "construction", "of", "the", "ErrorList", "returned", "is", "controlled", "by", "the", "mode", "parameter", ".", "If", "there", "are", "no", "errors", "the", "result", "is", "nil", "." ]
5784335da72394c8f53d9036c26fcc876718879b
https://github.com/rogpeppe/godef/blob/5784335da72394c8f53d9036c26fcc876718879b/go/scanner/errors.go#L111-L137
152,725
rogpeppe/godef
go/scanner/errors.go
GetError
func (h *ErrorVector) GetError(mode int) error { if len(h.errors) == 0 { return nil } return h.GetErrorList(mode) }
go
func (h *ErrorVector) GetError(mode int) error { if len(h.errors) == 0 { return nil } return h.GetErrorList(mode) }
[ "func", "(", "h", "*", "ErrorVector", ")", "GetError", "(", "mode", "int", ")", "error", "{", "if", "len", "(", "h", ".", "errors", ")", "==", "0", "{", "return", "nil", "\n", "}", "\n\n", "return", "h", ".", "GetErrorList", "(", "mode", ")", "\n", "}" ]
// GetError is like GetErrorList, but it returns an os.Error instead // so that a nil result can be assigned to an os.Error variable and // remains nil. //
[ "GetError", "is", "like", "GetErrorList", "but", "it", "returns", "an", "os", ".", "Error", "instead", "so", "that", "a", "nil", "result", "can", "be", "assigned", "to", "an", "os", ".", "Error", "variable", "and", "remains", "nil", "." ]
5784335da72394c8f53d9036c26fcc876718879b
https://github.com/rogpeppe/godef/blob/5784335da72394c8f53d9036c26fcc876718879b/go/scanner/errors.go#L143-L149
152,726
rogpeppe/godef
go/scanner/errors.go
Error
func (h *ErrorVector) Error(pos token.Position, msg string) { h.errors = append(h.errors, &Error{pos, msg}) }
go
func (h *ErrorVector) Error(pos token.Position, msg string) { h.errors = append(h.errors, &Error{pos, msg}) }
[ "func", "(", "h", "*", "ErrorVector", ")", "Error", "(", "pos", "token", ".", "Position", ",", "msg", "string", ")", "{", "h", ".", "errors", "=", "append", "(", "h", ".", "errors", ",", "&", "Error", "{", "pos", ",", "msg", "}", ")", "\n", "}" ]
// ErrorVector implements the ErrorHandler interface.
[ "ErrorVector", "implements", "the", "ErrorHandler", "interface", "." ]
5784335da72394c8f53d9036c26fcc876718879b
https://github.com/rogpeppe/godef/blob/5784335da72394c8f53d9036c26fcc876718879b/go/scanner/errors.go#L152-L154
152,727
rogpeppe/godef
go/parser/interface.go
ParseStmtList
func ParseStmtList(fset *token.FileSet, filename string, src interface{}, scope *ast.Scope, pathToName ImportPathToName) ([]ast.Stmt, error) { data, err := readSource(filename, src) if err != nil { return nil, err } var p parser p.init(fset, filename, data, 0, scope, pathToName) return p.parseStmtList(), p.parseEOF() }
go
func ParseStmtList(fset *token.FileSet, filename string, src interface{}, scope *ast.Scope, pathToName ImportPathToName) ([]ast.Stmt, error) { data, err := readSource(filename, src) if err != nil { return nil, err } var p parser p.init(fset, filename, data, 0, scope, pathToName) return p.parseStmtList(), p.parseEOF() }
[ "func", "ParseStmtList", "(", "fset", "*", "token", ".", "FileSet", ",", "filename", "string", ",", "src", "interface", "{", "}", ",", "scope", "*", "ast", ".", "Scope", ",", "pathToName", "ImportPathToName", ")", "(", "[", "]", "ast", ".", "Stmt", ",", "error", ")", "{", "data", ",", "err", ":=", "readSource", "(", "filename", ",", "src", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "var", "p", "parser", "\n", "p", ".", "init", "(", "fset", ",", "filename", ",", "data", ",", "0", ",", "scope", ",", "pathToName", ")", "\n", "return", "p", ".", "parseStmtList", "(", ")", ",", "p", ".", "parseEOF", "(", ")", "\n", "}" ]
// ParseStmtList parses a list of Go statements and returns the list // of corresponding AST nodes. The fset, filename, and src arguments have the same // interpretation as for ParseFile. If there is an error, the node // list may be nil or contain partial ASTs. // // if scope is non-nil, it will be used as the scope for the statements. //
[ "ParseStmtList", "parses", "a", "list", "of", "Go", "statements", "and", "returns", "the", "list", "of", "corresponding", "AST", "nodes", ".", "The", "fset", "filename", "and", "src", "arguments", "have", "the", "same", "interpretation", "as", "for", "ParseFile", ".", "If", "there", "is", "an", "error", "the", "node", "list", "may", "be", "nil", "or", "contain", "partial", "ASTs", ".", "if", "scope", "is", "non", "-", "nil", "it", "will", "be", "used", "as", "the", "scope", "for", "the", "statements", "." ]
5784335da72394c8f53d9036c26fcc876718879b
https://github.com/rogpeppe/godef/blob/5784335da72394c8f53d9036c26fcc876718879b/go/parser/interface.go#L93-L102
152,728
rogpeppe/godef
go/parser/interface.go
ParseDeclList
func ParseDeclList(fset *token.FileSet, filename string, src interface{}, scope *ast.Scope, pathToName ImportPathToName) ([]ast.Decl, error) { data, err := readSource(filename, src) if err != nil { return nil, err } var p parser p.init(fset, filename, data, 0, scope, pathToName) p.pkgScope = scope p.fileScope = scope return p.parseDeclList(), p.parseEOF() }
go
func ParseDeclList(fset *token.FileSet, filename string, src interface{}, scope *ast.Scope, pathToName ImportPathToName) ([]ast.Decl, error) { data, err := readSource(filename, src) if err != nil { return nil, err } var p parser p.init(fset, filename, data, 0, scope, pathToName) p.pkgScope = scope p.fileScope = scope return p.parseDeclList(), p.parseEOF() }
[ "func", "ParseDeclList", "(", "fset", "*", "token", ".", "FileSet", ",", "filename", "string", ",", "src", "interface", "{", "}", ",", "scope", "*", "ast", ".", "Scope", ",", "pathToName", "ImportPathToName", ")", "(", "[", "]", "ast", ".", "Decl", ",", "error", ")", "{", "data", ",", "err", ":=", "readSource", "(", "filename", ",", "src", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "var", "p", "parser", "\n", "p", ".", "init", "(", "fset", ",", "filename", ",", "data", ",", "0", ",", "scope", ",", "pathToName", ")", "\n", "p", ".", "pkgScope", "=", "scope", "\n", "p", ".", "fileScope", "=", "scope", "\n", "return", "p", ".", "parseDeclList", "(", ")", ",", "p", ".", "parseEOF", "(", ")", "\n", "}" ]
// ParseDeclList parses a list of Go declarations and returns the list // of corresponding AST nodes. The fset, filename, and src arguments have the same // interpretation as for ParseFile. If there is an error, the node // list may be nil or contain partial ASTs. // // If scope is non-nil, it will be used for declarations. //
[ "ParseDeclList", "parses", "a", "list", "of", "Go", "declarations", "and", "returns", "the", "list", "of", "corresponding", "AST", "nodes", ".", "The", "fset", "filename", "and", "src", "arguments", "have", "the", "same", "interpretation", "as", "for", "ParseFile", ".", "If", "there", "is", "an", "error", "the", "node", "list", "may", "be", "nil", "or", "contain", "partial", "ASTs", ".", "If", "scope", "is", "non", "-", "nil", "it", "will", "be", "used", "for", "declarations", "." ]
5784335da72394c8f53d9036c26fcc876718879b
https://github.com/rogpeppe/godef/blob/5784335da72394c8f53d9036c26fcc876718879b/go/parser/interface.go#L111-L122
152,729
rogpeppe/godef
go/token/position.go
Position
func (s *FileSet) Position(p Pos) (pos Position) { if p != NoPos { // TODO(gri) consider optimizing the case where p // is in the last file addded, or perhaps // looked at - will eliminate one level // of search s.mutex.RLock() if f := s.file(p); f != nil { pos = f.position(p) } s.mutex.RUnlock() } return }
go
func (s *FileSet) Position(p Pos) (pos Position) { if p != NoPos { // TODO(gri) consider optimizing the case where p // is in the last file addded, or perhaps // looked at - will eliminate one level // of search s.mutex.RLock() if f := s.file(p); f != nil { pos = f.position(p) } s.mutex.RUnlock() } return }
[ "func", "(", "s", "*", "FileSet", ")", "Position", "(", "p", "Pos", ")", "(", "pos", "Position", ")", "{", "if", "p", "!=", "NoPos", "{", "// TODO(gri) consider optimizing the case where p", "// is in the last file addded, or perhaps", "// looked at - will eliminate one level", "// of search", "s", ".", "mutex", ".", "RLock", "(", ")", "\n", "if", "f", ":=", "s", ".", "file", "(", "p", ")", ";", "f", "!=", "nil", "{", "pos", "=", "f", ".", "position", "(", "p", ")", "\n", "}", "\n", "s", ".", "mutex", ".", "RUnlock", "(", ")", "\n", "}", "\n", "return", "\n", "}" ]
// Position converts a Pos in the fileset into a general Position.
[ "Position", "converts", "a", "Pos", "in", "the", "fileset", "into", "a", "general", "Position", "." ]
5784335da72394c8f53d9036c26fcc876718879b
https://github.com/rogpeppe/godef/blob/5784335da72394c8f53d9036c26fcc876718879b/go/token/position.go#L120-L133
152,730
rogpeppe/godef
go/token/position.go
LineCount
func (f *File) LineCount() int { f.set.mutex.RLock() n := len(f.lines) f.set.mutex.RUnlock() return n }
go
func (f *File) LineCount() int { f.set.mutex.RLock() n := len(f.lines) f.set.mutex.RUnlock() return n }
[ "func", "(", "f", "*", "File", ")", "LineCount", "(", ")", "int", "{", "f", ".", "set", ".", "mutex", ".", "RLock", "(", ")", "\n", "n", ":=", "len", "(", "f", ".", "lines", ")", "\n", "f", ".", "set", ".", "mutex", ".", "RUnlock", "(", ")", "\n", "return", "n", "\n", "}" ]
// LineCount returns the number of lines in file f.
[ "LineCount", "returns", "the", "number", "of", "lines", "in", "file", "f", "." ]
5784335da72394c8f53d9036c26fcc876718879b
https://github.com/rogpeppe/godef/blob/5784335da72394c8f53d9036c26fcc876718879b/go/token/position.go#L187-L192
152,731
rogpeppe/godef
go/token/position.go
AddLine
func (f *File) AddLine(offset int) { f.set.mutex.Lock() if i := len(f.lines); (i == 0 || f.lines[i-1] < offset) && offset < f.size { f.lines = append(f.lines, offset) } f.set.mutex.Unlock() }
go
func (f *File) AddLine(offset int) { f.set.mutex.Lock() if i := len(f.lines); (i == 0 || f.lines[i-1] < offset) && offset < f.size { f.lines = append(f.lines, offset) } f.set.mutex.Unlock() }
[ "func", "(", "f", "*", "File", ")", "AddLine", "(", "offset", "int", ")", "{", "f", ".", "set", ".", "mutex", ".", "Lock", "(", ")", "\n", "if", "i", ":=", "len", "(", "f", ".", "lines", ")", ";", "(", "i", "==", "0", "||", "f", ".", "lines", "[", "i", "-", "1", "]", "<", "offset", ")", "&&", "offset", "<", "f", ".", "size", "{", "f", ".", "lines", "=", "append", "(", "f", ".", "lines", ",", "offset", ")", "\n", "}", "\n", "f", ".", "set", ".", "mutex", ".", "Unlock", "(", ")", "\n", "}" ]
// AddLine adds the line offset for a new line. // The line offset must be larger than the offset for the previous line // and smaller than the file size; otherwise the line offset is ignored. //
[ "AddLine", "adds", "the", "line", "offset", "for", "a", "new", "line", ".", "The", "line", "offset", "must", "be", "larger", "than", "the", "offset", "for", "the", "previous", "line", "and", "smaller", "than", "the", "file", "size", ";", "otherwise", "the", "line", "offset", "is", "ignored", "." ]
5784335da72394c8f53d9036c26fcc876718879b
https://github.com/rogpeppe/godef/blob/5784335da72394c8f53d9036c26fcc876718879b/go/token/position.go#L198-L204
152,732
rogpeppe/godef
go/token/position.go
SetLinesForContent
func (f *File) SetLinesForContent(content []byte) { var lines []int line := 0 for offset, b := range content { if line >= 0 { lines = append(lines, line) } line = -1 if b == '\n' { line = offset + 1 } } // set lines table f.set.mutex.Lock() f.lines = lines f.set.mutex.Unlock() }
go
func (f *File) SetLinesForContent(content []byte) { var lines []int line := 0 for offset, b := range content { if line >= 0 { lines = append(lines, line) } line = -1 if b == '\n' { line = offset + 1 } } // set lines table f.set.mutex.Lock() f.lines = lines f.set.mutex.Unlock() }
[ "func", "(", "f", "*", "File", ")", "SetLinesForContent", "(", "content", "[", "]", "byte", ")", "{", "var", "lines", "[", "]", "int", "\n", "line", ":=", "0", "\n", "for", "offset", ",", "b", ":=", "range", "content", "{", "if", "line", ">=", "0", "{", "lines", "=", "append", "(", "lines", ",", "line", ")", "\n", "}", "\n", "line", "=", "-", "1", "\n", "if", "b", "==", "'\\n'", "{", "line", "=", "offset", "+", "1", "\n", "}", "\n", "}", "\n\n", "// set lines table", "f", ".", "set", ".", "mutex", ".", "Lock", "(", ")", "\n", "f", ".", "lines", "=", "lines", "\n", "f", ".", "set", ".", "mutex", ".", "Unlock", "(", ")", "\n", "}" ]
// SetLinesForContent sets the line offsets for the given file content.
[ "SetLinesForContent", "sets", "the", "line", "offsets", "for", "the", "given", "file", "content", "." ]
5784335da72394c8f53d9036c26fcc876718879b
https://github.com/rogpeppe/godef/blob/5784335da72394c8f53d9036c26fcc876718879b/go/token/position.go#L231-L248
152,733
rogpeppe/godef
go/token/position.go
Line
func (f *File) Line(p Pos) int { // TODO(gri) this can be implemented much more efficiently return f.Position(p).Line }
go
func (f *File) Line(p Pos) int { // TODO(gri) this can be implemented much more efficiently return f.Position(p).Line }
[ "func", "(", "f", "*", "File", ")", "Line", "(", "p", "Pos", ")", "int", "{", "// TODO(gri) this can be implemented much more efficiently", "return", "f", ".", "Position", "(", "p", ")", ".", "Line", "\n", "}" ]
// Line returns the line number for the given file position p; // p must be a Pos value in that file or NoPos. //
[ "Line", "returns", "the", "line", "number", "for", "the", "given", "file", "position", "p", ";", "p", "must", "be", "a", "Pos", "value", "in", "that", "file", "or", "NoPos", "." ]
5784335da72394c8f53d9036c26fcc876718879b
https://github.com/rogpeppe/godef/blob/5784335da72394c8f53d9036c26fcc876718879b/go/token/position.go#L275-L278
152,734
rogpeppe/godef
go/token/position.go
Position
func (f *File) Position(p Pos) (pos Position) { if p != NoPos { if int(p) < f.base || int(p) > f.base+f.size { panic("illegal Pos value") } pos = f.position(p) } return }
go
func (f *File) Position(p Pos) (pos Position) { if p != NoPos { if int(p) < f.base || int(p) > f.base+f.size { panic("illegal Pos value") } pos = f.position(p) } return }
[ "func", "(", "f", "*", "File", ")", "Position", "(", "p", "Pos", ")", "(", "pos", "Position", ")", "{", "if", "p", "!=", "NoPos", "{", "if", "int", "(", "p", ")", "<", "f", ".", "base", "||", "int", "(", "p", ")", ">", "f", ".", "base", "+", "f", ".", "size", "{", "panic", "(", "\"", "\"", ")", "\n", "}", "\n", "pos", "=", "f", ".", "position", "(", "p", ")", "\n", "}", "\n", "return", "\n", "}" ]
// Position returns the Position value for the given file position p; // p must be a Pos value in that file or NoPos. //
[ "Position", "returns", "the", "Position", "value", "for", "the", "given", "file", "position", "p", ";", "p", "must", "be", "a", "Pos", "value", "in", "that", "file", "or", "NoPos", "." ]
5784335da72394c8f53d9036c26fcc876718879b
https://github.com/rogpeppe/godef/blob/5784335da72394c8f53d9036c26fcc876718879b/go/token/position.go#L283-L291
152,735
rogpeppe/godef
go/token/position.go
NewFileSet
func NewFileSet() *FileSet { s := new(FileSet) s.base = 1 // 0 == NoPos s.index = make(map[*File]int) return s }
go
func NewFileSet() *FileSet { s := new(FileSet) s.base = 1 // 0 == NoPos s.index = make(map[*File]int) return s }
[ "func", "NewFileSet", "(", ")", "*", "FileSet", "{", "s", ":=", "new", "(", "FileSet", ")", "\n", "s", ".", "base", "=", "1", "// 0 == NoPos", "\n", "s", ".", "index", "=", "make", "(", "map", "[", "*", "File", "]", "int", ")", "\n", "return", "s", "\n", "}" ]
// NewFileSet creates a new file set.
[ "NewFileSet", "creates", "a", "new", "file", "set", "." ]
5784335da72394c8f53d9036c26fcc876718879b
https://github.com/rogpeppe/godef/blob/5784335da72394c8f53d9036c26fcc876718879b/go/token/position.go#L329-L334
152,736
rogpeppe/godef
go/token/position.go
Base
func (s *FileSet) Base() int { s.mutex.RLock() b := s.base s.mutex.RUnlock() return b }
go
func (s *FileSet) Base() int { s.mutex.RLock() b := s.base s.mutex.RUnlock() return b }
[ "func", "(", "s", "*", "FileSet", ")", "Base", "(", ")", "int", "{", "s", ".", "mutex", ".", "RLock", "(", ")", "\n", "b", ":=", "s", ".", "base", "\n", "s", ".", "mutex", ".", "RUnlock", "(", ")", "\n", "return", "b", "\n\n", "}" ]
// Base returns the minimum base offset that must be provided to // AddFile when adding the next file. //
[ "Base", "returns", "the", "minimum", "base", "offset", "that", "must", "be", "provided", "to", "AddFile", "when", "adding", "the", "next", "file", "." ]
5784335da72394c8f53d9036c26fcc876718879b
https://github.com/rogpeppe/godef/blob/5784335da72394c8f53d9036c26fcc876718879b/go/token/position.go#L339-L345
152,737
rogpeppe/godef
go/token/position.go
Iterate
func (s *FileSet) Iterate(f func(*File) bool) { for i := 0; ; i++ { var file *File s.mutex.RLock() if i < len(s.files) { file = s.files[i] } s.mutex.RUnlock() if file == nil || !f(file) { break } } }
go
func (s *FileSet) Iterate(f func(*File) bool) { for i := 0; ; i++ { var file *File s.mutex.RLock() if i < len(s.files) { file = s.files[i] } s.mutex.RUnlock() if file == nil || !f(file) { break } } }
[ "func", "(", "s", "*", "FileSet", ")", "Iterate", "(", "f", "func", "(", "*", "File", ")", "bool", ")", "{", "for", "i", ":=", "0", ";", ";", "i", "++", "{", "var", "file", "*", "File", "\n", "s", ".", "mutex", ".", "RLock", "(", ")", "\n", "if", "i", "<", "len", "(", "s", ".", "files", ")", "{", "file", "=", "s", ".", "files", "[", "i", "]", "\n", "}", "\n", "s", ".", "mutex", ".", "RUnlock", "(", ")", "\n", "if", "file", "==", "nil", "||", "!", "f", "(", "file", ")", "{", "break", "\n", "}", "\n", "}", "\n", "}" ]
// Files returns the files added to the file set.
[ "Files", "returns", "the", "files", "added", "to", "the", "file", "set", "." ]
5784335da72394c8f53d9036c26fcc876718879b
https://github.com/rogpeppe/godef/blob/5784335da72394c8f53d9036c26fcc876718879b/go/token/position.go#L382-L394
152,738
rogpeppe/godef
adapt.go
cleanFilename
func cleanFilename(path string) string { const prefix = "$GOROOT" if len(path) < len(prefix) || !strings.EqualFold(prefix, path[:len(prefix)]) { return path } //TODO: we need a better way to get the GOROOT that uses the packages api return runtime.GOROOT() + path[len(prefix):] }
go
func cleanFilename(path string) string { const prefix = "$GOROOT" if len(path) < len(prefix) || !strings.EqualFold(prefix, path[:len(prefix)]) { return path } //TODO: we need a better way to get the GOROOT that uses the packages api return runtime.GOROOT() + path[len(prefix):] }
[ "func", "cleanFilename", "(", "path", "string", ")", "string", "{", "const", "prefix", "=", "\"", "\"", "\n", "if", "len", "(", "path", ")", "<", "len", "(", "prefix", ")", "||", "!", "strings", ".", "EqualFold", "(", "prefix", ",", "path", "[", ":", "len", "(", "prefix", ")", "]", ")", "{", "return", "path", "\n", "}", "\n", "//TODO: we need a better way to get the GOROOT that uses the packages api", "return", "runtime", ".", "GOROOT", "(", ")", "+", "path", "[", "len", "(", "prefix", ")", ":", "]", "\n", "}" ]
// cleanFilename normalizes any file names that come out of the fileset.
[ "cleanFilename", "normalizes", "any", "file", "names", "that", "come", "out", "of", "the", "fileset", "." ]
5784335da72394c8f53d9036c26fcc876718879b
https://github.com/rogpeppe/godef/blob/5784335da72394c8f53d9036c26fcc876718879b/adapt.go#L251-L258
152,739
rogpeppe/godef
go/ast/filter.go
fieldName
func fieldName(x Expr) *Ident { switch t := x.(type) { case *Ident: return t case *SelectorExpr: if _, ok := t.X.(*Ident); ok { return t.Sel } case *StarExpr: return fieldName(t.X) } return nil }
go
func fieldName(x Expr) *Ident { switch t := x.(type) { case *Ident: return t case *SelectorExpr: if _, ok := t.X.(*Ident); ok { return t.Sel } case *StarExpr: return fieldName(t.X) } return nil }
[ "func", "fieldName", "(", "x", "Expr", ")", "*", "Ident", "{", "switch", "t", ":=", "x", ".", "(", "type", ")", "{", "case", "*", "Ident", ":", "return", "t", "\n", "case", "*", "SelectorExpr", ":", "if", "_", ",", "ok", ":=", "t", ".", "X", ".", "(", "*", "Ident", ")", ";", "ok", "{", "return", "t", ".", "Sel", "\n", "}", "\n", "case", "*", "StarExpr", ":", "return", "fieldName", "(", "t", ".", "X", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// fieldName assumes that x is the type of an anonymous field and // returns the corresponding field name. If x is not an acceptable // anonymous field, the result is nil. //
[ "fieldName", "assumes", "that", "x", "is", "the", "type", "of", "an", "anonymous", "field", "and", "returns", "the", "corresponding", "field", "name", ".", "If", "x", "is", "not", "an", "acceptable", "anonymous", "field", "the", "result", "is", "nil", "." ]
5784335da72394c8f53d9036c26fcc876718879b
https://github.com/rogpeppe/godef/blob/5784335da72394c8f53d9036c26fcc876718879b/go/ast/filter.go#L27-L39
152,740
rogpeppe/godef
go/ast/filter.go
PackageExports
func PackageExports(pkg *Package) bool { hasExports := false for _, f := range pkg.Files { if FileExports(f) { hasExports = true } } return hasExports }
go
func PackageExports(pkg *Package) bool { hasExports := false for _, f := range pkg.Files { if FileExports(f) { hasExports = true } } return hasExports }
[ "func", "PackageExports", "(", "pkg", "*", "Package", ")", "bool", "{", "hasExports", ":=", "false", "\n", "for", "_", ",", "f", ":=", "range", "pkg", ".", "Files", "{", "if", "FileExports", "(", "f", ")", "{", "hasExports", "=", "true", "\n", "}", "\n", "}", "\n", "return", "hasExports", "\n", "}" ]
// PackageExports trims the AST for a Go package in place such that only // exported nodes remain. The pkg.Files list is not changed, so that file // names and top-level package comments don't get lost. // // PackageExports returns true if there is an exported declaration; it // returns false otherwise. //
[ "PackageExports", "trims", "the", "AST", "for", "a", "Go", "package", "in", "place", "such", "that", "only", "exported", "nodes", "remain", ".", "The", "pkg", ".", "Files", "list", "is", "not", "changed", "so", "that", "file", "names", "and", "top", "-", "level", "package", "comments", "don", "t", "get", "lost", ".", "PackageExports", "returns", "true", "if", "there", "is", "an", "exported", "declaration", ";", "it", "returns", "false", "otherwise", "." ]
5784335da72394c8f53d9036c26fcc876718879b
https://github.com/rogpeppe/godef/blob/5784335da72394c8f53d9036c26fcc876718879b/go/ast/filter.go#L180-L188
152,741
rogpeppe/godef
go/ast/filter.go
MergePackageFiles
func MergePackageFiles(pkg *Package, mode MergeMode) *File { // Count the number of package docs, comments and declarations across // all package files. ndocs := 0 ncomments := 0 ndecls := 0 for _, f := range pkg.Files { if f.Doc != nil { ndocs += len(f.Doc.List) + 1 // +1 for separator } ncomments += len(f.Comments) ndecls += len(f.Decls) } // Collect package comments from all package files into a single // CommentGroup - the collected package documentation. The order // is unspecified. In general there should be only one file with // a package comment; but it's better to collect extra comments // than drop them on the floor. var doc *CommentGroup var pos token.Pos if ndocs > 0 { list := make([]*Comment, ndocs-1) // -1: no separator before first group i := 0 for _, f := range pkg.Files { if f.Doc != nil { if i > 0 { // not the first group - add separator list[i] = separator i++ } for _, c := range f.Doc.List { list[i] = c i++ } if f.Package > pos { // Keep the maximum package clause position as // position for the package clause of the merged // files. pos = f.Package } } } doc = &CommentGroup{list} } // Collect declarations from all package files. var decls []Decl if ndecls > 0 { decls = make([]Decl, ndecls) funcs := make(map[string]int) // map of global function name -> decls index i := 0 // current index n := 0 // number of filtered entries for _, f := range pkg.Files { for _, d := range f.Decls { if mode&FilterFuncDuplicates != 0 { // A language entity may be declared multiple // times in different package files; only at // build time declarations must be unique. // For now, exclude multiple declarations of // functions - keep the one with documentation. // // TODO(gri): Expand this filtering to other // entities (const, type, vars) if // multiple declarations are common. if f, isFun := d.(*FuncDecl); isFun { name := f.Name.Name if j, exists := funcs[name]; exists { // function declared already if decls[j] != nil && decls[j].(*FuncDecl).Doc == nil { // existing declaration has no documentation; // ignore the existing declaration decls[j] = nil } else { // ignore the new declaration d = nil } n++ // filtered an entry } else { funcs[name] = i } } } decls[i] = d i++ } } // Eliminate nil entries from the decls list if entries were // filtered. We do this using a 2nd pass in order to not disturb // the original declaration order in the source (otherwise, this // would also invalidate the monotonically increasing position // info within a single file). if n > 0 { i = 0 for _, d := range decls { if d != nil { decls[i] = d i++ } } decls = decls[0:i] } } // Collect comments from all package files. var comments []*CommentGroup if mode&FilterUnassociatedComments == 0 { comments = make([]*CommentGroup, ncomments) i := 0 for _, f := range pkg.Files { i += copy(comments[i:], f.Comments) } } // TODO(gri) need to compute pkgScope and unresolved identifiers! // TODO(gri) need to compute imports! return &File{doc, pos, NewIdent(pkg.Name), decls, nil, nil, nil, comments} }
go
func MergePackageFiles(pkg *Package, mode MergeMode) *File { // Count the number of package docs, comments and declarations across // all package files. ndocs := 0 ncomments := 0 ndecls := 0 for _, f := range pkg.Files { if f.Doc != nil { ndocs += len(f.Doc.List) + 1 // +1 for separator } ncomments += len(f.Comments) ndecls += len(f.Decls) } // Collect package comments from all package files into a single // CommentGroup - the collected package documentation. The order // is unspecified. In general there should be only one file with // a package comment; but it's better to collect extra comments // than drop them on the floor. var doc *CommentGroup var pos token.Pos if ndocs > 0 { list := make([]*Comment, ndocs-1) // -1: no separator before first group i := 0 for _, f := range pkg.Files { if f.Doc != nil { if i > 0 { // not the first group - add separator list[i] = separator i++ } for _, c := range f.Doc.List { list[i] = c i++ } if f.Package > pos { // Keep the maximum package clause position as // position for the package clause of the merged // files. pos = f.Package } } } doc = &CommentGroup{list} } // Collect declarations from all package files. var decls []Decl if ndecls > 0 { decls = make([]Decl, ndecls) funcs := make(map[string]int) // map of global function name -> decls index i := 0 // current index n := 0 // number of filtered entries for _, f := range pkg.Files { for _, d := range f.Decls { if mode&FilterFuncDuplicates != 0 { // A language entity may be declared multiple // times in different package files; only at // build time declarations must be unique. // For now, exclude multiple declarations of // functions - keep the one with documentation. // // TODO(gri): Expand this filtering to other // entities (const, type, vars) if // multiple declarations are common. if f, isFun := d.(*FuncDecl); isFun { name := f.Name.Name if j, exists := funcs[name]; exists { // function declared already if decls[j] != nil && decls[j].(*FuncDecl).Doc == nil { // existing declaration has no documentation; // ignore the existing declaration decls[j] = nil } else { // ignore the new declaration d = nil } n++ // filtered an entry } else { funcs[name] = i } } } decls[i] = d i++ } } // Eliminate nil entries from the decls list if entries were // filtered. We do this using a 2nd pass in order to not disturb // the original declaration order in the source (otherwise, this // would also invalidate the monotonically increasing position // info within a single file). if n > 0 { i = 0 for _, d := range decls { if d != nil { decls[i] = d i++ } } decls = decls[0:i] } } // Collect comments from all package files. var comments []*CommentGroup if mode&FilterUnassociatedComments == 0 { comments = make([]*CommentGroup, ncomments) i := 0 for _, f := range pkg.Files { i += copy(comments[i:], f.Comments) } } // TODO(gri) need to compute pkgScope and unresolved identifiers! // TODO(gri) need to compute imports! return &File{doc, pos, NewIdent(pkg.Name), decls, nil, nil, nil, comments} }
[ "func", "MergePackageFiles", "(", "pkg", "*", "Package", ",", "mode", "MergeMode", ")", "*", "File", "{", "// Count the number of package docs, comments and declarations across", "// all package files.", "ndocs", ":=", "0", "\n", "ncomments", ":=", "0", "\n", "ndecls", ":=", "0", "\n", "for", "_", ",", "f", ":=", "range", "pkg", ".", "Files", "{", "if", "f", ".", "Doc", "!=", "nil", "{", "ndocs", "+=", "len", "(", "f", ".", "Doc", ".", "List", ")", "+", "1", "// +1 for separator", "\n", "}", "\n", "ncomments", "+=", "len", "(", "f", ".", "Comments", ")", "\n", "ndecls", "+=", "len", "(", "f", ".", "Decls", ")", "\n", "}", "\n\n", "// Collect package comments from all package files into a single", "// CommentGroup - the collected package documentation. The order", "// is unspecified. In general there should be only one file with", "// a package comment; but it's better to collect extra comments", "// than drop them on the floor.", "var", "doc", "*", "CommentGroup", "\n", "var", "pos", "token", ".", "Pos", "\n", "if", "ndocs", ">", "0", "{", "list", ":=", "make", "(", "[", "]", "*", "Comment", ",", "ndocs", "-", "1", ")", "// -1: no separator before first group", "\n", "i", ":=", "0", "\n", "for", "_", ",", "f", ":=", "range", "pkg", ".", "Files", "{", "if", "f", ".", "Doc", "!=", "nil", "{", "if", "i", ">", "0", "{", "// not the first group - add separator", "list", "[", "i", "]", "=", "separator", "\n", "i", "++", "\n", "}", "\n", "for", "_", ",", "c", ":=", "range", "f", ".", "Doc", ".", "List", "{", "list", "[", "i", "]", "=", "c", "\n", "i", "++", "\n", "}", "\n", "if", "f", ".", "Package", ">", "pos", "{", "// Keep the maximum package clause position as", "// position for the package clause of the merged", "// files.", "pos", "=", "f", ".", "Package", "\n", "}", "\n", "}", "\n", "}", "\n", "doc", "=", "&", "CommentGroup", "{", "list", "}", "\n", "}", "\n\n", "// Collect declarations from all package files.", "var", "decls", "[", "]", "Decl", "\n", "if", "ndecls", ">", "0", "{", "decls", "=", "make", "(", "[", "]", "Decl", ",", "ndecls", ")", "\n", "funcs", ":=", "make", "(", "map", "[", "string", "]", "int", ")", "// map of global function name -> decls index", "\n", "i", ":=", "0", "// current index", "\n", "n", ":=", "0", "// number of filtered entries", "\n", "for", "_", ",", "f", ":=", "range", "pkg", ".", "Files", "{", "for", "_", ",", "d", ":=", "range", "f", ".", "Decls", "{", "if", "mode", "&", "FilterFuncDuplicates", "!=", "0", "{", "// A language entity may be declared multiple", "// times in different package files; only at", "// build time declarations must be unique.", "// For now, exclude multiple declarations of", "// functions - keep the one with documentation.", "//", "// TODO(gri): Expand this filtering to other", "// entities (const, type, vars) if", "// multiple declarations are common.", "if", "f", ",", "isFun", ":=", "d", ".", "(", "*", "FuncDecl", ")", ";", "isFun", "{", "name", ":=", "f", ".", "Name", ".", "Name", "\n", "if", "j", ",", "exists", ":=", "funcs", "[", "name", "]", ";", "exists", "{", "// function declared already", "if", "decls", "[", "j", "]", "!=", "nil", "&&", "decls", "[", "j", "]", ".", "(", "*", "FuncDecl", ")", ".", "Doc", "==", "nil", "{", "// existing declaration has no documentation;", "// ignore the existing declaration", "decls", "[", "j", "]", "=", "nil", "\n", "}", "else", "{", "// ignore the new declaration", "d", "=", "nil", "\n", "}", "\n", "n", "++", "// filtered an entry", "\n", "}", "else", "{", "funcs", "[", "name", "]", "=", "i", "\n", "}", "\n", "}", "\n", "}", "\n", "decls", "[", "i", "]", "=", "d", "\n", "i", "++", "\n", "}", "\n", "}", "\n\n", "// Eliminate nil entries from the decls list if entries were", "// filtered. We do this using a 2nd pass in order to not disturb", "// the original declaration order in the source (otherwise, this", "// would also invalidate the monotonically increasing position", "// info within a single file).", "if", "n", ">", "0", "{", "i", "=", "0", "\n", "for", "_", ",", "d", ":=", "range", "decls", "{", "if", "d", "!=", "nil", "{", "decls", "[", "i", "]", "=", "d", "\n", "i", "++", "\n", "}", "\n", "}", "\n", "decls", "=", "decls", "[", "0", ":", "i", "]", "\n", "}", "\n", "}", "\n\n", "// Collect comments from all package files.", "var", "comments", "[", "]", "*", "CommentGroup", "\n", "if", "mode", "&", "FilterUnassociatedComments", "==", "0", "{", "comments", "=", "make", "(", "[", "]", "*", "CommentGroup", ",", "ncomments", ")", "\n", "i", ":=", "0", "\n", "for", "_", ",", "f", ":=", "range", "pkg", ".", "Files", "{", "i", "+=", "copy", "(", "comments", "[", "i", ":", "]", ",", "f", ".", "Comments", ")", "\n", "}", "\n", "}", "\n\n", "// TODO(gri) need to compute pkgScope and unresolved identifiers!", "// TODO(gri) need to compute imports!", "return", "&", "File", "{", "doc", ",", "pos", ",", "NewIdent", "(", "pkg", ".", "Name", ")", ",", "decls", ",", "nil", ",", "nil", ",", "nil", ",", "comments", "}", "\n", "}" ]
// MergePackageFiles creates a file AST by merging the ASTs of the // files belonging to a package. The mode flags control merging behavior. //
[ "MergePackageFiles", "creates", "a", "file", "AST", "by", "merging", "the", "ASTs", "of", "the", "files", "belonging", "to", "a", "package", ".", "The", "mode", "flags", "control", "merging", "behavior", "." ]
5784335da72394c8f53d9036c26fcc876718879b
https://github.com/rogpeppe/godef/blob/5784335da72394c8f53d9036c26fcc876718879b/go/ast/filter.go#L357-L475
152,742
rogpeppe/godef
acme.go
readBody
func readBody(win *acme.Win) ([]byte, error) { var body []byte buf := make([]byte, 8000) for { n, err := win.Read("body", buf) if err == io.EOF { break } if err != nil { return nil, err } body = append(body, buf[0:n]...) } return body, nil }
go
func readBody(win *acme.Win) ([]byte, error) { var body []byte buf := make([]byte, 8000) for { n, err := win.Read("body", buf) if err == io.EOF { break } if err != nil { return nil, err } body = append(body, buf[0:n]...) } return body, nil }
[ "func", "readBody", "(", "win", "*", "acme", ".", "Win", ")", "(", "[", "]", "byte", ",", "error", ")", "{", "var", "body", "[", "]", "byte", "\n", "buf", ":=", "make", "(", "[", "]", "byte", ",", "8000", ")", "\n", "for", "{", "n", ",", "err", ":=", "win", ".", "Read", "(", "\"", "\"", ",", "buf", ")", "\n", "if", "err", "==", "io", ".", "EOF", "{", "break", "\n", "}", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "body", "=", "append", "(", "body", ",", "buf", "[", "0", ":", "n", "]", "...", ")", "\n", "}", "\n", "return", "body", ",", "nil", "\n", "}" ]
// We would use win.ReadAll except for a bug in acme // where it crashes when reading trying to read more // than the negotiated 9P message size.
[ "We", "would", "use", "win", ".", "ReadAll", "except", "for", "a", "bug", "in", "acme", "where", "it", "crashes", "when", "reading", "trying", "to", "read", "more", "than", "the", "negotiated", "9P", "message", "size", "." ]
5784335da72394c8f53d9036c26fcc876718879b
https://github.com/rogpeppe/godef/blob/5784335da72394c8f53d9036c26fcc876718879b/acme.go#L65-L79
152,743
rogpeppe/godef
packages.go
parseFile
func parseFile(filename string, searchpos int) (func(*token.FileSet, string, []byte) (*ast.File, error), chan match) { result := make(chan match, 1) isInputFile := newFileCompare(filename) return func(fset *token.FileSet, fname string, filedata []byte) (*ast.File, error) { isInput := isInputFile(fname) file, err := parser.ParseFile(fset, fname, filedata, 0) if file == nil { return nil, err } pos := token.Pos(-1) if isInput { tfile := fset.File(file.Pos()) if tfile == nil { return file, fmt.Errorf("cursor %d is beyond end of file %s (%d)", searchpos, fname, file.End()-file.Pos()) } if searchpos > tfile.Size() { return file, fmt.Errorf("cursor %d is beyond end of file %s (%d)", searchpos, fname, tfile.Size()) } pos = tfile.Pos(searchpos) m, err := findMatch(file, pos) if err != nil { return nil, err } result <- m } // Trim unneeded parts from the AST to make the type checking faster. trimAST(file, pos) return file, err }, result }
go
func parseFile(filename string, searchpos int) (func(*token.FileSet, string, []byte) (*ast.File, error), chan match) { result := make(chan match, 1) isInputFile := newFileCompare(filename) return func(fset *token.FileSet, fname string, filedata []byte) (*ast.File, error) { isInput := isInputFile(fname) file, err := parser.ParseFile(fset, fname, filedata, 0) if file == nil { return nil, err } pos := token.Pos(-1) if isInput { tfile := fset.File(file.Pos()) if tfile == nil { return file, fmt.Errorf("cursor %d is beyond end of file %s (%d)", searchpos, fname, file.End()-file.Pos()) } if searchpos > tfile.Size() { return file, fmt.Errorf("cursor %d is beyond end of file %s (%d)", searchpos, fname, tfile.Size()) } pos = tfile.Pos(searchpos) m, err := findMatch(file, pos) if err != nil { return nil, err } result <- m } // Trim unneeded parts from the AST to make the type checking faster. trimAST(file, pos) return file, err }, result }
[ "func", "parseFile", "(", "filename", "string", ",", "searchpos", "int", ")", "(", "func", "(", "*", "token", ".", "FileSet", ",", "string", ",", "[", "]", "byte", ")", "(", "*", "ast", ".", "File", ",", "error", ")", ",", "chan", "match", ")", "{", "result", ":=", "make", "(", "chan", "match", ",", "1", ")", "\n", "isInputFile", ":=", "newFileCompare", "(", "filename", ")", "\n", "return", "func", "(", "fset", "*", "token", ".", "FileSet", ",", "fname", "string", ",", "filedata", "[", "]", "byte", ")", "(", "*", "ast", ".", "File", ",", "error", ")", "{", "isInput", ":=", "isInputFile", "(", "fname", ")", "\n", "file", ",", "err", ":=", "parser", ".", "ParseFile", "(", "fset", ",", "fname", ",", "filedata", ",", "0", ")", "\n", "if", "file", "==", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "pos", ":=", "token", ".", "Pos", "(", "-", "1", ")", "\n", "if", "isInput", "{", "tfile", ":=", "fset", ".", "File", "(", "file", ".", "Pos", "(", ")", ")", "\n", "if", "tfile", "==", "nil", "{", "return", "file", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "searchpos", ",", "fname", ",", "file", ".", "End", "(", ")", "-", "file", ".", "Pos", "(", ")", ")", "\n", "}", "\n", "if", "searchpos", ">", "tfile", ".", "Size", "(", ")", "{", "return", "file", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "searchpos", ",", "fname", ",", "tfile", ".", "Size", "(", ")", ")", "\n", "}", "\n", "pos", "=", "tfile", ".", "Pos", "(", "searchpos", ")", "\n", "m", ",", "err", ":=", "findMatch", "(", "file", ",", "pos", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "result", "<-", "m", "\n", "}", "\n", "// Trim unneeded parts from the AST to make the type checking faster.", "trimAST", "(", "file", ",", "pos", ")", "\n", "return", "file", ",", "err", "\n", "}", ",", "result", "\n", "}" ]
// parseFile returns a function that can be used as a Parser in packages.Config // and a channel which will be sent a value when a token is found at the given // search position. // It replaces the contents of a file that matches filename with the src. // It also drops all function bodies that do not contain the searchpos.
[ "parseFile", "returns", "a", "function", "that", "can", "be", "used", "as", "a", "Parser", "in", "packages", ".", "Config", "and", "a", "channel", "which", "will", "be", "sent", "a", "value", "when", "a", "token", "is", "found", "at", "the", "given", "search", "position", ".", "It", "replaces", "the", "contents", "of", "a", "file", "that", "matches", "filename", "with", "the", "src", ".", "It", "also", "drops", "all", "function", "bodies", "that", "do", "not", "contain", "the", "searchpos", "." ]
5784335da72394c8f53d9036c26fcc876718879b
https://github.com/rogpeppe/godef/blob/5784335da72394c8f53d9036c26fcc876718879b/packages.go#L78-L107
152,744
rogpeppe/godef
packages.go
newFileCompare
func newFileCompare(filename string) func(string) bool { fstat, fstatErr := os.Stat(filename) return func(compare string) bool { if filename == compare { return true } if fstatErr != nil { return false } if s, err := os.Stat(compare); err == nil { return os.SameFile(fstat, s) } return false } }
go
func newFileCompare(filename string) func(string) bool { fstat, fstatErr := os.Stat(filename) return func(compare string) bool { if filename == compare { return true } if fstatErr != nil { return false } if s, err := os.Stat(compare); err == nil { return os.SameFile(fstat, s) } return false } }
[ "func", "newFileCompare", "(", "filename", "string", ")", "func", "(", "string", ")", "bool", "{", "fstat", ",", "fstatErr", ":=", "os", ".", "Stat", "(", "filename", ")", "\n", "return", "func", "(", "compare", "string", ")", "bool", "{", "if", "filename", "==", "compare", "{", "return", "true", "\n", "}", "\n", "if", "fstatErr", "!=", "nil", "{", "return", "false", "\n", "}", "\n", "if", "s", ",", "err", ":=", "os", ".", "Stat", "(", "compare", ")", ";", "err", "==", "nil", "{", "return", "os", ".", "SameFile", "(", "fstat", ",", "s", ")", "\n", "}", "\n", "return", "false", "\n", "}", "\n", "}" ]
// newFileCompare returns a function that reports whether its argument // refers to the same file as the given filename.
[ "newFileCompare", "returns", "a", "function", "that", "reports", "whether", "its", "argument", "refers", "to", "the", "same", "file", "as", "the", "given", "filename", "." ]
5784335da72394c8f53d9036c26fcc876718879b
https://github.com/rogpeppe/godef/blob/5784335da72394c8f53d9036c26fcc876718879b/packages.go#L111-L125
152,745
rogpeppe/godef
packages.go
checkMatch
func checkMatch(f *ast.File, pos token.Pos) (match, error) { path, _ := astutil.PathEnclosingInterval(f, pos, pos) result := match{} if path == nil { return result, fmt.Errorf("can't find node enclosing position") } switch node := path[0].(type) { case *ast.Ident: result.ident = node case *ast.SelectorExpr: result.ident = node.Sel case *ast.BasicLit: // if there was a literal import path, we build a special ident of // the same value, which we eventually use to print the path if len(path) > 1 { if spec, ok := path[1].(*ast.ImportSpec); ok { if p, err := strconv.Unquote(spec.Path.Value); err == nil { result.ident = ast.NewIdent(p) } } } } if result.ident != nil { for _, n := range path[1:] { if field, ok := n.(*ast.Field); ok { result.wasEmbeddedField = len(field.Names) == 0 } } } return result, nil }
go
func checkMatch(f *ast.File, pos token.Pos) (match, error) { path, _ := astutil.PathEnclosingInterval(f, pos, pos) result := match{} if path == nil { return result, fmt.Errorf("can't find node enclosing position") } switch node := path[0].(type) { case *ast.Ident: result.ident = node case *ast.SelectorExpr: result.ident = node.Sel case *ast.BasicLit: // if there was a literal import path, we build a special ident of // the same value, which we eventually use to print the path if len(path) > 1 { if spec, ok := path[1].(*ast.ImportSpec); ok { if p, err := strconv.Unquote(spec.Path.Value); err == nil { result.ident = ast.NewIdent(p) } } } } if result.ident != nil { for _, n := range path[1:] { if field, ok := n.(*ast.Field); ok { result.wasEmbeddedField = len(field.Names) == 0 } } } return result, nil }
[ "func", "checkMatch", "(", "f", "*", "ast", ".", "File", ",", "pos", "token", ".", "Pos", ")", "(", "match", ",", "error", ")", "{", "path", ",", "_", ":=", "astutil", ".", "PathEnclosingInterval", "(", "f", ",", "pos", ",", "pos", ")", "\n", "result", ":=", "match", "{", "}", "\n", "if", "path", "==", "nil", "{", "return", "result", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n", "switch", "node", ":=", "path", "[", "0", "]", ".", "(", "type", ")", "{", "case", "*", "ast", ".", "Ident", ":", "result", ".", "ident", "=", "node", "\n", "case", "*", "ast", ".", "SelectorExpr", ":", "result", ".", "ident", "=", "node", ".", "Sel", "\n", "case", "*", "ast", ".", "BasicLit", ":", "// if there was a literal import path, we build a special ident of", "// the same value, which we eventually use to print the path", "if", "len", "(", "path", ")", ">", "1", "{", "if", "spec", ",", "ok", ":=", "path", "[", "1", "]", ".", "(", "*", "ast", ".", "ImportSpec", ")", ";", "ok", "{", "if", "p", ",", "err", ":=", "strconv", ".", "Unquote", "(", "spec", ".", "Path", ".", "Value", ")", ";", "err", "==", "nil", "{", "result", ".", "ident", "=", "ast", ".", "NewIdent", "(", "p", ")", "\n", "}", "\n", "}", "\n", "}", "\n", "}", "\n", "if", "result", ".", "ident", "!=", "nil", "{", "for", "_", ",", "n", ":=", "range", "path", "[", "1", ":", "]", "{", "if", "field", ",", "ok", ":=", "n", ".", "(", "*", "ast", ".", "Field", ")", ";", "ok", "{", "result", ".", "wasEmbeddedField", "=", "len", "(", "field", ".", "Names", ")", "==", "0", "\n", "}", "\n", "}", "\n", "}", "\n", "return", "result", ",", "nil", "\n", "}" ]
// checkMatch checks a single position for a potential identifier.
[ "checkMatch", "checks", "a", "single", "position", "for", "a", "potential", "identifier", "." ]
5784335da72394c8f53d9036c26fcc876718879b
https://github.com/rogpeppe/godef/blob/5784335da72394c8f53d9036c26fcc876718879b/packages.go#L142-L172
152,746
mvdan/xurls
xurls.go
Strict
func Strict() *regexp.Regexp { re := regexp.MustCompile(strictExp()) re.Longest() return re }
go
func Strict() *regexp.Regexp { re := regexp.MustCompile(strictExp()) re.Longest() return re }
[ "func", "Strict", "(", ")", "*", "regexp", ".", "Regexp", "{", "re", ":=", "regexp", ".", "MustCompile", "(", "strictExp", "(", ")", ")", "\n", "re", ".", "Longest", "(", ")", "\n", "return", "re", "\n", "}" ]
// Strict produces a regexp that matches any URL with a scheme in either the // Schemes or SchemesNoAuthority lists.
[ "Strict", "produces", "a", "regexp", "that", "matches", "any", "URL", "with", "a", "scheme", "in", "either", "the", "Schemes", "or", "SchemesNoAuthority", "lists", "." ]
20723a7d9031ce424dd37d4b43ee581b1b8680ba
https://github.com/mvdan/xurls/blob/20723a7d9031ce424dd37d4b43ee581b1b8680ba/xurls.go#L83-L87
152,747
mvdan/xurls
xurls.go
Relaxed
func Relaxed() *regexp.Regexp { re := regexp.MustCompile(relaxedExp()) re.Longest() return re }
go
func Relaxed() *regexp.Regexp { re := regexp.MustCompile(relaxedExp()) re.Longest() return re }
[ "func", "Relaxed", "(", ")", "*", "regexp", ".", "Regexp", "{", "re", ":=", "regexp", ".", "MustCompile", "(", "relaxedExp", "(", ")", ")", "\n", "re", ".", "Longest", "(", ")", "\n", "return", "re", "\n", "}" ]
// Relaxed produces a regexp that matches any URL matched by Strict, plus any // URL with no scheme.
[ "Relaxed", "produces", "a", "regexp", "that", "matches", "any", "URL", "matched", "by", "Strict", "plus", "any", "URL", "with", "no", "scheme", "." ]
20723a7d9031ce424dd37d4b43ee581b1b8680ba
https://github.com/mvdan/xurls/blob/20723a7d9031ce424dd37d4b43ee581b1b8680ba/xurls.go#L91-L95
152,748
mvdan/xurls
xurls.go
StrictMatchingScheme
func StrictMatchingScheme(exp string) (*regexp.Regexp, error) { strictMatching := `(?i)(` + exp + `)(?-i)` + pathCont re, err := regexp.Compile(strictMatching) if err != nil { return nil, err } re.Longest() return re, nil }
go
func StrictMatchingScheme(exp string) (*regexp.Regexp, error) { strictMatching := `(?i)(` + exp + `)(?-i)` + pathCont re, err := regexp.Compile(strictMatching) if err != nil { return nil, err } re.Longest() return re, nil }
[ "func", "StrictMatchingScheme", "(", "exp", "string", ")", "(", "*", "regexp", ".", "Regexp", ",", "error", ")", "{", "strictMatching", ":=", "`(?i)(`", "+", "exp", "+", "`)(?-i)`", "+", "pathCont", "\n", "re", ",", "err", ":=", "regexp", ".", "Compile", "(", "strictMatching", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "re", ".", "Longest", "(", ")", "\n", "return", "re", ",", "nil", "\n", "}" ]
// StrictMatchingScheme produces a regexp similar to Strict, but requiring that // the scheme match the given regular expression. See AnyScheme too.
[ "StrictMatchingScheme", "produces", "a", "regexp", "similar", "to", "Strict", "but", "requiring", "that", "the", "scheme", "match", "the", "given", "regular", "expression", ".", "See", "AnyScheme", "too", "." ]
20723a7d9031ce424dd37d4b43ee581b1b8680ba
https://github.com/mvdan/xurls/blob/20723a7d9031ce424dd37d4b43ee581b1b8680ba/xurls.go#L99-L107
152,749
kubernetes-incubator/custom-metrics-apiserver
pkg/provider/helpers/helpers.go
ResourceFor
func ResourceFor(mapper apimeta.RESTMapper, info provider.CustomMetricInfo) (schema.GroupVersionResource, error) { fullResources, err := mapper.ResourcesFor(info.GroupResource.WithVersion("")) if err == nil && len(fullResources) == 0 { err = fmt.Errorf("no fully versioned resources known for group-resource %v", info.GroupResource) } if err != nil { return schema.GroupVersionResource{}, fmt.Errorf("unable to find preferred version to list matching resource names: %v", err) } return fullResources[0], nil }
go
func ResourceFor(mapper apimeta.RESTMapper, info provider.CustomMetricInfo) (schema.GroupVersionResource, error) { fullResources, err := mapper.ResourcesFor(info.GroupResource.WithVersion("")) if err == nil && len(fullResources) == 0 { err = fmt.Errorf("no fully versioned resources known for group-resource %v", info.GroupResource) } if err != nil { return schema.GroupVersionResource{}, fmt.Errorf("unable to find preferred version to list matching resource names: %v", err) } return fullResources[0], nil }
[ "func", "ResourceFor", "(", "mapper", "apimeta", ".", "RESTMapper", ",", "info", "provider", ".", "CustomMetricInfo", ")", "(", "schema", ".", "GroupVersionResource", ",", "error", ")", "{", "fullResources", ",", "err", ":=", "mapper", ".", "ResourcesFor", "(", "info", ".", "GroupResource", ".", "WithVersion", "(", "\"", "\"", ")", ")", "\n", "if", "err", "==", "nil", "&&", "len", "(", "fullResources", ")", "==", "0", "{", "err", "=", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "info", ".", "GroupResource", ")", "\n", "}", "\n", "if", "err", "!=", "nil", "{", "return", "schema", ".", "GroupVersionResource", "{", "}", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n\n", "return", "fullResources", "[", "0", "]", ",", "nil", "\n", "}" ]
// ResourceFor attempts to resolve a single qualified resource for the given metric. // You can use this to resolve a particular piece of CustomMetricInfo to the underlying // resource that it describes, so that you can list matching objects in the cluster.
[ "ResourceFor", "attempts", "to", "resolve", "a", "single", "qualified", "resource", "for", "the", "given", "metric", ".", "You", "can", "use", "this", "to", "resolve", "a", "particular", "piece", "of", "CustomMetricInfo", "to", "the", "underlying", "resource", "that", "it", "describes", "so", "that", "you", "can", "list", "matching", "objects", "in", "the", "cluster", "." ]
e303a5e75372662801308008ccdff9b57717e75d
https://github.com/kubernetes-incubator/custom-metrics-apiserver/blob/e303a5e75372662801308008ccdff9b57717e75d/pkg/provider/helpers/helpers.go#L38-L48
152,750
kubernetes-incubator/custom-metrics-apiserver
pkg/provider/helpers/helpers.go
ReferenceFor
func ReferenceFor(mapper apimeta.RESTMapper, name types.NamespacedName, info provider.CustomMetricInfo) (custom_metrics.ObjectReference, error) { kind, err := mapper.KindFor(info.GroupResource.WithVersion("")) if err != nil { return custom_metrics.ObjectReference{}, err } // NB: return straight value, not a reference, so that the object can easily // be copied for use multiple times with a different name. return custom_metrics.ObjectReference{ APIVersion: kind.Group + "/" + kind.Version, Kind: kind.Kind, Name: name.Name, Namespace: name.Namespace, }, nil }
go
func ReferenceFor(mapper apimeta.RESTMapper, name types.NamespacedName, info provider.CustomMetricInfo) (custom_metrics.ObjectReference, error) { kind, err := mapper.KindFor(info.GroupResource.WithVersion("")) if err != nil { return custom_metrics.ObjectReference{}, err } // NB: return straight value, not a reference, so that the object can easily // be copied for use multiple times with a different name. return custom_metrics.ObjectReference{ APIVersion: kind.Group + "/" + kind.Version, Kind: kind.Kind, Name: name.Name, Namespace: name.Namespace, }, nil }
[ "func", "ReferenceFor", "(", "mapper", "apimeta", ".", "RESTMapper", ",", "name", "types", ".", "NamespacedName", ",", "info", "provider", ".", "CustomMetricInfo", ")", "(", "custom_metrics", ".", "ObjectReference", ",", "error", ")", "{", "kind", ",", "err", ":=", "mapper", ".", "KindFor", "(", "info", ".", "GroupResource", ".", "WithVersion", "(", "\"", "\"", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "custom_metrics", ".", "ObjectReference", "{", "}", ",", "err", "\n", "}", "\n\n", "// NB: return straight value, not a reference, so that the object can easily", "// be copied for use multiple times with a different name.", "return", "custom_metrics", ".", "ObjectReference", "{", "APIVersion", ":", "kind", ".", "Group", "+", "\"", "\"", "+", "kind", ".", "Version", ",", "Kind", ":", "kind", ".", "Kind", ",", "Name", ":", "name", ".", "Name", ",", "Namespace", ":", "name", ".", "Namespace", ",", "}", ",", "nil", "\n", "}" ]
// ReferenceFor returns a new ObjectReference for the given group-resource and name. // The group-resource is converted into a group-version-kind using the given RESTMapper. // You can use this to easily construct an object reference for use in the DescribedObject // field of CustomMetricInfo.
[ "ReferenceFor", "returns", "a", "new", "ObjectReference", "for", "the", "given", "group", "-", "resource", "and", "name", ".", "The", "group", "-", "resource", "is", "converted", "into", "a", "group", "-", "version", "-", "kind", "using", "the", "given", "RESTMapper", ".", "You", "can", "use", "this", "to", "easily", "construct", "an", "object", "reference", "for", "use", "in", "the", "DescribedObject", "field", "of", "CustomMetricInfo", "." ]
e303a5e75372662801308008ccdff9b57717e75d
https://github.com/kubernetes-incubator/custom-metrics-apiserver/blob/e303a5e75372662801308008ccdff9b57717e75d/pkg/provider/helpers/helpers.go#L54-L68
152,751
kubernetes-incubator/custom-metrics-apiserver
pkg/provider/helpers/helpers.go
ListObjectNames
func ListObjectNames(mapper apimeta.RESTMapper, client dynamic.Interface, namespace string, selector labels.Selector, info provider.CustomMetricInfo) ([]string, error) { res, err := ResourceFor(mapper, info) if err != nil { return nil, err } var resClient dynamic.ResourceInterface if info.Namespaced { resClient = client.Resource(res).Namespace(namespace) } else { resClient = client.Resource(res) } matchingObjectsRaw, err := resClient.List(metav1.ListOptions{LabelSelector: selector.String()}) if err != nil { return nil, err } if !apimeta.IsListType(matchingObjectsRaw) { return nil, fmt.Errorf("result of label selector list operation was not a list") } var names []string err = apimeta.EachListItem(matchingObjectsRaw, func(item runtime.Object) error { objName := item.(*unstructured.Unstructured).GetName() names = append(names, objName) return nil }) if err != nil { return nil, err } return names, nil }
go
func ListObjectNames(mapper apimeta.RESTMapper, client dynamic.Interface, namespace string, selector labels.Selector, info provider.CustomMetricInfo) ([]string, error) { res, err := ResourceFor(mapper, info) if err != nil { return nil, err } var resClient dynamic.ResourceInterface if info.Namespaced { resClient = client.Resource(res).Namespace(namespace) } else { resClient = client.Resource(res) } matchingObjectsRaw, err := resClient.List(metav1.ListOptions{LabelSelector: selector.String()}) if err != nil { return nil, err } if !apimeta.IsListType(matchingObjectsRaw) { return nil, fmt.Errorf("result of label selector list operation was not a list") } var names []string err = apimeta.EachListItem(matchingObjectsRaw, func(item runtime.Object) error { objName := item.(*unstructured.Unstructured).GetName() names = append(names, objName) return nil }) if err != nil { return nil, err } return names, nil }
[ "func", "ListObjectNames", "(", "mapper", "apimeta", ".", "RESTMapper", ",", "client", "dynamic", ".", "Interface", ",", "namespace", "string", ",", "selector", "labels", ".", "Selector", ",", "info", "provider", ".", "CustomMetricInfo", ")", "(", "[", "]", "string", ",", "error", ")", "{", "res", ",", "err", ":=", "ResourceFor", "(", "mapper", ",", "info", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "var", "resClient", "dynamic", ".", "ResourceInterface", "\n", "if", "info", ".", "Namespaced", "{", "resClient", "=", "client", ".", "Resource", "(", "res", ")", ".", "Namespace", "(", "namespace", ")", "\n", "}", "else", "{", "resClient", "=", "client", ".", "Resource", "(", "res", ")", "\n", "}", "\n\n", "matchingObjectsRaw", ",", "err", ":=", "resClient", ".", "List", "(", "metav1", ".", "ListOptions", "{", "LabelSelector", ":", "selector", ".", "String", "(", ")", "}", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "if", "!", "apimeta", ".", "IsListType", "(", "matchingObjectsRaw", ")", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n\n", "var", "names", "[", "]", "string", "\n", "err", "=", "apimeta", ".", "EachListItem", "(", "matchingObjectsRaw", ",", "func", "(", "item", "runtime", ".", "Object", ")", "error", "{", "objName", ":=", "item", ".", "(", "*", "unstructured", ".", "Unstructured", ")", ".", "GetName", "(", ")", "\n", "names", "=", "append", "(", "names", ",", "objName", ")", "\n", "return", "nil", "\n", "}", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "return", "names", ",", "nil", "\n", "}" ]
// ListObjectNames uses the given dynamic client to list the names of all objects // of the given resource matching the given selector. Namespace may be empty // if the metric is for a root-scoped resource.
[ "ListObjectNames", "uses", "the", "given", "dynamic", "client", "to", "list", "the", "names", "of", "all", "objects", "of", "the", "given", "resource", "matching", "the", "given", "selector", ".", "Namespace", "may", "be", "empty", "if", "the", "metric", "is", "for", "a", "root", "-", "scoped", "resource", "." ]
e303a5e75372662801308008ccdff9b57717e75d
https://github.com/kubernetes-incubator/custom-metrics-apiserver/blob/e303a5e75372662801308008ccdff9b57717e75d/pkg/provider/helpers/helpers.go#L73-L106
152,752
kubernetes-incubator/custom-metrics-apiserver
pkg/provider/errors.go
NewMetricNotFoundError
func NewMetricNotFoundError(resource schema.GroupResource, metricName string) *apierr.StatusError { return &apierr.StatusError{metav1.Status{ Status: metav1.StatusFailure, Code: int32(http.StatusNotFound), Reason: metav1.StatusReasonNotFound, Message: fmt.Sprintf("the server could not find the metric %s for %s", metricName, resource.String()), }} }
go
func NewMetricNotFoundError(resource schema.GroupResource, metricName string) *apierr.StatusError { return &apierr.StatusError{metav1.Status{ Status: metav1.StatusFailure, Code: int32(http.StatusNotFound), Reason: metav1.StatusReasonNotFound, Message: fmt.Sprintf("the server could not find the metric %s for %s", metricName, resource.String()), }} }
[ "func", "NewMetricNotFoundError", "(", "resource", "schema", ".", "GroupResource", ",", "metricName", "string", ")", "*", "apierr", ".", "StatusError", "{", "return", "&", "apierr", ".", "StatusError", "{", "metav1", ".", "Status", "{", "Status", ":", "metav1", ".", "StatusFailure", ",", "Code", ":", "int32", "(", "http", ".", "StatusNotFound", ")", ",", "Reason", ":", "metav1", ".", "StatusReasonNotFound", ",", "Message", ":", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "metricName", ",", "resource", ".", "String", "(", ")", ")", ",", "}", "}", "\n", "}" ]
// NewMetricNotFoundError returns a StatusError indicating the given metric could not be found. // It is similar to NewNotFound, but more specialized
[ "NewMetricNotFoundError", "returns", "a", "StatusError", "indicating", "the", "given", "metric", "could", "not", "be", "found", ".", "It", "is", "similar", "to", "NewNotFound", "but", "more", "specialized" ]
e303a5e75372662801308008ccdff9b57717e75d
https://github.com/kubernetes-incubator/custom-metrics-apiserver/blob/e303a5e75372662801308008ccdff9b57717e75d/pkg/provider/errors.go#L31-L38
152,753
kubernetes-incubator/custom-metrics-apiserver
pkg/cmd/builder.go
InstallFlags
func (b *AdapterBase) InstallFlags() { b.initFlagSet() b.flagOnce.Do(func() { if b.CustomMetricsAdapterServerOptions == nil { b.CustomMetricsAdapterServerOptions = server.NewCustomMetricsAdapterServerOptions() } b.SecureServing.AddFlags(b.FlagSet) b.Authentication.AddFlags(b.FlagSet) b.Authorization.AddFlags(b.FlagSet) b.Features.AddFlags(b.FlagSet) b.FlagSet.StringVar(&b.RemoteKubeConfigFile, "lister-kubeconfig", b.RemoteKubeConfigFile, "kubeconfig file pointing at the 'core' kubernetes server with enough rights to list "+ "any described objects") b.FlagSet.DurationVar(&b.DiscoveryInterval, "discovery-interval", b.DiscoveryInterval, "interval at which to refresh API discovery information") }) }
go
func (b *AdapterBase) InstallFlags() { b.initFlagSet() b.flagOnce.Do(func() { if b.CustomMetricsAdapterServerOptions == nil { b.CustomMetricsAdapterServerOptions = server.NewCustomMetricsAdapterServerOptions() } b.SecureServing.AddFlags(b.FlagSet) b.Authentication.AddFlags(b.FlagSet) b.Authorization.AddFlags(b.FlagSet) b.Features.AddFlags(b.FlagSet) b.FlagSet.StringVar(&b.RemoteKubeConfigFile, "lister-kubeconfig", b.RemoteKubeConfigFile, "kubeconfig file pointing at the 'core' kubernetes server with enough rights to list "+ "any described objects") b.FlagSet.DurationVar(&b.DiscoveryInterval, "discovery-interval", b.DiscoveryInterval, "interval at which to refresh API discovery information") }) }
[ "func", "(", "b", "*", "AdapterBase", ")", "InstallFlags", "(", ")", "{", "b", ".", "initFlagSet", "(", ")", "\n", "b", ".", "flagOnce", ".", "Do", "(", "func", "(", ")", "{", "if", "b", ".", "CustomMetricsAdapterServerOptions", "==", "nil", "{", "b", ".", "CustomMetricsAdapterServerOptions", "=", "server", ".", "NewCustomMetricsAdapterServerOptions", "(", ")", "\n", "}", "\n\n", "b", ".", "SecureServing", ".", "AddFlags", "(", "b", ".", "FlagSet", ")", "\n", "b", ".", "Authentication", ".", "AddFlags", "(", "b", ".", "FlagSet", ")", "\n", "b", ".", "Authorization", ".", "AddFlags", "(", "b", ".", "FlagSet", ")", "\n", "b", ".", "Features", ".", "AddFlags", "(", "b", ".", "FlagSet", ")", "\n\n", "b", ".", "FlagSet", ".", "StringVar", "(", "&", "b", ".", "RemoteKubeConfigFile", ",", "\"", "\"", ",", "b", ".", "RemoteKubeConfigFile", ",", "\"", "\"", "+", "\"", "\"", ")", "\n", "b", ".", "FlagSet", ".", "DurationVar", "(", "&", "b", ".", "DiscoveryInterval", ",", "\"", "\"", ",", "b", ".", "DiscoveryInterval", ",", "\"", "\"", ")", "\n", "}", ")", "\n", "}" ]
// InstallFlags installs the minimum required set of flags into the flagset.
[ "InstallFlags", "installs", "the", "minimum", "required", "set", "of", "flags", "into", "the", "flagset", "." ]
e303a5e75372662801308008ccdff9b57717e75d
https://github.com/kubernetes-incubator/custom-metrics-apiserver/blob/e303a5e75372662801308008ccdff9b57717e75d/pkg/cmd/builder.go#L86-L104
152,754
kubernetes-incubator/custom-metrics-apiserver
pkg/cmd/builder.go
initFlagSet
func (b *AdapterBase) initFlagSet() { if b.FlagSet == nil { // default to the normal commandline flags b.FlagSet = pflag.CommandLine } }
go
func (b *AdapterBase) initFlagSet() { if b.FlagSet == nil { // default to the normal commandline flags b.FlagSet = pflag.CommandLine } }
[ "func", "(", "b", "*", "AdapterBase", ")", "initFlagSet", "(", ")", "{", "if", "b", ".", "FlagSet", "==", "nil", "{", "// default to the normal commandline flags", "b", ".", "FlagSet", "=", "pflag", ".", "CommandLine", "\n", "}", "\n", "}" ]
// initFlagSet populates the flagset to the CommandLine flags if it's not already set.
[ "initFlagSet", "populates", "the", "flagset", "to", "the", "CommandLine", "flags", "if", "it", "s", "not", "already", "set", "." ]
e303a5e75372662801308008ccdff9b57717e75d
https://github.com/kubernetes-incubator/custom-metrics-apiserver/blob/e303a5e75372662801308008ccdff9b57717e75d/pkg/cmd/builder.go#L107-L112
152,755
kubernetes-incubator/custom-metrics-apiserver
pkg/cmd/builder.go
Flags
func (b *AdapterBase) Flags() *pflag.FlagSet { b.initFlagSet() b.InstallFlags() return b.FlagSet }
go
func (b *AdapterBase) Flags() *pflag.FlagSet { b.initFlagSet() b.InstallFlags() return b.FlagSet }
[ "func", "(", "b", "*", "AdapterBase", ")", "Flags", "(", ")", "*", "pflag", ".", "FlagSet", "{", "b", ".", "initFlagSet", "(", ")", "\n", "b", ".", "InstallFlags", "(", ")", "\n\n", "return", "b", ".", "FlagSet", "\n", "}" ]
// Flags returns the flagset used by this adapter. // It will initialize the flagset with the minimum required set // of flags as well.
[ "Flags", "returns", "the", "flagset", "used", "by", "this", "adapter", ".", "It", "will", "initialize", "the", "flagset", "with", "the", "minimum", "required", "set", "of", "flags", "as", "well", "." ]
e303a5e75372662801308008ccdff9b57717e75d
https://github.com/kubernetes-incubator/custom-metrics-apiserver/blob/e303a5e75372662801308008ccdff9b57717e75d/pkg/cmd/builder.go#L117-L122
152,756
kubernetes-incubator/custom-metrics-apiserver
pkg/cmd/builder.go
ClientConfig
func (b *AdapterBase) ClientConfig() (*rest.Config, error) { if b.clientConfig == nil { var clientConfig *rest.Config var err error if len(b.RemoteKubeConfigFile) > 0 { loadingRules := &clientcmd.ClientConfigLoadingRules{ExplicitPath: b.RemoteKubeConfigFile} loader := clientcmd.NewNonInteractiveDeferredLoadingClientConfig(loadingRules, &clientcmd.ConfigOverrides{}) clientConfig, err = loader.ClientConfig() } else { clientConfig, err = rest.InClusterConfig() } if err != nil { return nil, fmt.Errorf("unable to construct lister client config to initialize provider: %v", err) } b.clientConfig = clientConfig } return b.clientConfig, nil }
go
func (b *AdapterBase) ClientConfig() (*rest.Config, error) { if b.clientConfig == nil { var clientConfig *rest.Config var err error if len(b.RemoteKubeConfigFile) > 0 { loadingRules := &clientcmd.ClientConfigLoadingRules{ExplicitPath: b.RemoteKubeConfigFile} loader := clientcmd.NewNonInteractiveDeferredLoadingClientConfig(loadingRules, &clientcmd.ConfigOverrides{}) clientConfig, err = loader.ClientConfig() } else { clientConfig, err = rest.InClusterConfig() } if err != nil { return nil, fmt.Errorf("unable to construct lister client config to initialize provider: %v", err) } b.clientConfig = clientConfig } return b.clientConfig, nil }
[ "func", "(", "b", "*", "AdapterBase", ")", "ClientConfig", "(", ")", "(", "*", "rest", ".", "Config", ",", "error", ")", "{", "if", "b", ".", "clientConfig", "==", "nil", "{", "var", "clientConfig", "*", "rest", ".", "Config", "\n", "var", "err", "error", "\n", "if", "len", "(", "b", ".", "RemoteKubeConfigFile", ")", ">", "0", "{", "loadingRules", ":=", "&", "clientcmd", ".", "ClientConfigLoadingRules", "{", "ExplicitPath", ":", "b", ".", "RemoteKubeConfigFile", "}", "\n", "loader", ":=", "clientcmd", ".", "NewNonInteractiveDeferredLoadingClientConfig", "(", "loadingRules", ",", "&", "clientcmd", ".", "ConfigOverrides", "{", "}", ")", "\n\n", "clientConfig", ",", "err", "=", "loader", ".", "ClientConfig", "(", ")", "\n", "}", "else", "{", "clientConfig", ",", "err", "=", "rest", ".", "InClusterConfig", "(", ")", "\n", "}", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n", "b", ".", "clientConfig", "=", "clientConfig", "\n", "}", "\n", "return", "b", ".", "clientConfig", ",", "nil", "\n", "}" ]
// ClientConfig returns the REST client configuration used to construct // clients for the clients and RESTMapper, and may be used for other // purposes as well. If you need to mutate it, be sure to copy it with // rest.CopyConfig first.
[ "ClientConfig", "returns", "the", "REST", "client", "configuration", "used", "to", "construct", "clients", "for", "the", "clients", "and", "RESTMapper", "and", "may", "be", "used", "for", "other", "purposes", "as", "well", ".", "If", "you", "need", "to", "mutate", "it", "be", "sure", "to", "copy", "it", "with", "rest", ".", "CopyConfig", "first", "." ]
e303a5e75372662801308008ccdff9b57717e75d
https://github.com/kubernetes-incubator/custom-metrics-apiserver/blob/e303a5e75372662801308008ccdff9b57717e75d/pkg/cmd/builder.go#L128-L146
152,757
kubernetes-incubator/custom-metrics-apiserver
pkg/cmd/builder.go
DiscoveryClient
func (b *AdapterBase) DiscoveryClient() (discovery.DiscoveryInterface, error) { if b.discoveryClient == nil { clientConfig, err := b.ClientConfig() if err != nil { return nil, err } discoveryClient, err := discovery.NewDiscoveryClientForConfig(clientConfig) if err != nil { return nil, fmt.Errorf("unable to construct discovery client for dynamic client: %v", err) } b.discoveryClient = discoveryClient } return b.discoveryClient, nil }
go
func (b *AdapterBase) DiscoveryClient() (discovery.DiscoveryInterface, error) { if b.discoveryClient == nil { clientConfig, err := b.ClientConfig() if err != nil { return nil, err } discoveryClient, err := discovery.NewDiscoveryClientForConfig(clientConfig) if err != nil { return nil, fmt.Errorf("unable to construct discovery client for dynamic client: %v", err) } b.discoveryClient = discoveryClient } return b.discoveryClient, nil }
[ "func", "(", "b", "*", "AdapterBase", ")", "DiscoveryClient", "(", ")", "(", "discovery", ".", "DiscoveryInterface", ",", "error", ")", "{", "if", "b", ".", "discoveryClient", "==", "nil", "{", "clientConfig", ",", "err", ":=", "b", ".", "ClientConfig", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "discoveryClient", ",", "err", ":=", "discovery", ".", "NewDiscoveryClientForConfig", "(", "clientConfig", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n", "b", ".", "discoveryClient", "=", "discoveryClient", "\n", "}", "\n", "return", "b", ".", "discoveryClient", ",", "nil", "\n", "}" ]
// DiscoveryClient returns a DiscoveryInterface suitable to for discovering resources // available on the cluster.
[ "DiscoveryClient", "returns", "a", "DiscoveryInterface", "suitable", "to", "for", "discovering", "resources", "available", "on", "the", "cluster", "." ]
e303a5e75372662801308008ccdff9b57717e75d
https://github.com/kubernetes-incubator/custom-metrics-apiserver/blob/e303a5e75372662801308008ccdff9b57717e75d/pkg/cmd/builder.go#L150-L163
152,758
kubernetes-incubator/custom-metrics-apiserver
pkg/cmd/builder.go
RESTMapper
func (b *AdapterBase) RESTMapper() (apimeta.RESTMapper, error) { if b.restMapper == nil { discoveryClient, err := b.DiscoveryClient() if err != nil { return nil, err } // NB: since we never actually look at the contents of // the objects we fetch (beyond ObjectMeta), unstructured should be fine dynamicMapper, err := dynamicmapper.NewRESTMapper(discoveryClient, b.DiscoveryInterval) if err != nil { return nil, fmt.Errorf("unable to construct dynamic discovery mapper: %v", err) } b.restMapper = dynamicMapper } return b.restMapper, nil }
go
func (b *AdapterBase) RESTMapper() (apimeta.RESTMapper, error) { if b.restMapper == nil { discoveryClient, err := b.DiscoveryClient() if err != nil { return nil, err } // NB: since we never actually look at the contents of // the objects we fetch (beyond ObjectMeta), unstructured should be fine dynamicMapper, err := dynamicmapper.NewRESTMapper(discoveryClient, b.DiscoveryInterval) if err != nil { return nil, fmt.Errorf("unable to construct dynamic discovery mapper: %v", err) } b.restMapper = dynamicMapper } return b.restMapper, nil }
[ "func", "(", "b", "*", "AdapterBase", ")", "RESTMapper", "(", ")", "(", "apimeta", ".", "RESTMapper", ",", "error", ")", "{", "if", "b", ".", "restMapper", "==", "nil", "{", "discoveryClient", ",", "err", ":=", "b", ".", "DiscoveryClient", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "// NB: since we never actually look at the contents of", "// the objects we fetch (beyond ObjectMeta), unstructured should be fine", "dynamicMapper", ",", "err", ":=", "dynamicmapper", ".", "NewRESTMapper", "(", "discoveryClient", ",", "b", ".", "DiscoveryInterval", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n\n", "b", ".", "restMapper", "=", "dynamicMapper", "\n", "}", "\n", "return", "b", ".", "restMapper", ",", "nil", "\n", "}" ]
// RESTMapper returns a RESTMapper dynamically populated with discovery information. // The discovery information will be periodically repopulated according to DiscoveryInterval.
[ "RESTMapper", "returns", "a", "RESTMapper", "dynamically", "populated", "with", "discovery", "information", ".", "The", "discovery", "information", "will", "be", "periodically", "repopulated", "according", "to", "DiscoveryInterval", "." ]
e303a5e75372662801308008ccdff9b57717e75d
https://github.com/kubernetes-incubator/custom-metrics-apiserver/blob/e303a5e75372662801308008ccdff9b57717e75d/pkg/cmd/builder.go#L167-L183
152,759
kubernetes-incubator/custom-metrics-apiserver
pkg/cmd/builder.go
DynamicClient
func (b *AdapterBase) DynamicClient() (dynamic.Interface, error) { if b.dynamicClient == nil { clientConfig, err := b.ClientConfig() if err != nil { return nil, err } dynClient, err := dynamic.NewForConfig(clientConfig) if err != nil { return nil, fmt.Errorf("unable to construct lister client to initialize provider: %v", err) } b.dynamicClient = dynClient } return b.dynamicClient, nil }
go
func (b *AdapterBase) DynamicClient() (dynamic.Interface, error) { if b.dynamicClient == nil { clientConfig, err := b.ClientConfig() if err != nil { return nil, err } dynClient, err := dynamic.NewForConfig(clientConfig) if err != nil { return nil, fmt.Errorf("unable to construct lister client to initialize provider: %v", err) } b.dynamicClient = dynClient } return b.dynamicClient, nil }
[ "func", "(", "b", "*", "AdapterBase", ")", "DynamicClient", "(", ")", "(", "dynamic", ".", "Interface", ",", "error", ")", "{", "if", "b", ".", "dynamicClient", "==", "nil", "{", "clientConfig", ",", "err", ":=", "b", ".", "ClientConfig", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "dynClient", ",", "err", ":=", "dynamic", ".", "NewForConfig", "(", "clientConfig", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n", "b", ".", "dynamicClient", "=", "dynClient", "\n", "}", "\n", "return", "b", ".", "dynamicClient", ",", "nil", "\n", "}" ]
// DynamicClient returns a dynamic Kubernetes client capable of listing and fetching // any resources on the cluster.
[ "DynamicClient", "returns", "a", "dynamic", "Kubernetes", "client", "capable", "of", "listing", "and", "fetching", "any", "resources", "on", "the", "cluster", "." ]
e303a5e75372662801308008ccdff9b57717e75d
https://github.com/kubernetes-incubator/custom-metrics-apiserver/blob/e303a5e75372662801308008ccdff9b57717e75d/pkg/cmd/builder.go#L187-L200
152,760
kubernetes-incubator/custom-metrics-apiserver
pkg/cmd/builder.go
Informers
func (b *AdapterBase) Informers() (informers.SharedInformerFactory, error) { if b.informers == nil { clientConfig, err := b.ClientConfig() if err != nil { return nil, err } kubeClient, err := kubernetes.NewForConfig(clientConfig) if err != nil { return nil, err } b.informers = informers.NewSharedInformerFactory(kubeClient, 0) } return b.informers, nil }
go
func (b *AdapterBase) Informers() (informers.SharedInformerFactory, error) { if b.informers == nil { clientConfig, err := b.ClientConfig() if err != nil { return nil, err } kubeClient, err := kubernetes.NewForConfig(clientConfig) if err != nil { return nil, err } b.informers = informers.NewSharedInformerFactory(kubeClient, 0) } return b.informers, nil }
[ "func", "(", "b", "*", "AdapterBase", ")", "Informers", "(", ")", "(", "informers", ".", "SharedInformerFactory", ",", "error", ")", "{", "if", "b", ".", "informers", "==", "nil", "{", "clientConfig", ",", "err", ":=", "b", ".", "ClientConfig", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "kubeClient", ",", "err", ":=", "kubernetes", ".", "NewForConfig", "(", "clientConfig", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "b", ".", "informers", "=", "informers", ".", "NewSharedInformerFactory", "(", "kubeClient", ",", "0", ")", "\n", "}", "\n\n", "return", "b", ".", "informers", ",", "nil", "\n", "}" ]
// Informers returns a SharedInformerFactory for constructing new informers. // The informers will be automatically started as part of starting the adapter.
[ "Informers", "returns", "a", "SharedInformerFactory", "for", "constructing", "new", "informers", ".", "The", "informers", "will", "be", "automatically", "started", "as", "part", "of", "starting", "the", "adapter", "." ]
e303a5e75372662801308008ccdff9b57717e75d
https://github.com/kubernetes-incubator/custom-metrics-apiserver/blob/e303a5e75372662801308008ccdff9b57717e75d/pkg/cmd/builder.go#L259-L273
152,761
kubernetes-incubator/custom-metrics-apiserver
pkg/cmd/builder.go
Run
func (b *AdapterBase) Run(stopCh <-chan struct{}) error { server, err := b.Server() if err != nil { return err } return server.GenericAPIServer.PrepareRun().Run(stopCh) }
go
func (b *AdapterBase) Run(stopCh <-chan struct{}) error { server, err := b.Server() if err != nil { return err } return server.GenericAPIServer.PrepareRun().Run(stopCh) }
[ "func", "(", "b", "*", "AdapterBase", ")", "Run", "(", "stopCh", "<-", "chan", "struct", "{", "}", ")", "error", "{", "server", ",", "err", ":=", "b", ".", "Server", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "return", "server", ".", "GenericAPIServer", ".", "PrepareRun", "(", ")", ".", "Run", "(", "stopCh", ")", "\n", "}" ]
// Run runs this custom metrics adapter until the given stop channel is closed.
[ "Run", "runs", "this", "custom", "metrics", "adapter", "until", "the", "given", "stop", "channel", "is", "closed", "." ]
e303a5e75372662801308008ccdff9b57717e75d
https://github.com/kubernetes-incubator/custom-metrics-apiserver/blob/e303a5e75372662801308008ccdff9b57717e75d/pkg/cmd/builder.go#L276-L283
152,762
kubernetes-incubator/custom-metrics-apiserver
pkg/registry/external_metrics/reststorage.go
List
func (r *REST) List(ctx context.Context, options *metainternalversion.ListOptions) (runtime.Object, error) { // populate the label selector, defaulting to all metricSelector := labels.Everything() if options != nil && options.LabelSelector != nil { metricSelector = options.LabelSelector } namespace := genericapirequest.NamespaceValue(ctx) requestInfo, ok := request.RequestInfoFrom(ctx) if !ok { return nil, fmt.Errorf("unable to get resource and metric name from request") } metricName := requestInfo.Resource return r.emProvider.GetExternalMetric(namespace, metricSelector, provider.ExternalMetricInfo{Metric: metricName}) }
go
func (r *REST) List(ctx context.Context, options *metainternalversion.ListOptions) (runtime.Object, error) { // populate the label selector, defaulting to all metricSelector := labels.Everything() if options != nil && options.LabelSelector != nil { metricSelector = options.LabelSelector } namespace := genericapirequest.NamespaceValue(ctx) requestInfo, ok := request.RequestInfoFrom(ctx) if !ok { return nil, fmt.Errorf("unable to get resource and metric name from request") } metricName := requestInfo.Resource return r.emProvider.GetExternalMetric(namespace, metricSelector, provider.ExternalMetricInfo{Metric: metricName}) }
[ "func", "(", "r", "*", "REST", ")", "List", "(", "ctx", "context", ".", "Context", ",", "options", "*", "metainternalversion", ".", "ListOptions", ")", "(", "runtime", ".", "Object", ",", "error", ")", "{", "// populate the label selector, defaulting to all", "metricSelector", ":=", "labels", ".", "Everything", "(", ")", "\n", "if", "options", "!=", "nil", "&&", "options", ".", "LabelSelector", "!=", "nil", "{", "metricSelector", "=", "options", ".", "LabelSelector", "\n", "}", "\n\n", "namespace", ":=", "genericapirequest", ".", "NamespaceValue", "(", "ctx", ")", "\n\n", "requestInfo", ",", "ok", ":=", "request", ".", "RequestInfoFrom", "(", "ctx", ")", "\n", "if", "!", "ok", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n", "metricName", ":=", "requestInfo", ".", "Resource", "\n\n", "return", "r", ".", "emProvider", ".", "GetExternalMetric", "(", "namespace", ",", "metricSelector", ",", "provider", ".", "ExternalMetricInfo", "{", "Metric", ":", "metricName", "}", ")", "\n", "}" ]
// List selects resources in the storage which match to the selector.
[ "List", "selects", "resources", "in", "the", "storage", "which", "match", "to", "the", "selector", "." ]
e303a5e75372662801308008ccdff9b57717e75d
https://github.com/kubernetes-incubator/custom-metrics-apiserver/blob/e303a5e75372662801308008ccdff9b57717e75d/pkg/registry/external_metrics/reststorage.go#L64-L80
152,763
kubernetes-incubator/custom-metrics-apiserver
pkg/provider/resource_lister.go
ListAPIResources
func (l *externalMetricsResourceLister) ListAPIResources() []metav1.APIResource { metrics := l.provider.ListAllExternalMetrics() resources := make([]metav1.APIResource, len(metrics)) for i, metric := range metrics { resources[i] = metav1.APIResource{ Name: metric.Metric, Namespaced: true, Kind: "ExternalMetricValueList", Verbs: metav1.Verbs{"get"}, } } return resources }
go
func (l *externalMetricsResourceLister) ListAPIResources() []metav1.APIResource { metrics := l.provider.ListAllExternalMetrics() resources := make([]metav1.APIResource, len(metrics)) for i, metric := range metrics { resources[i] = metav1.APIResource{ Name: metric.Metric, Namespaced: true, Kind: "ExternalMetricValueList", Verbs: metav1.Verbs{"get"}, } } return resources }
[ "func", "(", "l", "*", "externalMetricsResourceLister", ")", "ListAPIResources", "(", ")", "[", "]", "metav1", ".", "APIResource", "{", "metrics", ":=", "l", ".", "provider", ".", "ListAllExternalMetrics", "(", ")", "\n", "resources", ":=", "make", "(", "[", "]", "metav1", ".", "APIResource", ",", "len", "(", "metrics", ")", ")", "\n\n", "for", "i", ",", "metric", ":=", "range", "metrics", "{", "resources", "[", "i", "]", "=", "metav1", ".", "APIResource", "{", "Name", ":", "metric", ".", "Metric", ",", "Namespaced", ":", "true", ",", "Kind", ":", "\"", "\"", ",", "Verbs", ":", "metav1", ".", "Verbs", "{", "\"", "\"", "}", ",", "}", "\n", "}", "\n\n", "return", "resources", "\n", "}" ]
// ListAPIResources lists all supported custom metrics.
[ "ListAPIResources", "lists", "all", "supported", "custom", "metrics", "." ]
e303a5e75372662801308008ccdff9b57717e75d
https://github.com/kubernetes-incubator/custom-metrics-apiserver/blob/e303a5e75372662801308008ccdff9b57717e75d/pkg/provider/resource_lister.go#L63-L77
152,764
kubernetes-incubator/custom-metrics-apiserver
pkg/apiserver/installer/installer.go
InstallREST
func (g *MetricsAPIGroupVersion) InstallREST(container *restful.Container) error { installer := g.newDynamicInstaller() ws := installer.NewWebService() registrationErrors := installer.Install(ws) lister := g.ResourceLister if lister == nil { return fmt.Errorf("must provide a dynamic lister for dynamic API groups") } versionDiscoveryHandler := discovery.NewAPIVersionHandler(g.Serializer, g.GroupVersion, lister) versionDiscoveryHandler.AddToWebService(ws) container.Add(ws) return utilerrors.NewAggregate(registrationErrors) }
go
func (g *MetricsAPIGroupVersion) InstallREST(container *restful.Container) error { installer := g.newDynamicInstaller() ws := installer.NewWebService() registrationErrors := installer.Install(ws) lister := g.ResourceLister if lister == nil { return fmt.Errorf("must provide a dynamic lister for dynamic API groups") } versionDiscoveryHandler := discovery.NewAPIVersionHandler(g.Serializer, g.GroupVersion, lister) versionDiscoveryHandler.AddToWebService(ws) container.Add(ws) return utilerrors.NewAggregate(registrationErrors) }
[ "func", "(", "g", "*", "MetricsAPIGroupVersion", ")", "InstallREST", "(", "container", "*", "restful", ".", "Container", ")", "error", "{", "installer", ":=", "g", ".", "newDynamicInstaller", "(", ")", "\n", "ws", ":=", "installer", ".", "NewWebService", "(", ")", "\n\n", "registrationErrors", ":=", "installer", ".", "Install", "(", "ws", ")", "\n", "lister", ":=", "g", ".", "ResourceLister", "\n", "if", "lister", "==", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n", "versionDiscoveryHandler", ":=", "discovery", ".", "NewAPIVersionHandler", "(", "g", ".", "Serializer", ",", "g", ".", "GroupVersion", ",", "lister", ")", "\n", "versionDiscoveryHandler", ".", "AddToWebService", "(", "ws", ")", "\n", "container", ".", "Add", "(", "ws", ")", "\n", "return", "utilerrors", ".", "NewAggregate", "(", "registrationErrors", ")", "\n", "}" ]
// InstallDynamicREST registers the dynamic REST handlers into a restful Container. // It is expected that the provided path root prefix will serve all operations. Root MUST // NOT end in a slash. It should mirror InstallREST in the plain APIGroupVersion.
[ "InstallDynamicREST", "registers", "the", "dynamic", "REST", "handlers", "into", "a", "restful", "Container", ".", "It", "is", "expected", "that", "the", "provided", "path", "root", "prefix", "will", "serve", "all", "operations", ".", "Root", "MUST", "NOT", "end", "in", "a", "slash", ".", "It", "should", "mirror", "InstallREST", "in", "the", "plain", "APIGroupVersion", "." ]
e303a5e75372662801308008ccdff9b57717e75d
https://github.com/kubernetes-incubator/custom-metrics-apiserver/blob/e303a5e75372662801308008ccdff9b57717e75d/pkg/apiserver/installer/installer.go#L68-L81
152,765
kubernetes-incubator/custom-metrics-apiserver
pkg/apiserver/installer/installer.go
newDynamicInstaller
func (g *MetricsAPIGroupVersion) newDynamicInstaller() *MetricsAPIInstaller { prefix := gpath.Join(g.Root, g.GroupVersion.Group, g.GroupVersion.Version) installer := &MetricsAPIInstaller{ group: g, prefix: prefix, minRequestTimeout: g.MinRequestTimeout, handlers: g.Handlers, } return installer }
go
func (g *MetricsAPIGroupVersion) newDynamicInstaller() *MetricsAPIInstaller { prefix := gpath.Join(g.Root, g.GroupVersion.Group, g.GroupVersion.Version) installer := &MetricsAPIInstaller{ group: g, prefix: prefix, minRequestTimeout: g.MinRequestTimeout, handlers: g.Handlers, } return installer }
[ "func", "(", "g", "*", "MetricsAPIGroupVersion", ")", "newDynamicInstaller", "(", ")", "*", "MetricsAPIInstaller", "{", "prefix", ":=", "gpath", ".", "Join", "(", "g", ".", "Root", ",", "g", ".", "GroupVersion", ".", "Group", ",", "g", ".", "GroupVersion", ".", "Version", ")", "\n", "installer", ":=", "&", "MetricsAPIInstaller", "{", "group", ":", "g", ",", "prefix", ":", "prefix", ",", "minRequestTimeout", ":", "g", ".", "MinRequestTimeout", ",", "handlers", ":", "g", ".", "Handlers", ",", "}", "\n\n", "return", "installer", "\n", "}" ]
// newDynamicInstaller is a helper to create the installer. It mirrors // newInstaller in APIGroupVersion.
[ "newDynamicInstaller", "is", "a", "helper", "to", "create", "the", "installer", ".", "It", "mirrors", "newInstaller", "in", "APIGroupVersion", "." ]
e303a5e75372662801308008ccdff9b57717e75d
https://github.com/kubernetes-incubator/custom-metrics-apiserver/blob/e303a5e75372662801308008ccdff9b57717e75d/pkg/apiserver/installer/installer.go#L85-L95
152,766
kubernetes-incubator/custom-metrics-apiserver
pkg/apiserver/installer/installer.go
Install
func (a *MetricsAPIInstaller) Install(ws *restful.WebService) (errors []error) { errors = make([]error, 0) err := a.handlers.registerResourceHandlers(a, ws) if err != nil { errors = append(errors, fmt.Errorf("error in registering custom metrics resource: %v", err)) } return errors }
go
func (a *MetricsAPIInstaller) Install(ws *restful.WebService) (errors []error) { errors = make([]error, 0) err := a.handlers.registerResourceHandlers(a, ws) if err != nil { errors = append(errors, fmt.Errorf("error in registering custom metrics resource: %v", err)) } return errors }
[ "func", "(", "a", "*", "MetricsAPIInstaller", ")", "Install", "(", "ws", "*", "restful", ".", "WebService", ")", "(", "errors", "[", "]", "error", ")", "{", "errors", "=", "make", "(", "[", "]", "error", ",", "0", ")", "\n\n", "err", ":=", "a", ".", "handlers", ".", "registerResourceHandlers", "(", "a", ",", "ws", ")", "\n", "if", "err", "!=", "nil", "{", "errors", "=", "append", "(", "errors", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", ")", "\n", "}", "\n\n", "return", "errors", "\n", "}" ]
// Install installs handlers for External Metrics API resources.
[ "Install", "installs", "handlers", "for", "External", "Metrics", "API", "resources", "." ]
e303a5e75372662801308008ccdff9b57717e75d
https://github.com/kubernetes-incubator/custom-metrics-apiserver/blob/e303a5e75372662801308008ccdff9b57717e75d/pkg/apiserver/installer/installer.go#L112-L121
152,767
kubernetes-incubator/custom-metrics-apiserver
pkg/apiserver/installer/installer.go
NewWebService
func (a *MetricsAPIInstaller) NewWebService() *restful.WebService { ws := new(restful.WebService) ws.Path(a.prefix) // a.prefix contains "prefix/group/version" ws.Doc("API at " + a.prefix) // Backwards compatibility, we accepted objects with empty content-type at V1. // If we stop using go-restful, we can default empty content-type to application/json on an // endpoint by endpoint basis ws.Consumes("*/*") mediaTypes, streamMediaTypes := negotiation.MediaTypesForSerializer(a.group.Serializer) ws.Produces(append(mediaTypes, streamMediaTypes...)...) ws.ApiVersion(a.group.GroupVersion.String()) return ws }
go
func (a *MetricsAPIInstaller) NewWebService() *restful.WebService { ws := new(restful.WebService) ws.Path(a.prefix) // a.prefix contains "prefix/group/version" ws.Doc("API at " + a.prefix) // Backwards compatibility, we accepted objects with empty content-type at V1. // If we stop using go-restful, we can default empty content-type to application/json on an // endpoint by endpoint basis ws.Consumes("*/*") mediaTypes, streamMediaTypes := negotiation.MediaTypesForSerializer(a.group.Serializer) ws.Produces(append(mediaTypes, streamMediaTypes...)...) ws.ApiVersion(a.group.GroupVersion.String()) return ws }
[ "func", "(", "a", "*", "MetricsAPIInstaller", ")", "NewWebService", "(", ")", "*", "restful", ".", "WebService", "{", "ws", ":=", "new", "(", "restful", ".", "WebService", ")", "\n", "ws", ".", "Path", "(", "a", ".", "prefix", ")", "\n", "// a.prefix contains \"prefix/group/version\"", "ws", ".", "Doc", "(", "\"", "\"", "+", "a", ".", "prefix", ")", "\n", "// Backwards compatibility, we accepted objects with empty content-type at V1.", "// If we stop using go-restful, we can default empty content-type to application/json on an", "// endpoint by endpoint basis", "ws", ".", "Consumes", "(", "\"", "\"", ")", "\n", "mediaTypes", ",", "streamMediaTypes", ":=", "negotiation", ".", "MediaTypesForSerializer", "(", "a", ".", "group", ".", "Serializer", ")", "\n", "ws", ".", "Produces", "(", "append", "(", "mediaTypes", ",", "streamMediaTypes", "...", ")", "...", ")", "\n", "ws", ".", "ApiVersion", "(", "a", ".", "group", ".", "GroupVersion", ".", "String", "(", ")", ")", "\n\n", "return", "ws", "\n", "}" ]
// NewWebService creates a new restful webservice with the api installer's prefix and version.
[ "NewWebService", "creates", "a", "new", "restful", "webservice", "with", "the", "api", "installer", "s", "prefix", "and", "version", "." ]
e303a5e75372662801308008ccdff9b57717e75d
https://github.com/kubernetes-incubator/custom-metrics-apiserver/blob/e303a5e75372662801308008ccdff9b57717e75d/pkg/apiserver/installer/installer.go#L124-L138
152,768
kubernetes-incubator/custom-metrics-apiserver
pkg/apiserver/installer/installer.go
getResourceKind
func (a *MetricsAPIInstaller) getResourceKind(storage rest.Storage) (schema.GroupVersionKind, error) { object := storage.New() fqKinds, _, err := a.group.Typer.ObjectKinds(object) if err != nil { return schema.GroupVersionKind{}, err } // a given go type can have multiple potential fully qualified kinds. Find the one that corresponds with the group // we're trying to register here fqKindToRegister := schema.GroupVersionKind{} for _, fqKind := range fqKinds { if fqKind.Group == a.group.GroupVersion.Group { fqKindToRegister = a.group.GroupVersion.WithKind(fqKind.Kind) break } // TODO: keep rid of extensions api group dependency here // This keeps it doing what it was doing before, but it doesn't feel right. if fqKind.Group == "extensions" && fqKind.Kind == "ThirdPartyResourceData" { fqKindToRegister = a.group.GroupVersion.WithKind(fqKind.Kind) } } if fqKindToRegister.Empty() { return schema.GroupVersionKind{}, fmt.Errorf("unable to locate fully qualified kind for %v: found %v when registering for %v", reflect.TypeOf(object), fqKinds, a.group.GroupVersion) } return fqKindToRegister, nil }
go
func (a *MetricsAPIInstaller) getResourceKind(storage rest.Storage) (schema.GroupVersionKind, error) { object := storage.New() fqKinds, _, err := a.group.Typer.ObjectKinds(object) if err != nil { return schema.GroupVersionKind{}, err } // a given go type can have multiple potential fully qualified kinds. Find the one that corresponds with the group // we're trying to register here fqKindToRegister := schema.GroupVersionKind{} for _, fqKind := range fqKinds { if fqKind.Group == a.group.GroupVersion.Group { fqKindToRegister = a.group.GroupVersion.WithKind(fqKind.Kind) break } // TODO: keep rid of extensions api group dependency here // This keeps it doing what it was doing before, but it doesn't feel right. if fqKind.Group == "extensions" && fqKind.Kind == "ThirdPartyResourceData" { fqKindToRegister = a.group.GroupVersion.WithKind(fqKind.Kind) } } if fqKindToRegister.Empty() { return schema.GroupVersionKind{}, fmt.Errorf("unable to locate fully qualified kind for %v: found %v when registering for %v", reflect.TypeOf(object), fqKinds, a.group.GroupVersion) } return fqKindToRegister, nil }
[ "func", "(", "a", "*", "MetricsAPIInstaller", ")", "getResourceKind", "(", "storage", "rest", ".", "Storage", ")", "(", "schema", ".", "GroupVersionKind", ",", "error", ")", "{", "object", ":=", "storage", ".", "New", "(", ")", "\n", "fqKinds", ",", "_", ",", "err", ":=", "a", ".", "group", ".", "Typer", ".", "ObjectKinds", "(", "object", ")", "\n", "if", "err", "!=", "nil", "{", "return", "schema", ".", "GroupVersionKind", "{", "}", ",", "err", "\n", "}", "\n\n", "// a given go type can have multiple potential fully qualified kinds. Find the one that corresponds with the group", "// we're trying to register here", "fqKindToRegister", ":=", "schema", ".", "GroupVersionKind", "{", "}", "\n", "for", "_", ",", "fqKind", ":=", "range", "fqKinds", "{", "if", "fqKind", ".", "Group", "==", "a", ".", "group", ".", "GroupVersion", ".", "Group", "{", "fqKindToRegister", "=", "a", ".", "group", ".", "GroupVersion", ".", "WithKind", "(", "fqKind", ".", "Kind", ")", "\n", "break", "\n", "}", "\n\n", "// TODO: keep rid of extensions api group dependency here", "// This keeps it doing what it was doing before, but it doesn't feel right.", "if", "fqKind", ".", "Group", "==", "\"", "\"", "&&", "fqKind", ".", "Kind", "==", "\"", "\"", "{", "fqKindToRegister", "=", "a", ".", "group", ".", "GroupVersion", ".", "WithKind", "(", "fqKind", ".", "Kind", ")", "\n", "}", "\n", "}", "\n", "if", "fqKindToRegister", ".", "Empty", "(", ")", "{", "return", "schema", ".", "GroupVersionKind", "{", "}", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "reflect", ".", "TypeOf", "(", "object", ")", ",", "fqKinds", ",", "a", ".", "group", ".", "GroupVersion", ")", "\n", "}", "\n", "return", "fqKindToRegister", ",", "nil", "\n", "}" ]
// getResourceKind returns the external group version kind registered for the given storage object.
[ "getResourceKind", "returns", "the", "external", "group", "version", "kind", "registered", "for", "the", "given", "storage", "object", "." ]
e303a5e75372662801308008ccdff9b57717e75d
https://github.com/kubernetes-incubator/custom-metrics-apiserver/blob/e303a5e75372662801308008ccdff9b57717e75d/pkg/apiserver/installer/installer.go#L146-L172
152,769
kubernetes-incubator/custom-metrics-apiserver
pkg/provider/interfaces.go
Normalized
func (i CustomMetricInfo) Normalized(mapper apimeta.RESTMapper) (normalizedInfo CustomMetricInfo, singluarResource string, err error) { normalizedGroupRes, err := mapper.ResourceFor(i.GroupResource.WithVersion("")) if err != nil { return i, "", err } i.GroupResource = normalizedGroupRes.GroupResource() singularResource, err := mapper.ResourceSingularizer(i.GroupResource.Resource) if err != nil { return i, "", err } return i, singularResource, nil }
go
func (i CustomMetricInfo) Normalized(mapper apimeta.RESTMapper) (normalizedInfo CustomMetricInfo, singluarResource string, err error) { normalizedGroupRes, err := mapper.ResourceFor(i.GroupResource.WithVersion("")) if err != nil { return i, "", err } i.GroupResource = normalizedGroupRes.GroupResource() singularResource, err := mapper.ResourceSingularizer(i.GroupResource.Resource) if err != nil { return i, "", err } return i, singularResource, nil }
[ "func", "(", "i", "CustomMetricInfo", ")", "Normalized", "(", "mapper", "apimeta", ".", "RESTMapper", ")", "(", "normalizedInfo", "CustomMetricInfo", ",", "singluarResource", "string", ",", "err", "error", ")", "{", "normalizedGroupRes", ",", "err", ":=", "mapper", ".", "ResourceFor", "(", "i", ".", "GroupResource", ".", "WithVersion", "(", "\"", "\"", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "i", ",", "\"", "\"", ",", "err", "\n", "}", "\n", "i", ".", "GroupResource", "=", "normalizedGroupRes", ".", "GroupResource", "(", ")", "\n\n", "singularResource", ",", "err", ":=", "mapper", ".", "ResourceSingularizer", "(", "i", ".", "GroupResource", ".", "Resource", ")", "\n", "if", "err", "!=", "nil", "{", "return", "i", ",", "\"", "\"", ",", "err", "\n", "}", "\n\n", "return", "i", ",", "singularResource", ",", "nil", "\n", "}" ]
// Normalized returns a copy of the current MetricInfo with the GroupResource resolved using the // provided REST mapper, to ensure consistent pluralization, etc, for use when looking up or comparing // the MetricInfo. It also returns the singular form of the GroupResource associated with the given // MetricInfo.
[ "Normalized", "returns", "a", "copy", "of", "the", "current", "MetricInfo", "with", "the", "GroupResource", "resolved", "using", "the", "provided", "REST", "mapper", "to", "ensure", "consistent", "pluralization", "etc", "for", "use", "when", "looking", "up", "or", "comparing", "the", "MetricInfo", ".", "It", "also", "returns", "the", "singular", "form", "of", "the", "GroupResource", "associated", "with", "the", "given", "MetricInfo", "." ]
e303a5e75372662801308008ccdff9b57717e75d
https://github.com/kubernetes-incubator/custom-metrics-apiserver/blob/e303a5e75372662801308008ccdff9b57717e75d/pkg/provider/interfaces.go#L55-L68
152,770
kubernetes-incubator/custom-metrics-apiserver
pkg/dynamicmapper/mapper.go
RunUntil
func (m *RegeneratingDiscoveryRESTMapper) RunUntil(stop <-chan struct{}) { go wait.Until(func() { if err := m.RegenerateMappings(); err != nil { klog.Errorf("error regenerating REST mappings from discovery: %v", err) } }, m.refreshInterval, stop) }
go
func (m *RegeneratingDiscoveryRESTMapper) RunUntil(stop <-chan struct{}) { go wait.Until(func() { if err := m.RegenerateMappings(); err != nil { klog.Errorf("error regenerating REST mappings from discovery: %v", err) } }, m.refreshInterval, stop) }
[ "func", "(", "m", "*", "RegeneratingDiscoveryRESTMapper", ")", "RunUntil", "(", "stop", "<-", "chan", "struct", "{", "}", ")", "{", "go", "wait", ".", "Until", "(", "func", "(", ")", "{", "if", "err", ":=", "m", ".", "RegenerateMappings", "(", ")", ";", "err", "!=", "nil", "{", "klog", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n", "}", ",", "m", ".", "refreshInterval", ",", "stop", ")", "\n", "}" ]
// RunUtil runs the mapping refresher until the given stop channel is closed.
[ "RunUtil", "runs", "the", "mapping", "refresher", "until", "the", "given", "stop", "channel", "is", "closed", "." ]
e303a5e75372662801308008ccdff9b57717e75d
https://github.com/kubernetes-incubator/custom-metrics-apiserver/blob/e303a5e75372662801308008ccdff9b57717e75d/pkg/dynamicmapper/mapper.go#L43-L49
152,771
linkedin/goavro
ocf_reader.go
CompressionName
func (ocfr *OCFReader) CompressionName() string { switch ocfr.header.compressionID { case compressionNull: return CompressionNullLabel case compressionDeflate: return CompressionDeflateLabel case compressionSnappy: return CompressionSnappyLabel default: return "should not get here: unrecognized compression algorithm" } }
go
func (ocfr *OCFReader) CompressionName() string { switch ocfr.header.compressionID { case compressionNull: return CompressionNullLabel case compressionDeflate: return CompressionDeflateLabel case compressionSnappy: return CompressionSnappyLabel default: return "should not get here: unrecognized compression algorithm" } }
[ "func", "(", "ocfr", "*", "OCFReader", ")", "CompressionName", "(", ")", "string", "{", "switch", "ocfr", ".", "header", ".", "compressionID", "{", "case", "compressionNull", ":", "return", "CompressionNullLabel", "\n", "case", "compressionDeflate", ":", "return", "CompressionDeflateLabel", "\n", "case", "compressionSnappy", ":", "return", "CompressionSnappyLabel", "\n", "default", ":", "return", "\"", "\"", "\n", "}", "\n", "}" ]
// CompressionName returns the name of the compression algorithm found within // the OCF file.
[ "CompressionName", "returns", "the", "name", "of", "the", "compression", "algorithm", "found", "within", "the", "OCF", "file", "." ]
45f9a215035e4767b6a0848975ec3df73ed9c1b0
https://github.com/linkedin/goavro/blob/45f9a215035e4767b6a0848975ec3df73ed9c1b0/ocf_reader.go#L75-L86
152,772
linkedin/goavro
ocf_reader.go
Read
func (ocfr *OCFReader) Read() (interface{}, error) { // NOTE: Test previous error before testing readReady to prevent overwriting // previous error. if ocfr.rerr != nil { return nil, ocfr.rerr } if !ocfr.readReady { ocfr.rerr = errors.New("Read called without successful Scan") return nil, ocfr.rerr } ocfr.readReady = false // decode one datum value from block var datum interface{} datum, ocfr.block, ocfr.rerr = ocfr.header.codec.NativeFromBinary(ocfr.block) if ocfr.rerr != nil { return false, ocfr.rerr } ocfr.remainingBlockItems-- return datum, nil }
go
func (ocfr *OCFReader) Read() (interface{}, error) { // NOTE: Test previous error before testing readReady to prevent overwriting // previous error. if ocfr.rerr != nil { return nil, ocfr.rerr } if !ocfr.readReady { ocfr.rerr = errors.New("Read called without successful Scan") return nil, ocfr.rerr } ocfr.readReady = false // decode one datum value from block var datum interface{} datum, ocfr.block, ocfr.rerr = ocfr.header.codec.NativeFromBinary(ocfr.block) if ocfr.rerr != nil { return false, ocfr.rerr } ocfr.remainingBlockItems-- return datum, nil }
[ "func", "(", "ocfr", "*", "OCFReader", ")", "Read", "(", ")", "(", "interface", "{", "}", ",", "error", ")", "{", "// NOTE: Test previous error before testing readReady to prevent overwriting", "// previous error.", "if", "ocfr", ".", "rerr", "!=", "nil", "{", "return", "nil", ",", "ocfr", ".", "rerr", "\n", "}", "\n", "if", "!", "ocfr", ".", "readReady", "{", "ocfr", ".", "rerr", "=", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "return", "nil", ",", "ocfr", ".", "rerr", "\n", "}", "\n", "ocfr", ".", "readReady", "=", "false", "\n\n", "// decode one datum value from block", "var", "datum", "interface", "{", "}", "\n", "datum", ",", "ocfr", ".", "block", ",", "ocfr", ".", "rerr", "=", "ocfr", ".", "header", ".", "codec", ".", "NativeFromBinary", "(", "ocfr", ".", "block", ")", "\n", "if", "ocfr", ".", "rerr", "!=", "nil", "{", "return", "false", ",", "ocfr", ".", "rerr", "\n", "}", "\n", "ocfr", ".", "remainingBlockItems", "--", "\n\n", "return", "datum", ",", "nil", "\n", "}" ]
// Read consumes one datum value from the Avro OCF stream and returns it. Read // is designed to be called only once after each invocation of the Scan method. // See `NewOCFReader` documentation for an example.
[ "Read", "consumes", "one", "datum", "value", "from", "the", "Avro", "OCF", "stream", "and", "returns", "it", ".", "Read", "is", "designed", "to", "be", "called", "only", "once", "after", "each", "invocation", "of", "the", "Scan", "method", ".", "See", "NewOCFReader", "documentation", "for", "an", "example", "." ]
45f9a215035e4767b6a0848975ec3df73ed9c1b0
https://github.com/linkedin/goavro/blob/45f9a215035e4767b6a0848975ec3df73ed9c1b0/ocf_reader.go#L97-L118
152,773
linkedin/goavro
ocf_reader.go
SkipThisBlockAndReset
func (ocfr *OCFReader) SkipThisBlockAndReset() { // ??? is it an error to call method unless the reader has had an error ocfr.remainingBlockItems = 0 ocfr.block = ocfr.block[:0] ocfr.rerr = nil }
go
func (ocfr *OCFReader) SkipThisBlockAndReset() { // ??? is it an error to call method unless the reader has had an error ocfr.remainingBlockItems = 0 ocfr.block = ocfr.block[:0] ocfr.rerr = nil }
[ "func", "(", "ocfr", "*", "OCFReader", ")", "SkipThisBlockAndReset", "(", ")", "{", "// ??? is it an error to call method unless the reader has had an error", "ocfr", ".", "remainingBlockItems", "=", "0", "\n", "ocfr", ".", "block", "=", "ocfr", ".", "block", "[", ":", "0", "]", "\n", "ocfr", ".", "rerr", "=", "nil", "\n", "}" ]
// SkipThisBlockAndReset can be called after an error occurs while reading or // decoding datum values from an OCF stream. OCF specifies each OCF stream // contain one or more blocks of data. Each block consists of a block count, the // number of bytes for the block, followed be the possibly compressed // block. Inside each decompressed block is all of the binary encoded datum // values concatenated together. In other words, OCF framing is at a block level // rather than a datum level. If there is an error while reading or decoding a // datum, the reader is not able to skip to the next datum value, because OCF // does not have any markers for where each datum ends and the next one // begins. Therefore, the reader is only able to skip this datum value and all // subsequent datum values in the current block, move to the next block and // start decoding datum values there.
[ "SkipThisBlockAndReset", "can", "be", "called", "after", "an", "error", "occurs", "while", "reading", "or", "decoding", "datum", "values", "from", "an", "OCF", "stream", ".", "OCF", "specifies", "each", "OCF", "stream", "contain", "one", "or", "more", "blocks", "of", "data", ".", "Each", "block", "consists", "of", "a", "block", "count", "the", "number", "of", "bytes", "for", "the", "block", "followed", "be", "the", "possibly", "compressed", "block", ".", "Inside", "each", "decompressed", "block", "is", "all", "of", "the", "binary", "encoded", "datum", "values", "concatenated", "together", ".", "In", "other", "words", "OCF", "framing", "is", "at", "a", "block", "level", "rather", "than", "a", "datum", "level", ".", "If", "there", "is", "an", "error", "while", "reading", "or", "decoding", "a", "datum", "the", "reader", "is", "not", "able", "to", "skip", "to", "the", "next", "datum", "value", "because", "OCF", "does", "not", "have", "any", "markers", "for", "where", "each", "datum", "ends", "and", "the", "next", "one", "begins", ".", "Therefore", "the", "reader", "is", "only", "able", "to", "skip", "this", "datum", "value", "and", "all", "subsequent", "datum", "values", "in", "the", "current", "block", "move", "to", "the", "next", "block", "and", "start", "decoding", "datum", "values", "there", "." ]
45f9a215035e4767b6a0848975ec3df73ed9c1b0
https://github.com/linkedin/goavro/blob/45f9a215035e4767b6a0848975ec3df73ed9c1b0/ocf_reader.go#L258-L263
152,774
linkedin/goavro
text.go
advanceAndConsume
func advanceAndConsume(buf []byte, expected byte) ([]byte, error) { var err error if buf, err = advanceToNonWhitespace(buf); err != nil { return nil, err } if actual := buf[0]; actual != expected { return nil, fmt.Errorf("expected: %q; actual: %q", expected, actual) } return buf[1:], nil }
go
func advanceAndConsume(buf []byte, expected byte) ([]byte, error) { var err error if buf, err = advanceToNonWhitespace(buf); err != nil { return nil, err } if actual := buf[0]; actual != expected { return nil, fmt.Errorf("expected: %q; actual: %q", expected, actual) } return buf[1:], nil }
[ "func", "advanceAndConsume", "(", "buf", "[", "]", "byte", ",", "expected", "byte", ")", "(", "[", "]", "byte", ",", "error", ")", "{", "var", "err", "error", "\n", "if", "buf", ",", "err", "=", "advanceToNonWhitespace", "(", "buf", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "if", "actual", ":=", "buf", "[", "0", "]", ";", "actual", "!=", "expected", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "expected", ",", "actual", ")", "\n", "}", "\n", "return", "buf", "[", "1", ":", "]", ",", "nil", "\n", "}" ]
// advanceAndConsume advances to non whitespace and returns an error if the next // non whitespace byte is not what is expected.
[ "advanceAndConsume", "advances", "to", "non", "whitespace", "and", "returns", "an", "error", "if", "the", "next", "non", "whitespace", "byte", "is", "not", "what", "is", "expected", "." ]
45f9a215035e4767b6a0848975ec3df73ed9c1b0
https://github.com/linkedin/goavro/blob/45f9a215035e4767b6a0848975ec3df73ed9c1b0/text.go#L20-L29
152,775
linkedin/goavro
text.go
advanceToNonWhitespace
func advanceToNonWhitespace(buf []byte) ([]byte, error) { for i, b := range buf { if !unicode.IsSpace(rune(b)) { return buf[i:], nil } } return nil, io.ErrShortBuffer }
go
func advanceToNonWhitespace(buf []byte) ([]byte, error) { for i, b := range buf { if !unicode.IsSpace(rune(b)) { return buf[i:], nil } } return nil, io.ErrShortBuffer }
[ "func", "advanceToNonWhitespace", "(", "buf", "[", "]", "byte", ")", "(", "[", "]", "byte", ",", "error", ")", "{", "for", "i", ",", "b", ":=", "range", "buf", "{", "if", "!", "unicode", ".", "IsSpace", "(", "rune", "(", "b", ")", ")", "{", "return", "buf", "[", "i", ":", "]", ",", "nil", "\n", "}", "\n", "}", "\n", "return", "nil", ",", "io", ".", "ErrShortBuffer", "\n", "}" ]
// advanceToNonWhitespace consumes bytes from buf until non-whitespace character // is found. It returns error when no more bytes remain, because its purpose is // to scan ahead to the next non-whitespace character.
[ "advanceToNonWhitespace", "consumes", "bytes", "from", "buf", "until", "non", "-", "whitespace", "character", "is", "found", ".", "It", "returns", "error", "when", "no", "more", "bytes", "remain", "because", "its", "purpose", "is", "to", "scan", "ahead", "to", "the", "next", "non", "-", "whitespace", "character", "." ]
45f9a215035e4767b6a0848975ec3df73ed9c1b0
https://github.com/linkedin/goavro/blob/45f9a215035e4767b6a0848975ec3df73ed9c1b0/text.go#L34-L41
152,776
linkedin/goavro
ocf_writer.go
NewOCFWriter
func NewOCFWriter(config OCFConfig) (*OCFWriter, error) { var err error ocf := &OCFWriter{iow: config.W} switch config.W.(type) { case nil: return nil, errors.New("cannot create OCFWriter when W is nil") case *os.File: file := config.W.(*os.File) stat, err := file.Stat() if err != nil { return nil, fmt.Errorf("cannot create OCFWriter: %s", err) } // NOTE: When upstream provides a new file, it will already exist but // have a size of 0 bytes. if stat.Size() > 0 { // attempt to read existing OCF header if ocf.header, err = readOCFHeader(file); err != nil { return nil, fmt.Errorf("cannot create OCFWriter: %s", err) } // prepare for appending data to existing OCF if err = ocf.quickScanToTail(file); err != nil { return nil, fmt.Errorf("cannot create OCFWriter: %s", err) } return ocf, nil // happy case for appending to existing OCF } } // create new OCF header based on configuration parameters if ocf.header, err = newOCFHeader(config); err != nil { return nil, fmt.Errorf("cannot create OCFWriter: %s", err) } if err = writeOCFHeader(ocf.header, config.W); err != nil { return nil, fmt.Errorf("cannot create OCFWriter: %s", err) } return ocf, nil // another happy case for creation of new OCF }
go
func NewOCFWriter(config OCFConfig) (*OCFWriter, error) { var err error ocf := &OCFWriter{iow: config.W} switch config.W.(type) { case nil: return nil, errors.New("cannot create OCFWriter when W is nil") case *os.File: file := config.W.(*os.File) stat, err := file.Stat() if err != nil { return nil, fmt.Errorf("cannot create OCFWriter: %s", err) } // NOTE: When upstream provides a new file, it will already exist but // have a size of 0 bytes. if stat.Size() > 0 { // attempt to read existing OCF header if ocf.header, err = readOCFHeader(file); err != nil { return nil, fmt.Errorf("cannot create OCFWriter: %s", err) } // prepare for appending data to existing OCF if err = ocf.quickScanToTail(file); err != nil { return nil, fmt.Errorf("cannot create OCFWriter: %s", err) } return ocf, nil // happy case for appending to existing OCF } } // create new OCF header based on configuration parameters if ocf.header, err = newOCFHeader(config); err != nil { return nil, fmt.Errorf("cannot create OCFWriter: %s", err) } if err = writeOCFHeader(ocf.header, config.W); err != nil { return nil, fmt.Errorf("cannot create OCFWriter: %s", err) } return ocf, nil // another happy case for creation of new OCF }
[ "func", "NewOCFWriter", "(", "config", "OCFConfig", ")", "(", "*", "OCFWriter", ",", "error", ")", "{", "var", "err", "error", "\n", "ocf", ":=", "&", "OCFWriter", "{", "iow", ":", "config", ".", "W", "}", "\n\n", "switch", "config", ".", "W", ".", "(", "type", ")", "{", "case", "nil", ":", "return", "nil", ",", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "case", "*", "os", ".", "File", ":", "file", ":=", "config", ".", "W", ".", "(", "*", "os", ".", "File", ")", "\n", "stat", ",", "err", ":=", "file", ".", "Stat", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n", "// NOTE: When upstream provides a new file, it will already exist but", "// have a size of 0 bytes.", "if", "stat", ".", "Size", "(", ")", ">", "0", "{", "// attempt to read existing OCF header", "if", "ocf", ".", "header", ",", "err", "=", "readOCFHeader", "(", "file", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n", "// prepare for appending data to existing OCF", "if", "err", "=", "ocf", ".", "quickScanToTail", "(", "file", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n", "return", "ocf", ",", "nil", "// happy case for appending to existing OCF", "\n", "}", "\n", "}", "\n\n", "// create new OCF header based on configuration parameters", "if", "ocf", ".", "header", ",", "err", "=", "newOCFHeader", "(", "config", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n", "if", "err", "=", "writeOCFHeader", "(", "ocf", ".", "header", ",", "config", ".", "W", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n", "return", "ocf", ",", "nil", "// another happy case for creation of new OCF", "\n", "}" ]
// NewOCFWriter returns a new OCFWriter instance that may be used for appending // binary Avro data, either by appending to an existing OCF file or creating a // new OCF file.
[ "NewOCFWriter", "returns", "a", "new", "OCFWriter", "instance", "that", "may", "be", "used", "for", "appending", "binary", "Avro", "data", "either", "by", "appending", "to", "an", "existing", "OCF", "file", "or", "creating", "a", "new", "OCF", "file", "." ]
45f9a215035e4767b6a0848975ec3df73ed9c1b0
https://github.com/linkedin/goavro/blob/45f9a215035e4767b6a0848975ec3df73ed9c1b0/ocf_writer.go#L71-L107
152,777
linkedin/goavro
ocf_writer.go
quickScanToTail
func (ocfw *OCFWriter) quickScanToTail(ior io.Reader) error { sync := make([]byte, ocfSyncLength) for { // Read and validate block count blockCount, err := longBinaryReader(ior) if err != nil { if err == io.EOF { return nil // merely end of file, rather than error } return fmt.Errorf("cannot read block count: %s", err) } if blockCount <= 0 { return fmt.Errorf("cannot read when block count is not greater than 0: %d", blockCount) } if blockCount > MaxBlockCount { return fmt.Errorf("cannot read when block count exceeds MaxBlockCount: %d > %d", blockCount, MaxBlockCount) } // Read block size blockSize, err := longBinaryReader(ior) if err != nil { return fmt.Errorf("cannot read block size: %s", err) } if blockSize <= 0 { return fmt.Errorf("cannot read when block size is not greater than 0: %d", blockSize) } if blockSize > MaxBlockSize { return fmt.Errorf("cannot read when block size exceeds MaxBlockSize: %d > %d", blockSize, MaxBlockSize) } // Advance reader to end of block if _, err = io.CopyN(ioutil.Discard, ior, blockSize); err != nil { return fmt.Errorf("cannot seek to next block: %s", err) } // Read and validate sync marker var n int if n, err = io.ReadFull(ior, sync); err != nil { return fmt.Errorf("cannot read sync marker: read %d out of %d bytes: %s", n, ocfSyncLength, err) } if !bytes.Equal(sync, ocfw.header.syncMarker[:]) { return fmt.Errorf("sync marker mismatch: %v != %v", sync, ocfw.header.syncMarker) } } }
go
func (ocfw *OCFWriter) quickScanToTail(ior io.Reader) error { sync := make([]byte, ocfSyncLength) for { // Read and validate block count blockCount, err := longBinaryReader(ior) if err != nil { if err == io.EOF { return nil // merely end of file, rather than error } return fmt.Errorf("cannot read block count: %s", err) } if blockCount <= 0 { return fmt.Errorf("cannot read when block count is not greater than 0: %d", blockCount) } if blockCount > MaxBlockCount { return fmt.Errorf("cannot read when block count exceeds MaxBlockCount: %d > %d", blockCount, MaxBlockCount) } // Read block size blockSize, err := longBinaryReader(ior) if err != nil { return fmt.Errorf("cannot read block size: %s", err) } if blockSize <= 0 { return fmt.Errorf("cannot read when block size is not greater than 0: %d", blockSize) } if blockSize > MaxBlockSize { return fmt.Errorf("cannot read when block size exceeds MaxBlockSize: %d > %d", blockSize, MaxBlockSize) } // Advance reader to end of block if _, err = io.CopyN(ioutil.Discard, ior, blockSize); err != nil { return fmt.Errorf("cannot seek to next block: %s", err) } // Read and validate sync marker var n int if n, err = io.ReadFull(ior, sync); err != nil { return fmt.Errorf("cannot read sync marker: read %d out of %d bytes: %s", n, ocfSyncLength, err) } if !bytes.Equal(sync, ocfw.header.syncMarker[:]) { return fmt.Errorf("sync marker mismatch: %v != %v", sync, ocfw.header.syncMarker) } } }
[ "func", "(", "ocfw", "*", "OCFWriter", ")", "quickScanToTail", "(", "ior", "io", ".", "Reader", ")", "error", "{", "sync", ":=", "make", "(", "[", "]", "byte", ",", "ocfSyncLength", ")", "\n", "for", "{", "// Read and validate block count", "blockCount", ",", "err", ":=", "longBinaryReader", "(", "ior", ")", "\n", "if", "err", "!=", "nil", "{", "if", "err", "==", "io", ".", "EOF", "{", "return", "nil", "// merely end of file, rather than error", "\n", "}", "\n", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n", "if", "blockCount", "<=", "0", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "blockCount", ")", "\n", "}", "\n", "if", "blockCount", ">", "MaxBlockCount", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "blockCount", ",", "MaxBlockCount", ")", "\n", "}", "\n", "// Read block size", "blockSize", ",", "err", ":=", "longBinaryReader", "(", "ior", ")", "\n", "if", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n", "if", "blockSize", "<=", "0", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "blockSize", ")", "\n", "}", "\n", "if", "blockSize", ">", "MaxBlockSize", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "blockSize", ",", "MaxBlockSize", ")", "\n", "}", "\n", "// Advance reader to end of block", "if", "_", ",", "err", "=", "io", ".", "CopyN", "(", "ioutil", ".", "Discard", ",", "ior", ",", "blockSize", ")", ";", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n", "// Read and validate sync marker", "var", "n", "int", "\n", "if", "n", ",", "err", "=", "io", ".", "ReadFull", "(", "ior", ",", "sync", ")", ";", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "n", ",", "ocfSyncLength", ",", "err", ")", "\n", "}", "\n", "if", "!", "bytes", ".", "Equal", "(", "sync", ",", "ocfw", ".", "header", ".", "syncMarker", "[", ":", "]", ")", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "sync", ",", "ocfw", ".", "header", ".", "syncMarker", ")", "\n", "}", "\n", "}", "\n", "}" ]
// quickScanToTail advances the stream reader to the tail end of the // file. Rather than reading each encoded block, optionally decompressing it, // and then decoding it, this method reads the block count, ignoring it, then // reads the block size, then skips ahead to the followig block. It does this // repeatedly until attempts to read the file return io.EOF.
[ "quickScanToTail", "advances", "the", "stream", "reader", "to", "the", "tail", "end", "of", "the", "file", ".", "Rather", "than", "reading", "each", "encoded", "block", "optionally", "decompressing", "it", "and", "then", "decoding", "it", "this", "method", "reads", "the", "block", "count", "ignoring", "it", "then", "reads", "the", "block", "size", "then", "skips", "ahead", "to", "the", "followig", "block", ".", "It", "does", "this", "repeatedly", "until", "attempts", "to", "read", "the", "file", "return", "io", ".", "EOF", "." ]
45f9a215035e4767b6a0848975ec3df73ed9c1b0
https://github.com/linkedin/goavro/blob/45f9a215035e4767b6a0848975ec3df73ed9c1b0/ocf_writer.go#L114-L155
152,778
linkedin/goavro
ocf_writer.go
Append
func (ocfw *OCFWriter) Append(data interface{}) error { arrayValues, err := convertArray(data) if err != nil { return err } // Chunk data so no block has more than MaxBlockCount items. for int64(len(arrayValues)) > MaxBlockCount { if err := ocfw.appendDataIntoBlock(arrayValues[:MaxBlockCount]); err != nil { return err } arrayValues = arrayValues[MaxBlockCount:] } return ocfw.appendDataIntoBlock(arrayValues) }
go
func (ocfw *OCFWriter) Append(data interface{}) error { arrayValues, err := convertArray(data) if err != nil { return err } // Chunk data so no block has more than MaxBlockCount items. for int64(len(arrayValues)) > MaxBlockCount { if err := ocfw.appendDataIntoBlock(arrayValues[:MaxBlockCount]); err != nil { return err } arrayValues = arrayValues[MaxBlockCount:] } return ocfw.appendDataIntoBlock(arrayValues) }
[ "func", "(", "ocfw", "*", "OCFWriter", ")", "Append", "(", "data", "interface", "{", "}", ")", "error", "{", "arrayValues", ",", "err", ":=", "convertArray", "(", "data", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "// Chunk data so no block has more than MaxBlockCount items.", "for", "int64", "(", "len", "(", "arrayValues", ")", ")", ">", "MaxBlockCount", "{", "if", "err", ":=", "ocfw", ".", "appendDataIntoBlock", "(", "arrayValues", "[", ":", "MaxBlockCount", "]", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "arrayValues", "=", "arrayValues", "[", "MaxBlockCount", ":", "]", "\n", "}", "\n", "return", "ocfw", ".", "appendDataIntoBlock", "(", "arrayValues", ")", "\n", "}" ]
// Append appends one or more data items to an OCF file in a block. If there are // more data items in the slice than MaxBlockCount allows, the data slice will // be chunked into multiple blocks, each not having more than MaxBlockCount // items.
[ "Append", "appends", "one", "or", "more", "data", "items", "to", "an", "OCF", "file", "in", "a", "block", ".", "If", "there", "are", "more", "data", "items", "in", "the", "slice", "than", "MaxBlockCount", "allows", "the", "data", "slice", "will", "be", "chunked", "into", "multiple", "blocks", "each", "not", "having", "more", "than", "MaxBlockCount", "items", "." ]
45f9a215035e4767b6a0848975ec3df73ed9c1b0
https://github.com/linkedin/goavro/blob/45f9a215035e4767b6a0848975ec3df73ed9c1b0/ocf_writer.go#L161-L175
152,779
linkedin/goavro
ocf_writer.go
CompressionName
func (ocfw *OCFWriter) CompressionName() string { switch ocfw.header.compressionID { case compressionNull: return CompressionNullLabel case compressionDeflate: return CompressionDeflateLabel case compressionSnappy: return CompressionSnappyLabel default: return "should not get here: unrecognized compression algorithm" } }
go
func (ocfw *OCFWriter) CompressionName() string { switch ocfw.header.compressionID { case compressionNull: return CompressionNullLabel case compressionDeflate: return CompressionDeflateLabel case compressionSnappy: return CompressionSnappyLabel default: return "should not get here: unrecognized compression algorithm" } }
[ "func", "(", "ocfw", "*", "OCFWriter", ")", "CompressionName", "(", ")", "string", "{", "switch", "ocfw", ".", "header", ".", "compressionID", "{", "case", "compressionNull", ":", "return", "CompressionNullLabel", "\n", "case", "compressionDeflate", ":", "return", "CompressionDeflateLabel", "\n", "case", "compressionSnappy", ":", "return", "CompressionSnappyLabel", "\n", "default", ":", "return", "\"", "\"", "\n", "}", "\n", "}" ]
// CompressionName returns the name of the compression algorithm used by // OCFWriter. This function provided because upstream may be appending to // existing OCF which uses a different compression algorithm than requested // during instantiation. the OCF file.
[ "CompressionName", "returns", "the", "name", "of", "the", "compression", "algorithm", "used", "by", "OCFWriter", ".", "This", "function", "provided", "because", "upstream", "may", "be", "appending", "to", "existing", "OCF", "which", "uses", "a", "different", "compression", "algorithm", "than", "requested", "during", "instantiation", ".", "the", "OCF", "file", "." ]
45f9a215035e4767b6a0848975ec3df73ed9c1b0
https://github.com/linkedin/goavro/blob/45f9a215035e4767b6a0848975ec3df73ed9c1b0/ocf_writer.go#L242-L253
152,780
linkedin/goavro
binaryReader.go
bytesBinaryReader
func bytesBinaryReader(ior io.Reader) ([]byte, error) { size, err := longBinaryReader(ior) if err != nil { return nil, fmt.Errorf("cannot read bytes: cannot read size: %s", err) } if size < 0 { return nil, fmt.Errorf("cannot read bytes: size is negative: %d", size) } if size > MaxBlockSize { return nil, fmt.Errorf("cannot read bytes: size exceeds MaxBlockSize: %d > %d", size, MaxBlockSize) } buf := make([]byte, size) _, err = io.ReadAtLeast(ior, buf, int(size)) if err != nil { return nil, fmt.Errorf("cannot read bytes: %s", err) } return buf, nil }
go
func bytesBinaryReader(ior io.Reader) ([]byte, error) { size, err := longBinaryReader(ior) if err != nil { return nil, fmt.Errorf("cannot read bytes: cannot read size: %s", err) } if size < 0 { return nil, fmt.Errorf("cannot read bytes: size is negative: %d", size) } if size > MaxBlockSize { return nil, fmt.Errorf("cannot read bytes: size exceeds MaxBlockSize: %d > %d", size, MaxBlockSize) } buf := make([]byte, size) _, err = io.ReadAtLeast(ior, buf, int(size)) if err != nil { return nil, fmt.Errorf("cannot read bytes: %s", err) } return buf, nil }
[ "func", "bytesBinaryReader", "(", "ior", "io", ".", "Reader", ")", "(", "[", "]", "byte", ",", "error", ")", "{", "size", ",", "err", ":=", "longBinaryReader", "(", "ior", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n", "if", "size", "<", "0", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "size", ")", "\n", "}", "\n", "if", "size", ">", "MaxBlockSize", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "size", ",", "MaxBlockSize", ")", "\n", "}", "\n", "buf", ":=", "make", "(", "[", "]", "byte", ",", "size", ")", "\n", "_", ",", "err", "=", "io", ".", "ReadAtLeast", "(", "ior", ",", "buf", ",", "int", "(", "size", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n", "return", "buf", ",", "nil", "\n", "}" ]
// bytesBinaryReader reads bytes from io.Reader and returns byte slice of // specified size or the error encountered while trying to read those bytes.
[ "bytesBinaryReader", "reads", "bytes", "from", "io", ".", "Reader", "and", "returns", "byte", "slice", "of", "specified", "size", "or", "the", "error", "encountered", "while", "trying", "to", "read", "those", "bytes", "." ]
45f9a215035e4767b6a0848975ec3df73ed9c1b0
https://github.com/linkedin/goavro/blob/45f9a215035e4767b6a0848975ec3df73ed9c1b0/binaryReader.go#L20-L37
152,781
linkedin/goavro
binaryReader.go
longBinaryReader
func longBinaryReader(ior io.Reader) (int64, error) { var value uint64 var shift uint var err error var b byte // NOTE: While benchmarks show it's more performant to invoke ReadByte when // available, testing whether a variable's data type implements a particular // method is quite slow too. So perform the test once, and branch to the // appropriate loop based on the results. if byteReader, ok := ior.(io.ByteReader); ok { for { if b, err = byteReader.ReadByte(); err != nil { return 0, err // NOTE: must send back unaltered error to detect io.EOF } value |= uint64(b&intMask) << shift if b&intFlag == 0 { return (int64(value>>1) ^ -int64(value&1)), nil } shift += 7 } } // NOTE: ior does not also implement io.ByteReader, so we must allocate a // byte slice with a single byte, and read each byte into the slice. buf := make([]byte, 1) for { if _, err = ior.Read(buf); err != nil { return 0, err // NOTE: must send back unaltered error to detect io.EOF } b = buf[0] value |= uint64(b&intMask) << shift if b&intFlag == 0 { return (int64(value>>1) ^ -int64(value&1)), nil } shift += 7 } }
go
func longBinaryReader(ior io.Reader) (int64, error) { var value uint64 var shift uint var err error var b byte // NOTE: While benchmarks show it's more performant to invoke ReadByte when // available, testing whether a variable's data type implements a particular // method is quite slow too. So perform the test once, and branch to the // appropriate loop based on the results. if byteReader, ok := ior.(io.ByteReader); ok { for { if b, err = byteReader.ReadByte(); err != nil { return 0, err // NOTE: must send back unaltered error to detect io.EOF } value |= uint64(b&intMask) << shift if b&intFlag == 0 { return (int64(value>>1) ^ -int64(value&1)), nil } shift += 7 } } // NOTE: ior does not also implement io.ByteReader, so we must allocate a // byte slice with a single byte, and read each byte into the slice. buf := make([]byte, 1) for { if _, err = ior.Read(buf); err != nil { return 0, err // NOTE: must send back unaltered error to detect io.EOF } b = buf[0] value |= uint64(b&intMask) << shift if b&intFlag == 0 { return (int64(value>>1) ^ -int64(value&1)), nil } shift += 7 } }
[ "func", "longBinaryReader", "(", "ior", "io", ".", "Reader", ")", "(", "int64", ",", "error", ")", "{", "var", "value", "uint64", "\n", "var", "shift", "uint", "\n", "var", "err", "error", "\n", "var", "b", "byte", "\n\n", "// NOTE: While benchmarks show it's more performant to invoke ReadByte when", "// available, testing whether a variable's data type implements a particular", "// method is quite slow too. So perform the test once, and branch to the", "// appropriate loop based on the results.", "if", "byteReader", ",", "ok", ":=", "ior", ".", "(", "io", ".", "ByteReader", ")", ";", "ok", "{", "for", "{", "if", "b", ",", "err", "=", "byteReader", ".", "ReadByte", "(", ")", ";", "err", "!=", "nil", "{", "return", "0", ",", "err", "// NOTE: must send back unaltered error to detect io.EOF", "\n", "}", "\n", "value", "|=", "uint64", "(", "b", "&", "intMask", ")", "<<", "shift", "\n", "if", "b", "&", "intFlag", "==", "0", "{", "return", "(", "int64", "(", "value", ">>", "1", ")", "^", "-", "int64", "(", "value", "&", "1", ")", ")", ",", "nil", "\n", "}", "\n", "shift", "+=", "7", "\n", "}", "\n", "}", "\n\n", "// NOTE: ior does not also implement io.ByteReader, so we must allocate a", "// byte slice with a single byte, and read each byte into the slice.", "buf", ":=", "make", "(", "[", "]", "byte", ",", "1", ")", "\n", "for", "{", "if", "_", ",", "err", "=", "ior", ".", "Read", "(", "buf", ")", ";", "err", "!=", "nil", "{", "return", "0", ",", "err", "// NOTE: must send back unaltered error to detect io.EOF", "\n", "}", "\n", "b", "=", "buf", "[", "0", "]", "\n", "value", "|=", "uint64", "(", "b", "&", "intMask", ")", "<<", "shift", "\n", "if", "b", "&", "intFlag", "==", "0", "{", "return", "(", "int64", "(", "value", ">>", "1", ")", "^", "-", "int64", "(", "value", "&", "1", ")", ")", ",", "nil", "\n", "}", "\n", "shift", "+=", "7", "\n", "}", "\n", "}" ]
// longBinaryReader reads bytes from io.Reader until has complete long value, or // read error.
[ "longBinaryReader", "reads", "bytes", "from", "io", ".", "Reader", "until", "has", "complete", "long", "value", "or", "read", "error", "." ]
45f9a215035e4767b6a0848975ec3df73ed9c1b0
https://github.com/linkedin/goavro/blob/45f9a215035e4767b6a0848975ec3df73ed9c1b0/binaryReader.go#L41-L79
152,782
linkedin/goavro
binaryReader.go
metadataBinaryReader
func metadataBinaryReader(ior io.Reader) (map[string][]byte, error) { var err error var value interface{} // block count and block size if value, err = longBinaryReader(ior); err != nil { return nil, fmt.Errorf("cannot read map block count: %s", err) } blockCount := value.(int64) if blockCount < 0 { if blockCount == math.MinInt64 { // The minimum number for any signed numerical type can never be // made positive return nil, fmt.Errorf("cannot read map with block count: %d", blockCount) } // NOTE: A negative block count implies there is a long encoded block // size following the negative block count. We have no use for the block // size in this decoder, so we read and discard the value. blockCount = -blockCount // convert to its positive equivalent if _, err = longBinaryReader(ior); err != nil { return nil, fmt.Errorf("cannot read map block size: %s", err) } } // Ensure block count does not exceed some sane value. if blockCount > MaxBlockCount { return nil, fmt.Errorf("cannot read map when block count exceeds MaxBlockCount: %d > %d", blockCount, MaxBlockCount) } // NOTE: While the attempt of a RAM optimization shown below is not // necessary, many encoders will encode all items in a single block. We can // optimize amount of RAM allocated by runtime for the array by initializing // the array for that number of items. mapValues := make(map[string][]byte, blockCount) for blockCount != 0 { // Decode `blockCount` datum values from buffer for i := int64(0); i < blockCount; i++ { // first decode the key string keyBytes, err := bytesBinaryReader(ior) if err != nil { return nil, fmt.Errorf("cannot read map key: %s", err) } key := string(keyBytes) if _, ok := mapValues[key]; ok { return nil, fmt.Errorf("cannot read map: duplicate key: %q", key) } // metadata values are always bytes buf, err := bytesBinaryReader(ior) if err != nil { return nil, fmt.Errorf("cannot read map value for key %q: %s", key, err) } mapValues[key] = buf } // Decode next blockCount from buffer, because there may be more blocks if value, err = longBinaryReader(ior); err != nil { return nil, fmt.Errorf("cannot read map block count: %s", err) } blockCount = value.(int64) if blockCount < 0 { if blockCount == math.MinInt64 { // The minimum number for any signed numerical type can never be // made positive return nil, fmt.Errorf("cannot read map with block count: %d", blockCount) } // NOTE: A negative block count implies there is a long encoded // block size following the negative block count. We have no use for // the block size in this decoder, so we read and discard the value. blockCount = -blockCount // convert to its positive equivalent if _, err = longBinaryReader(ior); err != nil { return nil, fmt.Errorf("cannot read map block size: %s", err) } } // Ensure block count does not exceed some sane value. if blockCount > MaxBlockCount { return nil, fmt.Errorf("cannot read map when block count exceeds MaxBlockCount: %d > %d", blockCount, MaxBlockCount) } } return mapValues, nil }
go
func metadataBinaryReader(ior io.Reader) (map[string][]byte, error) { var err error var value interface{} // block count and block size if value, err = longBinaryReader(ior); err != nil { return nil, fmt.Errorf("cannot read map block count: %s", err) } blockCount := value.(int64) if blockCount < 0 { if blockCount == math.MinInt64 { // The minimum number for any signed numerical type can never be // made positive return nil, fmt.Errorf("cannot read map with block count: %d", blockCount) } // NOTE: A negative block count implies there is a long encoded block // size following the negative block count. We have no use for the block // size in this decoder, so we read and discard the value. blockCount = -blockCount // convert to its positive equivalent if _, err = longBinaryReader(ior); err != nil { return nil, fmt.Errorf("cannot read map block size: %s", err) } } // Ensure block count does not exceed some sane value. if blockCount > MaxBlockCount { return nil, fmt.Errorf("cannot read map when block count exceeds MaxBlockCount: %d > %d", blockCount, MaxBlockCount) } // NOTE: While the attempt of a RAM optimization shown below is not // necessary, many encoders will encode all items in a single block. We can // optimize amount of RAM allocated by runtime for the array by initializing // the array for that number of items. mapValues := make(map[string][]byte, blockCount) for blockCount != 0 { // Decode `blockCount` datum values from buffer for i := int64(0); i < blockCount; i++ { // first decode the key string keyBytes, err := bytesBinaryReader(ior) if err != nil { return nil, fmt.Errorf("cannot read map key: %s", err) } key := string(keyBytes) if _, ok := mapValues[key]; ok { return nil, fmt.Errorf("cannot read map: duplicate key: %q", key) } // metadata values are always bytes buf, err := bytesBinaryReader(ior) if err != nil { return nil, fmt.Errorf("cannot read map value for key %q: %s", key, err) } mapValues[key] = buf } // Decode next blockCount from buffer, because there may be more blocks if value, err = longBinaryReader(ior); err != nil { return nil, fmt.Errorf("cannot read map block count: %s", err) } blockCount = value.(int64) if blockCount < 0 { if blockCount == math.MinInt64 { // The minimum number for any signed numerical type can never be // made positive return nil, fmt.Errorf("cannot read map with block count: %d", blockCount) } // NOTE: A negative block count implies there is a long encoded // block size following the negative block count. We have no use for // the block size in this decoder, so we read and discard the value. blockCount = -blockCount // convert to its positive equivalent if _, err = longBinaryReader(ior); err != nil { return nil, fmt.Errorf("cannot read map block size: %s", err) } } // Ensure block count does not exceed some sane value. if blockCount > MaxBlockCount { return nil, fmt.Errorf("cannot read map when block count exceeds MaxBlockCount: %d > %d", blockCount, MaxBlockCount) } } return mapValues, nil }
[ "func", "metadataBinaryReader", "(", "ior", "io", ".", "Reader", ")", "(", "map", "[", "string", "]", "[", "]", "byte", ",", "error", ")", "{", "var", "err", "error", "\n", "var", "value", "interface", "{", "}", "\n\n", "// block count and block size", "if", "value", ",", "err", "=", "longBinaryReader", "(", "ior", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n", "blockCount", ":=", "value", ".", "(", "int64", ")", "\n", "if", "blockCount", "<", "0", "{", "if", "blockCount", "==", "math", ".", "MinInt64", "{", "// The minimum number for any signed numerical type can never be", "// made positive", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "blockCount", ")", "\n", "}", "\n", "// NOTE: A negative block count implies there is a long encoded block", "// size following the negative block count. We have no use for the block", "// size in this decoder, so we read and discard the value.", "blockCount", "=", "-", "blockCount", "// convert to its positive equivalent", "\n", "if", "_", ",", "err", "=", "longBinaryReader", "(", "ior", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n", "}", "\n", "// Ensure block count does not exceed some sane value.", "if", "blockCount", ">", "MaxBlockCount", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "blockCount", ",", "MaxBlockCount", ")", "\n", "}", "\n", "// NOTE: While the attempt of a RAM optimization shown below is not", "// necessary, many encoders will encode all items in a single block. We can", "// optimize amount of RAM allocated by runtime for the array by initializing", "// the array for that number of items.", "mapValues", ":=", "make", "(", "map", "[", "string", "]", "[", "]", "byte", ",", "blockCount", ")", "\n\n", "for", "blockCount", "!=", "0", "{", "// Decode `blockCount` datum values from buffer", "for", "i", ":=", "int64", "(", "0", ")", ";", "i", "<", "blockCount", ";", "i", "++", "{", "// first decode the key string", "keyBytes", ",", "err", ":=", "bytesBinaryReader", "(", "ior", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n", "key", ":=", "string", "(", "keyBytes", ")", "\n", "if", "_", ",", "ok", ":=", "mapValues", "[", "key", "]", ";", "ok", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "key", ")", "\n", "}", "\n", "// metadata values are always bytes", "buf", ",", "err", ":=", "bytesBinaryReader", "(", "ior", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "key", ",", "err", ")", "\n", "}", "\n", "mapValues", "[", "key", "]", "=", "buf", "\n", "}", "\n", "// Decode next blockCount from buffer, because there may be more blocks", "if", "value", ",", "err", "=", "longBinaryReader", "(", "ior", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n", "blockCount", "=", "value", ".", "(", "int64", ")", "\n", "if", "blockCount", "<", "0", "{", "if", "blockCount", "==", "math", ".", "MinInt64", "{", "// The minimum number for any signed numerical type can never be", "// made positive", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "blockCount", ")", "\n", "}", "\n", "// NOTE: A negative block count implies there is a long encoded", "// block size following the negative block count. We have no use for", "// the block size in this decoder, so we read and discard the value.", "blockCount", "=", "-", "blockCount", "// convert to its positive equivalent", "\n", "if", "_", ",", "err", "=", "longBinaryReader", "(", "ior", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n", "}", "\n", "// Ensure block count does not exceed some sane value.", "if", "blockCount", ">", "MaxBlockCount", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "blockCount", ",", "MaxBlockCount", ")", "\n", "}", "\n", "}", "\n", "return", "mapValues", ",", "nil", "\n", "}" ]
// metadataBinaryReader reads bytes from io.Reader until has entire map value, // or read error.
[ "metadataBinaryReader", "reads", "bytes", "from", "io", ".", "Reader", "until", "has", "entire", "map", "value", "or", "read", "error", "." ]
45f9a215035e4767b6a0848975ec3df73ed9c1b0
https://github.com/linkedin/goavro/blob/45f9a215035e4767b6a0848975ec3df73ed9c1b0/binaryReader.go#L83-L160
152,783
linkedin/goavro
map.go
genericMapTextDecoder
func genericMapTextDecoder(buf []byte, defaultCodec *Codec, codecFromKey map[string]*Codec) (map[string]interface{}, []byte, error) { var value interface{} var err error var b byte lencodec := len(codecFromKey) mapValues := make(map[string]interface{}, lencodec) if buf, err = advanceAndConsume(buf, '{'); err != nil { return nil, nil, err } if buf, _ = advanceToNonWhitespace(buf); len(buf) == 0 { return nil, nil, io.ErrShortBuffer } // NOTE: Special case empty map if buf[0] == '}' { return mapValues, buf[1:], nil } // NOTE: Also terminates when read '}' byte. for len(buf) > 0 { // decode key string value, buf, err = stringNativeFromTextual(buf) if err != nil { return nil, nil, fmt.Errorf("cannot decode textual map: expected key: %s", err) } key := value.(string) // Is key already used? if _, ok := mapValues[key]; ok { return nil, nil, fmt.Errorf("cannot decode textual map: duplicate key: %q", key) } // Find a codec for the key fieldCodec := codecFromKey[key] if fieldCodec == nil { fieldCodec = defaultCodec } if fieldCodec == nil { return nil, nil, fmt.Errorf("cannot decode textual map: cannot determine codec: %q", key) } // decode colon if buf, err = advanceAndConsume(buf, ':'); err != nil { return nil, nil, err } // decode value if buf, _ = advanceToNonWhitespace(buf); len(buf) == 0 { return nil, nil, io.ErrShortBuffer } value, buf, err = fieldCodec.nativeFromTextual(buf) if err != nil { return nil, nil, err } // set map value for key mapValues[key] = value // either comma or closing curly brace if buf, _ = advanceToNonWhitespace(buf); len(buf) == 0 { return nil, nil, io.ErrShortBuffer } switch b = buf[0]; b { case '}': return mapValues, buf[1:], nil case ',': // no-op default: return nil, nil, fmt.Errorf("cannot decode textual map: expected ',' or '}'; received: %q", b) } // NOTE: consume comma from above if buf, _ = advanceToNonWhitespace(buf[1:]); len(buf) == 0 { return nil, nil, io.ErrShortBuffer } } return nil, nil, io.ErrShortBuffer }
go
func genericMapTextDecoder(buf []byte, defaultCodec *Codec, codecFromKey map[string]*Codec) (map[string]interface{}, []byte, error) { var value interface{} var err error var b byte lencodec := len(codecFromKey) mapValues := make(map[string]interface{}, lencodec) if buf, err = advanceAndConsume(buf, '{'); err != nil { return nil, nil, err } if buf, _ = advanceToNonWhitespace(buf); len(buf) == 0 { return nil, nil, io.ErrShortBuffer } // NOTE: Special case empty map if buf[0] == '}' { return mapValues, buf[1:], nil } // NOTE: Also terminates when read '}' byte. for len(buf) > 0 { // decode key string value, buf, err = stringNativeFromTextual(buf) if err != nil { return nil, nil, fmt.Errorf("cannot decode textual map: expected key: %s", err) } key := value.(string) // Is key already used? if _, ok := mapValues[key]; ok { return nil, nil, fmt.Errorf("cannot decode textual map: duplicate key: %q", key) } // Find a codec for the key fieldCodec := codecFromKey[key] if fieldCodec == nil { fieldCodec = defaultCodec } if fieldCodec == nil { return nil, nil, fmt.Errorf("cannot decode textual map: cannot determine codec: %q", key) } // decode colon if buf, err = advanceAndConsume(buf, ':'); err != nil { return nil, nil, err } // decode value if buf, _ = advanceToNonWhitespace(buf); len(buf) == 0 { return nil, nil, io.ErrShortBuffer } value, buf, err = fieldCodec.nativeFromTextual(buf) if err != nil { return nil, nil, err } // set map value for key mapValues[key] = value // either comma or closing curly brace if buf, _ = advanceToNonWhitespace(buf); len(buf) == 0 { return nil, nil, io.ErrShortBuffer } switch b = buf[0]; b { case '}': return mapValues, buf[1:], nil case ',': // no-op default: return nil, nil, fmt.Errorf("cannot decode textual map: expected ',' or '}'; received: %q", b) } // NOTE: consume comma from above if buf, _ = advanceToNonWhitespace(buf[1:]); len(buf) == 0 { return nil, nil, io.ErrShortBuffer } } return nil, nil, io.ErrShortBuffer }
[ "func", "genericMapTextDecoder", "(", "buf", "[", "]", "byte", ",", "defaultCodec", "*", "Codec", ",", "codecFromKey", "map", "[", "string", "]", "*", "Codec", ")", "(", "map", "[", "string", "]", "interface", "{", "}", ",", "[", "]", "byte", ",", "error", ")", "{", "var", "value", "interface", "{", "}", "\n", "var", "err", "error", "\n", "var", "b", "byte", "\n\n", "lencodec", ":=", "len", "(", "codecFromKey", ")", "\n", "mapValues", ":=", "make", "(", "map", "[", "string", "]", "interface", "{", "}", ",", "lencodec", ")", "\n\n", "if", "buf", ",", "err", "=", "advanceAndConsume", "(", "buf", ",", "'{'", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "nil", ",", "err", "\n", "}", "\n", "if", "buf", ",", "_", "=", "advanceToNonWhitespace", "(", "buf", ")", ";", "len", "(", "buf", ")", "==", "0", "{", "return", "nil", ",", "nil", ",", "io", ".", "ErrShortBuffer", "\n", "}", "\n", "// NOTE: Special case empty map", "if", "buf", "[", "0", "]", "==", "'}'", "{", "return", "mapValues", ",", "buf", "[", "1", ":", "]", ",", "nil", "\n", "}", "\n\n", "// NOTE: Also terminates when read '}' byte.", "for", "len", "(", "buf", ")", ">", "0", "{", "// decode key string", "value", ",", "buf", ",", "err", "=", "stringNativeFromTextual", "(", "buf", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n", "key", ":=", "value", ".", "(", "string", ")", "\n", "// Is key already used?", "if", "_", ",", "ok", ":=", "mapValues", "[", "key", "]", ";", "ok", "{", "return", "nil", ",", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "key", ")", "\n", "}", "\n", "// Find a codec for the key", "fieldCodec", ":=", "codecFromKey", "[", "key", "]", "\n", "if", "fieldCodec", "==", "nil", "{", "fieldCodec", "=", "defaultCodec", "\n", "}", "\n", "if", "fieldCodec", "==", "nil", "{", "return", "nil", ",", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "key", ")", "\n", "}", "\n", "// decode colon", "if", "buf", ",", "err", "=", "advanceAndConsume", "(", "buf", ",", "':'", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "nil", ",", "err", "\n", "}", "\n", "// decode value", "if", "buf", ",", "_", "=", "advanceToNonWhitespace", "(", "buf", ")", ";", "len", "(", "buf", ")", "==", "0", "{", "return", "nil", ",", "nil", ",", "io", ".", "ErrShortBuffer", "\n", "}", "\n", "value", ",", "buf", ",", "err", "=", "fieldCodec", ".", "nativeFromTextual", "(", "buf", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "nil", ",", "err", "\n", "}", "\n", "// set map value for key", "mapValues", "[", "key", "]", "=", "value", "\n", "// either comma or closing curly brace", "if", "buf", ",", "_", "=", "advanceToNonWhitespace", "(", "buf", ")", ";", "len", "(", "buf", ")", "==", "0", "{", "return", "nil", ",", "nil", ",", "io", ".", "ErrShortBuffer", "\n", "}", "\n", "switch", "b", "=", "buf", "[", "0", "]", ";", "b", "{", "case", "'}'", ":", "return", "mapValues", ",", "buf", "[", "1", ":", "]", ",", "nil", "\n", "case", "','", ":", "// no-op", "default", ":", "return", "nil", ",", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "b", ")", "\n", "}", "\n", "// NOTE: consume comma from above", "if", "buf", ",", "_", "=", "advanceToNonWhitespace", "(", "buf", "[", "1", ":", "]", ")", ";", "len", "(", "buf", ")", "==", "0", "{", "return", "nil", ",", "nil", ",", "io", ".", "ErrShortBuffer", "\n", "}", "\n", "}", "\n", "return", "nil", ",", "nil", ",", "io", ".", "ErrShortBuffer", "\n", "}" ]
// genericMapTextDecoder decodes a JSON text blob to a native Go map, using the // codecs from codecFromKey, and if a key is not found in that map, from // defaultCodec if provided. If defaultCodec is nil, this function returns an // error if it encounters a map key that is not present in codecFromKey. If // codecFromKey is nil, every map value will be decoded using defaultCodec, if // possible.
[ "genericMapTextDecoder", "decodes", "a", "JSON", "text", "blob", "to", "a", "native", "Go", "map", "using", "the", "codecs", "from", "codecFromKey", "and", "if", "a", "key", "is", "not", "found", "in", "that", "map", "from", "defaultCodec", "if", "provided", ".", "If", "defaultCodec", "is", "nil", "this", "function", "returns", "an", "error", "if", "it", "encounters", "a", "map", "key", "that", "is", "not", "present", "in", "codecFromKey", ".", "If", "codecFromKey", "is", "nil", "every", "map", "value", "will", "be", "decoded", "using", "defaultCodec", "if", "possible", "." ]
45f9a215035e4767b6a0848975ec3df73ed9c1b0
https://github.com/linkedin/goavro/blob/45f9a215035e4767b6a0848975ec3df73ed9c1b0/map.go#L158-L229
152,784
linkedin/goavro
map.go
genericMapTextEncoder
func genericMapTextEncoder(buf []byte, datum interface{}, defaultCodec *Codec, codecFromKey map[string]*Codec) ([]byte, error) { mapValues, err := convertMap(datum) if err != nil { return nil, fmt.Errorf("cannot encode textual map: %s", err) } var atLeastOne bool buf = append(buf, '{') for key, value := range mapValues { atLeastOne = true // Find a codec for the key fieldCodec := codecFromKey[key] if fieldCodec == nil { fieldCodec = defaultCodec } if fieldCodec == nil { return nil, fmt.Errorf("cannot encode textual map: cannot determine codec: %q", key) } // Encode key string buf, err = stringTextualFromNative(buf, key) if err != nil { return nil, err } buf = append(buf, ':') // Encode value buf, err = fieldCodec.textualFromNative(buf, value) if err != nil { // field was specified in datum; therefore its value was invalid return nil, fmt.Errorf("cannot encode textual map: value for %q does not match its schema: %s", key, err) } buf = append(buf, ',') } if atLeastOne { return append(buf[:len(buf)-1], '}'), nil } return append(buf, '}'), nil }
go
func genericMapTextEncoder(buf []byte, datum interface{}, defaultCodec *Codec, codecFromKey map[string]*Codec) ([]byte, error) { mapValues, err := convertMap(datum) if err != nil { return nil, fmt.Errorf("cannot encode textual map: %s", err) } var atLeastOne bool buf = append(buf, '{') for key, value := range mapValues { atLeastOne = true // Find a codec for the key fieldCodec := codecFromKey[key] if fieldCodec == nil { fieldCodec = defaultCodec } if fieldCodec == nil { return nil, fmt.Errorf("cannot encode textual map: cannot determine codec: %q", key) } // Encode key string buf, err = stringTextualFromNative(buf, key) if err != nil { return nil, err } buf = append(buf, ':') // Encode value buf, err = fieldCodec.textualFromNative(buf, value) if err != nil { // field was specified in datum; therefore its value was invalid return nil, fmt.Errorf("cannot encode textual map: value for %q does not match its schema: %s", key, err) } buf = append(buf, ',') } if atLeastOne { return append(buf[:len(buf)-1], '}'), nil } return append(buf, '}'), nil }
[ "func", "genericMapTextEncoder", "(", "buf", "[", "]", "byte", ",", "datum", "interface", "{", "}", ",", "defaultCodec", "*", "Codec", ",", "codecFromKey", "map", "[", "string", "]", "*", "Codec", ")", "(", "[", "]", "byte", ",", "error", ")", "{", "mapValues", ",", "err", ":=", "convertMap", "(", "datum", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n\n", "var", "atLeastOne", "bool", "\n\n", "buf", "=", "append", "(", "buf", ",", "'{'", ")", "\n\n", "for", "key", ",", "value", ":=", "range", "mapValues", "{", "atLeastOne", "=", "true", "\n\n", "// Find a codec for the key", "fieldCodec", ":=", "codecFromKey", "[", "key", "]", "\n", "if", "fieldCodec", "==", "nil", "{", "fieldCodec", "=", "defaultCodec", "\n", "}", "\n", "if", "fieldCodec", "==", "nil", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "key", ")", "\n", "}", "\n", "// Encode key string", "buf", ",", "err", "=", "stringTextualFromNative", "(", "buf", ",", "key", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "buf", "=", "append", "(", "buf", ",", "':'", ")", "\n", "// Encode value", "buf", ",", "err", "=", "fieldCodec", ".", "textualFromNative", "(", "buf", ",", "value", ")", "\n", "if", "err", "!=", "nil", "{", "// field was specified in datum; therefore its value was invalid", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "key", ",", "err", ")", "\n", "}", "\n", "buf", "=", "append", "(", "buf", ",", "','", ")", "\n", "}", "\n\n", "if", "atLeastOne", "{", "return", "append", "(", "buf", "[", ":", "len", "(", "buf", ")", "-", "1", "]", ",", "'}'", ")", ",", "nil", "\n", "}", "\n", "return", "append", "(", "buf", ",", "'}'", ")", ",", "nil", "\n", "}" ]
// genericMapTextEncoder encodes a native Go map to a JSON text blob, using the // codecs from codecFromKey, and if a key is not found in that map, from // defaultCodec if provided. If defaultCodec is nil, this function returns an // error if it encounters a map key that is not present in codecFromKey. If // codecFromKey is nil, every map value will be encoded using defaultCodec, if // possible.
[ "genericMapTextEncoder", "encodes", "a", "native", "Go", "map", "to", "a", "JSON", "text", "blob", "using", "the", "codecs", "from", "codecFromKey", "and", "if", "a", "key", "is", "not", "found", "in", "that", "map", "from", "defaultCodec", "if", "provided", ".", "If", "defaultCodec", "is", "nil", "this", "function", "returns", "an", "error", "if", "it", "encounters", "a", "map", "key", "that", "is", "not", "present", "in", "codecFromKey", ".", "If", "codecFromKey", "is", "nil", "every", "map", "value", "will", "be", "encoded", "using", "defaultCodec", "if", "possible", "." ]
45f9a215035e4767b6a0848975ec3df73ed9c1b0
https://github.com/linkedin/goavro/blob/45f9a215035e4767b6a0848975ec3df73ed9c1b0/map.go#L237-L277
152,785
linkedin/goavro
codec.go
buildCodec
func buildCodec(st map[string]*Codec, enclosingNamespace string, schema interface{}) (*Codec, error) { switch schemaType := schema.(type) { case map[string]interface{}: return buildCodecForTypeDescribedByMap(st, enclosingNamespace, schemaType) case string: return buildCodecForTypeDescribedByString(st, enclosingNamespace, schemaType, nil) case []interface{}: return buildCodecForTypeDescribedBySlice(st, enclosingNamespace, schemaType) default: return nil, fmt.Errorf("unknown schema type: %T", schema) } }
go
func buildCodec(st map[string]*Codec, enclosingNamespace string, schema interface{}) (*Codec, error) { switch schemaType := schema.(type) { case map[string]interface{}: return buildCodecForTypeDescribedByMap(st, enclosingNamespace, schemaType) case string: return buildCodecForTypeDescribedByString(st, enclosingNamespace, schemaType, nil) case []interface{}: return buildCodecForTypeDescribedBySlice(st, enclosingNamespace, schemaType) default: return nil, fmt.Errorf("unknown schema type: %T", schema) } }
[ "func", "buildCodec", "(", "st", "map", "[", "string", "]", "*", "Codec", ",", "enclosingNamespace", "string", ",", "schema", "interface", "{", "}", ")", "(", "*", "Codec", ",", "error", ")", "{", "switch", "schemaType", ":=", "schema", ".", "(", "type", ")", "{", "case", "map", "[", "string", "]", "interface", "{", "}", ":", "return", "buildCodecForTypeDescribedByMap", "(", "st", ",", "enclosingNamespace", ",", "schemaType", ")", "\n", "case", "string", ":", "return", "buildCodecForTypeDescribedByString", "(", "st", ",", "enclosingNamespace", ",", "schemaType", ",", "nil", ")", "\n", "case", "[", "]", "interface", "{", "}", ":", "return", "buildCodecForTypeDescribedBySlice", "(", "st", ",", "enclosingNamespace", ",", "schemaType", ")", "\n", "default", ":", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "schema", ")", "\n", "}", "\n", "}" ]
// convert a schema data structure to a codec, prefixing with specified // namespace
[ "convert", "a", "schema", "data", "structure", "to", "a", "codec", "prefixing", "with", "specified", "namespace" ]
45f9a215035e4767b6a0848975ec3df73ed9c1b0
https://github.com/linkedin/goavro/blob/45f9a215035e4767b6a0848975ec3df73ed9c1b0/codec.go#L445-L456
152,786
linkedin/goavro
codec.go
buildCodecForTypeDescribedByMap
func buildCodecForTypeDescribedByMap(st map[string]*Codec, enclosingNamespace string, schemaMap map[string]interface{}) (*Codec, error) { t, ok := schemaMap["type"] if !ok { return nil, fmt.Errorf("missing type: %v", schemaMap) } switch v := t.(type) { case string: // Already defined types may be abbreviated with its string name. // EXAMPLE: "type":"array" // EXAMPLE: "type":"enum" // EXAMPLE: "type":"fixed" // EXAMPLE: "type":"int" // EXAMPLE: "type":"record" // EXAMPLE: "type":"somePreviouslyDefinedCustomTypeString" return buildCodecForTypeDescribedByString(st, enclosingNamespace, v, schemaMap) case map[string]interface{}: return buildCodecForTypeDescribedByMap(st, enclosingNamespace, v) case []interface{}: return buildCodecForTypeDescribedBySlice(st, enclosingNamespace, v) default: return nil, fmt.Errorf("type ought to be either string, map[string]interface{}, or []interface{}; received: %T", t) } }
go
func buildCodecForTypeDescribedByMap(st map[string]*Codec, enclosingNamespace string, schemaMap map[string]interface{}) (*Codec, error) { t, ok := schemaMap["type"] if !ok { return nil, fmt.Errorf("missing type: %v", schemaMap) } switch v := t.(type) { case string: // Already defined types may be abbreviated with its string name. // EXAMPLE: "type":"array" // EXAMPLE: "type":"enum" // EXAMPLE: "type":"fixed" // EXAMPLE: "type":"int" // EXAMPLE: "type":"record" // EXAMPLE: "type":"somePreviouslyDefinedCustomTypeString" return buildCodecForTypeDescribedByString(st, enclosingNamespace, v, schemaMap) case map[string]interface{}: return buildCodecForTypeDescribedByMap(st, enclosingNamespace, v) case []interface{}: return buildCodecForTypeDescribedBySlice(st, enclosingNamespace, v) default: return nil, fmt.Errorf("type ought to be either string, map[string]interface{}, or []interface{}; received: %T", t) } }
[ "func", "buildCodecForTypeDescribedByMap", "(", "st", "map", "[", "string", "]", "*", "Codec", ",", "enclosingNamespace", "string", ",", "schemaMap", "map", "[", "string", "]", "interface", "{", "}", ")", "(", "*", "Codec", ",", "error", ")", "{", "t", ",", "ok", ":=", "schemaMap", "[", "\"", "\"", "]", "\n", "if", "!", "ok", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "schemaMap", ")", "\n", "}", "\n", "switch", "v", ":=", "t", ".", "(", "type", ")", "{", "case", "string", ":", "// Already defined types may be abbreviated with its string name.", "// EXAMPLE: \"type\":\"array\"", "// EXAMPLE: \"type\":\"enum\"", "// EXAMPLE: \"type\":\"fixed\"", "// EXAMPLE: \"type\":\"int\"", "// EXAMPLE: \"type\":\"record\"", "// EXAMPLE: \"type\":\"somePreviouslyDefinedCustomTypeString\"", "return", "buildCodecForTypeDescribedByString", "(", "st", ",", "enclosingNamespace", ",", "v", ",", "schemaMap", ")", "\n", "case", "map", "[", "string", "]", "interface", "{", "}", ":", "return", "buildCodecForTypeDescribedByMap", "(", "st", ",", "enclosingNamespace", ",", "v", ")", "\n", "case", "[", "]", "interface", "{", "}", ":", "return", "buildCodecForTypeDescribedBySlice", "(", "st", ",", "enclosingNamespace", ",", "v", ")", "\n", "default", ":", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "t", ")", "\n", "}", "\n", "}" ]
// Reach into the map, grabbing its "type". Use that to create the codec.
[ "Reach", "into", "the", "map", "grabbing", "its", "type", ".", "Use", "that", "to", "create", "the", "codec", "." ]
45f9a215035e4767b6a0848975ec3df73ed9c1b0
https://github.com/linkedin/goavro/blob/45f9a215035e4767b6a0848975ec3df73ed9c1b0/codec.go#L459-L481
152,787
linkedin/goavro
codec.go
registerNewCodec
func registerNewCodec(st map[string]*Codec, schemaMap map[string]interface{}, enclosingNamespace string) (*Codec, error) { n, err := newNameFromSchemaMap(enclosingNamespace, schemaMap) if err != nil { return nil, err } c := &Codec{typeName: n} st[n.fullName] = c return c, nil }
go
func registerNewCodec(st map[string]*Codec, schemaMap map[string]interface{}, enclosingNamespace string) (*Codec, error) { n, err := newNameFromSchemaMap(enclosingNamespace, schemaMap) if err != nil { return nil, err } c := &Codec{typeName: n} st[n.fullName] = c return c, nil }
[ "func", "registerNewCodec", "(", "st", "map", "[", "string", "]", "*", "Codec", ",", "schemaMap", "map", "[", "string", "]", "interface", "{", "}", ",", "enclosingNamespace", "string", ")", "(", "*", "Codec", ",", "error", ")", "{", "n", ",", "err", ":=", "newNameFromSchemaMap", "(", "enclosingNamespace", ",", "schemaMap", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "c", ":=", "&", "Codec", "{", "typeName", ":", "n", "}", "\n", "st", "[", "n", ".", "fullName", "]", "=", "c", "\n", "return", "c", ",", "nil", "\n", "}" ]
// notion of enclosing namespace changes when record, enum, or fixed create a // new namespace, for child objects.
[ "notion", "of", "enclosing", "namespace", "changes", "when", "record", "enum", "or", "fixed", "create", "a", "new", "namespace", "for", "child", "objects", "." ]
45f9a215035e4767b6a0848975ec3df73ed9c1b0
https://github.com/linkedin/goavro/blob/45f9a215035e4767b6a0848975ec3df73ed9c1b0/codec.go#L532-L540
152,788
linkedin/goavro
name.go
newName
func newName(n, ns, ens string) (*name, error) { var nn name if index := strings.LastIndexByte(n, '.'); index > -1 { // inputName does contain a dot, so ignore everything else and use it as the full name nn.fullName = n nn.namespace = n[:index] } else { // inputName does not contain a dot, therefore is not the full name if ns != nullNamespace { // if namespace provided in the schema in the same schema level, use it nn.fullName = ns + "." + n nn.namespace = ns } else if ens != nullNamespace { // otherwise if enclosing namespace provided, use it nn.fullName = ens + "." + n nn.namespace = ens } else { // otherwise no namespace, so use null namespace, the empty string nn.fullName = n } } // verify all components of the full name for adherence to Avro naming rules for i, component := range strings.Split(nn.fullName, ".") { if i == 0 && RelaxedNameValidation && component == "" { continue } if err := checkNameComponent(component); err != nil { return nil, err } } return &nn, nil }
go
func newName(n, ns, ens string) (*name, error) { var nn name if index := strings.LastIndexByte(n, '.'); index > -1 { // inputName does contain a dot, so ignore everything else and use it as the full name nn.fullName = n nn.namespace = n[:index] } else { // inputName does not contain a dot, therefore is not the full name if ns != nullNamespace { // if namespace provided in the schema in the same schema level, use it nn.fullName = ns + "." + n nn.namespace = ns } else if ens != nullNamespace { // otherwise if enclosing namespace provided, use it nn.fullName = ens + "." + n nn.namespace = ens } else { // otherwise no namespace, so use null namespace, the empty string nn.fullName = n } } // verify all components of the full name for adherence to Avro naming rules for i, component := range strings.Split(nn.fullName, ".") { if i == 0 && RelaxedNameValidation && component == "" { continue } if err := checkNameComponent(component); err != nil { return nil, err } } return &nn, nil }
[ "func", "newName", "(", "n", ",", "ns", ",", "ens", "string", ")", "(", "*", "name", ",", "error", ")", "{", "var", "nn", "name", "\n\n", "if", "index", ":=", "strings", ".", "LastIndexByte", "(", "n", ",", "'.'", ")", ";", "index", ">", "-", "1", "{", "// inputName does contain a dot, so ignore everything else and use it as the full name", "nn", ".", "fullName", "=", "n", "\n", "nn", ".", "namespace", "=", "n", "[", ":", "index", "]", "\n", "}", "else", "{", "// inputName does not contain a dot, therefore is not the full name", "if", "ns", "!=", "nullNamespace", "{", "// if namespace provided in the schema in the same schema level, use it", "nn", ".", "fullName", "=", "ns", "+", "\"", "\"", "+", "n", "\n", "nn", ".", "namespace", "=", "ns", "\n", "}", "else", "if", "ens", "!=", "nullNamespace", "{", "// otherwise if enclosing namespace provided, use it", "nn", ".", "fullName", "=", "ens", "+", "\"", "\"", "+", "n", "\n", "nn", ".", "namespace", "=", "ens", "\n", "}", "else", "{", "// otherwise no namespace, so use null namespace, the empty string", "nn", ".", "fullName", "=", "n", "\n", "}", "\n", "}", "\n\n", "// verify all components of the full name for adherence to Avro naming rules", "for", "i", ",", "component", ":=", "range", "strings", ".", "Split", "(", "nn", ".", "fullName", ",", "\"", "\"", ")", "{", "if", "i", "==", "0", "&&", "RelaxedNameValidation", "&&", "component", "==", "\"", "\"", "{", "continue", "\n", "}", "\n", "if", "err", ":=", "checkNameComponent", "(", "component", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "}", "\n\n", "return", "&", "nn", ",", "nil", "\n", "}" ]
// newName returns a new Name instance after first ensuring the arguments do not // violate any of the Avro naming rules.
[ "newName", "returns", "a", "new", "Name", "instance", "after", "first", "ensuring", "the", "arguments", "do", "not", "violate", "any", "of", "the", "Avro", "naming", "rules", "." ]
45f9a215035e4767b6a0848975ec3df73ed9c1b0
https://github.com/linkedin/goavro/blob/45f9a215035e4767b6a0848975ec3df73ed9c1b0/name.go#L69-L103
152,789
linkedin/goavro
name.go
short
func (n *name) short() string { if index := strings.LastIndexByte(n.fullName, '.'); index > -1 { return n.fullName[index+1:] } return n.fullName }
go
func (n *name) short() string { if index := strings.LastIndexByte(n.fullName, '.'); index > -1 { return n.fullName[index+1:] } return n.fullName }
[ "func", "(", "n", "*", "name", ")", "short", "(", ")", "string", "{", "if", "index", ":=", "strings", ".", "LastIndexByte", "(", "n", ".", "fullName", ",", "'.'", ")", ";", "index", ">", "-", "1", "{", "return", "n", ".", "fullName", "[", "index", "+", "1", ":", "]", "\n", "}", "\n", "return", "n", ".", "fullName", "\n", "}" ]
// short returns the name without the prefixed namespace.
[ "short", "returns", "the", "name", "without", "the", "prefixed", "namespace", "." ]
45f9a215035e4767b6a0848975ec3df73ed9c1b0
https://github.com/linkedin/goavro/blob/45f9a215035e4767b6a0848975ec3df73ed9c1b0/name.go#L137-L142
152,790
linkedin/goavro
canonical.go
pcfArray
func pcfArray(val []interface{}) (string, error) { items := make([]string, len(val)) for i, el := range val { p, err := parsingCanonicalForm(el) if err != nil { return "", err } items[i] = p } return "[" + strings.Join(items, ",") + "]", nil }
go
func pcfArray(val []interface{}) (string, error) { items := make([]string, len(val)) for i, el := range val { p, err := parsingCanonicalForm(el) if err != nil { return "", err } items[i] = p } return "[" + strings.Join(items, ",") + "]", nil }
[ "func", "pcfArray", "(", "val", "[", "]", "interface", "{", "}", ")", "(", "string", ",", "error", ")", "{", "items", ":=", "make", "(", "[", "]", "string", ",", "len", "(", "val", ")", ")", "\n", "for", "i", ",", "el", ":=", "range", "val", "{", "p", ",", "err", ":=", "parsingCanonicalForm", "(", "el", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "err", "\n", "}", "\n", "items", "[", "i", "]", "=", "p", "\n", "}", "\n", "return", "\"", "\"", "+", "strings", ".", "Join", "(", "items", ",", "\"", "\"", ")", "+", "\"", "\"", ",", "nil", "\n", "}" ]
// pcfArray returns the parsing canonical form for a JSON array.
[ "pcfArray", "returns", "the", "parsing", "canonical", "form", "for", "a", "JSON", "array", "." ]
45f9a215035e4767b6a0848975ec3df73ed9c1b0
https://github.com/linkedin/goavro/blob/45f9a215035e4767b6a0848975ec3df73ed9c1b0/canonical.go#L56-L66
152,791
linkedin/goavro
canonical.go
pcfObject
func pcfObject(jsonMap map[string]interface{}) (string, error) { pairs := make(stringPairs, 0, len(jsonMap)) // Remember the namespace to fully qualify names later var namespace string if namespaceJSON, ok := jsonMap["namespace"]; ok { if namespaceStr, ok := namespaceJSON.(string); ok { // and it's value is string (otherwise invalid schema) namespace = namespaceStr } } for k, v := range jsonMap { // Reduce primitive schemas to their simple form. if len(jsonMap) == 1 && k == "type" { if t, ok := v.(string); ok { return "\"" + t + "\"", nil } } // Only keep relevant attributes (strip 'doc', 'alias', 'namespace') if _, ok := fieldOrder[k]; !ok { continue } // Add namespace to a non-qualified name. if k == "name" && namespace != "" { // Check if the name isn't already qualified. if t, ok := v.(string); ok && !strings.ContainsRune(t, '.') { v = namespace + "." + t } } // Only fixed type allows size, and we must convert a string size to a // float. if k == "size" { if s, ok := v.(string); ok { s, err := strconv.ParseUint(s, 10, 0) if err != nil { // should never get here because already validated schema return "", fmt.Errorf("Fixed size ought to be number greater than zero: %v", s) } v = float64(s) } } pk, err := parsingCanonicalForm(k) if err != nil { return "", err } pv, err := parsingCanonicalForm(v) if err != nil { return "", err } pairs = append(pairs, stringPair{k, pk + ":" + pv}) } // Sort keys by their order in specification. sort.Sort(byAvroFieldOrder(pairs)) return "{" + strings.Join(pairs.Bs(), ",") + "}", nil }
go
func pcfObject(jsonMap map[string]interface{}) (string, error) { pairs := make(stringPairs, 0, len(jsonMap)) // Remember the namespace to fully qualify names later var namespace string if namespaceJSON, ok := jsonMap["namespace"]; ok { if namespaceStr, ok := namespaceJSON.(string); ok { // and it's value is string (otherwise invalid schema) namespace = namespaceStr } } for k, v := range jsonMap { // Reduce primitive schemas to their simple form. if len(jsonMap) == 1 && k == "type" { if t, ok := v.(string); ok { return "\"" + t + "\"", nil } } // Only keep relevant attributes (strip 'doc', 'alias', 'namespace') if _, ok := fieldOrder[k]; !ok { continue } // Add namespace to a non-qualified name. if k == "name" && namespace != "" { // Check if the name isn't already qualified. if t, ok := v.(string); ok && !strings.ContainsRune(t, '.') { v = namespace + "." + t } } // Only fixed type allows size, and we must convert a string size to a // float. if k == "size" { if s, ok := v.(string); ok { s, err := strconv.ParseUint(s, 10, 0) if err != nil { // should never get here because already validated schema return "", fmt.Errorf("Fixed size ought to be number greater than zero: %v", s) } v = float64(s) } } pk, err := parsingCanonicalForm(k) if err != nil { return "", err } pv, err := parsingCanonicalForm(v) if err != nil { return "", err } pairs = append(pairs, stringPair{k, pk + ":" + pv}) } // Sort keys by their order in specification. sort.Sort(byAvroFieldOrder(pairs)) return "{" + strings.Join(pairs.Bs(), ",") + "}", nil }
[ "func", "pcfObject", "(", "jsonMap", "map", "[", "string", "]", "interface", "{", "}", ")", "(", "string", ",", "error", ")", "{", "pairs", ":=", "make", "(", "stringPairs", ",", "0", ",", "len", "(", "jsonMap", ")", ")", "\n\n", "// Remember the namespace to fully qualify names later", "var", "namespace", "string", "\n", "if", "namespaceJSON", ",", "ok", ":=", "jsonMap", "[", "\"", "\"", "]", ";", "ok", "{", "if", "namespaceStr", ",", "ok", ":=", "namespaceJSON", ".", "(", "string", ")", ";", "ok", "{", "// and it's value is string (otherwise invalid schema)", "namespace", "=", "namespaceStr", "\n", "}", "\n", "}", "\n\n", "for", "k", ",", "v", ":=", "range", "jsonMap", "{", "// Reduce primitive schemas to their simple form.", "if", "len", "(", "jsonMap", ")", "==", "1", "&&", "k", "==", "\"", "\"", "{", "if", "t", ",", "ok", ":=", "v", ".", "(", "string", ")", ";", "ok", "{", "return", "\"", "\\\"", "\"", "+", "t", "+", "\"", "\\\"", "\"", ",", "nil", "\n", "}", "\n", "}", "\n\n", "// Only keep relevant attributes (strip 'doc', 'alias', 'namespace')", "if", "_", ",", "ok", ":=", "fieldOrder", "[", "k", "]", ";", "!", "ok", "{", "continue", "\n", "}", "\n\n", "// Add namespace to a non-qualified name.", "if", "k", "==", "\"", "\"", "&&", "namespace", "!=", "\"", "\"", "{", "// Check if the name isn't already qualified.", "if", "t", ",", "ok", ":=", "v", ".", "(", "string", ")", ";", "ok", "&&", "!", "strings", ".", "ContainsRune", "(", "t", ",", "'.'", ")", "{", "v", "=", "namespace", "+", "\"", "\"", "+", "t", "\n", "}", "\n", "}", "\n\n", "// Only fixed type allows size, and we must convert a string size to a", "// float.", "if", "k", "==", "\"", "\"", "{", "if", "s", ",", "ok", ":=", "v", ".", "(", "string", ")", ";", "ok", "{", "s", ",", "err", ":=", "strconv", ".", "ParseUint", "(", "s", ",", "10", ",", "0", ")", "\n", "if", "err", "!=", "nil", "{", "// should never get here because already validated schema", "return", "\"", "\"", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "s", ")", "\n", "}", "\n", "v", "=", "float64", "(", "s", ")", "\n", "}", "\n", "}", "\n\n", "pk", ",", "err", ":=", "parsingCanonicalForm", "(", "k", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "err", "\n", "}", "\n", "pv", ",", "err", ":=", "parsingCanonicalForm", "(", "v", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "err", "\n", "}", "\n\n", "pairs", "=", "append", "(", "pairs", ",", "stringPair", "{", "k", ",", "pk", "+", "\"", "\"", "+", "pv", "}", ")", "\n", "}", "\n\n", "// Sort keys by their order in specification.", "sort", ".", "Sort", "(", "byAvroFieldOrder", "(", "pairs", ")", ")", "\n", "return", "\"", "\"", "+", "strings", ".", "Join", "(", "pairs", ".", "Bs", "(", ")", ",", "\"", "\"", ")", "+", "\"", "\"", ",", "nil", "\n", "}" ]
// pcfObject returns the parsing canonical form for a JSON object.
[ "pcfObject", "returns", "the", "parsing", "canonical", "form", "for", "a", "JSON", "object", "." ]
45f9a215035e4767b6a0848975ec3df73ed9c1b0
https://github.com/linkedin/goavro/blob/45f9a215035e4767b6a0848975ec3df73ed9c1b0/canonical.go#L69-L131
152,792
linkedin/goavro
canonical.go
Bs
func (sp *stringPairs) Bs() []string { items := make([]string, len(*sp)) for i, el := range *sp { items[i] = el.B } return items }
go
func (sp *stringPairs) Bs() []string { items := make([]string, len(*sp)) for i, el := range *sp { items[i] = el.B } return items }
[ "func", "(", "sp", "*", "stringPairs", ")", "Bs", "(", ")", "[", "]", "string", "{", "items", ":=", "make", "(", "[", "]", "string", ",", "len", "(", "*", "sp", ")", ")", "\n", "for", "i", ",", "el", ":=", "range", "*", "sp", "{", "items", "[", "i", "]", "=", "el", ".", "B", "\n", "}", "\n", "return", "items", "\n", "}" ]
// Bs returns an array of second values of an array of pairs.
[ "Bs", "returns", "an", "array", "of", "second", "values", "of", "an", "array", "of", "pairs", "." ]
45f9a215035e4767b6a0848975ec3df73ed9c1b0
https://github.com/linkedin/goavro/blob/45f9a215035e4767b6a0848975ec3df73ed9c1b0/canonical.go#L143-L149
152,793
linkedin/goavro
logical_type.go
toSignedBytes
func toSignedBytes(n *big.Int) ([]byte, error) { switch n.Sign() { case 0: return []byte{0}, nil case 1: b := n.Bytes() if b[0]&0x80 > 0 { b = append([]byte{0}, b...) } return b, nil case -1: length := uint(n.BitLen()/8+1) * 8 b := new(big.Int).Add(n, new(big.Int).Lsh(one, length)).Bytes() // When the most significant bit is on a byte // boundary, we can get some extra significant // bits, so strip them off when that happens. if len(b) >= 2 && b[0] == 0xff && b[1]&0x80 != 0 { b = b[1:] } return b, nil } return nil, fmt.Errorf("toSignedBytes: error big.Int.Sign() returned unexpected value") }
go
func toSignedBytes(n *big.Int) ([]byte, error) { switch n.Sign() { case 0: return []byte{0}, nil case 1: b := n.Bytes() if b[0]&0x80 > 0 { b = append([]byte{0}, b...) } return b, nil case -1: length := uint(n.BitLen()/8+1) * 8 b := new(big.Int).Add(n, new(big.Int).Lsh(one, length)).Bytes() // When the most significant bit is on a byte // boundary, we can get some extra significant // bits, so strip them off when that happens. if len(b) >= 2 && b[0] == 0xff && b[1]&0x80 != 0 { b = b[1:] } return b, nil } return nil, fmt.Errorf("toSignedBytes: error big.Int.Sign() returned unexpected value") }
[ "func", "toSignedBytes", "(", "n", "*", "big", ".", "Int", ")", "(", "[", "]", "byte", ",", "error", ")", "{", "switch", "n", ".", "Sign", "(", ")", "{", "case", "0", ":", "return", "[", "]", "byte", "{", "0", "}", ",", "nil", "\n", "case", "1", ":", "b", ":=", "n", ".", "Bytes", "(", ")", "\n", "if", "b", "[", "0", "]", "&", "0x80", ">", "0", "{", "b", "=", "append", "(", "[", "]", "byte", "{", "0", "}", ",", "b", "...", ")", "\n", "}", "\n", "return", "b", ",", "nil", "\n", "case", "-", "1", ":", "length", ":=", "uint", "(", "n", ".", "BitLen", "(", ")", "/", "8", "+", "1", ")", "*", "8", "\n", "b", ":=", "new", "(", "big", ".", "Int", ")", ".", "Add", "(", "n", ",", "new", "(", "big", ".", "Int", ")", ".", "Lsh", "(", "one", ",", "length", ")", ")", ".", "Bytes", "(", ")", "\n", "// When the most significant bit is on a byte", "// boundary, we can get some extra significant", "// bits, so strip them off when that happens.", "if", "len", "(", "b", ")", ">=", "2", "&&", "b", "[", "0", "]", "==", "0xff", "&&", "b", "[", "1", "]", "&", "0x80", "!=", "0", "{", "b", "=", "b", "[", "1", ":", "]", "\n", "}", "\n", "return", "b", ",", "nil", "\n", "}", "\n", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}" ]
// toSignedBytes returns the big-endian two's complement // form of n.
[ "toSignedBytes", "returns", "the", "big", "-", "endian", "two", "s", "complement", "form", "of", "n", "." ]
45f9a215035e4767b6a0848975ec3df73ed9c1b0
https://github.com/linkedin/goavro/blob/45f9a215035e4767b6a0848975ec3df73ed9c1b0/logical_type.go#L330-L352
152,794
linkedin/goavro
logical_type.go
toSignedFixedBytes
func toSignedFixedBytes(size uint) func(*big.Int) ([]byte, error) { return func(n *big.Int) ([]byte, error) { switch n.Sign() { case 0: return []byte{0}, nil case 1: b := n.Bytes() if b[0]&0x80 > 0 { b = append([]byte{0}, b...) } return padBytes(b, size), nil case -1: length := size * 8 b := new(big.Int).Add(n, new(big.Int).Lsh(one, length)).Bytes() // Unlike a variable length byte length we need the extra bits to meet byte length return b, nil } return nil, fmt.Errorf("toSignedBytes: error big.Int.Sign() returned unexpected value") } }
go
func toSignedFixedBytes(size uint) func(*big.Int) ([]byte, error) { return func(n *big.Int) ([]byte, error) { switch n.Sign() { case 0: return []byte{0}, nil case 1: b := n.Bytes() if b[0]&0x80 > 0 { b = append([]byte{0}, b...) } return padBytes(b, size), nil case -1: length := size * 8 b := new(big.Int).Add(n, new(big.Int).Lsh(one, length)).Bytes() // Unlike a variable length byte length we need the extra bits to meet byte length return b, nil } return nil, fmt.Errorf("toSignedBytes: error big.Int.Sign() returned unexpected value") } }
[ "func", "toSignedFixedBytes", "(", "size", "uint", ")", "func", "(", "*", "big", ".", "Int", ")", "(", "[", "]", "byte", ",", "error", ")", "{", "return", "func", "(", "n", "*", "big", ".", "Int", ")", "(", "[", "]", "byte", ",", "error", ")", "{", "switch", "n", ".", "Sign", "(", ")", "{", "case", "0", ":", "return", "[", "]", "byte", "{", "0", "}", ",", "nil", "\n", "case", "1", ":", "b", ":=", "n", ".", "Bytes", "(", ")", "\n", "if", "b", "[", "0", "]", "&", "0x80", ">", "0", "{", "b", "=", "append", "(", "[", "]", "byte", "{", "0", "}", ",", "b", "...", ")", "\n", "}", "\n", "return", "padBytes", "(", "b", ",", "size", ")", ",", "nil", "\n", "case", "-", "1", ":", "length", ":=", "size", "*", "8", "\n", "b", ":=", "new", "(", "big", ".", "Int", ")", ".", "Add", "(", "n", ",", "new", "(", "big", ".", "Int", ")", ".", "Lsh", "(", "one", ",", "length", ")", ")", ".", "Bytes", "(", ")", "\n", "// Unlike a variable length byte length we need the extra bits to meet byte length", "return", "b", ",", "nil", "\n", "}", "\n", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n", "}" ]
// toSignedFixedBytes returns the big-endian two's complement // form of n for a given length of bytes.
[ "toSignedFixedBytes", "returns", "the", "big", "-", "endian", "two", "s", "complement", "form", "of", "n", "for", "a", "given", "length", "of", "bytes", "." ]
45f9a215035e4767b6a0848975ec3df73ed9c1b0
https://github.com/linkedin/goavro/blob/45f9a215035e4767b6a0848975ec3df73ed9c1b0/logical_type.go#L356-L375
152,795
linkedin/goavro
examples/nested/main.go
ToStringMap
func (u *User) ToStringMap() map[string]interface{} { datumIn := map[string]interface{}{ "FirstName": string(u.FirstName), "LastName": string(u.LastName), } if len(u.Errors) > 0 { datumIn["Errors"] = goavro.Union("array", u.Errors) } else { datumIn["Errors"] = goavro.Union("null", nil) } if u.Address != nil { addDatum := map[string]interface{}{ "Address1": string(u.Address.Address1), "City": string(u.Address.City), "State": string(u.Address.State), "Zip": int(u.Address.Zip), } if u.Address.Address2 != "" { addDatum["Address2"] = goavro.Union("string", u.Address.Address2) } else { addDatum["Address2"] = goavro.Union("null", nil) } //important need namespace and record name datumIn["Address"] = goavro.Union("my.namespace.com.address", addDatum) } else { datumIn["Address"] = goavro.Union("null", nil) } return datumIn }
go
func (u *User) ToStringMap() map[string]interface{} { datumIn := map[string]interface{}{ "FirstName": string(u.FirstName), "LastName": string(u.LastName), } if len(u.Errors) > 0 { datumIn["Errors"] = goavro.Union("array", u.Errors) } else { datumIn["Errors"] = goavro.Union("null", nil) } if u.Address != nil { addDatum := map[string]interface{}{ "Address1": string(u.Address.Address1), "City": string(u.Address.City), "State": string(u.Address.State), "Zip": int(u.Address.Zip), } if u.Address.Address2 != "" { addDatum["Address2"] = goavro.Union("string", u.Address.Address2) } else { addDatum["Address2"] = goavro.Union("null", nil) } //important need namespace and record name datumIn["Address"] = goavro.Union("my.namespace.com.address", addDatum) } else { datumIn["Address"] = goavro.Union("null", nil) } return datumIn }
[ "func", "(", "u", "*", "User", ")", "ToStringMap", "(", ")", "map", "[", "string", "]", "interface", "{", "}", "{", "datumIn", ":=", "map", "[", "string", "]", "interface", "{", "}", "{", "\"", "\"", ":", "string", "(", "u", ".", "FirstName", ")", ",", "\"", "\"", ":", "string", "(", "u", ".", "LastName", ")", ",", "}", "\n\n", "if", "len", "(", "u", ".", "Errors", ")", ">", "0", "{", "datumIn", "[", "\"", "\"", "]", "=", "goavro", ".", "Union", "(", "\"", "\"", ",", "u", ".", "Errors", ")", "\n", "}", "else", "{", "datumIn", "[", "\"", "\"", "]", "=", "goavro", ".", "Union", "(", "\"", "\"", ",", "nil", ")", "\n", "}", "\n\n", "if", "u", ".", "Address", "!=", "nil", "{", "addDatum", ":=", "map", "[", "string", "]", "interface", "{", "}", "{", "\"", "\"", ":", "string", "(", "u", ".", "Address", ".", "Address1", ")", ",", "\"", "\"", ":", "string", "(", "u", ".", "Address", ".", "City", ")", ",", "\"", "\"", ":", "string", "(", "u", ".", "Address", ".", "State", ")", ",", "\"", "\"", ":", "int", "(", "u", ".", "Address", ".", "Zip", ")", ",", "}", "\n", "if", "u", ".", "Address", ".", "Address2", "!=", "\"", "\"", "{", "addDatum", "[", "\"", "\"", "]", "=", "goavro", ".", "Union", "(", "\"", "\"", ",", "u", ".", "Address", ".", "Address2", ")", "\n", "}", "else", "{", "addDatum", "[", "\"", "\"", "]", "=", "goavro", ".", "Union", "(", "\"", "\"", ",", "nil", ")", "\n", "}", "\n\n", "//important need namespace and record name", "datumIn", "[", "\"", "\"", "]", "=", "goavro", ".", "Union", "(", "\"", "\"", ",", "addDatum", ")", "\n\n", "}", "else", "{", "datumIn", "[", "\"", "\"", "]", "=", "goavro", ".", "Union", "(", "\"", "\"", ",", "nil", ")", "\n", "}", "\n", "return", "datumIn", "\n", "}" ]
// ToStringMap returns a map representation of the User.
[ "ToStringMap", "returns", "a", "map", "representation", "of", "the", "User", "." ]
45f9a215035e4767b6a0848975ec3df73ed9c1b0
https://github.com/linkedin/goavro/blob/45f9a215035e4767b6a0848975ec3df73ed9c1b0/examples/nested/main.go#L85-L117
152,796
linkedin/goavro
examples/nested/main.go
StringMapToUser
func StringMapToUser(data map[string]interface{}) *User { ind := &User{} for k, v := range data { switch k { case "FirstName": if value, ok := v.(string); ok { ind.FirstName = value } case "LastName": if value, ok := v.(string); ok { ind.LastName = value } case "Errors": if value, ok := v.(map[string]interface{}); ok { for _, item := range value["array"].([]interface{}) { ind.Errors = append(ind.Errors, item.(string)) } } case "Address": if vmap, ok := v.(map[string]interface{}); ok { //important need namespace and record name if cookieSMap, ok := vmap["my.namespace.com.address"].(map[string]interface{}); ok { add := &Address{} for k, v := range cookieSMap { switch k { case "Address1": if value, ok := v.(string); ok { add.Address1 = value } case "Address2": if value, ok := v.(string); ok { add.Address2 = value } case "City": if value, ok := v.(string); ok { add.City = value } case "Zip": if value, ok := v.(int); ok { add.Zip = value } } } ind.Address = add } } } } return ind }
go
func StringMapToUser(data map[string]interface{}) *User { ind := &User{} for k, v := range data { switch k { case "FirstName": if value, ok := v.(string); ok { ind.FirstName = value } case "LastName": if value, ok := v.(string); ok { ind.LastName = value } case "Errors": if value, ok := v.(map[string]interface{}); ok { for _, item := range value["array"].([]interface{}) { ind.Errors = append(ind.Errors, item.(string)) } } case "Address": if vmap, ok := v.(map[string]interface{}); ok { //important need namespace and record name if cookieSMap, ok := vmap["my.namespace.com.address"].(map[string]interface{}); ok { add := &Address{} for k, v := range cookieSMap { switch k { case "Address1": if value, ok := v.(string); ok { add.Address1 = value } case "Address2": if value, ok := v.(string); ok { add.Address2 = value } case "City": if value, ok := v.(string); ok { add.City = value } case "Zip": if value, ok := v.(int); ok { add.Zip = value } } } ind.Address = add } } } } return ind }
[ "func", "StringMapToUser", "(", "data", "map", "[", "string", "]", "interface", "{", "}", ")", "*", "User", "{", "ind", ":=", "&", "User", "{", "}", "\n", "for", "k", ",", "v", ":=", "range", "data", "{", "switch", "k", "{", "case", "\"", "\"", ":", "if", "value", ",", "ok", ":=", "v", ".", "(", "string", ")", ";", "ok", "{", "ind", ".", "FirstName", "=", "value", "\n", "}", "\n", "case", "\"", "\"", ":", "if", "value", ",", "ok", ":=", "v", ".", "(", "string", ")", ";", "ok", "{", "ind", ".", "LastName", "=", "value", "\n", "}", "\n", "case", "\"", "\"", ":", "if", "value", ",", "ok", ":=", "v", ".", "(", "map", "[", "string", "]", "interface", "{", "}", ")", ";", "ok", "{", "for", "_", ",", "item", ":=", "range", "value", "[", "\"", "\"", "]", ".", "(", "[", "]", "interface", "{", "}", ")", "{", "ind", ".", "Errors", "=", "append", "(", "ind", ".", "Errors", ",", "item", ".", "(", "string", ")", ")", "\n", "}", "\n", "}", "\n", "case", "\"", "\"", ":", "if", "vmap", ",", "ok", ":=", "v", ".", "(", "map", "[", "string", "]", "interface", "{", "}", ")", ";", "ok", "{", "//important need namespace and record name", "if", "cookieSMap", ",", "ok", ":=", "vmap", "[", "\"", "\"", "]", ".", "(", "map", "[", "string", "]", "interface", "{", "}", ")", ";", "ok", "{", "add", ":=", "&", "Address", "{", "}", "\n", "for", "k", ",", "v", ":=", "range", "cookieSMap", "{", "switch", "k", "{", "case", "\"", "\"", ":", "if", "value", ",", "ok", ":=", "v", ".", "(", "string", ")", ";", "ok", "{", "add", ".", "Address1", "=", "value", "\n", "}", "\n", "case", "\"", "\"", ":", "if", "value", ",", "ok", ":=", "v", ".", "(", "string", ")", ";", "ok", "{", "add", ".", "Address2", "=", "value", "\n", "}", "\n", "case", "\"", "\"", ":", "if", "value", ",", "ok", ":=", "v", ".", "(", "string", ")", ";", "ok", "{", "add", ".", "City", "=", "value", "\n", "}", "\n", "case", "\"", "\"", ":", "if", "value", ",", "ok", ":=", "v", ".", "(", "int", ")", ";", "ok", "{", "add", ".", "Zip", "=", "value", "\n", "}", "\n", "}", "\n", "}", "\n", "ind", ".", "Address", "=", "add", "\n", "}", "\n", "}", "\n", "}", "\n\n", "}", "\n", "return", "ind", "\n\n", "}" ]
// StringMapToUser returns a User from a map representation of the User.
[ "StringMapToUser", "returns", "a", "User", "from", "a", "map", "representation", "of", "the", "User", "." ]
45f9a215035e4767b6a0848975ec3df73ed9c1b0
https://github.com/linkedin/goavro/blob/45f9a215035e4767b6a0848975ec3df73ed9c1b0/examples/nested/main.go#L120-L172
152,797
JamesClonk/vultr
lib/account_info.go
GetAccountInfo
func (c *Client) GetAccountInfo() (info AccountInfo, err error) { if err := c.get(`account/info`, &info); err != nil { return AccountInfo{}, err } return }
go
func (c *Client) GetAccountInfo() (info AccountInfo, err error) { if err := c.get(`account/info`, &info); err != nil { return AccountInfo{}, err } return }
[ "func", "(", "c", "*", "Client", ")", "GetAccountInfo", "(", ")", "(", "info", "AccountInfo", ",", "err", "error", ")", "{", "if", "err", ":=", "c", ".", "get", "(", "`account/info`", ",", "&", "info", ")", ";", "err", "!=", "nil", "{", "return", "AccountInfo", "{", "}", ",", "err", "\n", "}", "\n", "return", "\n", "}" ]
// GetAccountInfo retrieves the Vultr account information about current balance, pending charges, etc..
[ "GetAccountInfo", "retrieves", "the", "Vultr", "account", "information", "about", "current", "balance", "pending", "charges", "etc", ".." ]
fed59ad207c9bda0a5dfe4d18de53ccbb3d80c91
https://github.com/JamesClonk/vultr/blob/fed59ad207c9bda0a5dfe4d18de53ccbb3d80c91/lib/account_info.go#L18-L23
152,798
JamesClonk/vultr
lib/account_info.go
UnmarshalJSON
func (a *AccountInfo) UnmarshalJSON(data []byte) (err error) { if a == nil { *a = AccountInfo{} } var fields map[string]interface{} if err := json.Unmarshal(data, &fields); err != nil { return err } value := fmt.Sprintf("%v", fields["balance"]) if len(value) == 0 || value == "<nil>" { value = "0" } b, err := strconv.ParseFloat(value, 64) if err != nil { return err } a.Balance = b value = fmt.Sprintf("%v", fields["pending_charges"]) if len(value) == 0 || value == "<nil>" { value = "0" } pc, err := strconv.ParseFloat(value, 64) if err != nil { return err } a.PendingCharges = pc value = fmt.Sprintf("%v", fields["last_payment_amount"]) if len(value) == 0 || value == "<nil>" { value = "0" } lpa, err := strconv.ParseFloat(value, 64) if err != nil { return err } a.LastPaymentAmount = lpa a.LastPaymentDate = fmt.Sprintf("%v", fields["last_payment_date"]) return }
go
func (a *AccountInfo) UnmarshalJSON(data []byte) (err error) { if a == nil { *a = AccountInfo{} } var fields map[string]interface{} if err := json.Unmarshal(data, &fields); err != nil { return err } value := fmt.Sprintf("%v", fields["balance"]) if len(value) == 0 || value == "<nil>" { value = "0" } b, err := strconv.ParseFloat(value, 64) if err != nil { return err } a.Balance = b value = fmt.Sprintf("%v", fields["pending_charges"]) if len(value) == 0 || value == "<nil>" { value = "0" } pc, err := strconv.ParseFloat(value, 64) if err != nil { return err } a.PendingCharges = pc value = fmt.Sprintf("%v", fields["last_payment_amount"]) if len(value) == 0 || value == "<nil>" { value = "0" } lpa, err := strconv.ParseFloat(value, 64) if err != nil { return err } a.LastPaymentAmount = lpa a.LastPaymentDate = fmt.Sprintf("%v", fields["last_payment_date"]) return }
[ "func", "(", "a", "*", "AccountInfo", ")", "UnmarshalJSON", "(", "data", "[", "]", "byte", ")", "(", "err", "error", ")", "{", "if", "a", "==", "nil", "{", "*", "a", "=", "AccountInfo", "{", "}", "\n", "}", "\n\n", "var", "fields", "map", "[", "string", "]", "interface", "{", "}", "\n", "if", "err", ":=", "json", ".", "Unmarshal", "(", "data", ",", "&", "fields", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "value", ":=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "fields", "[", "\"", "\"", "]", ")", "\n", "if", "len", "(", "value", ")", "==", "0", "||", "value", "==", "\"", "\"", "{", "value", "=", "\"", "\"", "\n", "}", "\n", "b", ",", "err", ":=", "strconv", ".", "ParseFloat", "(", "value", ",", "64", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "a", ".", "Balance", "=", "b", "\n\n", "value", "=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "fields", "[", "\"", "\"", "]", ")", "\n", "if", "len", "(", "value", ")", "==", "0", "||", "value", "==", "\"", "\"", "{", "value", "=", "\"", "\"", "\n", "}", "\n", "pc", ",", "err", ":=", "strconv", ".", "ParseFloat", "(", "value", ",", "64", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "a", ".", "PendingCharges", "=", "pc", "\n\n", "value", "=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "fields", "[", "\"", "\"", "]", ")", "\n", "if", "len", "(", "value", ")", "==", "0", "||", "value", "==", "\"", "\"", "{", "value", "=", "\"", "\"", "\n", "}", "\n", "lpa", ",", "err", ":=", "strconv", ".", "ParseFloat", "(", "value", ",", "64", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "a", ".", "LastPaymentAmount", "=", "lpa", "\n\n", "a", ".", "LastPaymentDate", "=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "fields", "[", "\"", "\"", "]", ")", "\n\n", "return", "\n", "}" ]
// UnmarshalJSON implements json.Unmarshaller on AccountInfo. // This is needed because the Vultr API is inconsistent in it's JSON responses for account info. // Some fields can change type, from JSON number to JSON string and vice-versa.
[ "UnmarshalJSON", "implements", "json", ".", "Unmarshaller", "on", "AccountInfo", ".", "This", "is", "needed", "because", "the", "Vultr", "API", "is", "inconsistent", "in", "it", "s", "JSON", "responses", "for", "account", "info", ".", "Some", "fields", "can", "change", "type", "from", "JSON", "number", "to", "JSON", "string", "and", "vice", "-", "versa", "." ]
fed59ad207c9bda0a5dfe4d18de53ccbb3d80c91
https://github.com/JamesClonk/vultr/blob/fed59ad207c9bda0a5dfe4d18de53ccbb3d80c91/lib/account_info.go#L28-L71
152,799
JamesClonk/vultr
lib/os.go
GetOS
func (c *Client) GetOS() ([]OS, error) { var osMap map[string]OS if err := c.get(`os/list`, &osMap); err != nil { return nil, err } var osList []OS for _, os := range osMap { osList = append(osList, os) } sort.Sort(oses(osList)) return osList, nil }
go
func (c *Client) GetOS() ([]OS, error) { var osMap map[string]OS if err := c.get(`os/list`, &osMap); err != nil { return nil, err } var osList []OS for _, os := range osMap { osList = append(osList, os) } sort.Sort(oses(osList)) return osList, nil }
[ "func", "(", "c", "*", "Client", ")", "GetOS", "(", ")", "(", "[", "]", "OS", ",", "error", ")", "{", "var", "osMap", "map", "[", "string", "]", "OS", "\n", "if", "err", ":=", "c", ".", "get", "(", "`os/list`", ",", "&", "osMap", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "var", "osList", "[", "]", "OS", "\n", "for", "_", ",", "os", ":=", "range", "osMap", "{", "osList", "=", "append", "(", "osList", ",", "os", ")", "\n", "}", "\n", "sort", ".", "Sort", "(", "oses", "(", "osList", ")", ")", "\n", "return", "osList", ",", "nil", "\n", "}" ]
// GetOS returns a list of all available operating systems on Vultr
[ "GetOS", "returns", "a", "list", "of", "all", "available", "operating", "systems", "on", "Vultr" ]
fed59ad207c9bda0a5dfe4d18de53ccbb3d80c91
https://github.com/JamesClonk/vultr/blob/fed59ad207c9bda0a5dfe4d18de53ccbb3d80c91/lib/os.go#L25-L37