id
int32 0
167k
| repo
stringlengths 5
54
| path
stringlengths 4
155
| func_name
stringlengths 1
118
| original_string
stringlengths 52
85.5k
| language
stringclasses 1
value | code
stringlengths 52
85.5k
| code_tokens
listlengths 21
1.41k
| docstring
stringlengths 6
2.61k
| docstring_tokens
listlengths 3
215
| sha
stringlengths 40
40
| url
stringlengths 85
252
|
|---|---|---|---|---|---|---|---|---|---|---|---|
21,700
|
golang/lint
|
lint.go
|
lintPackageComment
|
func (f *file) lintPackageComment() {
if f.isTest() {
return
}
const ref = styleGuideBase + "#package-comments"
prefix := "Package " + f.f.Name.Name + " "
// Look for a detached package comment.
// First, scan for the last comment that occurs before the "package" keyword.
var lastCG *ast.CommentGroup
for _, cg := range f.f.Comments {
if cg.Pos() > f.f.Package {
// Gone past "package" keyword.
break
}
lastCG = cg
}
if lastCG != nil && strings.HasPrefix(lastCG.Text(), prefix) {
endPos := f.fset.Position(lastCG.End())
pkgPos := f.fset.Position(f.f.Package)
if endPos.Line+1 < pkgPos.Line {
// There isn't a great place to anchor this error;
// the start of the blank lines between the doc and the package statement
// is at least pointing at the location of the problem.
pos := token.Position{
Filename: endPos.Filename,
// Offset not set; it is non-trivial, and doesn't appear to be needed.
Line: endPos.Line + 1,
Column: 1,
}
f.pkg.errorfAt(pos, 0.9, link(ref), category("comments"), "package comment is detached; there should be no blank lines between it and the package statement")
return
}
}
if f.f.Doc == nil {
f.errorf(f.f, 0.2, link(ref), category("comments"), "should have a package comment, unless it's in another file for this package")
return
}
s := f.f.Doc.Text()
if ts := strings.TrimLeft(s, " \t"); ts != s {
f.errorf(f.f.Doc, 1, link(ref), category("comments"), "package comment should not have leading space")
s = ts
}
// Only non-main packages need to keep to this form.
if !f.pkg.main && !strings.HasPrefix(s, prefix) {
f.errorf(f.f.Doc, 1, link(ref), category("comments"), `package comment should be of the form "%s..."`, prefix)
}
}
|
go
|
func (f *file) lintPackageComment() {
if f.isTest() {
return
}
const ref = styleGuideBase + "#package-comments"
prefix := "Package " + f.f.Name.Name + " "
// Look for a detached package comment.
// First, scan for the last comment that occurs before the "package" keyword.
var lastCG *ast.CommentGroup
for _, cg := range f.f.Comments {
if cg.Pos() > f.f.Package {
// Gone past "package" keyword.
break
}
lastCG = cg
}
if lastCG != nil && strings.HasPrefix(lastCG.Text(), prefix) {
endPos := f.fset.Position(lastCG.End())
pkgPos := f.fset.Position(f.f.Package)
if endPos.Line+1 < pkgPos.Line {
// There isn't a great place to anchor this error;
// the start of the blank lines between the doc and the package statement
// is at least pointing at the location of the problem.
pos := token.Position{
Filename: endPos.Filename,
// Offset not set; it is non-trivial, and doesn't appear to be needed.
Line: endPos.Line + 1,
Column: 1,
}
f.pkg.errorfAt(pos, 0.9, link(ref), category("comments"), "package comment is detached; there should be no blank lines between it and the package statement")
return
}
}
if f.f.Doc == nil {
f.errorf(f.f, 0.2, link(ref), category("comments"), "should have a package comment, unless it's in another file for this package")
return
}
s := f.f.Doc.Text()
if ts := strings.TrimLeft(s, " \t"); ts != s {
f.errorf(f.f.Doc, 1, link(ref), category("comments"), "package comment should not have leading space")
s = ts
}
// Only non-main packages need to keep to this form.
if !f.pkg.main && !strings.HasPrefix(s, prefix) {
f.errorf(f.f.Doc, 1, link(ref), category("comments"), `package comment should be of the form "%s..."`, prefix)
}
}
|
[
"func",
"(",
"f",
"*",
"file",
")",
"lintPackageComment",
"(",
")",
"{",
"if",
"f",
".",
"isTest",
"(",
")",
"{",
"return",
"\n",
"}",
"\n\n",
"const",
"ref",
"=",
"styleGuideBase",
"+",
"\"",
"\"",
"\n",
"prefix",
":=",
"\"",
"\"",
"+",
"f",
".",
"f",
".",
"Name",
".",
"Name",
"+",
"\"",
"\"",
"\n\n",
"// Look for a detached package comment.",
"// First, scan for the last comment that occurs before the \"package\" keyword.",
"var",
"lastCG",
"*",
"ast",
".",
"CommentGroup",
"\n",
"for",
"_",
",",
"cg",
":=",
"range",
"f",
".",
"f",
".",
"Comments",
"{",
"if",
"cg",
".",
"Pos",
"(",
")",
">",
"f",
".",
"f",
".",
"Package",
"{",
"// Gone past \"package\" keyword.",
"break",
"\n",
"}",
"\n",
"lastCG",
"=",
"cg",
"\n",
"}",
"\n",
"if",
"lastCG",
"!=",
"nil",
"&&",
"strings",
".",
"HasPrefix",
"(",
"lastCG",
".",
"Text",
"(",
")",
",",
"prefix",
")",
"{",
"endPos",
":=",
"f",
".",
"fset",
".",
"Position",
"(",
"lastCG",
".",
"End",
"(",
")",
")",
"\n",
"pkgPos",
":=",
"f",
".",
"fset",
".",
"Position",
"(",
"f",
".",
"f",
".",
"Package",
")",
"\n",
"if",
"endPos",
".",
"Line",
"+",
"1",
"<",
"pkgPos",
".",
"Line",
"{",
"// There isn't a great place to anchor this error;",
"// the start of the blank lines between the doc and the package statement",
"// is at least pointing at the location of the problem.",
"pos",
":=",
"token",
".",
"Position",
"{",
"Filename",
":",
"endPos",
".",
"Filename",
",",
"// Offset not set; it is non-trivial, and doesn't appear to be needed.",
"Line",
":",
"endPos",
".",
"Line",
"+",
"1",
",",
"Column",
":",
"1",
",",
"}",
"\n",
"f",
".",
"pkg",
".",
"errorfAt",
"(",
"pos",
",",
"0.9",
",",
"link",
"(",
"ref",
")",
",",
"category",
"(",
"\"",
"\"",
")",
",",
"\"",
"\"",
")",
"\n",
"return",
"\n",
"}",
"\n",
"}",
"\n\n",
"if",
"f",
".",
"f",
".",
"Doc",
"==",
"nil",
"{",
"f",
".",
"errorf",
"(",
"f",
".",
"f",
",",
"0.2",
",",
"link",
"(",
"ref",
")",
",",
"category",
"(",
"\"",
"\"",
")",
",",
"\"",
"\"",
")",
"\n",
"return",
"\n",
"}",
"\n",
"s",
":=",
"f",
".",
"f",
".",
"Doc",
".",
"Text",
"(",
")",
"\n",
"if",
"ts",
":=",
"strings",
".",
"TrimLeft",
"(",
"s",
",",
"\"",
"\\t",
"\"",
")",
";",
"ts",
"!=",
"s",
"{",
"f",
".",
"errorf",
"(",
"f",
".",
"f",
".",
"Doc",
",",
"1",
",",
"link",
"(",
"ref",
")",
",",
"category",
"(",
"\"",
"\"",
")",
",",
"\"",
"\"",
")",
"\n",
"s",
"=",
"ts",
"\n",
"}",
"\n",
"// Only non-main packages need to keep to this form.",
"if",
"!",
"f",
".",
"pkg",
".",
"main",
"&&",
"!",
"strings",
".",
"HasPrefix",
"(",
"s",
",",
"prefix",
")",
"{",
"f",
".",
"errorf",
"(",
"f",
".",
"f",
".",
"Doc",
",",
"1",
",",
"link",
"(",
"ref",
")",
",",
"category",
"(",
"\"",
"\"",
")",
",",
"`package comment should be of the form \"%s...\"`",
",",
"prefix",
")",
"\n",
"}",
"\n",
"}"
] |
// lintPackageComment checks package comments. It complains if
// there is no package comment, or if it is not of the right form.
// This has a notable false positive in that a package comment
// could rightfully appear in a different file of the same package,
// but that's not easy to fix since this linter is file-oriented.
|
[
"lintPackageComment",
"checks",
"package",
"comments",
".",
"It",
"complains",
"if",
"there",
"is",
"no",
"package",
"comment",
"or",
"if",
"it",
"is",
"not",
"of",
"the",
"right",
"form",
".",
"This",
"has",
"a",
"notable",
"false",
"positive",
"in",
"that",
"a",
"package",
"comment",
"could",
"rightfully",
"appear",
"in",
"a",
"different",
"file",
"of",
"the",
"same",
"package",
"but",
"that",
"s",
"not",
"easy",
"to",
"fix",
"since",
"this",
"linter",
"is",
"file",
"-",
"oriented",
"."
] |
959b441ac422379a43da2230f62be024250818b0
|
https://github.com/golang/lint/blob/959b441ac422379a43da2230f62be024250818b0/lint.go#L380-L429
|
21,701
|
golang/lint
|
lint.go
|
lintBlankImports
|
func (f *file) lintBlankImports() {
// In package main and in tests, we don't complain about blank imports.
if f.pkg.main || f.isTest() {
return
}
// The first element of each contiguous group of blank imports should have
// an explanatory comment of some kind.
for i, imp := range f.f.Imports {
pos := f.fset.Position(imp.Pos())
if !isBlank(imp.Name) {
continue // Ignore non-blank imports.
}
if i > 0 {
prev := f.f.Imports[i-1]
prevPos := f.fset.Position(prev.Pos())
if isBlank(prev.Name) && prevPos.Line+1 == pos.Line {
continue // A subsequent blank in a group.
}
}
// This is the first blank import of a group.
if imp.Doc == nil && imp.Comment == nil {
ref := ""
f.errorf(imp, 1, link(ref), category("imports"), "a blank import should be only in a main or test package, or have a comment justifying it")
}
}
}
|
go
|
func (f *file) lintBlankImports() {
// In package main and in tests, we don't complain about blank imports.
if f.pkg.main || f.isTest() {
return
}
// The first element of each contiguous group of blank imports should have
// an explanatory comment of some kind.
for i, imp := range f.f.Imports {
pos := f.fset.Position(imp.Pos())
if !isBlank(imp.Name) {
continue // Ignore non-blank imports.
}
if i > 0 {
prev := f.f.Imports[i-1]
prevPos := f.fset.Position(prev.Pos())
if isBlank(prev.Name) && prevPos.Line+1 == pos.Line {
continue // A subsequent blank in a group.
}
}
// This is the first blank import of a group.
if imp.Doc == nil && imp.Comment == nil {
ref := ""
f.errorf(imp, 1, link(ref), category("imports"), "a blank import should be only in a main or test package, or have a comment justifying it")
}
}
}
|
[
"func",
"(",
"f",
"*",
"file",
")",
"lintBlankImports",
"(",
")",
"{",
"// In package main and in tests, we don't complain about blank imports.",
"if",
"f",
".",
"pkg",
".",
"main",
"||",
"f",
".",
"isTest",
"(",
")",
"{",
"return",
"\n",
"}",
"\n\n",
"// The first element of each contiguous group of blank imports should have",
"// an explanatory comment of some kind.",
"for",
"i",
",",
"imp",
":=",
"range",
"f",
".",
"f",
".",
"Imports",
"{",
"pos",
":=",
"f",
".",
"fset",
".",
"Position",
"(",
"imp",
".",
"Pos",
"(",
")",
")",
"\n\n",
"if",
"!",
"isBlank",
"(",
"imp",
".",
"Name",
")",
"{",
"continue",
"// Ignore non-blank imports.",
"\n",
"}",
"\n",
"if",
"i",
">",
"0",
"{",
"prev",
":=",
"f",
".",
"f",
".",
"Imports",
"[",
"i",
"-",
"1",
"]",
"\n",
"prevPos",
":=",
"f",
".",
"fset",
".",
"Position",
"(",
"prev",
".",
"Pos",
"(",
")",
")",
"\n",
"if",
"isBlank",
"(",
"prev",
".",
"Name",
")",
"&&",
"prevPos",
".",
"Line",
"+",
"1",
"==",
"pos",
".",
"Line",
"{",
"continue",
"// A subsequent blank in a group.",
"\n",
"}",
"\n",
"}",
"\n\n",
"// This is the first blank import of a group.",
"if",
"imp",
".",
"Doc",
"==",
"nil",
"&&",
"imp",
".",
"Comment",
"==",
"nil",
"{",
"ref",
":=",
"\"",
"\"",
"\n",
"f",
".",
"errorf",
"(",
"imp",
",",
"1",
",",
"link",
"(",
"ref",
")",
",",
"category",
"(",
"\"",
"\"",
")",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"}",
"\n",
"}"
] |
// lintBlankImports complains if a non-main package has blank imports that are
// not documented.
|
[
"lintBlankImports",
"complains",
"if",
"a",
"non",
"-",
"main",
"package",
"has",
"blank",
"imports",
"that",
"are",
"not",
"documented",
"."
] |
959b441ac422379a43da2230f62be024250818b0
|
https://github.com/golang/lint/blob/959b441ac422379a43da2230f62be024250818b0/lint.go#L433-L461
|
21,702
|
golang/lint
|
lint.go
|
lintImports
|
func (f *file) lintImports() {
for i, is := range f.f.Imports {
_ = i
if is.Name != nil && is.Name.Name == "." && !f.isTest() {
f.errorf(is, 1, link(styleGuideBase+"#import-dot"), category("imports"), "should not use dot imports")
}
}
}
|
go
|
func (f *file) lintImports() {
for i, is := range f.f.Imports {
_ = i
if is.Name != nil && is.Name.Name == "." && !f.isTest() {
f.errorf(is, 1, link(styleGuideBase+"#import-dot"), category("imports"), "should not use dot imports")
}
}
}
|
[
"func",
"(",
"f",
"*",
"file",
")",
"lintImports",
"(",
")",
"{",
"for",
"i",
",",
"is",
":=",
"range",
"f",
".",
"f",
".",
"Imports",
"{",
"_",
"=",
"i",
"\n",
"if",
"is",
".",
"Name",
"!=",
"nil",
"&&",
"is",
".",
"Name",
".",
"Name",
"==",
"\"",
"\"",
"&&",
"!",
"f",
".",
"isTest",
"(",
")",
"{",
"f",
".",
"errorf",
"(",
"is",
",",
"1",
",",
"link",
"(",
"styleGuideBase",
"+",
"\"",
"\"",
")",
",",
"category",
"(",
"\"",
"\"",
")",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"}",
"\n",
"}"
] |
// lintImports examines import blocks.
|
[
"lintImports",
"examines",
"import",
"blocks",
"."
] |
959b441ac422379a43da2230f62be024250818b0
|
https://github.com/golang/lint/blob/959b441ac422379a43da2230f62be024250818b0/lint.go#L464-L472
|
21,703
|
golang/lint
|
lint.go
|
lintExported
|
func (f *file) lintExported() {
if f.isTest() {
return
}
var lastGen *ast.GenDecl // last GenDecl entered.
// Set of GenDecls that have already had missing comments flagged.
genDeclMissingComments := make(map[*ast.GenDecl]bool)
f.walk(func(node ast.Node) bool {
switch v := node.(type) {
case *ast.GenDecl:
if v.Tok == token.IMPORT {
return false
}
// token.CONST, token.TYPE or token.VAR
lastGen = v
return true
case *ast.FuncDecl:
f.lintFuncDoc(v)
if v.Recv == nil {
// Only check for stutter on functions, not methods.
// Method names are not used package-qualified.
f.checkStutter(v.Name, "func")
}
// Don't proceed inside funcs.
return false
case *ast.TypeSpec:
// inside a GenDecl, which usually has the doc
doc := v.Doc
if doc == nil {
doc = lastGen.Doc
}
f.lintTypeDoc(v, doc)
f.checkStutter(v.Name, "type")
// Don't proceed inside types.
return false
case *ast.ValueSpec:
f.lintValueSpecDoc(v, lastGen, genDeclMissingComments)
return false
}
return true
})
}
|
go
|
func (f *file) lintExported() {
if f.isTest() {
return
}
var lastGen *ast.GenDecl // last GenDecl entered.
// Set of GenDecls that have already had missing comments flagged.
genDeclMissingComments := make(map[*ast.GenDecl]bool)
f.walk(func(node ast.Node) bool {
switch v := node.(type) {
case *ast.GenDecl:
if v.Tok == token.IMPORT {
return false
}
// token.CONST, token.TYPE or token.VAR
lastGen = v
return true
case *ast.FuncDecl:
f.lintFuncDoc(v)
if v.Recv == nil {
// Only check for stutter on functions, not methods.
// Method names are not used package-qualified.
f.checkStutter(v.Name, "func")
}
// Don't proceed inside funcs.
return false
case *ast.TypeSpec:
// inside a GenDecl, which usually has the doc
doc := v.Doc
if doc == nil {
doc = lastGen.Doc
}
f.lintTypeDoc(v, doc)
f.checkStutter(v.Name, "type")
// Don't proceed inside types.
return false
case *ast.ValueSpec:
f.lintValueSpecDoc(v, lastGen, genDeclMissingComments)
return false
}
return true
})
}
|
[
"func",
"(",
"f",
"*",
"file",
")",
"lintExported",
"(",
")",
"{",
"if",
"f",
".",
"isTest",
"(",
")",
"{",
"return",
"\n",
"}",
"\n\n",
"var",
"lastGen",
"*",
"ast",
".",
"GenDecl",
"// last GenDecl entered.",
"\n\n",
"// Set of GenDecls that have already had missing comments flagged.",
"genDeclMissingComments",
":=",
"make",
"(",
"map",
"[",
"*",
"ast",
".",
"GenDecl",
"]",
"bool",
")",
"\n\n",
"f",
".",
"walk",
"(",
"func",
"(",
"node",
"ast",
".",
"Node",
")",
"bool",
"{",
"switch",
"v",
":=",
"node",
".",
"(",
"type",
")",
"{",
"case",
"*",
"ast",
".",
"GenDecl",
":",
"if",
"v",
".",
"Tok",
"==",
"token",
".",
"IMPORT",
"{",
"return",
"false",
"\n",
"}",
"\n",
"// token.CONST, token.TYPE or token.VAR",
"lastGen",
"=",
"v",
"\n",
"return",
"true",
"\n",
"case",
"*",
"ast",
".",
"FuncDecl",
":",
"f",
".",
"lintFuncDoc",
"(",
"v",
")",
"\n",
"if",
"v",
".",
"Recv",
"==",
"nil",
"{",
"// Only check for stutter on functions, not methods.",
"// Method names are not used package-qualified.",
"f",
".",
"checkStutter",
"(",
"v",
".",
"Name",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"// Don't proceed inside funcs.",
"return",
"false",
"\n",
"case",
"*",
"ast",
".",
"TypeSpec",
":",
"// inside a GenDecl, which usually has the doc",
"doc",
":=",
"v",
".",
"Doc",
"\n",
"if",
"doc",
"==",
"nil",
"{",
"doc",
"=",
"lastGen",
".",
"Doc",
"\n",
"}",
"\n",
"f",
".",
"lintTypeDoc",
"(",
"v",
",",
"doc",
")",
"\n",
"f",
".",
"checkStutter",
"(",
"v",
".",
"Name",
",",
"\"",
"\"",
")",
"\n",
"// Don't proceed inside types.",
"return",
"false",
"\n",
"case",
"*",
"ast",
".",
"ValueSpec",
":",
"f",
".",
"lintValueSpecDoc",
"(",
"v",
",",
"lastGen",
",",
"genDeclMissingComments",
")",
"\n",
"return",
"false",
"\n",
"}",
"\n",
"return",
"true",
"\n",
"}",
")",
"\n",
"}"
] |
// lintExported examines the exported names.
// It complains if any required doc comments are missing,
// or if they are not of the right form. The exact rules are in
// lintFuncDoc, lintTypeDoc and lintValueSpecDoc; this function
// also tracks the GenDecl structure being traversed to permit
// doc comments for constants to be on top of the const block.
// It also complains if the names stutter when combined with
// the package name.
|
[
"lintExported",
"examines",
"the",
"exported",
"names",
".",
"It",
"complains",
"if",
"any",
"required",
"doc",
"comments",
"are",
"missing",
"or",
"if",
"they",
"are",
"not",
"of",
"the",
"right",
"form",
".",
"The",
"exact",
"rules",
"are",
"in",
"lintFuncDoc",
"lintTypeDoc",
"and",
"lintValueSpecDoc",
";",
"this",
"function",
"also",
"tracks",
"the",
"GenDecl",
"structure",
"being",
"traversed",
"to",
"permit",
"doc",
"comments",
"for",
"constants",
"to",
"be",
"on",
"top",
"of",
"the",
"const",
"block",
".",
"It",
"also",
"complains",
"if",
"the",
"names",
"stutter",
"when",
"combined",
"with",
"the",
"package",
"name",
"."
] |
959b441ac422379a43da2230f62be024250818b0
|
https://github.com/golang/lint/blob/959b441ac422379a43da2230f62be024250818b0/lint.go#L484-L528
|
21,704
|
golang/lint
|
lint.go
|
lintTypeDoc
|
func (f *file) lintTypeDoc(t *ast.TypeSpec, doc *ast.CommentGroup) {
if !ast.IsExported(t.Name.Name) {
return
}
if doc == nil {
f.errorf(t, 1, link(docCommentsLink), category("comments"), "exported type %v should have comment or be unexported", t.Name)
return
}
s := doc.Text()
articles := [...]string{"A", "An", "The"}
for _, a := range articles {
if strings.HasPrefix(s, a+" ") {
s = s[len(a)+1:]
break
}
}
if !strings.HasPrefix(s, t.Name.Name+" ") {
f.errorf(doc, 1, link(docCommentsLink), category("comments"), `comment on exported type %v should be of the form "%v ..." (with optional leading article)`, t.Name, t.Name)
}
}
|
go
|
func (f *file) lintTypeDoc(t *ast.TypeSpec, doc *ast.CommentGroup) {
if !ast.IsExported(t.Name.Name) {
return
}
if doc == nil {
f.errorf(t, 1, link(docCommentsLink), category("comments"), "exported type %v should have comment or be unexported", t.Name)
return
}
s := doc.Text()
articles := [...]string{"A", "An", "The"}
for _, a := range articles {
if strings.HasPrefix(s, a+" ") {
s = s[len(a)+1:]
break
}
}
if !strings.HasPrefix(s, t.Name.Name+" ") {
f.errorf(doc, 1, link(docCommentsLink), category("comments"), `comment on exported type %v should be of the form "%v ..." (with optional leading article)`, t.Name, t.Name)
}
}
|
[
"func",
"(",
"f",
"*",
"file",
")",
"lintTypeDoc",
"(",
"t",
"*",
"ast",
".",
"TypeSpec",
",",
"doc",
"*",
"ast",
".",
"CommentGroup",
")",
"{",
"if",
"!",
"ast",
".",
"IsExported",
"(",
"t",
".",
"Name",
".",
"Name",
")",
"{",
"return",
"\n",
"}",
"\n",
"if",
"doc",
"==",
"nil",
"{",
"f",
".",
"errorf",
"(",
"t",
",",
"1",
",",
"link",
"(",
"docCommentsLink",
")",
",",
"category",
"(",
"\"",
"\"",
")",
",",
"\"",
"\"",
",",
"t",
".",
"Name",
")",
"\n",
"return",
"\n",
"}",
"\n\n",
"s",
":=",
"doc",
".",
"Text",
"(",
")",
"\n",
"articles",
":=",
"[",
"...",
"]",
"string",
"{",
"\"",
"\"",
",",
"\"",
"\"",
",",
"\"",
"\"",
"}",
"\n",
"for",
"_",
",",
"a",
":=",
"range",
"articles",
"{",
"if",
"strings",
".",
"HasPrefix",
"(",
"s",
",",
"a",
"+",
"\"",
"\"",
")",
"{",
"s",
"=",
"s",
"[",
"len",
"(",
"a",
")",
"+",
"1",
":",
"]",
"\n",
"break",
"\n",
"}",
"\n",
"}",
"\n",
"if",
"!",
"strings",
".",
"HasPrefix",
"(",
"s",
",",
"t",
".",
"Name",
".",
"Name",
"+",
"\"",
"\"",
")",
"{",
"f",
".",
"errorf",
"(",
"doc",
",",
"1",
",",
"link",
"(",
"docCommentsLink",
")",
",",
"category",
"(",
"\"",
"\"",
")",
",",
"`comment on exported type %v should be of the form \"%v ...\" (with optional leading article)`",
",",
"t",
".",
"Name",
",",
"t",
".",
"Name",
")",
"\n",
"}",
"\n",
"}"
] |
// lintTypeDoc examines the doc comment on a type.
// It complains if they are missing from an exported type,
// or if they are not of the standard form.
|
[
"lintTypeDoc",
"examines",
"the",
"doc",
"comment",
"on",
"a",
"type",
".",
"It",
"complains",
"if",
"they",
"are",
"missing",
"from",
"an",
"exported",
"type",
"or",
"if",
"they",
"are",
"not",
"of",
"the",
"standard",
"form",
"."
] |
959b441ac422379a43da2230f62be024250818b0
|
https://github.com/golang/lint/blob/959b441ac422379a43da2230f62be024250818b0/lint.go#L815-L835
|
21,705
|
golang/lint
|
lint.go
|
lintVarDecls
|
func (f *file) lintVarDecls() {
var lastGen *ast.GenDecl // last GenDecl entered.
f.walk(func(node ast.Node) bool {
switch v := node.(type) {
case *ast.GenDecl:
if v.Tok != token.CONST && v.Tok != token.VAR {
return false
}
lastGen = v
return true
case *ast.ValueSpec:
if lastGen.Tok == token.CONST {
return false
}
if len(v.Names) > 1 || v.Type == nil || len(v.Values) == 0 {
return false
}
rhs := v.Values[0]
// An underscore var appears in a common idiom for compile-time interface satisfaction,
// as in "var _ Interface = (*Concrete)(nil)".
if isIdent(v.Names[0], "_") {
return false
}
// If the RHS is a zero value, suggest dropping it.
zero := false
if lit, ok := rhs.(*ast.BasicLit); ok {
zero = zeroLiteral[lit.Value]
} else if isIdent(rhs, "nil") {
zero = true
}
if zero {
f.errorf(rhs, 0.9, category("zero-value"), "should drop = %s from declaration of var %s; it is the zero value", f.render(rhs), v.Names[0])
return false
}
lhsTyp := f.pkg.typeOf(v.Type)
rhsTyp := f.pkg.typeOf(rhs)
if !validType(lhsTyp) || !validType(rhsTyp) {
// Type checking failed (often due to missing imports).
return false
}
if !types.Identical(lhsTyp, rhsTyp) {
// Assignment to a different type is not redundant.
return false
}
// The next three conditions are for suppressing the warning in situations
// where we were unable to typecheck.
// If the LHS type is an interface, don't warn, since it is probably a
// concrete type on the RHS. Note that our feeble lexical check here
// will only pick up interface{} and other literal interface types;
// that covers most of the cases we care to exclude right now.
if _, ok := v.Type.(*ast.InterfaceType); ok {
return false
}
// If the RHS is an untyped const, only warn if the LHS type is its default type.
if defType, ok := f.isUntypedConst(rhs); ok && !isIdent(v.Type, defType) {
return false
}
f.errorf(v.Type, 0.8, category("type-inference"), "should omit type %s from declaration of var %s; it will be inferred from the right-hand side", f.render(v.Type), v.Names[0])
return false
}
return true
})
}
|
go
|
func (f *file) lintVarDecls() {
var lastGen *ast.GenDecl // last GenDecl entered.
f.walk(func(node ast.Node) bool {
switch v := node.(type) {
case *ast.GenDecl:
if v.Tok != token.CONST && v.Tok != token.VAR {
return false
}
lastGen = v
return true
case *ast.ValueSpec:
if lastGen.Tok == token.CONST {
return false
}
if len(v.Names) > 1 || v.Type == nil || len(v.Values) == 0 {
return false
}
rhs := v.Values[0]
// An underscore var appears in a common idiom for compile-time interface satisfaction,
// as in "var _ Interface = (*Concrete)(nil)".
if isIdent(v.Names[0], "_") {
return false
}
// If the RHS is a zero value, suggest dropping it.
zero := false
if lit, ok := rhs.(*ast.BasicLit); ok {
zero = zeroLiteral[lit.Value]
} else if isIdent(rhs, "nil") {
zero = true
}
if zero {
f.errorf(rhs, 0.9, category("zero-value"), "should drop = %s from declaration of var %s; it is the zero value", f.render(rhs), v.Names[0])
return false
}
lhsTyp := f.pkg.typeOf(v.Type)
rhsTyp := f.pkg.typeOf(rhs)
if !validType(lhsTyp) || !validType(rhsTyp) {
// Type checking failed (often due to missing imports).
return false
}
if !types.Identical(lhsTyp, rhsTyp) {
// Assignment to a different type is not redundant.
return false
}
// The next three conditions are for suppressing the warning in situations
// where we were unable to typecheck.
// If the LHS type is an interface, don't warn, since it is probably a
// concrete type on the RHS. Note that our feeble lexical check here
// will only pick up interface{} and other literal interface types;
// that covers most of the cases we care to exclude right now.
if _, ok := v.Type.(*ast.InterfaceType); ok {
return false
}
// If the RHS is an untyped const, only warn if the LHS type is its default type.
if defType, ok := f.isUntypedConst(rhs); ok && !isIdent(v.Type, defType) {
return false
}
f.errorf(v.Type, 0.8, category("type-inference"), "should omit type %s from declaration of var %s; it will be inferred from the right-hand side", f.render(v.Type), v.Names[0])
return false
}
return true
})
}
|
[
"func",
"(",
"f",
"*",
"file",
")",
"lintVarDecls",
"(",
")",
"{",
"var",
"lastGen",
"*",
"ast",
".",
"GenDecl",
"// last GenDecl entered.",
"\n\n",
"f",
".",
"walk",
"(",
"func",
"(",
"node",
"ast",
".",
"Node",
")",
"bool",
"{",
"switch",
"v",
":=",
"node",
".",
"(",
"type",
")",
"{",
"case",
"*",
"ast",
".",
"GenDecl",
":",
"if",
"v",
".",
"Tok",
"!=",
"token",
".",
"CONST",
"&&",
"v",
".",
"Tok",
"!=",
"token",
".",
"VAR",
"{",
"return",
"false",
"\n",
"}",
"\n",
"lastGen",
"=",
"v",
"\n",
"return",
"true",
"\n",
"case",
"*",
"ast",
".",
"ValueSpec",
":",
"if",
"lastGen",
".",
"Tok",
"==",
"token",
".",
"CONST",
"{",
"return",
"false",
"\n",
"}",
"\n",
"if",
"len",
"(",
"v",
".",
"Names",
")",
">",
"1",
"||",
"v",
".",
"Type",
"==",
"nil",
"||",
"len",
"(",
"v",
".",
"Values",
")",
"==",
"0",
"{",
"return",
"false",
"\n",
"}",
"\n",
"rhs",
":=",
"v",
".",
"Values",
"[",
"0",
"]",
"\n",
"// An underscore var appears in a common idiom for compile-time interface satisfaction,",
"// as in \"var _ Interface = (*Concrete)(nil)\".",
"if",
"isIdent",
"(",
"v",
".",
"Names",
"[",
"0",
"]",
",",
"\"",
"\"",
")",
"{",
"return",
"false",
"\n",
"}",
"\n",
"// If the RHS is a zero value, suggest dropping it.",
"zero",
":=",
"false",
"\n",
"if",
"lit",
",",
"ok",
":=",
"rhs",
".",
"(",
"*",
"ast",
".",
"BasicLit",
")",
";",
"ok",
"{",
"zero",
"=",
"zeroLiteral",
"[",
"lit",
".",
"Value",
"]",
"\n",
"}",
"else",
"if",
"isIdent",
"(",
"rhs",
",",
"\"",
"\"",
")",
"{",
"zero",
"=",
"true",
"\n",
"}",
"\n",
"if",
"zero",
"{",
"f",
".",
"errorf",
"(",
"rhs",
",",
"0.9",
",",
"category",
"(",
"\"",
"\"",
")",
",",
"\"",
"\"",
",",
"f",
".",
"render",
"(",
"rhs",
")",
",",
"v",
".",
"Names",
"[",
"0",
"]",
")",
"\n",
"return",
"false",
"\n",
"}",
"\n",
"lhsTyp",
":=",
"f",
".",
"pkg",
".",
"typeOf",
"(",
"v",
".",
"Type",
")",
"\n",
"rhsTyp",
":=",
"f",
".",
"pkg",
".",
"typeOf",
"(",
"rhs",
")",
"\n\n",
"if",
"!",
"validType",
"(",
"lhsTyp",
")",
"||",
"!",
"validType",
"(",
"rhsTyp",
")",
"{",
"// Type checking failed (often due to missing imports).",
"return",
"false",
"\n",
"}",
"\n\n",
"if",
"!",
"types",
".",
"Identical",
"(",
"lhsTyp",
",",
"rhsTyp",
")",
"{",
"// Assignment to a different type is not redundant.",
"return",
"false",
"\n",
"}",
"\n\n",
"// The next three conditions are for suppressing the warning in situations",
"// where we were unable to typecheck.",
"// If the LHS type is an interface, don't warn, since it is probably a",
"// concrete type on the RHS. Note that our feeble lexical check here",
"// will only pick up interface{} and other literal interface types;",
"// that covers most of the cases we care to exclude right now.",
"if",
"_",
",",
"ok",
":=",
"v",
".",
"Type",
".",
"(",
"*",
"ast",
".",
"InterfaceType",
")",
";",
"ok",
"{",
"return",
"false",
"\n",
"}",
"\n",
"// If the RHS is an untyped const, only warn if the LHS type is its default type.",
"if",
"defType",
",",
"ok",
":=",
"f",
".",
"isUntypedConst",
"(",
"rhs",
")",
";",
"ok",
"&&",
"!",
"isIdent",
"(",
"v",
".",
"Type",
",",
"defType",
")",
"{",
"return",
"false",
"\n",
"}",
"\n\n",
"f",
".",
"errorf",
"(",
"v",
".",
"Type",
",",
"0.8",
",",
"category",
"(",
"\"",
"\"",
")",
",",
"\"",
"\"",
",",
"f",
".",
"render",
"(",
"v",
".",
"Type",
")",
",",
"v",
".",
"Names",
"[",
"0",
"]",
")",
"\n",
"return",
"false",
"\n",
"}",
"\n",
"return",
"true",
"\n",
"}",
")",
"\n",
"}"
] |
// lintVarDecls examines variable declarations. It complains about declarations with
// redundant LHS types that can be inferred from the RHS.
|
[
"lintVarDecls",
"examines",
"variable",
"declarations",
".",
"It",
"complains",
"about",
"declarations",
"with",
"redundant",
"LHS",
"types",
"that",
"can",
"be",
"inferred",
"from",
"the",
"RHS",
"."
] |
959b441ac422379a43da2230f62be024250818b0
|
https://github.com/golang/lint/blob/959b441ac422379a43da2230f62be024250818b0/lint.go#L982-L1050
|
21,706
|
golang/lint
|
lint.go
|
lintElses
|
func (f *file) lintElses() {
// We don't want to flag if { } else if { } else { } constructions.
// They will appear as an IfStmt whose Else field is also an IfStmt.
// Record such a node so we ignore it when we visit it.
ignore := make(map[*ast.IfStmt]bool)
f.walk(func(node ast.Node) bool {
ifStmt, ok := node.(*ast.IfStmt)
if !ok || ifStmt.Else == nil {
return true
}
if elseif, ok := ifStmt.Else.(*ast.IfStmt); ok {
ignore[elseif] = true
return true
}
if ignore[ifStmt] {
return true
}
if _, ok := ifStmt.Else.(*ast.BlockStmt); !ok {
// only care about elses without conditions
return true
}
if len(ifStmt.Body.List) == 0 {
return true
}
shortDecl := false // does the if statement have a ":=" initialization statement?
if ifStmt.Init != nil {
if as, ok := ifStmt.Init.(*ast.AssignStmt); ok && as.Tok == token.DEFINE {
shortDecl = true
}
}
lastStmt := ifStmt.Body.List[len(ifStmt.Body.List)-1]
if _, ok := lastStmt.(*ast.ReturnStmt); ok {
extra := ""
if shortDecl {
extra = " (move short variable declaration to its own line if necessary)"
}
f.errorf(ifStmt.Else, 1, link(styleGuideBase+"#indent-error-flow"), category("indent"), "if block ends with a return statement, so drop this else and outdent its block"+extra)
}
return true
})
}
|
go
|
func (f *file) lintElses() {
// We don't want to flag if { } else if { } else { } constructions.
// They will appear as an IfStmt whose Else field is also an IfStmt.
// Record such a node so we ignore it when we visit it.
ignore := make(map[*ast.IfStmt]bool)
f.walk(func(node ast.Node) bool {
ifStmt, ok := node.(*ast.IfStmt)
if !ok || ifStmt.Else == nil {
return true
}
if elseif, ok := ifStmt.Else.(*ast.IfStmt); ok {
ignore[elseif] = true
return true
}
if ignore[ifStmt] {
return true
}
if _, ok := ifStmt.Else.(*ast.BlockStmt); !ok {
// only care about elses without conditions
return true
}
if len(ifStmt.Body.List) == 0 {
return true
}
shortDecl := false // does the if statement have a ":=" initialization statement?
if ifStmt.Init != nil {
if as, ok := ifStmt.Init.(*ast.AssignStmt); ok && as.Tok == token.DEFINE {
shortDecl = true
}
}
lastStmt := ifStmt.Body.List[len(ifStmt.Body.List)-1]
if _, ok := lastStmt.(*ast.ReturnStmt); ok {
extra := ""
if shortDecl {
extra = " (move short variable declaration to its own line if necessary)"
}
f.errorf(ifStmt.Else, 1, link(styleGuideBase+"#indent-error-flow"), category("indent"), "if block ends with a return statement, so drop this else and outdent its block"+extra)
}
return true
})
}
|
[
"func",
"(",
"f",
"*",
"file",
")",
"lintElses",
"(",
")",
"{",
"// We don't want to flag if { } else if { } else { } constructions.",
"// They will appear as an IfStmt whose Else field is also an IfStmt.",
"// Record such a node so we ignore it when we visit it.",
"ignore",
":=",
"make",
"(",
"map",
"[",
"*",
"ast",
".",
"IfStmt",
"]",
"bool",
")",
"\n\n",
"f",
".",
"walk",
"(",
"func",
"(",
"node",
"ast",
".",
"Node",
")",
"bool",
"{",
"ifStmt",
",",
"ok",
":=",
"node",
".",
"(",
"*",
"ast",
".",
"IfStmt",
")",
"\n",
"if",
"!",
"ok",
"||",
"ifStmt",
".",
"Else",
"==",
"nil",
"{",
"return",
"true",
"\n",
"}",
"\n",
"if",
"elseif",
",",
"ok",
":=",
"ifStmt",
".",
"Else",
".",
"(",
"*",
"ast",
".",
"IfStmt",
")",
";",
"ok",
"{",
"ignore",
"[",
"elseif",
"]",
"=",
"true",
"\n",
"return",
"true",
"\n",
"}",
"\n",
"if",
"ignore",
"[",
"ifStmt",
"]",
"{",
"return",
"true",
"\n",
"}",
"\n",
"if",
"_",
",",
"ok",
":=",
"ifStmt",
".",
"Else",
".",
"(",
"*",
"ast",
".",
"BlockStmt",
")",
";",
"!",
"ok",
"{",
"// only care about elses without conditions",
"return",
"true",
"\n",
"}",
"\n",
"if",
"len",
"(",
"ifStmt",
".",
"Body",
".",
"List",
")",
"==",
"0",
"{",
"return",
"true",
"\n",
"}",
"\n",
"shortDecl",
":=",
"false",
"// does the if statement have a \":=\" initialization statement?",
"\n",
"if",
"ifStmt",
".",
"Init",
"!=",
"nil",
"{",
"if",
"as",
",",
"ok",
":=",
"ifStmt",
".",
"Init",
".",
"(",
"*",
"ast",
".",
"AssignStmt",
")",
";",
"ok",
"&&",
"as",
".",
"Tok",
"==",
"token",
".",
"DEFINE",
"{",
"shortDecl",
"=",
"true",
"\n",
"}",
"\n",
"}",
"\n",
"lastStmt",
":=",
"ifStmt",
".",
"Body",
".",
"List",
"[",
"len",
"(",
"ifStmt",
".",
"Body",
".",
"List",
")",
"-",
"1",
"]",
"\n",
"if",
"_",
",",
"ok",
":=",
"lastStmt",
".",
"(",
"*",
"ast",
".",
"ReturnStmt",
")",
";",
"ok",
"{",
"extra",
":=",
"\"",
"\"",
"\n",
"if",
"shortDecl",
"{",
"extra",
"=",
"\"",
"\"",
"\n",
"}",
"\n",
"f",
".",
"errorf",
"(",
"ifStmt",
".",
"Else",
",",
"1",
",",
"link",
"(",
"styleGuideBase",
"+",
"\"",
"\"",
")",
",",
"category",
"(",
"\"",
"\"",
")",
",",
"\"",
"\"",
"+",
"extra",
")",
"\n",
"}",
"\n",
"return",
"true",
"\n",
"}",
")",
"\n",
"}"
] |
// lintElses examines else blocks. It complains about any else block whose if block ends in a return.
|
[
"lintElses",
"examines",
"else",
"blocks",
".",
"It",
"complains",
"about",
"any",
"else",
"block",
"whose",
"if",
"block",
"ends",
"in",
"a",
"return",
"."
] |
959b441ac422379a43da2230f62be024250818b0
|
https://github.com/golang/lint/blob/959b441ac422379a43da2230f62be024250818b0/lint.go#L1059-L1100
|
21,707
|
golang/lint
|
lint.go
|
lintRanges
|
func (f *file) lintRanges() {
f.walk(func(node ast.Node) bool {
rs, ok := node.(*ast.RangeStmt)
if !ok {
return true
}
if isIdent(rs.Key, "_") && (rs.Value == nil || isIdent(rs.Value, "_")) {
p := f.errorf(rs.Key, 1, category("range-loop"), "should omit values from range; this loop is equivalent to `for range ...`")
newRS := *rs // shallow copy
newRS.Value = nil
newRS.Key = nil
p.ReplacementLine = f.firstLineOf(&newRS, rs)
return true
}
if isIdent(rs.Value, "_") {
p := f.errorf(rs.Value, 1, category("range-loop"), "should omit 2nd value from range; this loop is equivalent to `for %s %s range ...`", f.render(rs.Key), rs.Tok)
newRS := *rs // shallow copy
newRS.Value = nil
p.ReplacementLine = f.firstLineOf(&newRS, rs)
}
return true
})
}
|
go
|
func (f *file) lintRanges() {
f.walk(func(node ast.Node) bool {
rs, ok := node.(*ast.RangeStmt)
if !ok {
return true
}
if isIdent(rs.Key, "_") && (rs.Value == nil || isIdent(rs.Value, "_")) {
p := f.errorf(rs.Key, 1, category("range-loop"), "should omit values from range; this loop is equivalent to `for range ...`")
newRS := *rs // shallow copy
newRS.Value = nil
newRS.Key = nil
p.ReplacementLine = f.firstLineOf(&newRS, rs)
return true
}
if isIdent(rs.Value, "_") {
p := f.errorf(rs.Value, 1, category("range-loop"), "should omit 2nd value from range; this loop is equivalent to `for %s %s range ...`", f.render(rs.Key), rs.Tok)
newRS := *rs // shallow copy
newRS.Value = nil
p.ReplacementLine = f.firstLineOf(&newRS, rs)
}
return true
})
}
|
[
"func",
"(",
"f",
"*",
"file",
")",
"lintRanges",
"(",
")",
"{",
"f",
".",
"walk",
"(",
"func",
"(",
"node",
"ast",
".",
"Node",
")",
"bool",
"{",
"rs",
",",
"ok",
":=",
"node",
".",
"(",
"*",
"ast",
".",
"RangeStmt",
")",
"\n",
"if",
"!",
"ok",
"{",
"return",
"true",
"\n",
"}",
"\n\n",
"if",
"isIdent",
"(",
"rs",
".",
"Key",
",",
"\"",
"\"",
")",
"&&",
"(",
"rs",
".",
"Value",
"==",
"nil",
"||",
"isIdent",
"(",
"rs",
".",
"Value",
",",
"\"",
"\"",
")",
")",
"{",
"p",
":=",
"f",
".",
"errorf",
"(",
"rs",
".",
"Key",
",",
"1",
",",
"category",
"(",
"\"",
"\"",
")",
",",
"\"",
"\"",
")",
"\n\n",
"newRS",
":=",
"*",
"rs",
"// shallow copy",
"\n",
"newRS",
".",
"Value",
"=",
"nil",
"\n",
"newRS",
".",
"Key",
"=",
"nil",
"\n",
"p",
".",
"ReplacementLine",
"=",
"f",
".",
"firstLineOf",
"(",
"&",
"newRS",
",",
"rs",
")",
"\n\n",
"return",
"true",
"\n",
"}",
"\n\n",
"if",
"isIdent",
"(",
"rs",
".",
"Value",
",",
"\"",
"\"",
")",
"{",
"p",
":=",
"f",
".",
"errorf",
"(",
"rs",
".",
"Value",
",",
"1",
",",
"category",
"(",
"\"",
"\"",
")",
",",
"\"",
"\"",
",",
"f",
".",
"render",
"(",
"rs",
".",
"Key",
")",
",",
"rs",
".",
"Tok",
")",
"\n\n",
"newRS",
":=",
"*",
"rs",
"// shallow copy",
"\n",
"newRS",
".",
"Value",
"=",
"nil",
"\n",
"p",
".",
"ReplacementLine",
"=",
"f",
".",
"firstLineOf",
"(",
"&",
"newRS",
",",
"rs",
")",
"\n",
"}",
"\n\n",
"return",
"true",
"\n",
"}",
")",
"\n",
"}"
] |
// lintRanges examines range clauses. It complains about redundant constructions.
|
[
"lintRanges",
"examines",
"range",
"clauses",
".",
"It",
"complains",
"about",
"redundant",
"constructions",
"."
] |
959b441ac422379a43da2230f62be024250818b0
|
https://github.com/golang/lint/blob/959b441ac422379a43da2230f62be024250818b0/lint.go#L1103-L1131
|
21,708
|
golang/lint
|
lint.go
|
lintErrorf
|
func (f *file) lintErrorf() {
f.walk(func(node ast.Node) bool {
ce, ok := node.(*ast.CallExpr)
if !ok || len(ce.Args) != 1 {
return true
}
isErrorsNew := isPkgDot(ce.Fun, "errors", "New")
var isTestingError bool
se, ok := ce.Fun.(*ast.SelectorExpr)
if ok && se.Sel.Name == "Error" {
if typ := f.pkg.typeOf(se.X); typ != nil {
isTestingError = typ.String() == "*testing.T"
}
}
if !isErrorsNew && !isTestingError {
return true
}
if !f.imports("errors") {
return true
}
arg := ce.Args[0]
ce, ok = arg.(*ast.CallExpr)
if !ok || !isPkgDot(ce.Fun, "fmt", "Sprintf") {
return true
}
errorfPrefix := "fmt"
if isTestingError {
errorfPrefix = f.render(se.X)
}
p := f.errorf(node, 1, category("errors"), "should replace %s(fmt.Sprintf(...)) with %s.Errorf(...)", f.render(se), errorfPrefix)
m := f.srcLineWithMatch(ce, `^(.*)`+f.render(se)+`\(fmt\.Sprintf\((.*)\)\)(.*)$`)
if m != nil {
p.ReplacementLine = m[1] + errorfPrefix + ".Errorf(" + m[2] + ")" + m[3]
}
return true
})
}
|
go
|
func (f *file) lintErrorf() {
f.walk(func(node ast.Node) bool {
ce, ok := node.(*ast.CallExpr)
if !ok || len(ce.Args) != 1 {
return true
}
isErrorsNew := isPkgDot(ce.Fun, "errors", "New")
var isTestingError bool
se, ok := ce.Fun.(*ast.SelectorExpr)
if ok && se.Sel.Name == "Error" {
if typ := f.pkg.typeOf(se.X); typ != nil {
isTestingError = typ.String() == "*testing.T"
}
}
if !isErrorsNew && !isTestingError {
return true
}
if !f.imports("errors") {
return true
}
arg := ce.Args[0]
ce, ok = arg.(*ast.CallExpr)
if !ok || !isPkgDot(ce.Fun, "fmt", "Sprintf") {
return true
}
errorfPrefix := "fmt"
if isTestingError {
errorfPrefix = f.render(se.X)
}
p := f.errorf(node, 1, category("errors"), "should replace %s(fmt.Sprintf(...)) with %s.Errorf(...)", f.render(se), errorfPrefix)
m := f.srcLineWithMatch(ce, `^(.*)`+f.render(se)+`\(fmt\.Sprintf\((.*)\)\)(.*)$`)
if m != nil {
p.ReplacementLine = m[1] + errorfPrefix + ".Errorf(" + m[2] + ")" + m[3]
}
return true
})
}
|
[
"func",
"(",
"f",
"*",
"file",
")",
"lintErrorf",
"(",
")",
"{",
"f",
".",
"walk",
"(",
"func",
"(",
"node",
"ast",
".",
"Node",
")",
"bool",
"{",
"ce",
",",
"ok",
":=",
"node",
".",
"(",
"*",
"ast",
".",
"CallExpr",
")",
"\n",
"if",
"!",
"ok",
"||",
"len",
"(",
"ce",
".",
"Args",
")",
"!=",
"1",
"{",
"return",
"true",
"\n",
"}",
"\n",
"isErrorsNew",
":=",
"isPkgDot",
"(",
"ce",
".",
"Fun",
",",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\n",
"var",
"isTestingError",
"bool",
"\n",
"se",
",",
"ok",
":=",
"ce",
".",
"Fun",
".",
"(",
"*",
"ast",
".",
"SelectorExpr",
")",
"\n",
"if",
"ok",
"&&",
"se",
".",
"Sel",
".",
"Name",
"==",
"\"",
"\"",
"{",
"if",
"typ",
":=",
"f",
".",
"pkg",
".",
"typeOf",
"(",
"se",
".",
"X",
")",
";",
"typ",
"!=",
"nil",
"{",
"isTestingError",
"=",
"typ",
".",
"String",
"(",
")",
"==",
"\"",
"\"",
"\n",
"}",
"\n",
"}",
"\n",
"if",
"!",
"isErrorsNew",
"&&",
"!",
"isTestingError",
"{",
"return",
"true",
"\n",
"}",
"\n",
"if",
"!",
"f",
".",
"imports",
"(",
"\"",
"\"",
")",
"{",
"return",
"true",
"\n",
"}",
"\n",
"arg",
":=",
"ce",
".",
"Args",
"[",
"0",
"]",
"\n",
"ce",
",",
"ok",
"=",
"arg",
".",
"(",
"*",
"ast",
".",
"CallExpr",
")",
"\n",
"if",
"!",
"ok",
"||",
"!",
"isPkgDot",
"(",
"ce",
".",
"Fun",
",",
"\"",
"\"",
",",
"\"",
"\"",
")",
"{",
"return",
"true",
"\n",
"}",
"\n",
"errorfPrefix",
":=",
"\"",
"\"",
"\n",
"if",
"isTestingError",
"{",
"errorfPrefix",
"=",
"f",
".",
"render",
"(",
"se",
".",
"X",
")",
"\n",
"}",
"\n",
"p",
":=",
"f",
".",
"errorf",
"(",
"node",
",",
"1",
",",
"category",
"(",
"\"",
"\"",
")",
",",
"\"",
"\"",
",",
"f",
".",
"render",
"(",
"se",
")",
",",
"errorfPrefix",
")",
"\n\n",
"m",
":=",
"f",
".",
"srcLineWithMatch",
"(",
"ce",
",",
"`^(.*)`",
"+",
"f",
".",
"render",
"(",
"se",
")",
"+",
"`\\(fmt\\.Sprintf\\((.*)\\)\\)(.*)$`",
")",
"\n",
"if",
"m",
"!=",
"nil",
"{",
"p",
".",
"ReplacementLine",
"=",
"m",
"[",
"1",
"]",
"+",
"errorfPrefix",
"+",
"\"",
"\"",
"+",
"m",
"[",
"2",
"]",
"+",
"\"",
"\"",
"+",
"m",
"[",
"3",
"]",
"\n",
"}",
"\n\n",
"return",
"true",
"\n",
"}",
")",
"\n",
"}"
] |
// lintErrorf examines errors.New and testing.Error calls. It complains if its only argument is an fmt.Sprintf invocation.
|
[
"lintErrorf",
"examines",
"errors",
".",
"New",
"and",
"testing",
".",
"Error",
"calls",
".",
"It",
"complains",
"if",
"its",
"only",
"argument",
"is",
"an",
"fmt",
".",
"Sprintf",
"invocation",
"."
] |
959b441ac422379a43da2230f62be024250818b0
|
https://github.com/golang/lint/blob/959b441ac422379a43da2230f62be024250818b0/lint.go#L1134-L1172
|
21,709
|
golang/lint
|
lint.go
|
lintErrors
|
func (f *file) lintErrors() {
for _, decl := range f.f.Decls {
gd, ok := decl.(*ast.GenDecl)
if !ok || gd.Tok != token.VAR {
continue
}
for _, spec := range gd.Specs {
spec := spec.(*ast.ValueSpec)
if len(spec.Names) != 1 || len(spec.Values) != 1 {
continue
}
ce, ok := spec.Values[0].(*ast.CallExpr)
if !ok {
continue
}
if !isPkgDot(ce.Fun, "errors", "New") && !isPkgDot(ce.Fun, "fmt", "Errorf") {
continue
}
id := spec.Names[0]
prefix := "err"
if id.IsExported() {
prefix = "Err"
}
if !strings.HasPrefix(id.Name, prefix) {
f.errorf(id, 0.9, category("naming"), "error var %s should have name of the form %sFoo", id.Name, prefix)
}
}
}
}
|
go
|
func (f *file) lintErrors() {
for _, decl := range f.f.Decls {
gd, ok := decl.(*ast.GenDecl)
if !ok || gd.Tok != token.VAR {
continue
}
for _, spec := range gd.Specs {
spec := spec.(*ast.ValueSpec)
if len(spec.Names) != 1 || len(spec.Values) != 1 {
continue
}
ce, ok := spec.Values[0].(*ast.CallExpr)
if !ok {
continue
}
if !isPkgDot(ce.Fun, "errors", "New") && !isPkgDot(ce.Fun, "fmt", "Errorf") {
continue
}
id := spec.Names[0]
prefix := "err"
if id.IsExported() {
prefix = "Err"
}
if !strings.HasPrefix(id.Name, prefix) {
f.errorf(id, 0.9, category("naming"), "error var %s should have name of the form %sFoo", id.Name, prefix)
}
}
}
}
|
[
"func",
"(",
"f",
"*",
"file",
")",
"lintErrors",
"(",
")",
"{",
"for",
"_",
",",
"decl",
":=",
"range",
"f",
".",
"f",
".",
"Decls",
"{",
"gd",
",",
"ok",
":=",
"decl",
".",
"(",
"*",
"ast",
".",
"GenDecl",
")",
"\n",
"if",
"!",
"ok",
"||",
"gd",
".",
"Tok",
"!=",
"token",
".",
"VAR",
"{",
"continue",
"\n",
"}",
"\n",
"for",
"_",
",",
"spec",
":=",
"range",
"gd",
".",
"Specs",
"{",
"spec",
":=",
"spec",
".",
"(",
"*",
"ast",
".",
"ValueSpec",
")",
"\n",
"if",
"len",
"(",
"spec",
".",
"Names",
")",
"!=",
"1",
"||",
"len",
"(",
"spec",
".",
"Values",
")",
"!=",
"1",
"{",
"continue",
"\n",
"}",
"\n",
"ce",
",",
"ok",
":=",
"spec",
".",
"Values",
"[",
"0",
"]",
".",
"(",
"*",
"ast",
".",
"CallExpr",
")",
"\n",
"if",
"!",
"ok",
"{",
"continue",
"\n",
"}",
"\n",
"if",
"!",
"isPkgDot",
"(",
"ce",
".",
"Fun",
",",
"\"",
"\"",
",",
"\"",
"\"",
")",
"&&",
"!",
"isPkgDot",
"(",
"ce",
".",
"Fun",
",",
"\"",
"\"",
",",
"\"",
"\"",
")",
"{",
"continue",
"\n",
"}",
"\n\n",
"id",
":=",
"spec",
".",
"Names",
"[",
"0",
"]",
"\n",
"prefix",
":=",
"\"",
"\"",
"\n",
"if",
"id",
".",
"IsExported",
"(",
")",
"{",
"prefix",
"=",
"\"",
"\"",
"\n",
"}",
"\n",
"if",
"!",
"strings",
".",
"HasPrefix",
"(",
"id",
".",
"Name",
",",
"prefix",
")",
"{",
"f",
".",
"errorf",
"(",
"id",
",",
"0.9",
",",
"category",
"(",
"\"",
"\"",
")",
",",
"\"",
"\"",
",",
"id",
".",
"Name",
",",
"prefix",
")",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n",
"}"
] |
// lintErrors examines global error vars. It complains if they aren't named in the standard way.
|
[
"lintErrors",
"examines",
"global",
"error",
"vars",
".",
"It",
"complains",
"if",
"they",
"aren",
"t",
"named",
"in",
"the",
"standard",
"way",
"."
] |
959b441ac422379a43da2230f62be024250818b0
|
https://github.com/golang/lint/blob/959b441ac422379a43da2230f62be024250818b0/lint.go#L1175-L1204
|
21,710
|
golang/lint
|
lint.go
|
lintErrorStrings
|
func (f *file) lintErrorStrings() {
f.walk(func(node ast.Node) bool {
ce, ok := node.(*ast.CallExpr)
if !ok {
return true
}
if !isPkgDot(ce.Fun, "errors", "New") && !isPkgDot(ce.Fun, "fmt", "Errorf") {
return true
}
if len(ce.Args) < 1 {
return true
}
str, ok := ce.Args[0].(*ast.BasicLit)
if !ok || str.Kind != token.STRING {
return true
}
s, _ := strconv.Unquote(str.Value) // can assume well-formed Go
if s == "" {
return true
}
clean, conf := lintErrorString(s)
if clean {
return true
}
f.errorf(str, conf, link(styleGuideBase+"#error-strings"), category("errors"),
"error strings should not be capitalized or end with punctuation or a newline")
return true
})
}
|
go
|
func (f *file) lintErrorStrings() {
f.walk(func(node ast.Node) bool {
ce, ok := node.(*ast.CallExpr)
if !ok {
return true
}
if !isPkgDot(ce.Fun, "errors", "New") && !isPkgDot(ce.Fun, "fmt", "Errorf") {
return true
}
if len(ce.Args) < 1 {
return true
}
str, ok := ce.Args[0].(*ast.BasicLit)
if !ok || str.Kind != token.STRING {
return true
}
s, _ := strconv.Unquote(str.Value) // can assume well-formed Go
if s == "" {
return true
}
clean, conf := lintErrorString(s)
if clean {
return true
}
f.errorf(str, conf, link(styleGuideBase+"#error-strings"), category("errors"),
"error strings should not be capitalized or end with punctuation or a newline")
return true
})
}
|
[
"func",
"(",
"f",
"*",
"file",
")",
"lintErrorStrings",
"(",
")",
"{",
"f",
".",
"walk",
"(",
"func",
"(",
"node",
"ast",
".",
"Node",
")",
"bool",
"{",
"ce",
",",
"ok",
":=",
"node",
".",
"(",
"*",
"ast",
".",
"CallExpr",
")",
"\n",
"if",
"!",
"ok",
"{",
"return",
"true",
"\n",
"}",
"\n",
"if",
"!",
"isPkgDot",
"(",
"ce",
".",
"Fun",
",",
"\"",
"\"",
",",
"\"",
"\"",
")",
"&&",
"!",
"isPkgDot",
"(",
"ce",
".",
"Fun",
",",
"\"",
"\"",
",",
"\"",
"\"",
")",
"{",
"return",
"true",
"\n",
"}",
"\n",
"if",
"len",
"(",
"ce",
".",
"Args",
")",
"<",
"1",
"{",
"return",
"true",
"\n",
"}",
"\n",
"str",
",",
"ok",
":=",
"ce",
".",
"Args",
"[",
"0",
"]",
".",
"(",
"*",
"ast",
".",
"BasicLit",
")",
"\n",
"if",
"!",
"ok",
"||",
"str",
".",
"Kind",
"!=",
"token",
".",
"STRING",
"{",
"return",
"true",
"\n",
"}",
"\n",
"s",
",",
"_",
":=",
"strconv",
".",
"Unquote",
"(",
"str",
".",
"Value",
")",
"// can assume well-formed Go",
"\n",
"if",
"s",
"==",
"\"",
"\"",
"{",
"return",
"true",
"\n",
"}",
"\n",
"clean",
",",
"conf",
":=",
"lintErrorString",
"(",
"s",
")",
"\n",
"if",
"clean",
"{",
"return",
"true",
"\n",
"}",
"\n\n",
"f",
".",
"errorf",
"(",
"str",
",",
"conf",
",",
"link",
"(",
"styleGuideBase",
"+",
"\"",
"\"",
")",
",",
"category",
"(",
"\"",
"\"",
")",
",",
"\"",
"\"",
")",
"\n",
"return",
"true",
"\n",
"}",
")",
"\n",
"}"
] |
// lintErrorStrings examines error strings.
// It complains if they are capitalized or end in punctuation or a newline.
|
[
"lintErrorStrings",
"examines",
"error",
"strings",
".",
"It",
"complains",
"if",
"they",
"are",
"capitalized",
"or",
"end",
"in",
"punctuation",
"or",
"a",
"newline",
"."
] |
959b441ac422379a43da2230f62be024250818b0
|
https://github.com/golang/lint/blob/959b441ac422379a43da2230f62be024250818b0/lint.go#L1230-L1259
|
21,711
|
golang/lint
|
lint.go
|
lintReceiverNames
|
func (f *file) lintReceiverNames() {
typeReceiver := map[string]string{}
f.walk(func(n ast.Node) bool {
fn, ok := n.(*ast.FuncDecl)
if !ok || fn.Recv == nil || len(fn.Recv.List) == 0 {
return true
}
names := fn.Recv.List[0].Names
if len(names) < 1 {
return true
}
name := names[0].Name
const ref = styleGuideBase + "#receiver-names"
if name == "_" {
f.errorf(n, 1, link(ref), category("naming"), `receiver name should not be an underscore, omit the name if it is unused`)
return true
}
if name == "this" || name == "self" {
f.errorf(n, 1, link(ref), category("naming"), `receiver name should be a reflection of its identity; don't use generic names such as "this" or "self"`)
return true
}
recv := receiverType(fn)
if prev, ok := typeReceiver[recv]; ok && prev != name {
f.errorf(n, 1, link(ref), category("naming"), "receiver name %s should be consistent with previous receiver name %s for %s", name, prev, recv)
return true
}
typeReceiver[recv] = name
return true
})
}
|
go
|
func (f *file) lintReceiverNames() {
typeReceiver := map[string]string{}
f.walk(func(n ast.Node) bool {
fn, ok := n.(*ast.FuncDecl)
if !ok || fn.Recv == nil || len(fn.Recv.List) == 0 {
return true
}
names := fn.Recv.List[0].Names
if len(names) < 1 {
return true
}
name := names[0].Name
const ref = styleGuideBase + "#receiver-names"
if name == "_" {
f.errorf(n, 1, link(ref), category("naming"), `receiver name should not be an underscore, omit the name if it is unused`)
return true
}
if name == "this" || name == "self" {
f.errorf(n, 1, link(ref), category("naming"), `receiver name should be a reflection of its identity; don't use generic names such as "this" or "self"`)
return true
}
recv := receiverType(fn)
if prev, ok := typeReceiver[recv]; ok && prev != name {
f.errorf(n, 1, link(ref), category("naming"), "receiver name %s should be consistent with previous receiver name %s for %s", name, prev, recv)
return true
}
typeReceiver[recv] = name
return true
})
}
|
[
"func",
"(",
"f",
"*",
"file",
")",
"lintReceiverNames",
"(",
")",
"{",
"typeReceiver",
":=",
"map",
"[",
"string",
"]",
"string",
"{",
"}",
"\n",
"f",
".",
"walk",
"(",
"func",
"(",
"n",
"ast",
".",
"Node",
")",
"bool",
"{",
"fn",
",",
"ok",
":=",
"n",
".",
"(",
"*",
"ast",
".",
"FuncDecl",
")",
"\n",
"if",
"!",
"ok",
"||",
"fn",
".",
"Recv",
"==",
"nil",
"||",
"len",
"(",
"fn",
".",
"Recv",
".",
"List",
")",
"==",
"0",
"{",
"return",
"true",
"\n",
"}",
"\n",
"names",
":=",
"fn",
".",
"Recv",
".",
"List",
"[",
"0",
"]",
".",
"Names",
"\n",
"if",
"len",
"(",
"names",
")",
"<",
"1",
"{",
"return",
"true",
"\n",
"}",
"\n",
"name",
":=",
"names",
"[",
"0",
"]",
".",
"Name",
"\n",
"const",
"ref",
"=",
"styleGuideBase",
"+",
"\"",
"\"",
"\n",
"if",
"name",
"==",
"\"",
"\"",
"{",
"f",
".",
"errorf",
"(",
"n",
",",
"1",
",",
"link",
"(",
"ref",
")",
",",
"category",
"(",
"\"",
"\"",
")",
",",
"`receiver name should not be an underscore, omit the name if it is unused`",
")",
"\n",
"return",
"true",
"\n",
"}",
"\n",
"if",
"name",
"==",
"\"",
"\"",
"||",
"name",
"==",
"\"",
"\"",
"{",
"f",
".",
"errorf",
"(",
"n",
",",
"1",
",",
"link",
"(",
"ref",
")",
",",
"category",
"(",
"\"",
"\"",
")",
",",
"`receiver name should be a reflection of its identity; don't use generic names such as \"this\" or \"self\"`",
")",
"\n",
"return",
"true",
"\n",
"}",
"\n",
"recv",
":=",
"receiverType",
"(",
"fn",
")",
"\n",
"if",
"prev",
",",
"ok",
":=",
"typeReceiver",
"[",
"recv",
"]",
";",
"ok",
"&&",
"prev",
"!=",
"name",
"{",
"f",
".",
"errorf",
"(",
"n",
",",
"1",
",",
"link",
"(",
"ref",
")",
",",
"category",
"(",
"\"",
"\"",
")",
",",
"\"",
"\"",
",",
"name",
",",
"prev",
",",
"recv",
")",
"\n",
"return",
"true",
"\n",
"}",
"\n",
"typeReceiver",
"[",
"recv",
"]",
"=",
"name",
"\n",
"return",
"true",
"\n",
"}",
")",
"\n",
"}"
] |
// lintReceiverNames examines receiver names. It complains about inconsistent
// names used for the same type and names such as "this".
|
[
"lintReceiverNames",
"examines",
"receiver",
"names",
".",
"It",
"complains",
"about",
"inconsistent",
"names",
"used",
"for",
"the",
"same",
"type",
"and",
"names",
"such",
"as",
"this",
"."
] |
959b441ac422379a43da2230f62be024250818b0
|
https://github.com/golang/lint/blob/959b441ac422379a43da2230f62be024250818b0/lint.go#L1263-L1292
|
21,712
|
golang/lint
|
lint.go
|
lintErrorReturn
|
func (f *file) lintErrorReturn() {
f.walk(func(n ast.Node) bool {
fn, ok := n.(*ast.FuncDecl)
if !ok || fn.Type.Results == nil {
return true
}
ret := fn.Type.Results.List
if len(ret) <= 1 {
return true
}
if isIdent(ret[len(ret)-1].Type, "error") {
return true
}
// An error return parameter should be the last parameter.
// Flag any error parameters found before the last.
for _, r := range ret[:len(ret)-1] {
if isIdent(r.Type, "error") {
f.errorf(fn, 0.9, category("arg-order"), "error should be the last type when returning multiple items")
break // only flag one
}
}
return true
})
}
|
go
|
func (f *file) lintErrorReturn() {
f.walk(func(n ast.Node) bool {
fn, ok := n.(*ast.FuncDecl)
if !ok || fn.Type.Results == nil {
return true
}
ret := fn.Type.Results.List
if len(ret) <= 1 {
return true
}
if isIdent(ret[len(ret)-1].Type, "error") {
return true
}
// An error return parameter should be the last parameter.
// Flag any error parameters found before the last.
for _, r := range ret[:len(ret)-1] {
if isIdent(r.Type, "error") {
f.errorf(fn, 0.9, category("arg-order"), "error should be the last type when returning multiple items")
break // only flag one
}
}
return true
})
}
|
[
"func",
"(",
"f",
"*",
"file",
")",
"lintErrorReturn",
"(",
")",
"{",
"f",
".",
"walk",
"(",
"func",
"(",
"n",
"ast",
".",
"Node",
")",
"bool",
"{",
"fn",
",",
"ok",
":=",
"n",
".",
"(",
"*",
"ast",
".",
"FuncDecl",
")",
"\n",
"if",
"!",
"ok",
"||",
"fn",
".",
"Type",
".",
"Results",
"==",
"nil",
"{",
"return",
"true",
"\n",
"}",
"\n",
"ret",
":=",
"fn",
".",
"Type",
".",
"Results",
".",
"List",
"\n",
"if",
"len",
"(",
"ret",
")",
"<=",
"1",
"{",
"return",
"true",
"\n",
"}",
"\n",
"if",
"isIdent",
"(",
"ret",
"[",
"len",
"(",
"ret",
")",
"-",
"1",
"]",
".",
"Type",
",",
"\"",
"\"",
")",
"{",
"return",
"true",
"\n",
"}",
"\n",
"// An error return parameter should be the last parameter.",
"// Flag any error parameters found before the last.",
"for",
"_",
",",
"r",
":=",
"range",
"ret",
"[",
":",
"len",
"(",
"ret",
")",
"-",
"1",
"]",
"{",
"if",
"isIdent",
"(",
"r",
".",
"Type",
",",
"\"",
"\"",
")",
"{",
"f",
".",
"errorf",
"(",
"fn",
",",
"0.9",
",",
"category",
"(",
"\"",
"\"",
")",
",",
"\"",
"\"",
")",
"\n",
"break",
"// only flag one",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"true",
"\n",
"}",
")",
"\n",
"}"
] |
// lintErrorReturn examines function declarations that return an error.
// It complains if the error isn't the last parameter.
|
[
"lintErrorReturn",
"examines",
"function",
"declarations",
"that",
"return",
"an",
"error",
".",
"It",
"complains",
"if",
"the",
"error",
"isn",
"t",
"the",
"last",
"parameter",
"."
] |
959b441ac422379a43da2230f62be024250818b0
|
https://github.com/golang/lint/blob/959b441ac422379a43da2230f62be024250818b0/lint.go#L1324-L1347
|
21,713
|
golang/lint
|
lint.go
|
lintUnexportedReturn
|
func (f *file) lintUnexportedReturn() {
f.walk(func(n ast.Node) bool {
fn, ok := n.(*ast.FuncDecl)
if !ok {
return true
}
if fn.Type.Results == nil {
return false
}
if !fn.Name.IsExported() {
return false
}
thing := "func"
if fn.Recv != nil && len(fn.Recv.List) > 0 {
thing = "method"
if !ast.IsExported(receiverType(fn)) {
// Don't report exported methods of unexported types,
// such as private implementations of sort.Interface.
return false
}
}
for _, ret := range fn.Type.Results.List {
typ := f.pkg.typeOf(ret.Type)
if exportedType(typ) {
continue
}
f.errorf(ret.Type, 0.8, category("unexported-type-in-api"),
"exported %s %s returns unexported type %s, which can be annoying to use",
thing, fn.Name.Name, typ)
break // only flag one
}
return false
})
}
|
go
|
func (f *file) lintUnexportedReturn() {
f.walk(func(n ast.Node) bool {
fn, ok := n.(*ast.FuncDecl)
if !ok {
return true
}
if fn.Type.Results == nil {
return false
}
if !fn.Name.IsExported() {
return false
}
thing := "func"
if fn.Recv != nil && len(fn.Recv.List) > 0 {
thing = "method"
if !ast.IsExported(receiverType(fn)) {
// Don't report exported methods of unexported types,
// such as private implementations of sort.Interface.
return false
}
}
for _, ret := range fn.Type.Results.List {
typ := f.pkg.typeOf(ret.Type)
if exportedType(typ) {
continue
}
f.errorf(ret.Type, 0.8, category("unexported-type-in-api"),
"exported %s %s returns unexported type %s, which can be annoying to use",
thing, fn.Name.Name, typ)
break // only flag one
}
return false
})
}
|
[
"func",
"(",
"f",
"*",
"file",
")",
"lintUnexportedReturn",
"(",
")",
"{",
"f",
".",
"walk",
"(",
"func",
"(",
"n",
"ast",
".",
"Node",
")",
"bool",
"{",
"fn",
",",
"ok",
":=",
"n",
".",
"(",
"*",
"ast",
".",
"FuncDecl",
")",
"\n",
"if",
"!",
"ok",
"{",
"return",
"true",
"\n",
"}",
"\n",
"if",
"fn",
".",
"Type",
".",
"Results",
"==",
"nil",
"{",
"return",
"false",
"\n",
"}",
"\n",
"if",
"!",
"fn",
".",
"Name",
".",
"IsExported",
"(",
")",
"{",
"return",
"false",
"\n",
"}",
"\n",
"thing",
":=",
"\"",
"\"",
"\n",
"if",
"fn",
".",
"Recv",
"!=",
"nil",
"&&",
"len",
"(",
"fn",
".",
"Recv",
".",
"List",
")",
">",
"0",
"{",
"thing",
"=",
"\"",
"\"",
"\n",
"if",
"!",
"ast",
".",
"IsExported",
"(",
"receiverType",
"(",
"fn",
")",
")",
"{",
"// Don't report exported methods of unexported types,",
"// such as private implementations of sort.Interface.",
"return",
"false",
"\n",
"}",
"\n",
"}",
"\n",
"for",
"_",
",",
"ret",
":=",
"range",
"fn",
".",
"Type",
".",
"Results",
".",
"List",
"{",
"typ",
":=",
"f",
".",
"pkg",
".",
"typeOf",
"(",
"ret",
".",
"Type",
")",
"\n",
"if",
"exportedType",
"(",
"typ",
")",
"{",
"continue",
"\n",
"}",
"\n",
"f",
".",
"errorf",
"(",
"ret",
".",
"Type",
",",
"0.8",
",",
"category",
"(",
"\"",
"\"",
")",
",",
"\"",
"\"",
",",
"thing",
",",
"fn",
".",
"Name",
".",
"Name",
",",
"typ",
")",
"\n",
"break",
"// only flag one",
"\n",
"}",
"\n",
"return",
"false",
"\n",
"}",
")",
"\n",
"}"
] |
// lintUnexportedReturn examines exported function declarations.
// It complains if any return an unexported type.
|
[
"lintUnexportedReturn",
"examines",
"exported",
"function",
"declarations",
".",
"It",
"complains",
"if",
"any",
"return",
"an",
"unexported",
"type",
"."
] |
959b441ac422379a43da2230f62be024250818b0
|
https://github.com/golang/lint/blob/959b441ac422379a43da2230f62be024250818b0/lint.go#L1351-L1384
|
21,714
|
golang/lint
|
lint.go
|
exportedType
|
func exportedType(typ types.Type) bool {
switch T := typ.(type) {
case *types.Named:
// Builtin types have no package.
return T.Obj().Pkg() == nil || T.Obj().Exported()
case *types.Map:
return exportedType(T.Key()) && exportedType(T.Elem())
case interface {
Elem() types.Type
}: // array, slice, pointer, chan
return exportedType(T.Elem())
}
// Be conservative about other types, such as struct, interface, etc.
return true
}
|
go
|
func exportedType(typ types.Type) bool {
switch T := typ.(type) {
case *types.Named:
// Builtin types have no package.
return T.Obj().Pkg() == nil || T.Obj().Exported()
case *types.Map:
return exportedType(T.Key()) && exportedType(T.Elem())
case interface {
Elem() types.Type
}: // array, slice, pointer, chan
return exportedType(T.Elem())
}
// Be conservative about other types, such as struct, interface, etc.
return true
}
|
[
"func",
"exportedType",
"(",
"typ",
"types",
".",
"Type",
")",
"bool",
"{",
"switch",
"T",
":=",
"typ",
".",
"(",
"type",
")",
"{",
"case",
"*",
"types",
".",
"Named",
":",
"// Builtin types have no package.",
"return",
"T",
".",
"Obj",
"(",
")",
".",
"Pkg",
"(",
")",
"==",
"nil",
"||",
"T",
".",
"Obj",
"(",
")",
".",
"Exported",
"(",
")",
"\n",
"case",
"*",
"types",
".",
"Map",
":",
"return",
"exportedType",
"(",
"T",
".",
"Key",
"(",
")",
")",
"&&",
"exportedType",
"(",
"T",
".",
"Elem",
"(",
")",
")",
"\n",
"case",
"interface",
"{",
"Elem",
"(",
")",
"types",
".",
"Type",
"\n",
"}",
":",
"// array, slice, pointer, chan",
"return",
"exportedType",
"(",
"T",
".",
"Elem",
"(",
")",
")",
"\n",
"}",
"\n",
"// Be conservative about other types, such as struct, interface, etc.",
"return",
"true",
"\n",
"}"
] |
// exportedType reports whether typ is an exported type.
// It is imprecise, and will err on the side of returning true,
// such as for composite types.
|
[
"exportedType",
"reports",
"whether",
"typ",
"is",
"an",
"exported",
"type",
".",
"It",
"is",
"imprecise",
"and",
"will",
"err",
"on",
"the",
"side",
"of",
"returning",
"true",
"such",
"as",
"for",
"composite",
"types",
"."
] |
959b441ac422379a43da2230f62be024250818b0
|
https://github.com/golang/lint/blob/959b441ac422379a43da2230f62be024250818b0/lint.go#L1389-L1403
|
21,715
|
golang/lint
|
lint.go
|
checkContextKeyType
|
func (f *file) checkContextKeyType(x *ast.CallExpr) {
sel, ok := x.Fun.(*ast.SelectorExpr)
if !ok {
return
}
pkg, ok := sel.X.(*ast.Ident)
if !ok || pkg.Name != "context" {
return
}
if sel.Sel.Name != "WithValue" {
return
}
// key is second argument to context.WithValue
if len(x.Args) != 3 {
return
}
key := f.pkg.typesInfo.Types[x.Args[1]]
if ktyp, ok := key.Type.(*types.Basic); ok && ktyp.Kind() != types.Invalid {
f.errorf(x, 1.0, category("context"), fmt.Sprintf("should not use basic type %s as key in context.WithValue", key.Type))
}
}
|
go
|
func (f *file) checkContextKeyType(x *ast.CallExpr) {
sel, ok := x.Fun.(*ast.SelectorExpr)
if !ok {
return
}
pkg, ok := sel.X.(*ast.Ident)
if !ok || pkg.Name != "context" {
return
}
if sel.Sel.Name != "WithValue" {
return
}
// key is second argument to context.WithValue
if len(x.Args) != 3 {
return
}
key := f.pkg.typesInfo.Types[x.Args[1]]
if ktyp, ok := key.Type.(*types.Basic); ok && ktyp.Kind() != types.Invalid {
f.errorf(x, 1.0, category("context"), fmt.Sprintf("should not use basic type %s as key in context.WithValue", key.Type))
}
}
|
[
"func",
"(",
"f",
"*",
"file",
")",
"checkContextKeyType",
"(",
"x",
"*",
"ast",
".",
"CallExpr",
")",
"{",
"sel",
",",
"ok",
":=",
"x",
".",
"Fun",
".",
"(",
"*",
"ast",
".",
"SelectorExpr",
")",
"\n",
"if",
"!",
"ok",
"{",
"return",
"\n",
"}",
"\n",
"pkg",
",",
"ok",
":=",
"sel",
".",
"X",
".",
"(",
"*",
"ast",
".",
"Ident",
")",
"\n",
"if",
"!",
"ok",
"||",
"pkg",
".",
"Name",
"!=",
"\"",
"\"",
"{",
"return",
"\n",
"}",
"\n",
"if",
"sel",
".",
"Sel",
".",
"Name",
"!=",
"\"",
"\"",
"{",
"return",
"\n",
"}",
"\n\n",
"// key is second argument to context.WithValue",
"if",
"len",
"(",
"x",
".",
"Args",
")",
"!=",
"3",
"{",
"return",
"\n",
"}",
"\n",
"key",
":=",
"f",
".",
"pkg",
".",
"typesInfo",
".",
"Types",
"[",
"x",
".",
"Args",
"[",
"1",
"]",
"]",
"\n\n",
"if",
"ktyp",
",",
"ok",
":=",
"key",
".",
"Type",
".",
"(",
"*",
"types",
".",
"Basic",
")",
";",
"ok",
"&&",
"ktyp",
".",
"Kind",
"(",
")",
"!=",
"types",
".",
"Invalid",
"{",
"f",
".",
"errorf",
"(",
"x",
",",
"1.0",
",",
"category",
"(",
"\"",
"\"",
")",
",",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"key",
".",
"Type",
")",
")",
"\n",
"}",
"\n",
"}"
] |
// checkContextKeyType reports an error if the call expression calls
// context.WithValue with a key argument of basic type.
|
[
"checkContextKeyType",
"reports",
"an",
"error",
"if",
"the",
"call",
"expression",
"calls",
"context",
".",
"WithValue",
"with",
"a",
"key",
"argument",
"of",
"basic",
"type",
"."
] |
959b441ac422379a43da2230f62be024250818b0
|
https://github.com/golang/lint/blob/959b441ac422379a43da2230f62be024250818b0/lint.go#L1464-L1486
|
21,716
|
golang/lint
|
lint.go
|
lintContextArgs
|
func (f *file) lintContextArgs() {
f.walk(func(n ast.Node) bool {
fn, ok := n.(*ast.FuncDecl)
if !ok || len(fn.Type.Params.List) <= 1 {
return true
}
// A context.Context should be the first parameter of a function.
// Flag any that show up after the first.
for _, arg := range fn.Type.Params.List[1:] {
if isPkgDot(arg.Type, "context", "Context") {
f.errorf(fn, 0.9, link("https://golang.org/pkg/context/"), category("arg-order"), "context.Context should be the first parameter of a function")
break // only flag one
}
}
return true
})
}
|
go
|
func (f *file) lintContextArgs() {
f.walk(func(n ast.Node) bool {
fn, ok := n.(*ast.FuncDecl)
if !ok || len(fn.Type.Params.List) <= 1 {
return true
}
// A context.Context should be the first parameter of a function.
// Flag any that show up after the first.
for _, arg := range fn.Type.Params.List[1:] {
if isPkgDot(arg.Type, "context", "Context") {
f.errorf(fn, 0.9, link("https://golang.org/pkg/context/"), category("arg-order"), "context.Context should be the first parameter of a function")
break // only flag one
}
}
return true
})
}
|
[
"func",
"(",
"f",
"*",
"file",
")",
"lintContextArgs",
"(",
")",
"{",
"f",
".",
"walk",
"(",
"func",
"(",
"n",
"ast",
".",
"Node",
")",
"bool",
"{",
"fn",
",",
"ok",
":=",
"n",
".",
"(",
"*",
"ast",
".",
"FuncDecl",
")",
"\n",
"if",
"!",
"ok",
"||",
"len",
"(",
"fn",
".",
"Type",
".",
"Params",
".",
"List",
")",
"<=",
"1",
"{",
"return",
"true",
"\n",
"}",
"\n",
"// A context.Context should be the first parameter of a function.",
"// Flag any that show up after the first.",
"for",
"_",
",",
"arg",
":=",
"range",
"fn",
".",
"Type",
".",
"Params",
".",
"List",
"[",
"1",
":",
"]",
"{",
"if",
"isPkgDot",
"(",
"arg",
".",
"Type",
",",
"\"",
"\"",
",",
"\"",
"\"",
")",
"{",
"f",
".",
"errorf",
"(",
"fn",
",",
"0.9",
",",
"link",
"(",
"\"",
"\"",
")",
",",
"category",
"(",
"\"",
"\"",
")",
",",
"\"",
"\"",
")",
"\n",
"break",
"// only flag one",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"true",
"\n",
"}",
")",
"\n",
"}"
] |
// lintContextArgs examines function declarations that contain an
// argument with a type of context.Context
// It complains if that argument isn't the first parameter.
|
[
"lintContextArgs",
"examines",
"function",
"declarations",
"that",
"contain",
"an",
"argument",
"with",
"a",
"type",
"of",
"context",
".",
"Context",
"It",
"complains",
"if",
"that",
"argument",
"isn",
"t",
"the",
"first",
"parameter",
"."
] |
959b441ac422379a43da2230f62be024250818b0
|
https://github.com/golang/lint/blob/959b441ac422379a43da2230f62be024250818b0/lint.go#L1491-L1507
|
21,717
|
golang/lint
|
lint.go
|
isUntypedConst
|
func (f *file) isUntypedConst(expr ast.Expr) (defType string, ok bool) {
// Re-evaluate expr outside of its context to see if it's untyped.
// (An expr evaluated within, for example, an assignment context will get the type of the LHS.)
exprStr := f.render(expr)
tv, err := types.Eval(f.fset, f.pkg.typesPkg, expr.Pos(), exprStr)
if err != nil {
return "", false
}
if b, ok := tv.Type.(*types.Basic); ok {
if dt, ok := basicTypeKinds[b.Kind()]; ok {
return dt, true
}
}
return "", false
}
|
go
|
func (f *file) isUntypedConst(expr ast.Expr) (defType string, ok bool) {
// Re-evaluate expr outside of its context to see if it's untyped.
// (An expr evaluated within, for example, an assignment context will get the type of the LHS.)
exprStr := f.render(expr)
tv, err := types.Eval(f.fset, f.pkg.typesPkg, expr.Pos(), exprStr)
if err != nil {
return "", false
}
if b, ok := tv.Type.(*types.Basic); ok {
if dt, ok := basicTypeKinds[b.Kind()]; ok {
return dt, true
}
}
return "", false
}
|
[
"func",
"(",
"f",
"*",
"file",
")",
"isUntypedConst",
"(",
"expr",
"ast",
".",
"Expr",
")",
"(",
"defType",
"string",
",",
"ok",
"bool",
")",
"{",
"// Re-evaluate expr outside of its context to see if it's untyped.",
"// (An expr evaluated within, for example, an assignment context will get the type of the LHS.)",
"exprStr",
":=",
"f",
".",
"render",
"(",
"expr",
")",
"\n",
"tv",
",",
"err",
":=",
"types",
".",
"Eval",
"(",
"f",
".",
"fset",
",",
"f",
".",
"pkg",
".",
"typesPkg",
",",
"expr",
".",
"Pos",
"(",
")",
",",
"exprStr",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\"",
"\"",
",",
"false",
"\n",
"}",
"\n",
"if",
"b",
",",
"ok",
":=",
"tv",
".",
"Type",
".",
"(",
"*",
"types",
".",
"Basic",
")",
";",
"ok",
"{",
"if",
"dt",
",",
"ok",
":=",
"basicTypeKinds",
"[",
"b",
".",
"Kind",
"(",
")",
"]",
";",
"ok",
"{",
"return",
"dt",
",",
"true",
"\n",
"}",
"\n",
"}",
"\n\n",
"return",
"\"",
"\"",
",",
"false",
"\n",
"}"
] |
// isUntypedConst reports whether expr is an untyped constant,
// and indicates what its default type is.
// scope may be nil.
|
[
"isUntypedConst",
"reports",
"whether",
"expr",
"is",
"an",
"untyped",
"constant",
"and",
"indicates",
"what",
"its",
"default",
"type",
"is",
".",
"scope",
"may",
"be",
"nil",
"."
] |
959b441ac422379a43da2230f62be024250818b0
|
https://github.com/golang/lint/blob/959b441ac422379a43da2230f62be024250818b0/lint.go#L1622-L1637
|
21,718
|
golang/lint
|
lint.go
|
firstLineOf
|
func (f *file) firstLineOf(node, match ast.Node) string {
line := f.render(node)
if i := strings.Index(line, "\n"); i >= 0 {
line = line[:i]
}
return f.indentOf(match) + line
}
|
go
|
func (f *file) firstLineOf(node, match ast.Node) string {
line := f.render(node)
if i := strings.Index(line, "\n"); i >= 0 {
line = line[:i]
}
return f.indentOf(match) + line
}
|
[
"func",
"(",
"f",
"*",
"file",
")",
"firstLineOf",
"(",
"node",
",",
"match",
"ast",
".",
"Node",
")",
"string",
"{",
"line",
":=",
"f",
".",
"render",
"(",
"node",
")",
"\n",
"if",
"i",
":=",
"strings",
".",
"Index",
"(",
"line",
",",
"\"",
"\\n",
"\"",
")",
";",
"i",
">=",
"0",
"{",
"line",
"=",
"line",
"[",
":",
"i",
"]",
"\n",
"}",
"\n",
"return",
"f",
".",
"indentOf",
"(",
"match",
")",
"+",
"line",
"\n",
"}"
] |
// firstLineOf renders the given node and returns its first line.
// It will also match the indentation of another node.
|
[
"firstLineOf",
"renders",
"the",
"given",
"node",
"and",
"returns",
"its",
"first",
"line",
".",
"It",
"will",
"also",
"match",
"the",
"indentation",
"of",
"another",
"node",
"."
] |
959b441ac422379a43da2230f62be024250818b0
|
https://github.com/golang/lint/blob/959b441ac422379a43da2230f62be024250818b0/lint.go#L1641-L1647
|
21,719
|
golang/lint
|
lint.go
|
imports
|
func (f *file) imports(importPath string) bool {
all := astutil.Imports(f.fset, f.f)
for _, p := range all {
for _, i := range p {
uq, err := strconv.Unquote(i.Path.Value)
if err == nil && importPath == uq {
return true
}
}
}
return false
}
|
go
|
func (f *file) imports(importPath string) bool {
all := astutil.Imports(f.fset, f.f)
for _, p := range all {
for _, i := range p {
uq, err := strconv.Unquote(i.Path.Value)
if err == nil && importPath == uq {
return true
}
}
}
return false
}
|
[
"func",
"(",
"f",
"*",
"file",
")",
"imports",
"(",
"importPath",
"string",
")",
"bool",
"{",
"all",
":=",
"astutil",
".",
"Imports",
"(",
"f",
".",
"fset",
",",
"f",
".",
"f",
")",
"\n",
"for",
"_",
",",
"p",
":=",
"range",
"all",
"{",
"for",
"_",
",",
"i",
":=",
"range",
"p",
"{",
"uq",
",",
"err",
":=",
"strconv",
".",
"Unquote",
"(",
"i",
".",
"Path",
".",
"Value",
")",
"\n",
"if",
"err",
"==",
"nil",
"&&",
"importPath",
"==",
"uq",
"{",
"return",
"true",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"false",
"\n",
"}"
] |
// imports returns true if the current file imports the specified package path.
|
[
"imports",
"returns",
"true",
"if",
"the",
"current",
"file",
"imports",
"the",
"specified",
"package",
"path",
"."
] |
959b441ac422379a43da2230f62be024250818b0
|
https://github.com/golang/lint/blob/959b441ac422379a43da2230f62be024250818b0/lint.go#L1669-L1680
|
21,720
|
golang/lint
|
lint.go
|
srcLine
|
func srcLine(src []byte, p token.Position) string {
// Run to end of line in both directions if not at line start/end.
lo, hi := p.Offset, p.Offset+1
for lo > 0 && src[lo-1] != '\n' {
lo--
}
for hi < len(src) && src[hi-1] != '\n' {
hi++
}
return string(src[lo:hi])
}
|
go
|
func srcLine(src []byte, p token.Position) string {
// Run to end of line in both directions if not at line start/end.
lo, hi := p.Offset, p.Offset+1
for lo > 0 && src[lo-1] != '\n' {
lo--
}
for hi < len(src) && src[hi-1] != '\n' {
hi++
}
return string(src[lo:hi])
}
|
[
"func",
"srcLine",
"(",
"src",
"[",
"]",
"byte",
",",
"p",
"token",
".",
"Position",
")",
"string",
"{",
"// Run to end of line in both directions if not at line start/end.",
"lo",
",",
"hi",
":=",
"p",
".",
"Offset",
",",
"p",
".",
"Offset",
"+",
"1",
"\n",
"for",
"lo",
">",
"0",
"&&",
"src",
"[",
"lo",
"-",
"1",
"]",
"!=",
"'\\n'",
"{",
"lo",
"--",
"\n",
"}",
"\n",
"for",
"hi",
"<",
"len",
"(",
"src",
")",
"&&",
"src",
"[",
"hi",
"-",
"1",
"]",
"!=",
"'\\n'",
"{",
"hi",
"++",
"\n",
"}",
"\n",
"return",
"string",
"(",
"src",
"[",
"lo",
":",
"hi",
"]",
")",
"\n",
"}"
] |
// srcLine returns the complete line at p, including the terminating newline.
|
[
"srcLine",
"returns",
"the",
"complete",
"line",
"at",
"p",
"including",
"the",
"terminating",
"newline",
"."
] |
959b441ac422379a43da2230f62be024250818b0
|
https://github.com/golang/lint/blob/959b441ac422379a43da2230f62be024250818b0/lint.go#L1683-L1693
|
21,721
|
golang/lint
|
golint/import.go
|
importPaths
|
func importPaths(args []string) []string {
args = importPathsNoDotExpansion(args)
var out []string
for _, a := range args {
if strings.Contains(a, "...") {
if build.IsLocalImport(a) {
out = append(out, allPackagesInFS(a)...)
} else {
out = append(out, allPackages(a)...)
}
continue
}
out = append(out, a)
}
return out
}
|
go
|
func importPaths(args []string) []string {
args = importPathsNoDotExpansion(args)
var out []string
for _, a := range args {
if strings.Contains(a, "...") {
if build.IsLocalImport(a) {
out = append(out, allPackagesInFS(a)...)
} else {
out = append(out, allPackages(a)...)
}
continue
}
out = append(out, a)
}
return out
}
|
[
"func",
"importPaths",
"(",
"args",
"[",
"]",
"string",
")",
"[",
"]",
"string",
"{",
"args",
"=",
"importPathsNoDotExpansion",
"(",
"args",
")",
"\n",
"var",
"out",
"[",
"]",
"string",
"\n",
"for",
"_",
",",
"a",
":=",
"range",
"args",
"{",
"if",
"strings",
".",
"Contains",
"(",
"a",
",",
"\"",
"\"",
")",
"{",
"if",
"build",
".",
"IsLocalImport",
"(",
"a",
")",
"{",
"out",
"=",
"append",
"(",
"out",
",",
"allPackagesInFS",
"(",
"a",
")",
"...",
")",
"\n",
"}",
"else",
"{",
"out",
"=",
"append",
"(",
"out",
",",
"allPackages",
"(",
"a",
")",
"...",
")",
"\n",
"}",
"\n",
"continue",
"\n",
"}",
"\n",
"out",
"=",
"append",
"(",
"out",
",",
"a",
")",
"\n",
"}",
"\n",
"return",
"out",
"\n",
"}"
] |
// importPaths returns the import paths to use for the given command line.
|
[
"importPaths",
"returns",
"the",
"import",
"paths",
"to",
"use",
"for",
"the",
"given",
"command",
"line",
"."
] |
959b441ac422379a43da2230f62be024250818b0
|
https://github.com/golang/lint/blob/959b441ac422379a43da2230f62be024250818b0/golint/import.go#L65-L80
|
21,722
|
golang/lint
|
golint/import.go
|
hasPathPrefix
|
func hasPathPrefix(s, prefix string) bool {
switch {
default:
return false
case len(s) == len(prefix):
return s == prefix
case len(s) > len(prefix):
if prefix != "" && prefix[len(prefix)-1] == '/' {
return strings.HasPrefix(s, prefix)
}
return s[len(prefix)] == '/' && s[:len(prefix)] == prefix
}
}
|
go
|
func hasPathPrefix(s, prefix string) bool {
switch {
default:
return false
case len(s) == len(prefix):
return s == prefix
case len(s) > len(prefix):
if prefix != "" && prefix[len(prefix)-1] == '/' {
return strings.HasPrefix(s, prefix)
}
return s[len(prefix)] == '/' && s[:len(prefix)] == prefix
}
}
|
[
"func",
"hasPathPrefix",
"(",
"s",
",",
"prefix",
"string",
")",
"bool",
"{",
"switch",
"{",
"default",
":",
"return",
"false",
"\n",
"case",
"len",
"(",
"s",
")",
"==",
"len",
"(",
"prefix",
")",
":",
"return",
"s",
"==",
"prefix",
"\n",
"case",
"len",
"(",
"s",
")",
">",
"len",
"(",
"prefix",
")",
":",
"if",
"prefix",
"!=",
"\"",
"\"",
"&&",
"prefix",
"[",
"len",
"(",
"prefix",
")",
"-",
"1",
"]",
"==",
"'/'",
"{",
"return",
"strings",
".",
"HasPrefix",
"(",
"s",
",",
"prefix",
")",
"\n",
"}",
"\n",
"return",
"s",
"[",
"len",
"(",
"prefix",
")",
"]",
"==",
"'/'",
"&&",
"s",
"[",
":",
"len",
"(",
"prefix",
")",
"]",
"==",
"prefix",
"\n",
"}",
"\n",
"}"
] |
// hasPathPrefix reports whether the path s begins with the
// elements in prefix.
|
[
"hasPathPrefix",
"reports",
"whether",
"the",
"path",
"s",
"begins",
"with",
"the",
"elements",
"in",
"prefix",
"."
] |
959b441ac422379a43da2230f62be024250818b0
|
https://github.com/golang/lint/blob/959b441ac422379a43da2230f62be024250818b0/golint/import.go#L101-L113
|
21,723
|
hashicorp/go-plugin
|
grpc_client.go
|
newGRPCClient
|
func newGRPCClient(doneCtx context.Context, c *Client) (*GRPCClient, error) {
conn, err := dialGRPCConn(c.config.TLSConfig, c.dialer)
if err != nil {
return nil, err
}
// Start the broker.
brokerGRPCClient := newGRPCBrokerClient(conn)
broker := newGRPCBroker(brokerGRPCClient, c.config.TLSConfig)
go broker.Run()
go brokerGRPCClient.StartStream()
cl := &GRPCClient{
Conn: conn,
Plugins: c.config.Plugins,
doneCtx: doneCtx,
broker: broker,
controller: plugin.NewGRPCControllerClient(conn),
}
return cl, nil
}
|
go
|
func newGRPCClient(doneCtx context.Context, c *Client) (*GRPCClient, error) {
conn, err := dialGRPCConn(c.config.TLSConfig, c.dialer)
if err != nil {
return nil, err
}
// Start the broker.
brokerGRPCClient := newGRPCBrokerClient(conn)
broker := newGRPCBroker(brokerGRPCClient, c.config.TLSConfig)
go broker.Run()
go brokerGRPCClient.StartStream()
cl := &GRPCClient{
Conn: conn,
Plugins: c.config.Plugins,
doneCtx: doneCtx,
broker: broker,
controller: plugin.NewGRPCControllerClient(conn),
}
return cl, nil
}
|
[
"func",
"newGRPCClient",
"(",
"doneCtx",
"context",
".",
"Context",
",",
"c",
"*",
"Client",
")",
"(",
"*",
"GRPCClient",
",",
"error",
")",
"{",
"conn",
",",
"err",
":=",
"dialGRPCConn",
"(",
"c",
".",
"config",
".",
"TLSConfig",
",",
"c",
".",
"dialer",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"// Start the broker.",
"brokerGRPCClient",
":=",
"newGRPCBrokerClient",
"(",
"conn",
")",
"\n",
"broker",
":=",
"newGRPCBroker",
"(",
"brokerGRPCClient",
",",
"c",
".",
"config",
".",
"TLSConfig",
")",
"\n",
"go",
"broker",
".",
"Run",
"(",
")",
"\n",
"go",
"brokerGRPCClient",
".",
"StartStream",
"(",
")",
"\n\n",
"cl",
":=",
"&",
"GRPCClient",
"{",
"Conn",
":",
"conn",
",",
"Plugins",
":",
"c",
".",
"config",
".",
"Plugins",
",",
"doneCtx",
":",
"doneCtx",
",",
"broker",
":",
"broker",
",",
"controller",
":",
"plugin",
".",
"NewGRPCControllerClient",
"(",
"conn",
")",
",",
"}",
"\n\n",
"return",
"cl",
",",
"nil",
"\n",
"}"
] |
// newGRPCClient creates a new GRPCClient. The Client argument is expected
// to be successfully started already with a lock held.
|
[
"newGRPCClient",
"creates",
"a",
"new",
"GRPCClient",
".",
"The",
"Client",
"argument",
"is",
"expected",
"to",
"be",
"successfully",
"started",
"already",
"with",
"a",
"lock",
"held",
"."
] |
5692942914bbdbc03558fde936b1f0bc2af365be
|
https://github.com/hashicorp/go-plugin/blob/5692942914bbdbc03558fde936b1f0bc2af365be/grpc_client.go#L47-L68
|
21,724
|
hashicorp/go-plugin
|
server_mux.go
|
ServeMux
|
func ServeMux(m ServeMuxMap) {
if len(os.Args) != 2 {
fmt.Fprintf(os.Stderr,
"Invoked improperly. This is an internal command that shouldn't\n"+
"be manually invoked.\n")
os.Exit(1)
}
opts, ok := m[os.Args[1]]
if !ok {
fmt.Fprintf(os.Stderr, "Unknown plugin: %s\n", os.Args[1])
os.Exit(1)
}
Serve(opts)
}
|
go
|
func ServeMux(m ServeMuxMap) {
if len(os.Args) != 2 {
fmt.Fprintf(os.Stderr,
"Invoked improperly. This is an internal command that shouldn't\n"+
"be manually invoked.\n")
os.Exit(1)
}
opts, ok := m[os.Args[1]]
if !ok {
fmt.Fprintf(os.Stderr, "Unknown plugin: %s\n", os.Args[1])
os.Exit(1)
}
Serve(opts)
}
|
[
"func",
"ServeMux",
"(",
"m",
"ServeMuxMap",
")",
"{",
"if",
"len",
"(",
"os",
".",
"Args",
")",
"!=",
"2",
"{",
"fmt",
".",
"Fprintf",
"(",
"os",
".",
"Stderr",
",",
"\"",
"\\n",
"\"",
"+",
"\"",
"\\n",
"\"",
")",
"\n",
"os",
".",
"Exit",
"(",
"1",
")",
"\n",
"}",
"\n\n",
"opts",
",",
"ok",
":=",
"m",
"[",
"os",
".",
"Args",
"[",
"1",
"]",
"]",
"\n",
"if",
"!",
"ok",
"{",
"fmt",
".",
"Fprintf",
"(",
"os",
".",
"Stderr",
",",
"\"",
"\\n",
"\"",
",",
"os",
".",
"Args",
"[",
"1",
"]",
")",
"\n",
"os",
".",
"Exit",
"(",
"1",
")",
"\n",
"}",
"\n\n",
"Serve",
"(",
"opts",
")",
"\n",
"}"
] |
// ServeMux is like Serve, but serves multiple types of plugins determined
// by the argument given on the command-line.
//
// This command doesn't return until the plugin is done being executed. Any
// errors are logged or output to stderr.
|
[
"ServeMux",
"is",
"like",
"Serve",
"but",
"serves",
"multiple",
"types",
"of",
"plugins",
"determined",
"by",
"the",
"argument",
"given",
"on",
"the",
"command",
"-",
"line",
".",
"This",
"command",
"doesn",
"t",
"return",
"until",
"the",
"plugin",
"is",
"done",
"being",
"executed",
".",
"Any",
"errors",
"are",
"logged",
"or",
"output",
"to",
"stderr",
"."
] |
5692942914bbdbc03558fde936b1f0bc2af365be
|
https://github.com/hashicorp/go-plugin/blob/5692942914bbdbc03558fde936b1f0bc2af365be/server_mux.go#L16-L31
|
21,725
|
hashicorp/go-plugin
|
grpc_broker.go
|
Recv
|
func (s *gRPCBrokerServer) Recv() (*plugin.ConnInfo, error) {
select {
case <-s.quit:
return nil, errors.New("broker closed")
case i := <-s.recv:
return i, nil
}
}
|
go
|
func (s *gRPCBrokerServer) Recv() (*plugin.ConnInfo, error) {
select {
case <-s.quit:
return nil, errors.New("broker closed")
case i := <-s.recv:
return i, nil
}
}
|
[
"func",
"(",
"s",
"*",
"gRPCBrokerServer",
")",
"Recv",
"(",
")",
"(",
"*",
"plugin",
".",
"ConnInfo",
",",
"error",
")",
"{",
"select",
"{",
"case",
"<-",
"s",
".",
"quit",
":",
"return",
"nil",
",",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"case",
"i",
":=",
"<-",
"s",
".",
"recv",
":",
"return",
"i",
",",
"nil",
"\n",
"}",
"\n",
"}"
] |
// Recv is used by the GRPCBroker to pass connection information that has been
// sent from the client from the stream to the broker.
|
[
"Recv",
"is",
"used",
"by",
"the",
"GRPCBroker",
"to",
"pass",
"connection",
"information",
"that",
"has",
"been",
"sent",
"from",
"the",
"client",
"from",
"the",
"stream",
"to",
"the",
"broker",
"."
] |
5692942914bbdbc03558fde936b1f0bc2af365be
|
https://github.com/hashicorp/go-plugin/blob/5692942914bbdbc03558fde936b1f0bc2af365be/grpc_broker.go#L120-L127
|
21,726
|
hashicorp/go-plugin
|
grpc_broker.go
|
Send
|
func (s *gRPCBrokerClientImpl) Send(i *plugin.ConnInfo) error {
ch := make(chan error)
defer close(ch)
select {
case <-s.quit:
return errors.New("broker closed")
case s.send <- &sendErr{
i: i,
ch: ch,
}:
}
return <-ch
}
|
go
|
func (s *gRPCBrokerClientImpl) Send(i *plugin.ConnInfo) error {
ch := make(chan error)
defer close(ch)
select {
case <-s.quit:
return errors.New("broker closed")
case s.send <- &sendErr{
i: i,
ch: ch,
}:
}
return <-ch
}
|
[
"func",
"(",
"s",
"*",
"gRPCBrokerClientImpl",
")",
"Send",
"(",
"i",
"*",
"plugin",
".",
"ConnInfo",
")",
"error",
"{",
"ch",
":=",
"make",
"(",
"chan",
"error",
")",
"\n",
"defer",
"close",
"(",
"ch",
")",
"\n\n",
"select",
"{",
"case",
"<-",
"s",
".",
"quit",
":",
"return",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"case",
"s",
".",
"send",
"<-",
"&",
"sendErr",
"{",
"i",
":",
"i",
",",
"ch",
":",
"ch",
",",
"}",
":",
"}",
"\n\n",
"return",
"<-",
"ch",
"\n",
"}"
] |
// Send is used by the GRPCBroker to pass connection information into the stream
// to the plugin.
|
[
"Send",
"is",
"used",
"by",
"the",
"GRPCBroker",
"to",
"pass",
"connection",
"information",
"into",
"the",
"stream",
"to",
"the",
"plugin",
"."
] |
5692942914bbdbc03558fde936b1f0bc2af365be
|
https://github.com/hashicorp/go-plugin/blob/5692942914bbdbc03558fde936b1f0bc2af365be/grpc_broker.go#L212-L226
|
21,727
|
hashicorp/go-plugin
|
grpc_broker.go
|
AcceptAndServe
|
func (b *GRPCBroker) AcceptAndServe(id uint32, s func([]grpc.ServerOption) *grpc.Server) {
listener, err := b.Accept(id)
if err != nil {
log.Printf("[ERR] plugin: plugin acceptAndServe error: %s", err)
return
}
defer listener.Close()
var opts []grpc.ServerOption
if b.tls != nil {
opts = []grpc.ServerOption{grpc.Creds(credentials.NewTLS(b.tls))}
}
server := s(opts)
// Here we use a run group to close this goroutine if the server is shutdown
// or the broker is shutdown.
var g run.Group
{
// Serve on the listener, if shutting down call GracefulStop.
g.Add(func() error {
return server.Serve(listener)
}, func(err error) {
server.GracefulStop()
})
}
{
// block on the closeCh or the doneCh. If we are shutting down close the
// closeCh.
closeCh := make(chan struct{})
g.Add(func() error {
select {
case <-b.doneCh:
case <-closeCh:
}
return nil
}, func(err error) {
close(closeCh)
})
}
// Block until we are done
g.Run()
}
|
go
|
func (b *GRPCBroker) AcceptAndServe(id uint32, s func([]grpc.ServerOption) *grpc.Server) {
listener, err := b.Accept(id)
if err != nil {
log.Printf("[ERR] plugin: plugin acceptAndServe error: %s", err)
return
}
defer listener.Close()
var opts []grpc.ServerOption
if b.tls != nil {
opts = []grpc.ServerOption{grpc.Creds(credentials.NewTLS(b.tls))}
}
server := s(opts)
// Here we use a run group to close this goroutine if the server is shutdown
// or the broker is shutdown.
var g run.Group
{
// Serve on the listener, if shutting down call GracefulStop.
g.Add(func() error {
return server.Serve(listener)
}, func(err error) {
server.GracefulStop()
})
}
{
// block on the closeCh or the doneCh. If we are shutting down close the
// closeCh.
closeCh := make(chan struct{})
g.Add(func() error {
select {
case <-b.doneCh:
case <-closeCh:
}
return nil
}, func(err error) {
close(closeCh)
})
}
// Block until we are done
g.Run()
}
|
[
"func",
"(",
"b",
"*",
"GRPCBroker",
")",
"AcceptAndServe",
"(",
"id",
"uint32",
",",
"s",
"func",
"(",
"[",
"]",
"grpc",
".",
"ServerOption",
")",
"*",
"grpc",
".",
"Server",
")",
"{",
"listener",
",",
"err",
":=",
"b",
".",
"Accept",
"(",
"id",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"log",
".",
"Printf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"return",
"\n",
"}",
"\n",
"defer",
"listener",
".",
"Close",
"(",
")",
"\n\n",
"var",
"opts",
"[",
"]",
"grpc",
".",
"ServerOption",
"\n",
"if",
"b",
".",
"tls",
"!=",
"nil",
"{",
"opts",
"=",
"[",
"]",
"grpc",
".",
"ServerOption",
"{",
"grpc",
".",
"Creds",
"(",
"credentials",
".",
"NewTLS",
"(",
"b",
".",
"tls",
")",
")",
"}",
"\n",
"}",
"\n\n",
"server",
":=",
"s",
"(",
"opts",
")",
"\n\n",
"// Here we use a run group to close this goroutine if the server is shutdown",
"// or the broker is shutdown.",
"var",
"g",
"run",
".",
"Group",
"\n",
"{",
"// Serve on the listener, if shutting down call GracefulStop.",
"g",
".",
"Add",
"(",
"func",
"(",
")",
"error",
"{",
"return",
"server",
".",
"Serve",
"(",
"listener",
")",
"\n",
"}",
",",
"func",
"(",
"err",
"error",
")",
"{",
"server",
".",
"GracefulStop",
"(",
")",
"\n",
"}",
")",
"\n",
"}",
"\n",
"{",
"// block on the closeCh or the doneCh. If we are shutting down close the",
"// closeCh.",
"closeCh",
":=",
"make",
"(",
"chan",
"struct",
"{",
"}",
")",
"\n",
"g",
".",
"Add",
"(",
"func",
"(",
")",
"error",
"{",
"select",
"{",
"case",
"<-",
"b",
".",
"doneCh",
":",
"case",
"<-",
"closeCh",
":",
"}",
"\n",
"return",
"nil",
"\n",
"}",
",",
"func",
"(",
"err",
"error",
")",
"{",
"close",
"(",
"closeCh",
")",
"\n",
"}",
")",
"\n",
"}",
"\n\n",
"// Block until we are done",
"g",
".",
"Run",
"(",
")",
"\n",
"}"
] |
// AcceptAndServe is used to accept a specific stream ID and immediately
// serve a gRPC server on that stream ID. This is used to easily serve
// complex arguments. Each AcceptAndServe call opens a new listener socket and
// sends the connection info down the stream to the dialer. Since a new
// connection is opened every call, these calls should be used sparingly.
// Multiple gRPC server implementations can be registered to a single
// AcceptAndServe call.
|
[
"AcceptAndServe",
"is",
"used",
"to",
"accept",
"a",
"specific",
"stream",
"ID",
"and",
"immediately",
"serve",
"a",
"gRPC",
"server",
"on",
"that",
"stream",
"ID",
".",
"This",
"is",
"used",
"to",
"easily",
"serve",
"complex",
"arguments",
".",
"Each",
"AcceptAndServe",
"call",
"opens",
"a",
"new",
"listener",
"socket",
"and",
"sends",
"the",
"connection",
"info",
"down",
"the",
"stream",
"to",
"the",
"dialer",
".",
"Since",
"a",
"new",
"connection",
"is",
"opened",
"every",
"call",
"these",
"calls",
"should",
"be",
"used",
"sparingly",
".",
"Multiple",
"gRPC",
"server",
"implementations",
"can",
"be",
"registered",
"to",
"a",
"single",
"AcceptAndServe",
"call",
"."
] |
5692942914bbdbc03558fde936b1f0bc2af365be
|
https://github.com/hashicorp/go-plugin/blob/5692942914bbdbc03558fde936b1f0bc2af365be/grpc_broker.go#L312-L355
|
21,728
|
hashicorp/go-plugin
|
grpc_broker.go
|
Close
|
func (b *GRPCBroker) Close() error {
b.streamer.Close()
b.o.Do(func() {
close(b.doneCh)
})
return nil
}
|
go
|
func (b *GRPCBroker) Close() error {
b.streamer.Close()
b.o.Do(func() {
close(b.doneCh)
})
return nil
}
|
[
"func",
"(",
"b",
"*",
"GRPCBroker",
")",
"Close",
"(",
")",
"error",
"{",
"b",
".",
"streamer",
".",
"Close",
"(",
")",
"\n",
"b",
".",
"o",
".",
"Do",
"(",
"func",
"(",
")",
"{",
"close",
"(",
"b",
".",
"doneCh",
")",
"\n",
"}",
")",
"\n",
"return",
"nil",
"\n",
"}"
] |
// Close closes the stream and all servers.
|
[
"Close",
"closes",
"the",
"stream",
"and",
"all",
"servers",
"."
] |
5692942914bbdbc03558fde936b1f0bc2af365be
|
https://github.com/hashicorp/go-plugin/blob/5692942914bbdbc03558fde936b1f0bc2af365be/grpc_broker.go#L358-L364
|
21,729
|
hashicorp/go-plugin
|
log_entry.go
|
parseJSON
|
func parseJSON(input []byte) (*logEntry, error) {
var raw map[string]interface{}
entry := &logEntry{}
err := json.Unmarshal(input, &raw)
if err != nil {
return nil, err
}
// Parse hclog-specific objects
if v, ok := raw["@message"]; ok {
entry.Message = v.(string)
delete(raw, "@message")
}
if v, ok := raw["@level"]; ok {
entry.Level = v.(string)
delete(raw, "@level")
}
if v, ok := raw["@timestamp"]; ok {
t, err := time.Parse("2006-01-02T15:04:05.000000Z07:00", v.(string))
if err != nil {
return nil, err
}
entry.Timestamp = t
delete(raw, "@timestamp")
}
// Parse dynamic KV args from the hclog payload.
for k, v := range raw {
entry.KVPairs = append(entry.KVPairs, &logEntryKV{
Key: k,
Value: v,
})
}
return entry, nil
}
|
go
|
func parseJSON(input []byte) (*logEntry, error) {
var raw map[string]interface{}
entry := &logEntry{}
err := json.Unmarshal(input, &raw)
if err != nil {
return nil, err
}
// Parse hclog-specific objects
if v, ok := raw["@message"]; ok {
entry.Message = v.(string)
delete(raw, "@message")
}
if v, ok := raw["@level"]; ok {
entry.Level = v.(string)
delete(raw, "@level")
}
if v, ok := raw["@timestamp"]; ok {
t, err := time.Parse("2006-01-02T15:04:05.000000Z07:00", v.(string))
if err != nil {
return nil, err
}
entry.Timestamp = t
delete(raw, "@timestamp")
}
// Parse dynamic KV args from the hclog payload.
for k, v := range raw {
entry.KVPairs = append(entry.KVPairs, &logEntryKV{
Key: k,
Value: v,
})
}
return entry, nil
}
|
[
"func",
"parseJSON",
"(",
"input",
"[",
"]",
"byte",
")",
"(",
"*",
"logEntry",
",",
"error",
")",
"{",
"var",
"raw",
"map",
"[",
"string",
"]",
"interface",
"{",
"}",
"\n",
"entry",
":=",
"&",
"logEntry",
"{",
"}",
"\n\n",
"err",
":=",
"json",
".",
"Unmarshal",
"(",
"input",
",",
"&",
"raw",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"// Parse hclog-specific objects",
"if",
"v",
",",
"ok",
":=",
"raw",
"[",
"\"",
"\"",
"]",
";",
"ok",
"{",
"entry",
".",
"Message",
"=",
"v",
".",
"(",
"string",
")",
"\n",
"delete",
"(",
"raw",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"if",
"v",
",",
"ok",
":=",
"raw",
"[",
"\"",
"\"",
"]",
";",
"ok",
"{",
"entry",
".",
"Level",
"=",
"v",
".",
"(",
"string",
")",
"\n",
"delete",
"(",
"raw",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"if",
"v",
",",
"ok",
":=",
"raw",
"[",
"\"",
"\"",
"]",
";",
"ok",
"{",
"t",
",",
"err",
":=",
"time",
".",
"Parse",
"(",
"\"",
"\"",
",",
"v",
".",
"(",
"string",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"entry",
".",
"Timestamp",
"=",
"t",
"\n",
"delete",
"(",
"raw",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"// Parse dynamic KV args from the hclog payload.",
"for",
"k",
",",
"v",
":=",
"range",
"raw",
"{",
"entry",
".",
"KVPairs",
"=",
"append",
"(",
"entry",
".",
"KVPairs",
",",
"&",
"logEntryKV",
"{",
"Key",
":",
"k",
",",
"Value",
":",
"v",
",",
"}",
")",
"\n",
"}",
"\n\n",
"return",
"entry",
",",
"nil",
"\n",
"}"
] |
// parseJSON handles parsing JSON output
|
[
"parseJSON",
"handles",
"parsing",
"JSON",
"output"
] |
5692942914bbdbc03558fde936b1f0bc2af365be
|
https://github.com/hashicorp/go-plugin/blob/5692942914bbdbc03558fde936b1f0bc2af365be/log_entry.go#L35-L73
|
21,730
|
hashicorp/go-plugin
|
client.go
|
Check
|
func (s *SecureConfig) Check(filePath string) (bool, error) {
if len(s.Checksum) == 0 {
return false, ErrSecureConfigNoChecksum
}
if s.Hash == nil {
return false, ErrSecureConfigNoHash
}
file, err := os.Open(filePath)
if err != nil {
return false, err
}
defer file.Close()
_, err = io.Copy(s.Hash, file)
if err != nil {
return false, err
}
sum := s.Hash.Sum(nil)
return subtle.ConstantTimeCompare(sum, s.Checksum) == 1, nil
}
|
go
|
func (s *SecureConfig) Check(filePath string) (bool, error) {
if len(s.Checksum) == 0 {
return false, ErrSecureConfigNoChecksum
}
if s.Hash == nil {
return false, ErrSecureConfigNoHash
}
file, err := os.Open(filePath)
if err != nil {
return false, err
}
defer file.Close()
_, err = io.Copy(s.Hash, file)
if err != nil {
return false, err
}
sum := s.Hash.Sum(nil)
return subtle.ConstantTimeCompare(sum, s.Checksum) == 1, nil
}
|
[
"func",
"(",
"s",
"*",
"SecureConfig",
")",
"Check",
"(",
"filePath",
"string",
")",
"(",
"bool",
",",
"error",
")",
"{",
"if",
"len",
"(",
"s",
".",
"Checksum",
")",
"==",
"0",
"{",
"return",
"false",
",",
"ErrSecureConfigNoChecksum",
"\n",
"}",
"\n\n",
"if",
"s",
".",
"Hash",
"==",
"nil",
"{",
"return",
"false",
",",
"ErrSecureConfigNoHash",
"\n",
"}",
"\n\n",
"file",
",",
"err",
":=",
"os",
".",
"Open",
"(",
"filePath",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"false",
",",
"err",
"\n",
"}",
"\n",
"defer",
"file",
".",
"Close",
"(",
")",
"\n\n",
"_",
",",
"err",
"=",
"io",
".",
"Copy",
"(",
"s",
".",
"Hash",
",",
"file",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"false",
",",
"err",
"\n",
"}",
"\n\n",
"sum",
":=",
"s",
".",
"Hash",
".",
"Sum",
"(",
"nil",
")",
"\n\n",
"return",
"subtle",
".",
"ConstantTimeCompare",
"(",
"sum",
",",
"s",
".",
"Checksum",
")",
"==",
"1",
",",
"nil",
"\n",
"}"
] |
// Check takes the filepath to an executable and returns true if the checksum of
// the file matches the checksum provided in the SecureConfig.
|
[
"Check",
"takes",
"the",
"filepath",
"to",
"an",
"executable",
"and",
"returns",
"true",
"if",
"the",
"checksum",
"of",
"the",
"file",
"matches",
"the",
"checksum",
"provided",
"in",
"the",
"SecureConfig",
"."
] |
5692942914bbdbc03558fde936b1f0bc2af365be
|
https://github.com/hashicorp/go-plugin/blob/5692942914bbdbc03558fde936b1f0bc2af365be/client.go#L233-L256
|
21,731
|
hashicorp/go-plugin
|
client.go
|
Client
|
func (c *Client) Client() (ClientProtocol, error) {
_, err := c.Start()
if err != nil {
return nil, err
}
c.l.Lock()
defer c.l.Unlock()
if c.client != nil {
return c.client, nil
}
switch c.protocol {
case ProtocolNetRPC:
c.client, err = newRPCClient(c)
case ProtocolGRPC:
c.client, err = newGRPCClient(c.doneCtx, c)
default:
return nil, fmt.Errorf("unknown server protocol: %s", c.protocol)
}
if err != nil {
c.client = nil
return nil, err
}
return c.client, nil
}
|
go
|
func (c *Client) Client() (ClientProtocol, error) {
_, err := c.Start()
if err != nil {
return nil, err
}
c.l.Lock()
defer c.l.Unlock()
if c.client != nil {
return c.client, nil
}
switch c.protocol {
case ProtocolNetRPC:
c.client, err = newRPCClient(c)
case ProtocolGRPC:
c.client, err = newGRPCClient(c.doneCtx, c)
default:
return nil, fmt.Errorf("unknown server protocol: %s", c.protocol)
}
if err != nil {
c.client = nil
return nil, err
}
return c.client, nil
}
|
[
"func",
"(",
"c",
"*",
"Client",
")",
"Client",
"(",
")",
"(",
"ClientProtocol",
",",
"error",
")",
"{",
"_",
",",
"err",
":=",
"c",
".",
"Start",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"c",
".",
"l",
".",
"Lock",
"(",
")",
"\n",
"defer",
"c",
".",
"l",
".",
"Unlock",
"(",
")",
"\n\n",
"if",
"c",
".",
"client",
"!=",
"nil",
"{",
"return",
"c",
".",
"client",
",",
"nil",
"\n",
"}",
"\n\n",
"switch",
"c",
".",
"protocol",
"{",
"case",
"ProtocolNetRPC",
":",
"c",
".",
"client",
",",
"err",
"=",
"newRPCClient",
"(",
"c",
")",
"\n\n",
"case",
"ProtocolGRPC",
":",
"c",
".",
"client",
",",
"err",
"=",
"newGRPCClient",
"(",
"c",
".",
"doneCtx",
",",
"c",
")",
"\n\n",
"default",
":",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"c",
".",
"protocol",
")",
"\n",
"}",
"\n\n",
"if",
"err",
"!=",
"nil",
"{",
"c",
".",
"client",
"=",
"nil",
"\n",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"return",
"c",
".",
"client",
",",
"nil",
"\n",
"}"
] |
// Client returns the protocol client for this connection.
//
// Subsequent calls to this will return the same client.
|
[
"Client",
"returns",
"the",
"protocol",
"client",
"for",
"this",
"connection",
".",
"Subsequent",
"calls",
"to",
"this",
"will",
"return",
"the",
"same",
"client",
"."
] |
5692942914bbdbc03558fde936b1f0bc2af365be
|
https://github.com/hashicorp/go-plugin/blob/5692942914bbdbc03558fde936b1f0bc2af365be/client.go#L340-L370
|
21,732
|
hashicorp/go-plugin
|
client.go
|
killed
|
func (c *Client) killed() bool {
c.l.Lock()
defer c.l.Unlock()
return c.processKilled
}
|
go
|
func (c *Client) killed() bool {
c.l.Lock()
defer c.l.Unlock()
return c.processKilled
}
|
[
"func",
"(",
"c",
"*",
"Client",
")",
"killed",
"(",
")",
"bool",
"{",
"c",
".",
"l",
".",
"Lock",
"(",
")",
"\n",
"defer",
"c",
".",
"l",
".",
"Unlock",
"(",
")",
"\n",
"return",
"c",
".",
"processKilled",
"\n",
"}"
] |
// killed is used in tests to check if a process failed to exit gracefully, and
// needed to be killed.
|
[
"killed",
"is",
"used",
"in",
"tests",
"to",
"check",
"if",
"a",
"process",
"failed",
"to",
"exit",
"gracefully",
"and",
"needed",
"to",
"be",
"killed",
"."
] |
5692942914bbdbc03558fde936b1f0bc2af365be
|
https://github.com/hashicorp/go-plugin/blob/5692942914bbdbc03558fde936b1f0bc2af365be/client.go#L381-L385
|
21,733
|
hashicorp/go-plugin
|
client.go
|
loadServerCert
|
func (c *Client) loadServerCert(cert string) error {
certPool := x509.NewCertPool()
asn1, err := base64.RawStdEncoding.DecodeString(cert)
if err != nil {
return err
}
x509Cert, err := x509.ParseCertificate([]byte(asn1))
if err != nil {
return err
}
certPool.AddCert(x509Cert)
c.config.TLSConfig.RootCAs = certPool
return nil
}
|
go
|
func (c *Client) loadServerCert(cert string) error {
certPool := x509.NewCertPool()
asn1, err := base64.RawStdEncoding.DecodeString(cert)
if err != nil {
return err
}
x509Cert, err := x509.ParseCertificate([]byte(asn1))
if err != nil {
return err
}
certPool.AddCert(x509Cert)
c.config.TLSConfig.RootCAs = certPool
return nil
}
|
[
"func",
"(",
"c",
"*",
"Client",
")",
"loadServerCert",
"(",
"cert",
"string",
")",
"error",
"{",
"certPool",
":=",
"x509",
".",
"NewCertPool",
"(",
")",
"\n\n",
"asn1",
",",
"err",
":=",
"base64",
".",
"RawStdEncoding",
".",
"DecodeString",
"(",
"cert",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"x509Cert",
",",
"err",
":=",
"x509",
".",
"ParseCertificate",
"(",
"[",
"]",
"byte",
"(",
"asn1",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"certPool",
".",
"AddCert",
"(",
"x509Cert",
")",
"\n\n",
"c",
".",
"config",
".",
"TLSConfig",
".",
"RootCAs",
"=",
"certPool",
"\n",
"return",
"nil",
"\n",
"}"
] |
// loadServerCert is used by AutoMTLS to read an x.509 cert returned by the
// server, and load it as the RootCA for the client TLSConfig.
|
[
"loadServerCert",
"is",
"used",
"by",
"AutoMTLS",
"to",
"read",
"an",
"x",
".",
"509",
"cert",
"returned",
"by",
"the",
"server",
"and",
"load",
"it",
"as",
"the",
"RootCA",
"for",
"the",
"client",
"TLSConfig",
"."
] |
5692942914bbdbc03558fde936b1f0bc2af365be
|
https://github.com/hashicorp/go-plugin/blob/5692942914bbdbc03558fde936b1f0bc2af365be/client.go#L759-L776
|
21,734
|
hashicorp/go-plugin
|
client.go
|
checkProtoVersion
|
func (c *Client) checkProtoVersion(protoVersion string) (int, PluginSet, error) {
serverVersion, err := strconv.Atoi(protoVersion)
if err != nil {
return 0, nil, fmt.Errorf("Error parsing protocol version %q: %s", protoVersion, err)
}
// record these for the error message
var clientVersions []int
// all versions, including the legacy ProtocolVersion have been added to
// the versions set
for version, plugins := range c.config.VersionedPlugins {
clientVersions = append(clientVersions, version)
if serverVersion != version {
continue
}
return version, plugins, nil
}
return 0, nil, fmt.Errorf("Incompatible API version with plugin. "+
"Plugin version: %d, Client versions: %d", serverVersion, clientVersions)
}
|
go
|
func (c *Client) checkProtoVersion(protoVersion string) (int, PluginSet, error) {
serverVersion, err := strconv.Atoi(protoVersion)
if err != nil {
return 0, nil, fmt.Errorf("Error parsing protocol version %q: %s", protoVersion, err)
}
// record these for the error message
var clientVersions []int
// all versions, including the legacy ProtocolVersion have been added to
// the versions set
for version, plugins := range c.config.VersionedPlugins {
clientVersions = append(clientVersions, version)
if serverVersion != version {
continue
}
return version, plugins, nil
}
return 0, nil, fmt.Errorf("Incompatible API version with plugin. "+
"Plugin version: %d, Client versions: %d", serverVersion, clientVersions)
}
|
[
"func",
"(",
"c",
"*",
"Client",
")",
"checkProtoVersion",
"(",
"protoVersion",
"string",
")",
"(",
"int",
",",
"PluginSet",
",",
"error",
")",
"{",
"serverVersion",
",",
"err",
":=",
"strconv",
".",
"Atoi",
"(",
"protoVersion",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"0",
",",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"protoVersion",
",",
"err",
")",
"\n",
"}",
"\n\n",
"// record these for the error message",
"var",
"clientVersions",
"[",
"]",
"int",
"\n\n",
"// all versions, including the legacy ProtocolVersion have been added to",
"// the versions set",
"for",
"version",
",",
"plugins",
":=",
"range",
"c",
".",
"config",
".",
"VersionedPlugins",
"{",
"clientVersions",
"=",
"append",
"(",
"clientVersions",
",",
"version",
")",
"\n\n",
"if",
"serverVersion",
"!=",
"version",
"{",
"continue",
"\n",
"}",
"\n",
"return",
"version",
",",
"plugins",
",",
"nil",
"\n",
"}",
"\n\n",
"return",
"0",
",",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
"+",
"\"",
"\"",
",",
"serverVersion",
",",
"clientVersions",
")",
"\n",
"}"
] |
// checkProtoVersion returns the negotiated version and PluginSet.
// This returns an error if the server returned an incompatible protocol
// version, or an invalid handshake response.
|
[
"checkProtoVersion",
"returns",
"the",
"negotiated",
"version",
"and",
"PluginSet",
".",
"This",
"returns",
"an",
"error",
"if",
"the",
"server",
"returned",
"an",
"incompatible",
"protocol",
"version",
"or",
"an",
"invalid",
"handshake",
"response",
"."
] |
5692942914bbdbc03558fde936b1f0bc2af365be
|
https://github.com/hashicorp/go-plugin/blob/5692942914bbdbc03558fde936b1f0bc2af365be/client.go#L834-L856
|
21,735
|
hashicorp/go-plugin
|
client.go
|
ReattachConfig
|
func (c *Client) ReattachConfig() *ReattachConfig {
c.l.Lock()
defer c.l.Unlock()
if c.address == nil {
return nil
}
if c.config.Cmd != nil && c.config.Cmd.Process == nil {
return nil
}
// If we connected via reattach, just return the information as-is
if c.config.Reattach != nil {
return c.config.Reattach
}
return &ReattachConfig{
Protocol: c.protocol,
Addr: c.address,
Pid: c.config.Cmd.Process.Pid,
}
}
|
go
|
func (c *Client) ReattachConfig() *ReattachConfig {
c.l.Lock()
defer c.l.Unlock()
if c.address == nil {
return nil
}
if c.config.Cmd != nil && c.config.Cmd.Process == nil {
return nil
}
// If we connected via reattach, just return the information as-is
if c.config.Reattach != nil {
return c.config.Reattach
}
return &ReattachConfig{
Protocol: c.protocol,
Addr: c.address,
Pid: c.config.Cmd.Process.Pid,
}
}
|
[
"func",
"(",
"c",
"*",
"Client",
")",
"ReattachConfig",
"(",
")",
"*",
"ReattachConfig",
"{",
"c",
".",
"l",
".",
"Lock",
"(",
")",
"\n",
"defer",
"c",
".",
"l",
".",
"Unlock",
"(",
")",
"\n\n",
"if",
"c",
".",
"address",
"==",
"nil",
"{",
"return",
"nil",
"\n",
"}",
"\n\n",
"if",
"c",
".",
"config",
".",
"Cmd",
"!=",
"nil",
"&&",
"c",
".",
"config",
".",
"Cmd",
".",
"Process",
"==",
"nil",
"{",
"return",
"nil",
"\n",
"}",
"\n\n",
"// If we connected via reattach, just return the information as-is",
"if",
"c",
".",
"config",
".",
"Reattach",
"!=",
"nil",
"{",
"return",
"c",
".",
"config",
".",
"Reattach",
"\n",
"}",
"\n\n",
"return",
"&",
"ReattachConfig",
"{",
"Protocol",
":",
"c",
".",
"protocol",
",",
"Addr",
":",
"c",
".",
"address",
",",
"Pid",
":",
"c",
".",
"config",
".",
"Cmd",
".",
"Process",
".",
"Pid",
",",
"}",
"\n",
"}"
] |
// ReattachConfig returns the information that must be provided to NewClient
// to reattach to the plugin process that this client started. This is
// useful for plugins that detach from their parent process.
//
// If this returns nil then the process hasn't been started yet. Please
// call Start or Client before calling this.
|
[
"ReattachConfig",
"returns",
"the",
"information",
"that",
"must",
"be",
"provided",
"to",
"NewClient",
"to",
"reattach",
"to",
"the",
"plugin",
"process",
"that",
"this",
"client",
"started",
".",
"This",
"is",
"useful",
"for",
"plugins",
"that",
"detach",
"from",
"their",
"parent",
"process",
".",
"If",
"this",
"returns",
"nil",
"then",
"the",
"process",
"hasn",
"t",
"been",
"started",
"yet",
".",
"Please",
"call",
"Start",
"or",
"Client",
"before",
"calling",
"this",
"."
] |
5692942914bbdbc03558fde936b1f0bc2af365be
|
https://github.com/hashicorp/go-plugin/blob/5692942914bbdbc03558fde936b1f0bc2af365be/client.go#L864-L886
|
21,736
|
hashicorp/go-plugin
|
client.go
|
Protocol
|
func (c *Client) Protocol() Protocol {
_, err := c.Start()
if err != nil {
return ProtocolInvalid
}
return c.protocol
}
|
go
|
func (c *Client) Protocol() Protocol {
_, err := c.Start()
if err != nil {
return ProtocolInvalid
}
return c.protocol
}
|
[
"func",
"(",
"c",
"*",
"Client",
")",
"Protocol",
"(",
")",
"Protocol",
"{",
"_",
",",
"err",
":=",
"c",
".",
"Start",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"ProtocolInvalid",
"\n",
"}",
"\n\n",
"return",
"c",
".",
"protocol",
"\n",
"}"
] |
// Protocol returns the protocol of server on the remote end. This will
// start the plugin process if it isn't already started. Errors from
// starting the plugin are surpressed and ProtocolInvalid is returned. It
// is recommended you call Start explicitly before calling Protocol to ensure
// no errors occur.
|
[
"Protocol",
"returns",
"the",
"protocol",
"of",
"server",
"on",
"the",
"remote",
"end",
".",
"This",
"will",
"start",
"the",
"plugin",
"process",
"if",
"it",
"isn",
"t",
"already",
"started",
".",
"Errors",
"from",
"starting",
"the",
"plugin",
"are",
"surpressed",
"and",
"ProtocolInvalid",
"is",
"returned",
".",
"It",
"is",
"recommended",
"you",
"call",
"Start",
"explicitly",
"before",
"calling",
"Protocol",
"to",
"ensure",
"no",
"errors",
"occur",
"."
] |
5692942914bbdbc03558fde936b1f0bc2af365be
|
https://github.com/hashicorp/go-plugin/blob/5692942914bbdbc03558fde936b1f0bc2af365be/client.go#L893-L900
|
21,737
|
hashicorp/go-plugin
|
client.go
|
dialer
|
func (c *Client) dialer(_ string, timeout time.Duration) (net.Conn, error) {
conn, err := netAddrDialer(c.address)("", timeout)
if err != nil {
return nil, err
}
// If we have a TLS config we wrap our connection. We only do this
// for net/rpc since gRPC uses its own mechanism for TLS.
if c.protocol == ProtocolNetRPC && c.config.TLSConfig != nil {
conn = tls.Client(conn, c.config.TLSConfig)
}
return conn, nil
}
|
go
|
func (c *Client) dialer(_ string, timeout time.Duration) (net.Conn, error) {
conn, err := netAddrDialer(c.address)("", timeout)
if err != nil {
return nil, err
}
// If we have a TLS config we wrap our connection. We only do this
// for net/rpc since gRPC uses its own mechanism for TLS.
if c.protocol == ProtocolNetRPC && c.config.TLSConfig != nil {
conn = tls.Client(conn, c.config.TLSConfig)
}
return conn, nil
}
|
[
"func",
"(",
"c",
"*",
"Client",
")",
"dialer",
"(",
"_",
"string",
",",
"timeout",
"time",
".",
"Duration",
")",
"(",
"net",
".",
"Conn",
",",
"error",
")",
"{",
"conn",
",",
"err",
":=",
"netAddrDialer",
"(",
"c",
".",
"address",
")",
"(",
"\"",
"\"",
",",
"timeout",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"// If we have a TLS config we wrap our connection. We only do this",
"// for net/rpc since gRPC uses its own mechanism for TLS.",
"if",
"c",
".",
"protocol",
"==",
"ProtocolNetRPC",
"&&",
"c",
".",
"config",
".",
"TLSConfig",
"!=",
"nil",
"{",
"conn",
"=",
"tls",
".",
"Client",
"(",
"conn",
",",
"c",
".",
"config",
".",
"TLSConfig",
")",
"\n",
"}",
"\n\n",
"return",
"conn",
",",
"nil",
"\n",
"}"
] |
// dialer is compatible with grpc.WithDialer and creates the connection
// to the plugin.
|
[
"dialer",
"is",
"compatible",
"with",
"grpc",
".",
"WithDialer",
"and",
"creates",
"the",
"connection",
"to",
"the",
"plugin",
"."
] |
5692942914bbdbc03558fde936b1f0bc2af365be
|
https://github.com/hashicorp/go-plugin/blob/5692942914bbdbc03558fde936b1f0bc2af365be/client.go#L920-L933
|
21,738
|
hashicorp/go-plugin
|
mtls.go
|
generateCert
|
func generateCert() (cert []byte, privateKey []byte, err error) {
key, err := ecdsa.GenerateKey(elliptic.P521(), rand.Reader)
if err != nil {
return nil, nil, err
}
serialNumberLimit := new(big.Int).Lsh(big.NewInt(1), 128)
sn, err := rand.Int(rand.Reader, serialNumberLimit)
if err != nil {
return nil, nil, err
}
host := "localhost"
template := &x509.Certificate{
Subject: pkix.Name{
CommonName: host,
Organization: []string{"HashiCorp"},
},
DNSNames: []string{host},
ExtKeyUsage: []x509.ExtKeyUsage{
x509.ExtKeyUsageClientAuth,
x509.ExtKeyUsageServerAuth,
},
KeyUsage: x509.KeyUsageDigitalSignature | x509.KeyUsageKeyEncipherment | x509.KeyUsageKeyAgreement | x509.KeyUsageCertSign,
BasicConstraintsValid: true,
SerialNumber: sn,
NotBefore: time.Now().Add(-30 * time.Second),
NotAfter: time.Now().Add(262980 * time.Hour),
IsCA: true,
}
der, err := x509.CreateCertificate(rand.Reader, template, template, key.Public(), key)
if err != nil {
return nil, nil, err
}
var certOut bytes.Buffer
if err := pem.Encode(&certOut, &pem.Block{Type: "CERTIFICATE", Bytes: der}); err != nil {
return nil, nil, err
}
keyBytes, err := x509.MarshalECPrivateKey(key)
if err != nil {
return nil, nil, err
}
var keyOut bytes.Buffer
if err := pem.Encode(&keyOut, &pem.Block{Type: "EC PRIVATE KEY", Bytes: keyBytes}); err != nil {
return nil, nil, err
}
cert = certOut.Bytes()
privateKey = keyOut.Bytes()
return cert, privateKey, nil
}
|
go
|
func generateCert() (cert []byte, privateKey []byte, err error) {
key, err := ecdsa.GenerateKey(elliptic.P521(), rand.Reader)
if err != nil {
return nil, nil, err
}
serialNumberLimit := new(big.Int).Lsh(big.NewInt(1), 128)
sn, err := rand.Int(rand.Reader, serialNumberLimit)
if err != nil {
return nil, nil, err
}
host := "localhost"
template := &x509.Certificate{
Subject: pkix.Name{
CommonName: host,
Organization: []string{"HashiCorp"},
},
DNSNames: []string{host},
ExtKeyUsage: []x509.ExtKeyUsage{
x509.ExtKeyUsageClientAuth,
x509.ExtKeyUsageServerAuth,
},
KeyUsage: x509.KeyUsageDigitalSignature | x509.KeyUsageKeyEncipherment | x509.KeyUsageKeyAgreement | x509.KeyUsageCertSign,
BasicConstraintsValid: true,
SerialNumber: sn,
NotBefore: time.Now().Add(-30 * time.Second),
NotAfter: time.Now().Add(262980 * time.Hour),
IsCA: true,
}
der, err := x509.CreateCertificate(rand.Reader, template, template, key.Public(), key)
if err != nil {
return nil, nil, err
}
var certOut bytes.Buffer
if err := pem.Encode(&certOut, &pem.Block{Type: "CERTIFICATE", Bytes: der}); err != nil {
return nil, nil, err
}
keyBytes, err := x509.MarshalECPrivateKey(key)
if err != nil {
return nil, nil, err
}
var keyOut bytes.Buffer
if err := pem.Encode(&keyOut, &pem.Block{Type: "EC PRIVATE KEY", Bytes: keyBytes}); err != nil {
return nil, nil, err
}
cert = certOut.Bytes()
privateKey = keyOut.Bytes()
return cert, privateKey, nil
}
|
[
"func",
"generateCert",
"(",
")",
"(",
"cert",
"[",
"]",
"byte",
",",
"privateKey",
"[",
"]",
"byte",
",",
"err",
"error",
")",
"{",
"key",
",",
"err",
":=",
"ecdsa",
".",
"GenerateKey",
"(",
"elliptic",
".",
"P521",
"(",
")",
",",
"rand",
".",
"Reader",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"serialNumberLimit",
":=",
"new",
"(",
"big",
".",
"Int",
")",
".",
"Lsh",
"(",
"big",
".",
"NewInt",
"(",
"1",
")",
",",
"128",
")",
"\n",
"sn",
",",
"err",
":=",
"rand",
".",
"Int",
"(",
"rand",
".",
"Reader",
",",
"serialNumberLimit",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"host",
":=",
"\"",
"\"",
"\n\n",
"template",
":=",
"&",
"x509",
".",
"Certificate",
"{",
"Subject",
":",
"pkix",
".",
"Name",
"{",
"CommonName",
":",
"host",
",",
"Organization",
":",
"[",
"]",
"string",
"{",
"\"",
"\"",
"}",
",",
"}",
",",
"DNSNames",
":",
"[",
"]",
"string",
"{",
"host",
"}",
",",
"ExtKeyUsage",
":",
"[",
"]",
"x509",
".",
"ExtKeyUsage",
"{",
"x509",
".",
"ExtKeyUsageClientAuth",
",",
"x509",
".",
"ExtKeyUsageServerAuth",
",",
"}",
",",
"KeyUsage",
":",
"x509",
".",
"KeyUsageDigitalSignature",
"|",
"x509",
".",
"KeyUsageKeyEncipherment",
"|",
"x509",
".",
"KeyUsageKeyAgreement",
"|",
"x509",
".",
"KeyUsageCertSign",
",",
"BasicConstraintsValid",
":",
"true",
",",
"SerialNumber",
":",
"sn",
",",
"NotBefore",
":",
"time",
".",
"Now",
"(",
")",
".",
"Add",
"(",
"-",
"30",
"*",
"time",
".",
"Second",
")",
",",
"NotAfter",
":",
"time",
".",
"Now",
"(",
")",
".",
"Add",
"(",
"262980",
"*",
"time",
".",
"Hour",
")",
",",
"IsCA",
":",
"true",
",",
"}",
"\n\n",
"der",
",",
"err",
":=",
"x509",
".",
"CreateCertificate",
"(",
"rand",
".",
"Reader",
",",
"template",
",",
"template",
",",
"key",
".",
"Public",
"(",
")",
",",
"key",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"var",
"certOut",
"bytes",
".",
"Buffer",
"\n",
"if",
"err",
":=",
"pem",
".",
"Encode",
"(",
"&",
"certOut",
",",
"&",
"pem",
".",
"Block",
"{",
"Type",
":",
"\"",
"\"",
",",
"Bytes",
":",
"der",
"}",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"keyBytes",
",",
"err",
":=",
"x509",
".",
"MarshalECPrivateKey",
"(",
"key",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"var",
"keyOut",
"bytes",
".",
"Buffer",
"\n",
"if",
"err",
":=",
"pem",
".",
"Encode",
"(",
"&",
"keyOut",
",",
"&",
"pem",
".",
"Block",
"{",
"Type",
":",
"\"",
"\"",
",",
"Bytes",
":",
"keyBytes",
"}",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"cert",
"=",
"certOut",
".",
"Bytes",
"(",
")",
"\n",
"privateKey",
"=",
"keyOut",
".",
"Bytes",
"(",
")",
"\n\n",
"return",
"cert",
",",
"privateKey",
",",
"nil",
"\n",
"}"
] |
// generateCert generates a temporary certificate for plugin authentication. The
// certificate and private key are returns in PEM format.
|
[
"generateCert",
"generates",
"a",
"temporary",
"certificate",
"for",
"plugin",
"authentication",
".",
"The",
"certificate",
"and",
"private",
"key",
"are",
"returns",
"in",
"PEM",
"format",
"."
] |
5692942914bbdbc03558fde936b1f0bc2af365be
|
https://github.com/hashicorp/go-plugin/blob/5692942914bbdbc03558fde936b1f0bc2af365be/mtls.go#L17-L73
|
21,739
|
hashicorp/go-plugin
|
process_windows.go
|
_pidAlive
|
func _pidAlive(pid int) bool {
h, err := syscall.OpenProcess(processDesiredAccess, false, uint32(pid))
if err != nil {
return false
}
var ec uint32
if e := syscall.GetExitCodeProcess(h, &ec); e != nil {
return false
}
return ec == exit_STILL_ACTIVE
}
|
go
|
func _pidAlive(pid int) bool {
h, err := syscall.OpenProcess(processDesiredAccess, false, uint32(pid))
if err != nil {
return false
}
var ec uint32
if e := syscall.GetExitCodeProcess(h, &ec); e != nil {
return false
}
return ec == exit_STILL_ACTIVE
}
|
[
"func",
"_pidAlive",
"(",
"pid",
"int",
")",
"bool",
"{",
"h",
",",
"err",
":=",
"syscall",
".",
"OpenProcess",
"(",
"processDesiredAccess",
",",
"false",
",",
"uint32",
"(",
"pid",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"false",
"\n",
"}",
"\n\n",
"var",
"ec",
"uint32",
"\n",
"if",
"e",
":=",
"syscall",
".",
"GetExitCodeProcess",
"(",
"h",
",",
"&",
"ec",
")",
";",
"e",
"!=",
"nil",
"{",
"return",
"false",
"\n",
"}",
"\n\n",
"return",
"ec",
"==",
"exit_STILL_ACTIVE",
"\n",
"}"
] |
// _pidAlive tests whether a process is alive or not
|
[
"_pidAlive",
"tests",
"whether",
"a",
"process",
"is",
"alive",
"or",
"not"
] |
5692942914bbdbc03558fde936b1f0bc2af365be
|
https://github.com/hashicorp/go-plugin/blob/5692942914bbdbc03558fde936b1f0bc2af365be/process_windows.go#L17-L29
|
21,740
|
hashicorp/go-plugin
|
grpc_server.go
|
Config
|
func (s *GRPCServer) Config() string {
// Create a buffer that will contain our final contents
var buf bytes.Buffer
// Wrap the base64 encoding with JSON encoding.
if err := json.NewEncoder(&buf).Encode(s.config); err != nil {
// We panic since ths shouldn't happen under any scenario. We
// carefully control the structure being encoded here and it should
// always be successful.
panic(err)
}
return buf.String()
}
|
go
|
func (s *GRPCServer) Config() string {
// Create a buffer that will contain our final contents
var buf bytes.Buffer
// Wrap the base64 encoding with JSON encoding.
if err := json.NewEncoder(&buf).Encode(s.config); err != nil {
// We panic since ths shouldn't happen under any scenario. We
// carefully control the structure being encoded here and it should
// always be successful.
panic(err)
}
return buf.String()
}
|
[
"func",
"(",
"s",
"*",
"GRPCServer",
")",
"Config",
"(",
")",
"string",
"{",
"// Create a buffer that will contain our final contents",
"var",
"buf",
"bytes",
".",
"Buffer",
"\n\n",
"// Wrap the base64 encoding with JSON encoding.",
"if",
"err",
":=",
"json",
".",
"NewEncoder",
"(",
"&",
"buf",
")",
".",
"Encode",
"(",
"s",
".",
"config",
")",
";",
"err",
"!=",
"nil",
"{",
"// We panic since ths shouldn't happen under any scenario. We",
"// carefully control the structure being encoded here and it should",
"// always be successful.",
"panic",
"(",
"err",
")",
"\n",
"}",
"\n\n",
"return",
"buf",
".",
"String",
"(",
")",
"\n",
"}"
] |
// Config is the GRPCServerConfig encoded as JSON then base64.
|
[
"Config",
"is",
"the",
"GRPCServerConfig",
"encoded",
"as",
"JSON",
"then",
"base64",
"."
] |
5692942914bbdbc03558fde936b1f0bc2af365be
|
https://github.com/hashicorp/go-plugin/blob/5692942914bbdbc03558fde936b1f0bc2af365be/grpc_server.go#L114-L127
|
21,741
|
hashicorp/go-plugin
|
rpc_client.go
|
newRPCClient
|
func newRPCClient(c *Client) (*RPCClient, error) {
// Connect to the client
conn, err := net.Dial(c.address.Network(), c.address.String())
if err != nil {
return nil, err
}
if tcpConn, ok := conn.(*net.TCPConn); ok {
// Make sure to set keep alive so that the connection doesn't die
tcpConn.SetKeepAlive(true)
}
if c.config.TLSConfig != nil {
conn = tls.Client(conn, c.config.TLSConfig)
}
// Create the actual RPC client
result, err := NewRPCClient(conn, c.config.Plugins)
if err != nil {
conn.Close()
return nil, err
}
// Begin the stream syncing so that stdin, out, err work properly
err = result.SyncStreams(
c.config.SyncStdout,
c.config.SyncStderr)
if err != nil {
result.Close()
return nil, err
}
return result, nil
}
|
go
|
func newRPCClient(c *Client) (*RPCClient, error) {
// Connect to the client
conn, err := net.Dial(c.address.Network(), c.address.String())
if err != nil {
return nil, err
}
if tcpConn, ok := conn.(*net.TCPConn); ok {
// Make sure to set keep alive so that the connection doesn't die
tcpConn.SetKeepAlive(true)
}
if c.config.TLSConfig != nil {
conn = tls.Client(conn, c.config.TLSConfig)
}
// Create the actual RPC client
result, err := NewRPCClient(conn, c.config.Plugins)
if err != nil {
conn.Close()
return nil, err
}
// Begin the stream syncing so that stdin, out, err work properly
err = result.SyncStreams(
c.config.SyncStdout,
c.config.SyncStderr)
if err != nil {
result.Close()
return nil, err
}
return result, nil
}
|
[
"func",
"newRPCClient",
"(",
"c",
"*",
"Client",
")",
"(",
"*",
"RPCClient",
",",
"error",
")",
"{",
"// Connect to the client",
"conn",
",",
"err",
":=",
"net",
".",
"Dial",
"(",
"c",
".",
"address",
".",
"Network",
"(",
")",
",",
"c",
".",
"address",
".",
"String",
"(",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"if",
"tcpConn",
",",
"ok",
":=",
"conn",
".",
"(",
"*",
"net",
".",
"TCPConn",
")",
";",
"ok",
"{",
"// Make sure to set keep alive so that the connection doesn't die",
"tcpConn",
".",
"SetKeepAlive",
"(",
"true",
")",
"\n",
"}",
"\n\n",
"if",
"c",
".",
"config",
".",
"TLSConfig",
"!=",
"nil",
"{",
"conn",
"=",
"tls",
".",
"Client",
"(",
"conn",
",",
"c",
".",
"config",
".",
"TLSConfig",
")",
"\n",
"}",
"\n\n",
"// Create the actual RPC client",
"result",
",",
"err",
":=",
"NewRPCClient",
"(",
"conn",
",",
"c",
".",
"config",
".",
"Plugins",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"conn",
".",
"Close",
"(",
")",
"\n",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"// Begin the stream syncing so that stdin, out, err work properly",
"err",
"=",
"result",
".",
"SyncStreams",
"(",
"c",
".",
"config",
".",
"SyncStdout",
",",
"c",
".",
"config",
".",
"SyncStderr",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"result",
".",
"Close",
"(",
")",
"\n",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"return",
"result",
",",
"nil",
"\n",
"}"
] |
// newRPCClient creates a new RPCClient. The Client argument is expected
// to be successfully started already with a lock held.
|
[
"newRPCClient",
"creates",
"a",
"new",
"RPCClient",
".",
"The",
"Client",
"argument",
"is",
"expected",
"to",
"be",
"successfully",
"started",
"already",
"with",
"a",
"lock",
"held",
"."
] |
5692942914bbdbc03558fde936b1f0bc2af365be
|
https://github.com/hashicorp/go-plugin/blob/5692942914bbdbc03558fde936b1f0bc2af365be/rpc_client.go#L25-L57
|
21,742
|
hashicorp/go-plugin
|
rpc_client.go
|
NewRPCClient
|
func NewRPCClient(conn io.ReadWriteCloser, plugins map[string]Plugin) (*RPCClient, error) {
// Create the yamux client so we can multiplex
mux, err := yamux.Client(conn, nil)
if err != nil {
conn.Close()
return nil, err
}
// Connect to the control stream.
control, err := mux.Open()
if err != nil {
mux.Close()
return nil, err
}
// Connect stdout, stderr streams
stdstream := make([]net.Conn, 2)
for i, _ := range stdstream {
stdstream[i], err = mux.Open()
if err != nil {
mux.Close()
return nil, err
}
}
// Create the broker and start it up
broker := newMuxBroker(mux)
go broker.Run()
// Build the client using our broker and control channel.
return &RPCClient{
broker: broker,
control: rpc.NewClient(control),
plugins: plugins,
stdout: stdstream[0],
stderr: stdstream[1],
}, nil
}
|
go
|
func NewRPCClient(conn io.ReadWriteCloser, plugins map[string]Plugin) (*RPCClient, error) {
// Create the yamux client so we can multiplex
mux, err := yamux.Client(conn, nil)
if err != nil {
conn.Close()
return nil, err
}
// Connect to the control stream.
control, err := mux.Open()
if err != nil {
mux.Close()
return nil, err
}
// Connect stdout, stderr streams
stdstream := make([]net.Conn, 2)
for i, _ := range stdstream {
stdstream[i], err = mux.Open()
if err != nil {
mux.Close()
return nil, err
}
}
// Create the broker and start it up
broker := newMuxBroker(mux)
go broker.Run()
// Build the client using our broker and control channel.
return &RPCClient{
broker: broker,
control: rpc.NewClient(control),
plugins: plugins,
stdout: stdstream[0],
stderr: stdstream[1],
}, nil
}
|
[
"func",
"NewRPCClient",
"(",
"conn",
"io",
".",
"ReadWriteCloser",
",",
"plugins",
"map",
"[",
"string",
"]",
"Plugin",
")",
"(",
"*",
"RPCClient",
",",
"error",
")",
"{",
"// Create the yamux client so we can multiplex",
"mux",
",",
"err",
":=",
"yamux",
".",
"Client",
"(",
"conn",
",",
"nil",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"conn",
".",
"Close",
"(",
")",
"\n",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"// Connect to the control stream.",
"control",
",",
"err",
":=",
"mux",
".",
"Open",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"mux",
".",
"Close",
"(",
")",
"\n",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"// Connect stdout, stderr streams",
"stdstream",
":=",
"make",
"(",
"[",
"]",
"net",
".",
"Conn",
",",
"2",
")",
"\n",
"for",
"i",
",",
"_",
":=",
"range",
"stdstream",
"{",
"stdstream",
"[",
"i",
"]",
",",
"err",
"=",
"mux",
".",
"Open",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"mux",
".",
"Close",
"(",
")",
"\n",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"}",
"\n\n",
"// Create the broker and start it up",
"broker",
":=",
"newMuxBroker",
"(",
"mux",
")",
"\n",
"go",
"broker",
".",
"Run",
"(",
")",
"\n\n",
"// Build the client using our broker and control channel.",
"return",
"&",
"RPCClient",
"{",
"broker",
":",
"broker",
",",
"control",
":",
"rpc",
".",
"NewClient",
"(",
"control",
")",
",",
"plugins",
":",
"plugins",
",",
"stdout",
":",
"stdstream",
"[",
"0",
"]",
",",
"stderr",
":",
"stdstream",
"[",
"1",
"]",
",",
"}",
",",
"nil",
"\n",
"}"
] |
// NewRPCClient creates a client from an already-open connection-like value.
// Dial is typically used instead.
|
[
"NewRPCClient",
"creates",
"a",
"client",
"from",
"an",
"already",
"-",
"open",
"connection",
"-",
"like",
"value",
".",
"Dial",
"is",
"typically",
"used",
"instead",
"."
] |
5692942914bbdbc03558fde936b1f0bc2af365be
|
https://github.com/hashicorp/go-plugin/blob/5692942914bbdbc03558fde936b1f0bc2af365be/rpc_client.go#L61-L98
|
21,743
|
hashicorp/go-plugin
|
rpc_client.go
|
SyncStreams
|
func (c *RPCClient) SyncStreams(stdout io.Writer, stderr io.Writer) error {
go copyStream("stdout", stdout, c.stdout)
go copyStream("stderr", stderr, c.stderr)
return nil
}
|
go
|
func (c *RPCClient) SyncStreams(stdout io.Writer, stderr io.Writer) error {
go copyStream("stdout", stdout, c.stdout)
go copyStream("stderr", stderr, c.stderr)
return nil
}
|
[
"func",
"(",
"c",
"*",
"RPCClient",
")",
"SyncStreams",
"(",
"stdout",
"io",
".",
"Writer",
",",
"stderr",
"io",
".",
"Writer",
")",
"error",
"{",
"go",
"copyStream",
"(",
"\"",
"\"",
",",
"stdout",
",",
"c",
".",
"stdout",
")",
"\n",
"go",
"copyStream",
"(",
"\"",
"\"",
",",
"stderr",
",",
"c",
".",
"stderr",
")",
"\n",
"return",
"nil",
"\n",
"}"
] |
// SyncStreams should be called to enable syncing of stdout,
// stderr with the plugin.
//
// This will return immediately and the syncing will continue to happen
// in the background. You do not need to launch this in a goroutine itself.
//
// This should never be called multiple times.
|
[
"SyncStreams",
"should",
"be",
"called",
"to",
"enable",
"syncing",
"of",
"stdout",
"stderr",
"with",
"the",
"plugin",
".",
"This",
"will",
"return",
"immediately",
"and",
"the",
"syncing",
"will",
"continue",
"to",
"happen",
"in",
"the",
"background",
".",
"You",
"do",
"not",
"need",
"to",
"launch",
"this",
"in",
"a",
"goroutine",
"itself",
".",
"This",
"should",
"never",
"be",
"called",
"multiple",
"times",
"."
] |
5692942914bbdbc03558fde936b1f0bc2af365be
|
https://github.com/hashicorp/go-plugin/blob/5692942914bbdbc03558fde936b1f0bc2af365be/rpc_client.go#L107-L111
|
21,744
|
hashicorp/go-plugin
|
rpc_client.go
|
Close
|
func (c *RPCClient) Close() error {
// Call the control channel and ask it to gracefully exit. If this
// errors, then we save it so that we always return an error but we
// want to try to close the other channels anyways.
var empty struct{}
returnErr := c.control.Call("Control.Quit", true, &empty)
// Close the other streams we have
if err := c.control.Close(); err != nil {
return err
}
if err := c.stdout.Close(); err != nil {
return err
}
if err := c.stderr.Close(); err != nil {
return err
}
if err := c.broker.Close(); err != nil {
return err
}
// Return back the error we got from Control.Quit. This is very important
// since we MUST return non-nil error if this fails so that Client.Kill
// will properly try a process.Kill.
return returnErr
}
|
go
|
func (c *RPCClient) Close() error {
// Call the control channel and ask it to gracefully exit. If this
// errors, then we save it so that we always return an error but we
// want to try to close the other channels anyways.
var empty struct{}
returnErr := c.control.Call("Control.Quit", true, &empty)
// Close the other streams we have
if err := c.control.Close(); err != nil {
return err
}
if err := c.stdout.Close(); err != nil {
return err
}
if err := c.stderr.Close(); err != nil {
return err
}
if err := c.broker.Close(); err != nil {
return err
}
// Return back the error we got from Control.Quit. This is very important
// since we MUST return non-nil error if this fails so that Client.Kill
// will properly try a process.Kill.
return returnErr
}
|
[
"func",
"(",
"c",
"*",
"RPCClient",
")",
"Close",
"(",
")",
"error",
"{",
"// Call the control channel and ask it to gracefully exit. If this",
"// errors, then we save it so that we always return an error but we",
"// want to try to close the other channels anyways.",
"var",
"empty",
"struct",
"{",
"}",
"\n",
"returnErr",
":=",
"c",
".",
"control",
".",
"Call",
"(",
"\"",
"\"",
",",
"true",
",",
"&",
"empty",
")",
"\n\n",
"// Close the other streams we have",
"if",
"err",
":=",
"c",
".",
"control",
".",
"Close",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"if",
"err",
":=",
"c",
".",
"stdout",
".",
"Close",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"if",
"err",
":=",
"c",
".",
"stderr",
".",
"Close",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"if",
"err",
":=",
"c",
".",
"broker",
".",
"Close",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"// Return back the error we got from Control.Quit. This is very important",
"// since we MUST return non-nil error if this fails so that Client.Kill",
"// will properly try a process.Kill.",
"return",
"returnErr",
"\n",
"}"
] |
// Close closes the connection. The client is no longer usable after this
// is called.
|
[
"Close",
"closes",
"the",
"connection",
".",
"The",
"client",
"is",
"no",
"longer",
"usable",
"after",
"this",
"is",
"called",
"."
] |
5692942914bbdbc03558fde936b1f0bc2af365be
|
https://github.com/hashicorp/go-plugin/blob/5692942914bbdbc03558fde936b1f0bc2af365be/rpc_client.go#L115-L140
|
21,745
|
hashicorp/go-plugin
|
rpc_client.go
|
Ping
|
func (c *RPCClient) Ping() error {
var empty struct{}
return c.control.Call("Control.Ping", true, &empty)
}
|
go
|
func (c *RPCClient) Ping() error {
var empty struct{}
return c.control.Call("Control.Ping", true, &empty)
}
|
[
"func",
"(",
"c",
"*",
"RPCClient",
")",
"Ping",
"(",
")",
"error",
"{",
"var",
"empty",
"struct",
"{",
"}",
"\n",
"return",
"c",
".",
"control",
".",
"Call",
"(",
"\"",
"\"",
",",
"true",
",",
"&",
"empty",
")",
"\n",
"}"
] |
// Ping pings the connection to ensure it is still alive.
//
// The error from the RPC call is returned exactly if you want to inspect
// it for further error analysis. Any error returned from here would indicate
// that the connection to the plugin is not healthy.
|
[
"Ping",
"pings",
"the",
"connection",
"to",
"ensure",
"it",
"is",
"still",
"alive",
".",
"The",
"error",
"from",
"the",
"RPC",
"call",
"is",
"returned",
"exactly",
"if",
"you",
"want",
"to",
"inspect",
"it",
"for",
"further",
"error",
"analysis",
".",
"Any",
"error",
"returned",
"from",
"here",
"would",
"indicate",
"that",
"the",
"connection",
"to",
"the",
"plugin",
"is",
"not",
"healthy",
"."
] |
5692942914bbdbc03558fde936b1f0bc2af365be
|
https://github.com/hashicorp/go-plugin/blob/5692942914bbdbc03558fde936b1f0bc2af365be/rpc_client.go#L167-L170
|
21,746
|
hashicorp/go-plugin
|
rpc_server.go
|
ServeConn
|
func (s *RPCServer) ServeConn(conn io.ReadWriteCloser) {
// First create the yamux server to wrap this connection
mux, err := yamux.Server(conn, nil)
if err != nil {
conn.Close()
log.Printf("[ERR] plugin: error creating yamux server: %s", err)
return
}
// Accept the control connection
control, err := mux.Accept()
if err != nil {
mux.Close()
if err != io.EOF {
log.Printf("[ERR] plugin: error accepting control connection: %s", err)
}
return
}
// Connect the stdstreams (in, out, err)
stdstream := make([]net.Conn, 2)
for i, _ := range stdstream {
stdstream[i], err = mux.Accept()
if err != nil {
mux.Close()
log.Printf("[ERR] plugin: accepting stream %d: %s", i, err)
return
}
}
// Copy std streams out to the proper place
go copyStream("stdout", stdstream[0], s.Stdout)
go copyStream("stderr", stdstream[1], s.Stderr)
// Create the broker and start it up
broker := newMuxBroker(mux)
go broker.Run()
// Use the control connection to build the dispenser and serve the
// connection.
server := rpc.NewServer()
server.RegisterName("Control", &controlServer{
server: s,
})
server.RegisterName("Dispenser", &dispenseServer{
broker: broker,
plugins: s.Plugins,
})
server.ServeConn(control)
}
|
go
|
func (s *RPCServer) ServeConn(conn io.ReadWriteCloser) {
// First create the yamux server to wrap this connection
mux, err := yamux.Server(conn, nil)
if err != nil {
conn.Close()
log.Printf("[ERR] plugin: error creating yamux server: %s", err)
return
}
// Accept the control connection
control, err := mux.Accept()
if err != nil {
mux.Close()
if err != io.EOF {
log.Printf("[ERR] plugin: error accepting control connection: %s", err)
}
return
}
// Connect the stdstreams (in, out, err)
stdstream := make([]net.Conn, 2)
for i, _ := range stdstream {
stdstream[i], err = mux.Accept()
if err != nil {
mux.Close()
log.Printf("[ERR] plugin: accepting stream %d: %s", i, err)
return
}
}
// Copy std streams out to the proper place
go copyStream("stdout", stdstream[0], s.Stdout)
go copyStream("stderr", stdstream[1], s.Stderr)
// Create the broker and start it up
broker := newMuxBroker(mux)
go broker.Run()
// Use the control connection to build the dispenser and serve the
// connection.
server := rpc.NewServer()
server.RegisterName("Control", &controlServer{
server: s,
})
server.RegisterName("Dispenser", &dispenseServer{
broker: broker,
plugins: s.Plugins,
})
server.ServeConn(control)
}
|
[
"func",
"(",
"s",
"*",
"RPCServer",
")",
"ServeConn",
"(",
"conn",
"io",
".",
"ReadWriteCloser",
")",
"{",
"// First create the yamux server to wrap this connection",
"mux",
",",
"err",
":=",
"yamux",
".",
"Server",
"(",
"conn",
",",
"nil",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"conn",
".",
"Close",
"(",
")",
"\n",
"log",
".",
"Printf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"return",
"\n",
"}",
"\n\n",
"// Accept the control connection",
"control",
",",
"err",
":=",
"mux",
".",
"Accept",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"mux",
".",
"Close",
"(",
")",
"\n",
"if",
"err",
"!=",
"io",
".",
"EOF",
"{",
"log",
".",
"Printf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n\n",
"return",
"\n",
"}",
"\n\n",
"// Connect the stdstreams (in, out, err)",
"stdstream",
":=",
"make",
"(",
"[",
"]",
"net",
".",
"Conn",
",",
"2",
")",
"\n",
"for",
"i",
",",
"_",
":=",
"range",
"stdstream",
"{",
"stdstream",
"[",
"i",
"]",
",",
"err",
"=",
"mux",
".",
"Accept",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"mux",
".",
"Close",
"(",
")",
"\n",
"log",
".",
"Printf",
"(",
"\"",
"\"",
",",
"i",
",",
"err",
")",
"\n",
"return",
"\n",
"}",
"\n",
"}",
"\n\n",
"// Copy std streams out to the proper place",
"go",
"copyStream",
"(",
"\"",
"\"",
",",
"stdstream",
"[",
"0",
"]",
",",
"s",
".",
"Stdout",
")",
"\n",
"go",
"copyStream",
"(",
"\"",
"\"",
",",
"stdstream",
"[",
"1",
"]",
",",
"s",
".",
"Stderr",
")",
"\n\n",
"// Create the broker and start it up",
"broker",
":=",
"newMuxBroker",
"(",
"mux",
")",
"\n",
"go",
"broker",
".",
"Run",
"(",
")",
"\n\n",
"// Use the control connection to build the dispenser and serve the",
"// connection.",
"server",
":=",
"rpc",
".",
"NewServer",
"(",
")",
"\n",
"server",
".",
"RegisterName",
"(",
"\"",
"\"",
",",
"&",
"controlServer",
"{",
"server",
":",
"s",
",",
"}",
")",
"\n",
"server",
".",
"RegisterName",
"(",
"\"",
"\"",
",",
"&",
"dispenseServer",
"{",
"broker",
":",
"broker",
",",
"plugins",
":",
"s",
".",
"Plugins",
",",
"}",
")",
"\n",
"server",
".",
"ServeConn",
"(",
"control",
")",
"\n",
"}"
] |
// ServeConn runs a single connection.
//
// ServeConn blocks, serving the connection until the client hangs up.
|
[
"ServeConn",
"runs",
"a",
"single",
"connection",
".",
"ServeConn",
"blocks",
"serving",
"the",
"connection",
"until",
"the",
"client",
"hangs",
"up",
"."
] |
5692942914bbdbc03558fde936b1f0bc2af365be
|
https://github.com/hashicorp/go-plugin/blob/5692942914bbdbc03558fde936b1f0bc2af365be/rpc_server.go#L59-L109
|
21,747
|
hashicorp/go-plugin
|
rpc_server.go
|
done
|
func (s *RPCServer) done() {
s.lock.Lock()
defer s.lock.Unlock()
if s.DoneCh != nil {
close(s.DoneCh)
s.DoneCh = nil
}
}
|
go
|
func (s *RPCServer) done() {
s.lock.Lock()
defer s.lock.Unlock()
if s.DoneCh != nil {
close(s.DoneCh)
s.DoneCh = nil
}
}
|
[
"func",
"(",
"s",
"*",
"RPCServer",
")",
"done",
"(",
")",
"{",
"s",
".",
"lock",
".",
"Lock",
"(",
")",
"\n",
"defer",
"s",
".",
"lock",
".",
"Unlock",
"(",
")",
"\n\n",
"if",
"s",
".",
"DoneCh",
"!=",
"nil",
"{",
"close",
"(",
"s",
".",
"DoneCh",
")",
"\n",
"s",
".",
"DoneCh",
"=",
"nil",
"\n",
"}",
"\n",
"}"
] |
// done is called internally by the control server to trigger the
// doneCh to close which is listened to by the main process to cleanly
// exit.
|
[
"done",
"is",
"called",
"internally",
"by",
"the",
"control",
"server",
"to",
"trigger",
"the",
"doneCh",
"to",
"close",
"which",
"is",
"listened",
"to",
"by",
"the",
"main",
"process",
"to",
"cleanly",
"exit",
"."
] |
5692942914bbdbc03558fde936b1f0bc2af365be
|
https://github.com/hashicorp/go-plugin/blob/5692942914bbdbc03558fde936b1f0bc2af365be/rpc_server.go#L114-L122
|
21,748
|
hashicorp/go-plugin
|
server.go
|
protocolVersion
|
func protocolVersion(opts *ServeConfig) (int, Protocol, PluginSet) {
protoVersion := int(opts.ProtocolVersion)
pluginSet := opts.Plugins
protoType := ProtocolNetRPC
// Check if the client sent a list of acceptable versions
var clientVersions []int
if vs := os.Getenv("PLUGIN_PROTOCOL_VERSIONS"); vs != "" {
for _, s := range strings.Split(vs, ",") {
v, err := strconv.Atoi(s)
if err != nil {
fmt.Fprintf(os.Stderr, "server sent invalid plugin version %q", s)
continue
}
clientVersions = append(clientVersions, v)
}
}
// We want to iterate in reverse order, to ensure we match the newest
// compatible plugin version.
sort.Sort(sort.Reverse(sort.IntSlice(clientVersions)))
// set the old un-versioned fields as if they were versioned plugins
if opts.VersionedPlugins == nil {
opts.VersionedPlugins = make(map[int]PluginSet)
}
if pluginSet != nil {
opts.VersionedPlugins[protoVersion] = pluginSet
}
// Sort the version to make sure we match the latest first
var versions []int
for v := range opts.VersionedPlugins {
versions = append(versions, v)
}
sort.Sort(sort.Reverse(sort.IntSlice(versions)))
// See if we have multiple versions of Plugins to choose from
for _, version := range versions {
// Record each version, since we guarantee that this returns valid
// values even if they are not a protocol match.
protoVersion = version
pluginSet = opts.VersionedPlugins[version]
// If we have a configured gRPC server we should select a protocol
if opts.GRPCServer != nil {
// All plugins in a set must use the same transport, so check the first
// for the protocol type
for _, p := range pluginSet {
switch p.(type) {
case GRPCPlugin:
protoType = ProtocolGRPC
default:
protoType = ProtocolNetRPC
}
break
}
}
for _, clientVersion := range clientVersions {
if clientVersion == protoVersion {
return protoVersion, protoType, pluginSet
}
}
}
// Return the lowest version as the fallback.
// Since we iterated over all the versions in reverse order above, these
// values are from the lowest version number plugins (which may be from
// a combination of the Handshake.ProtocolVersion and ServeConfig.Plugins
// fields). This allows serving the oldest version of our plugins to a
// legacy client that did not send a PLUGIN_PROTOCOL_VERSIONS list.
return protoVersion, protoType, pluginSet
}
|
go
|
func protocolVersion(opts *ServeConfig) (int, Protocol, PluginSet) {
protoVersion := int(opts.ProtocolVersion)
pluginSet := opts.Plugins
protoType := ProtocolNetRPC
// Check if the client sent a list of acceptable versions
var clientVersions []int
if vs := os.Getenv("PLUGIN_PROTOCOL_VERSIONS"); vs != "" {
for _, s := range strings.Split(vs, ",") {
v, err := strconv.Atoi(s)
if err != nil {
fmt.Fprintf(os.Stderr, "server sent invalid plugin version %q", s)
continue
}
clientVersions = append(clientVersions, v)
}
}
// We want to iterate in reverse order, to ensure we match the newest
// compatible plugin version.
sort.Sort(sort.Reverse(sort.IntSlice(clientVersions)))
// set the old un-versioned fields as if they were versioned plugins
if opts.VersionedPlugins == nil {
opts.VersionedPlugins = make(map[int]PluginSet)
}
if pluginSet != nil {
opts.VersionedPlugins[protoVersion] = pluginSet
}
// Sort the version to make sure we match the latest first
var versions []int
for v := range opts.VersionedPlugins {
versions = append(versions, v)
}
sort.Sort(sort.Reverse(sort.IntSlice(versions)))
// See if we have multiple versions of Plugins to choose from
for _, version := range versions {
// Record each version, since we guarantee that this returns valid
// values even if they are not a protocol match.
protoVersion = version
pluginSet = opts.VersionedPlugins[version]
// If we have a configured gRPC server we should select a protocol
if opts.GRPCServer != nil {
// All plugins in a set must use the same transport, so check the first
// for the protocol type
for _, p := range pluginSet {
switch p.(type) {
case GRPCPlugin:
protoType = ProtocolGRPC
default:
protoType = ProtocolNetRPC
}
break
}
}
for _, clientVersion := range clientVersions {
if clientVersion == protoVersion {
return protoVersion, protoType, pluginSet
}
}
}
// Return the lowest version as the fallback.
// Since we iterated over all the versions in reverse order above, these
// values are from the lowest version number plugins (which may be from
// a combination of the Handshake.ProtocolVersion and ServeConfig.Plugins
// fields). This allows serving the oldest version of our plugins to a
// legacy client that did not send a PLUGIN_PROTOCOL_VERSIONS list.
return protoVersion, protoType, pluginSet
}
|
[
"func",
"protocolVersion",
"(",
"opts",
"*",
"ServeConfig",
")",
"(",
"int",
",",
"Protocol",
",",
"PluginSet",
")",
"{",
"protoVersion",
":=",
"int",
"(",
"opts",
".",
"ProtocolVersion",
")",
"\n",
"pluginSet",
":=",
"opts",
".",
"Plugins",
"\n",
"protoType",
":=",
"ProtocolNetRPC",
"\n",
"// Check if the client sent a list of acceptable versions",
"var",
"clientVersions",
"[",
"]",
"int",
"\n",
"if",
"vs",
":=",
"os",
".",
"Getenv",
"(",
"\"",
"\"",
")",
";",
"vs",
"!=",
"\"",
"\"",
"{",
"for",
"_",
",",
"s",
":=",
"range",
"strings",
".",
"Split",
"(",
"vs",
",",
"\"",
"\"",
")",
"{",
"v",
",",
"err",
":=",
"strconv",
".",
"Atoi",
"(",
"s",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"fmt",
".",
"Fprintf",
"(",
"os",
".",
"Stderr",
",",
"\"",
"\"",
",",
"s",
")",
"\n",
"continue",
"\n",
"}",
"\n",
"clientVersions",
"=",
"append",
"(",
"clientVersions",
",",
"v",
")",
"\n",
"}",
"\n",
"}",
"\n\n",
"// We want to iterate in reverse order, to ensure we match the newest",
"// compatible plugin version.",
"sort",
".",
"Sort",
"(",
"sort",
".",
"Reverse",
"(",
"sort",
".",
"IntSlice",
"(",
"clientVersions",
")",
")",
")",
"\n\n",
"// set the old un-versioned fields as if they were versioned plugins",
"if",
"opts",
".",
"VersionedPlugins",
"==",
"nil",
"{",
"opts",
".",
"VersionedPlugins",
"=",
"make",
"(",
"map",
"[",
"int",
"]",
"PluginSet",
")",
"\n",
"}",
"\n\n",
"if",
"pluginSet",
"!=",
"nil",
"{",
"opts",
".",
"VersionedPlugins",
"[",
"protoVersion",
"]",
"=",
"pluginSet",
"\n",
"}",
"\n\n",
"// Sort the version to make sure we match the latest first",
"var",
"versions",
"[",
"]",
"int",
"\n",
"for",
"v",
":=",
"range",
"opts",
".",
"VersionedPlugins",
"{",
"versions",
"=",
"append",
"(",
"versions",
",",
"v",
")",
"\n",
"}",
"\n\n",
"sort",
".",
"Sort",
"(",
"sort",
".",
"Reverse",
"(",
"sort",
".",
"IntSlice",
"(",
"versions",
")",
")",
")",
"\n\n",
"// See if we have multiple versions of Plugins to choose from",
"for",
"_",
",",
"version",
":=",
"range",
"versions",
"{",
"// Record each version, since we guarantee that this returns valid",
"// values even if they are not a protocol match.",
"protoVersion",
"=",
"version",
"\n",
"pluginSet",
"=",
"opts",
".",
"VersionedPlugins",
"[",
"version",
"]",
"\n\n",
"// If we have a configured gRPC server we should select a protocol",
"if",
"opts",
".",
"GRPCServer",
"!=",
"nil",
"{",
"// All plugins in a set must use the same transport, so check the first",
"// for the protocol type",
"for",
"_",
",",
"p",
":=",
"range",
"pluginSet",
"{",
"switch",
"p",
".",
"(",
"type",
")",
"{",
"case",
"GRPCPlugin",
":",
"protoType",
"=",
"ProtocolGRPC",
"\n",
"default",
":",
"protoType",
"=",
"ProtocolNetRPC",
"\n",
"}",
"\n",
"break",
"\n",
"}",
"\n",
"}",
"\n\n",
"for",
"_",
",",
"clientVersion",
":=",
"range",
"clientVersions",
"{",
"if",
"clientVersion",
"==",
"protoVersion",
"{",
"return",
"protoVersion",
",",
"protoType",
",",
"pluginSet",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n\n",
"// Return the lowest version as the fallback.",
"// Since we iterated over all the versions in reverse order above, these",
"// values are from the lowest version number plugins (which may be from",
"// a combination of the Handshake.ProtocolVersion and ServeConfig.Plugins",
"// fields). This allows serving the oldest version of our plugins to a",
"// legacy client that did not send a PLUGIN_PROTOCOL_VERSIONS list.",
"return",
"protoVersion",
",",
"protoType",
",",
"pluginSet",
"\n",
"}"
] |
// protocolVersion determines the protocol version and plugin set to be used by
// the server. In the event that there is no suitable version, the last version
// in the config is returned leaving the client to report the incompatibility.
|
[
"protocolVersion",
"determines",
"the",
"protocol",
"version",
"and",
"plugin",
"set",
"to",
"be",
"used",
"by",
"the",
"server",
".",
"In",
"the",
"event",
"that",
"there",
"is",
"no",
"suitable",
"version",
"the",
"last",
"version",
"in",
"the",
"config",
"is",
"returned",
"leaving",
"the",
"client",
"to",
"report",
"the",
"incompatibility",
"."
] |
5692942914bbdbc03558fde936b1f0bc2af365be
|
https://github.com/hashicorp/go-plugin/blob/5692942914bbdbc03558fde936b1f0bc2af365be/server.go#L93-L167
|
21,749
|
hashicorp/go-plugin
|
process_posix.go
|
_pidAlive
|
func _pidAlive(pid int) bool {
proc, err := os.FindProcess(pid)
if err == nil {
err = proc.Signal(syscall.Signal(0))
}
return err == nil
}
|
go
|
func _pidAlive(pid int) bool {
proc, err := os.FindProcess(pid)
if err == nil {
err = proc.Signal(syscall.Signal(0))
}
return err == nil
}
|
[
"func",
"_pidAlive",
"(",
"pid",
"int",
")",
"bool",
"{",
"proc",
",",
"err",
":=",
"os",
".",
"FindProcess",
"(",
"pid",
")",
"\n",
"if",
"err",
"==",
"nil",
"{",
"err",
"=",
"proc",
".",
"Signal",
"(",
"syscall",
".",
"Signal",
"(",
"0",
")",
")",
"\n",
"}",
"\n\n",
"return",
"err",
"==",
"nil",
"\n",
"}"
] |
// _pidAlive tests whether a process is alive or not by sending it Signal 0,
// since Go otherwise has no way to test this.
|
[
"_pidAlive",
"tests",
"whether",
"a",
"process",
"is",
"alive",
"or",
"not",
"by",
"sending",
"it",
"Signal",
"0",
"since",
"Go",
"otherwise",
"has",
"no",
"way",
"to",
"test",
"this",
"."
] |
5692942914bbdbc03558fde936b1f0bc2af365be
|
https://github.com/hashicorp/go-plugin/blob/5692942914bbdbc03558fde936b1f0bc2af365be/process_posix.go#L12-L19
|
21,750
|
hashicorp/go-plugin
|
mux_broker.go
|
AcceptAndServe
|
func (m *MuxBroker) AcceptAndServe(id uint32, v interface{}) {
conn, err := m.Accept(id)
if err != nil {
log.Printf("[ERR] plugin: plugin acceptAndServe error: %s", err)
return
}
serve(conn, "Plugin", v)
}
|
go
|
func (m *MuxBroker) AcceptAndServe(id uint32, v interface{}) {
conn, err := m.Accept(id)
if err != nil {
log.Printf("[ERR] plugin: plugin acceptAndServe error: %s", err)
return
}
serve(conn, "Plugin", v)
}
|
[
"func",
"(",
"m",
"*",
"MuxBroker",
")",
"AcceptAndServe",
"(",
"id",
"uint32",
",",
"v",
"interface",
"{",
"}",
")",
"{",
"conn",
",",
"err",
":=",
"m",
".",
"Accept",
"(",
"id",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"log",
".",
"Printf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"return",
"\n",
"}",
"\n\n",
"serve",
"(",
"conn",
",",
"\"",
"\"",
",",
"v",
")",
"\n",
"}"
] |
// AcceptAndServe is used to accept a specific stream ID and immediately
// serve an RPC server on that stream ID. This is used to easily serve
// complex arguments.
//
// The served interface is always registered to the "Plugin" name.
|
[
"AcceptAndServe",
"is",
"used",
"to",
"accept",
"a",
"specific",
"stream",
"ID",
"and",
"immediately",
"serve",
"an",
"RPC",
"server",
"on",
"that",
"stream",
"ID",
".",
"This",
"is",
"used",
"to",
"easily",
"serve",
"complex",
"arguments",
".",
"The",
"served",
"interface",
"is",
"always",
"registered",
"to",
"the",
"Plugin",
"name",
"."
] |
5692942914bbdbc03558fde936b1f0bc2af365be
|
https://github.com/hashicorp/go-plugin/blob/5692942914bbdbc03558fde936b1f0bc2af365be/mux_broker.go#L80-L88
|
21,751
|
hashicorp/go-plugin
|
process.go
|
pidWait
|
func pidWait(pid int) error {
ticker := time.NewTicker(1 * time.Second)
defer ticker.Stop()
for range ticker.C {
if !pidAlive(pid) {
break
}
}
return nil
}
|
go
|
func pidWait(pid int) error {
ticker := time.NewTicker(1 * time.Second)
defer ticker.Stop()
for range ticker.C {
if !pidAlive(pid) {
break
}
}
return nil
}
|
[
"func",
"pidWait",
"(",
"pid",
"int",
")",
"error",
"{",
"ticker",
":=",
"time",
".",
"NewTicker",
"(",
"1",
"*",
"time",
".",
"Second",
")",
"\n",
"defer",
"ticker",
".",
"Stop",
"(",
")",
"\n\n",
"for",
"range",
"ticker",
".",
"C",
"{",
"if",
"!",
"pidAlive",
"(",
"pid",
")",
"{",
"break",
"\n",
"}",
"\n",
"}",
"\n\n",
"return",
"nil",
"\n",
"}"
] |
// pidWait blocks for a process to exit.
|
[
"pidWait",
"blocks",
"for",
"a",
"process",
"to",
"exit",
"."
] |
5692942914bbdbc03558fde936b1f0bc2af365be
|
https://github.com/hashicorp/go-plugin/blob/5692942914bbdbc03558fde936b1f0bc2af365be/process.go#L13-L24
|
21,752
|
hashicorp/go-plugin
|
grpc_controller.go
|
Shutdown
|
func (s *grpcControllerServer) Shutdown(ctx context.Context, _ *plugin.Empty) (*plugin.Empty, error) {
resp := &plugin.Empty{}
// TODO: figure out why GracefullStop doesn't work.
s.server.Stop()
return resp, nil
}
|
go
|
func (s *grpcControllerServer) Shutdown(ctx context.Context, _ *plugin.Empty) (*plugin.Empty, error) {
resp := &plugin.Empty{}
// TODO: figure out why GracefullStop doesn't work.
s.server.Stop()
return resp, nil
}
|
[
"func",
"(",
"s",
"*",
"grpcControllerServer",
")",
"Shutdown",
"(",
"ctx",
"context",
".",
"Context",
",",
"_",
"*",
"plugin",
".",
"Empty",
")",
"(",
"*",
"plugin",
".",
"Empty",
",",
"error",
")",
"{",
"resp",
":=",
"&",
"plugin",
".",
"Empty",
"{",
"}",
"\n\n",
"// TODO: figure out why GracefullStop doesn't work.",
"s",
".",
"server",
".",
"Stop",
"(",
")",
"\n",
"return",
"resp",
",",
"nil",
"\n",
"}"
] |
// Shutdown stops the grpc server. It first will attempt a graceful stop, then a
// full stop on the server.
|
[
"Shutdown",
"stops",
"the",
"grpc",
"server",
".",
"It",
"first",
"will",
"attempt",
"a",
"graceful",
"stop",
"then",
"a",
"full",
"stop",
"on",
"the",
"server",
"."
] |
5692942914bbdbc03558fde936b1f0bc2af365be
|
https://github.com/hashicorp/go-plugin/blob/5692942914bbdbc03558fde936b1f0bc2af365be/grpc_controller.go#L17-L23
|
21,753
|
nareix/joy4
|
av/av.go
|
IsPlanar
|
func (self SampleFormat) IsPlanar() bool {
switch self {
case S16P, S32P, FLTP, DBLP:
return true
default:
return false
}
}
|
go
|
func (self SampleFormat) IsPlanar() bool {
switch self {
case S16P, S32P, FLTP, DBLP:
return true
default:
return false
}
}
|
[
"func",
"(",
"self",
"SampleFormat",
")",
"IsPlanar",
"(",
")",
"bool",
"{",
"switch",
"self",
"{",
"case",
"S16P",
",",
"S32P",
",",
"FLTP",
",",
"DBLP",
":",
"return",
"true",
"\n",
"default",
":",
"return",
"false",
"\n",
"}",
"\n",
"}"
] |
// Check if this sample format is in planar.
|
[
"Check",
"if",
"this",
"sample",
"format",
"is",
"in",
"planar",
"."
] |
3ddbc8f9d4316ab2bbec2bc9ee98127862e3af02
|
https://github.com/nareix/joy4/blob/3ddbc8f9d4316ab2bbec2bc9ee98127862e3af02/av/av.go#L70-L77
|
21,754
|
nareix/joy4
|
av/av.go
|
MakeAudioCodecType
|
func MakeAudioCodecType(base uint32) (c CodecType) {
c = CodecType(base)<<codecTypeOtherBits | CodecType(codecTypeAudioBit)
return
}
|
go
|
func MakeAudioCodecType(base uint32) (c CodecType) {
c = CodecType(base)<<codecTypeOtherBits | CodecType(codecTypeAudioBit)
return
}
|
[
"func",
"MakeAudioCodecType",
"(",
"base",
"uint32",
")",
"(",
"c",
"CodecType",
")",
"{",
"c",
"=",
"CodecType",
"(",
"base",
")",
"<<",
"codecTypeOtherBits",
"|",
"CodecType",
"(",
"codecTypeAudioBit",
")",
"\n",
"return",
"\n",
"}"
] |
// Make a new audio codec type.
|
[
"Make",
"a",
"new",
"audio",
"codec",
"type",
"."
] |
3ddbc8f9d4316ab2bbec2bc9ee98127862e3af02
|
https://github.com/nareix/joy4/blob/3ddbc8f9d4316ab2bbec2bc9ee98127862e3af02/av/av.go#L157-L160
|
21,755
|
nareix/joy4
|
av/av.go
|
HasSameFormat
|
func (self AudioFrame) HasSameFormat(other AudioFrame) bool {
if self.SampleRate != other.SampleRate {
return false
}
if self.ChannelLayout != other.ChannelLayout {
return false
}
if self.SampleFormat != other.SampleFormat {
return false
}
return true
}
|
go
|
func (self AudioFrame) HasSameFormat(other AudioFrame) bool {
if self.SampleRate != other.SampleRate {
return false
}
if self.ChannelLayout != other.ChannelLayout {
return false
}
if self.SampleFormat != other.SampleFormat {
return false
}
return true
}
|
[
"func",
"(",
"self",
"AudioFrame",
")",
"HasSameFormat",
"(",
"other",
"AudioFrame",
")",
"bool",
"{",
"if",
"self",
".",
"SampleRate",
"!=",
"other",
".",
"SampleRate",
"{",
"return",
"false",
"\n",
"}",
"\n",
"if",
"self",
".",
"ChannelLayout",
"!=",
"other",
".",
"ChannelLayout",
"{",
"return",
"false",
"\n",
"}",
"\n",
"if",
"self",
".",
"SampleFormat",
"!=",
"other",
".",
"SampleFormat",
"{",
"return",
"false",
"\n",
"}",
"\n",
"return",
"true",
"\n",
"}"
] |
// Check this audio frame has same format as other audio frame.
|
[
"Check",
"this",
"audio",
"frame",
"has",
"same",
"format",
"as",
"other",
"audio",
"frame",
"."
] |
3ddbc8f9d4316ab2bbec2bc9ee98127862e3af02
|
https://github.com/nareix/joy4/blob/3ddbc8f9d4316ab2bbec2bc9ee98127862e3af02/av/av.go#L252-L263
|
21,756
|
nareix/joy4
|
av/av.go
|
Slice
|
func (self AudioFrame) Slice(start int, end int) (out AudioFrame) {
if start > end {
panic(fmt.Sprintf("av: AudioFrame split failed start=%d end=%d invalid", start, end))
}
out = self
out.Data = append([][]byte(nil), out.Data...)
out.SampleCount = end - start
size := self.SampleFormat.BytesPerSample()
for i := range out.Data {
out.Data[i] = out.Data[i][start*size : end*size]
}
return
}
|
go
|
func (self AudioFrame) Slice(start int, end int) (out AudioFrame) {
if start > end {
panic(fmt.Sprintf("av: AudioFrame split failed start=%d end=%d invalid", start, end))
}
out = self
out.Data = append([][]byte(nil), out.Data...)
out.SampleCount = end - start
size := self.SampleFormat.BytesPerSample()
for i := range out.Data {
out.Data[i] = out.Data[i][start*size : end*size]
}
return
}
|
[
"func",
"(",
"self",
"AudioFrame",
")",
"Slice",
"(",
"start",
"int",
",",
"end",
"int",
")",
"(",
"out",
"AudioFrame",
")",
"{",
"if",
"start",
">",
"end",
"{",
"panic",
"(",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"start",
",",
"end",
")",
")",
"\n",
"}",
"\n",
"out",
"=",
"self",
"\n",
"out",
".",
"Data",
"=",
"append",
"(",
"[",
"]",
"[",
"]",
"byte",
"(",
"nil",
")",
",",
"out",
".",
"Data",
"...",
")",
"\n",
"out",
".",
"SampleCount",
"=",
"end",
"-",
"start",
"\n",
"size",
":=",
"self",
".",
"SampleFormat",
".",
"BytesPerSample",
"(",
")",
"\n",
"for",
"i",
":=",
"range",
"out",
".",
"Data",
"{",
"out",
".",
"Data",
"[",
"i",
"]",
"=",
"out",
".",
"Data",
"[",
"i",
"]",
"[",
"start",
"*",
"size",
":",
"end",
"*",
"size",
"]",
"\n",
"}",
"\n",
"return",
"\n",
"}"
] |
// Split sample audio sample from this frame.
|
[
"Split",
"sample",
"audio",
"sample",
"from",
"this",
"frame",
"."
] |
3ddbc8f9d4316ab2bbec2bc9ee98127862e3af02
|
https://github.com/nareix/joy4/blob/3ddbc8f9d4316ab2bbec2bc9ee98127862e3af02/av/av.go#L266-L278
|
21,757
|
nareix/joy4
|
av/av.go
|
Concat
|
func (self AudioFrame) Concat(in AudioFrame) (out AudioFrame) {
out = self
out.Data = append([][]byte(nil), out.Data...)
out.SampleCount += in.SampleCount
for i := range out.Data {
out.Data[i] = append(out.Data[i], in.Data[i]...)
}
return
}
|
go
|
func (self AudioFrame) Concat(in AudioFrame) (out AudioFrame) {
out = self
out.Data = append([][]byte(nil), out.Data...)
out.SampleCount += in.SampleCount
for i := range out.Data {
out.Data[i] = append(out.Data[i], in.Data[i]...)
}
return
}
|
[
"func",
"(",
"self",
"AudioFrame",
")",
"Concat",
"(",
"in",
"AudioFrame",
")",
"(",
"out",
"AudioFrame",
")",
"{",
"out",
"=",
"self",
"\n",
"out",
".",
"Data",
"=",
"append",
"(",
"[",
"]",
"[",
"]",
"byte",
"(",
"nil",
")",
",",
"out",
".",
"Data",
"...",
")",
"\n",
"out",
".",
"SampleCount",
"+=",
"in",
".",
"SampleCount",
"\n",
"for",
"i",
":=",
"range",
"out",
".",
"Data",
"{",
"out",
".",
"Data",
"[",
"i",
"]",
"=",
"append",
"(",
"out",
".",
"Data",
"[",
"i",
"]",
",",
"in",
".",
"Data",
"[",
"i",
"]",
"...",
")",
"\n",
"}",
"\n",
"return",
"\n",
"}"
] |
// Concat two audio frames.
|
[
"Concat",
"two",
"audio",
"frames",
"."
] |
3ddbc8f9d4316ab2bbec2bc9ee98127862e3af02
|
https://github.com/nareix/joy4/blob/3ddbc8f9d4316ab2bbec2bc9ee98127862e3af02/av/av.go#L281-L289
|
21,758
|
nareix/joy4
|
av/transcode/transcode.go
|
Do
|
func (self *Transcoder) Do(pkt av.Packet) (out []av.Packet, err error) {
stream := self.streams[pkt.Idx]
if stream.aenc != nil && stream.adec != nil {
if out, err = stream.audioDecodeAndEncode(pkt); err != nil {
return
}
} else {
out = append(out, pkt)
}
return
}
|
go
|
func (self *Transcoder) Do(pkt av.Packet) (out []av.Packet, err error) {
stream := self.streams[pkt.Idx]
if stream.aenc != nil && stream.adec != nil {
if out, err = stream.audioDecodeAndEncode(pkt); err != nil {
return
}
} else {
out = append(out, pkt)
}
return
}
|
[
"func",
"(",
"self",
"*",
"Transcoder",
")",
"Do",
"(",
"pkt",
"av",
".",
"Packet",
")",
"(",
"out",
"[",
"]",
"av",
".",
"Packet",
",",
"err",
"error",
")",
"{",
"stream",
":=",
"self",
".",
"streams",
"[",
"pkt",
".",
"Idx",
"]",
"\n",
"if",
"stream",
".",
"aenc",
"!=",
"nil",
"&&",
"stream",
".",
"adec",
"!=",
"nil",
"{",
"if",
"out",
",",
"err",
"=",
"stream",
".",
"audioDecodeAndEncode",
"(",
"pkt",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"\n",
"}",
"\n",
"}",
"else",
"{",
"out",
"=",
"append",
"(",
"out",
",",
"pkt",
")",
"\n",
"}",
"\n",
"return",
"\n",
"}"
] |
// Do the transcode.
//
// In audio transcoding one Packet may transcode into many Packets
// packet time will be adjusted automatically.
|
[
"Do",
"the",
"transcode",
".",
"In",
"audio",
"transcoding",
"one",
"Packet",
"may",
"transcode",
"into",
"many",
"Packets",
"packet",
"time",
"will",
"be",
"adjusted",
"automatically",
"."
] |
3ddbc8f9d4316ab2bbec2bc9ee98127862e3af02
|
https://github.com/nareix/joy4/blob/3ddbc8f9d4316ab2bbec2bc9ee98127862e3af02/av/transcode/transcode.go#L114-L124
|
21,759
|
nareix/joy4
|
av/transcode/transcode.go
|
Streams
|
func (self *Transcoder) Streams() (streams []av.CodecData, err error) {
for _, stream := range self.streams {
streams = append(streams, stream.codec)
}
return
}
|
go
|
func (self *Transcoder) Streams() (streams []av.CodecData, err error) {
for _, stream := range self.streams {
streams = append(streams, stream.codec)
}
return
}
|
[
"func",
"(",
"self",
"*",
"Transcoder",
")",
"Streams",
"(",
")",
"(",
"streams",
"[",
"]",
"av",
".",
"CodecData",
",",
"err",
"error",
")",
"{",
"for",
"_",
",",
"stream",
":=",
"range",
"self",
".",
"streams",
"{",
"streams",
"=",
"append",
"(",
"streams",
",",
"stream",
".",
"codec",
")",
"\n",
"}",
"\n",
"return",
"\n",
"}"
] |
// Get CodecDatas after transcoding.
|
[
"Get",
"CodecDatas",
"after",
"transcoding",
"."
] |
3ddbc8f9d4316ab2bbec2bc9ee98127862e3af02
|
https://github.com/nareix/joy4/blob/3ddbc8f9d4316ab2bbec2bc9ee98127862e3af02/av/transcode/transcode.go#L127-L132
|
21,760
|
nareix/joy4
|
av/transcode/transcode.go
|
Close
|
func (self *Transcoder) Close() (err error) {
for _, stream := range self.streams {
if stream.aenc != nil {
stream.aenc.Close()
stream.aenc = nil
}
if stream.adec != nil {
stream.adec.Close()
stream.adec = nil
}
}
self.streams = nil
return
}
|
go
|
func (self *Transcoder) Close() (err error) {
for _, stream := range self.streams {
if stream.aenc != nil {
stream.aenc.Close()
stream.aenc = nil
}
if stream.adec != nil {
stream.adec.Close()
stream.adec = nil
}
}
self.streams = nil
return
}
|
[
"func",
"(",
"self",
"*",
"Transcoder",
")",
"Close",
"(",
")",
"(",
"err",
"error",
")",
"{",
"for",
"_",
",",
"stream",
":=",
"range",
"self",
".",
"streams",
"{",
"if",
"stream",
".",
"aenc",
"!=",
"nil",
"{",
"stream",
".",
"aenc",
".",
"Close",
"(",
")",
"\n",
"stream",
".",
"aenc",
"=",
"nil",
"\n",
"}",
"\n",
"if",
"stream",
".",
"adec",
"!=",
"nil",
"{",
"stream",
".",
"adec",
".",
"Close",
"(",
")",
"\n",
"stream",
".",
"adec",
"=",
"nil",
"\n",
"}",
"\n",
"}",
"\n",
"self",
".",
"streams",
"=",
"nil",
"\n",
"return",
"\n",
"}"
] |
// Close transcoder, close related encoder and decoders.
|
[
"Close",
"transcoder",
"close",
"related",
"encoder",
"and",
"decoders",
"."
] |
3ddbc8f9d4316ab2bbec2bc9ee98127862e3af02
|
https://github.com/nareix/joy4/blob/3ddbc8f9d4316ab2bbec2bc9ee98127862e3af02/av/transcode/transcode.go#L135-L148
|
21,761
|
nareix/joy4
|
av/pubsub/queue.go
|
WritePacket
|
func (self *Queue) WritePacket(pkt av.Packet) (err error) {
self.lock.Lock()
self.buf.Push(pkt)
if pkt.Idx == int8(self.videoidx) && pkt.IsKeyFrame {
self.curgopcount++
}
for self.curgopcount >= self.maxgopcount && self.buf.Count > 1 {
pkt := self.buf.Pop()
if pkt.Idx == int8(self.videoidx) && pkt.IsKeyFrame {
self.curgopcount--
}
if self.curgopcount < self.maxgopcount {
break
}
}
//println("shrink", self.curgopcount, self.maxgopcount, self.buf.Head, self.buf.Tail, "count", self.buf.Count, "size", self.buf.Size)
self.cond.Broadcast()
self.lock.Unlock()
return
}
|
go
|
func (self *Queue) WritePacket(pkt av.Packet) (err error) {
self.lock.Lock()
self.buf.Push(pkt)
if pkt.Idx == int8(self.videoidx) && pkt.IsKeyFrame {
self.curgopcount++
}
for self.curgopcount >= self.maxgopcount && self.buf.Count > 1 {
pkt := self.buf.Pop()
if pkt.Idx == int8(self.videoidx) && pkt.IsKeyFrame {
self.curgopcount--
}
if self.curgopcount < self.maxgopcount {
break
}
}
//println("shrink", self.curgopcount, self.maxgopcount, self.buf.Head, self.buf.Tail, "count", self.buf.Count, "size", self.buf.Size)
self.cond.Broadcast()
self.lock.Unlock()
return
}
|
[
"func",
"(",
"self",
"*",
"Queue",
")",
"WritePacket",
"(",
"pkt",
"av",
".",
"Packet",
")",
"(",
"err",
"error",
")",
"{",
"self",
".",
"lock",
".",
"Lock",
"(",
")",
"\n\n",
"self",
".",
"buf",
".",
"Push",
"(",
"pkt",
")",
"\n",
"if",
"pkt",
".",
"Idx",
"==",
"int8",
"(",
"self",
".",
"videoidx",
")",
"&&",
"pkt",
".",
"IsKeyFrame",
"{",
"self",
".",
"curgopcount",
"++",
"\n",
"}",
"\n\n",
"for",
"self",
".",
"curgopcount",
">=",
"self",
".",
"maxgopcount",
"&&",
"self",
".",
"buf",
".",
"Count",
">",
"1",
"{",
"pkt",
":=",
"self",
".",
"buf",
".",
"Pop",
"(",
")",
"\n",
"if",
"pkt",
".",
"Idx",
"==",
"int8",
"(",
"self",
".",
"videoidx",
")",
"&&",
"pkt",
".",
"IsKeyFrame",
"{",
"self",
".",
"curgopcount",
"--",
"\n",
"}",
"\n",
"if",
"self",
".",
"curgopcount",
"<",
"self",
".",
"maxgopcount",
"{",
"break",
"\n",
"}",
"\n",
"}",
"\n",
"//println(\"shrink\", self.curgopcount, self.maxgopcount, self.buf.Head, self.buf.Tail, \"count\", self.buf.Count, \"size\", self.buf.Size)",
"self",
".",
"cond",
".",
"Broadcast",
"(",
")",
"\n\n",
"self",
".",
"lock",
".",
"Unlock",
"(",
")",
"\n",
"return",
"\n",
"}"
] |
// Put packet into buffer, old packets will be discared.
|
[
"Put",
"packet",
"into",
"buffer",
"old",
"packets",
"will",
"be",
"discared",
"."
] |
3ddbc8f9d4316ab2bbec2bc9ee98127862e3af02
|
https://github.com/nareix/joy4/blob/3ddbc8f9d4316ab2bbec2bc9ee98127862e3af02/av/pubsub/queue.go#L83-L106
|
21,762
|
nareix/joy4
|
av/pubsub/queue.go
|
Oldest
|
func (self *Queue) Oldest() *QueueCursor {
cursor := self.newCursor()
cursor.init = func(buf *pktque.Buf, videoidx int) pktque.BufPos {
return buf.Head
}
return cursor
}
|
go
|
func (self *Queue) Oldest() *QueueCursor {
cursor := self.newCursor()
cursor.init = func(buf *pktque.Buf, videoidx int) pktque.BufPos {
return buf.Head
}
return cursor
}
|
[
"func",
"(",
"self",
"*",
"Queue",
")",
"Oldest",
"(",
")",
"*",
"QueueCursor",
"{",
"cursor",
":=",
"self",
".",
"newCursor",
"(",
")",
"\n",
"cursor",
".",
"init",
"=",
"func",
"(",
"buf",
"*",
"pktque",
".",
"Buf",
",",
"videoidx",
"int",
")",
"pktque",
".",
"BufPos",
"{",
"return",
"buf",
".",
"Head",
"\n",
"}",
"\n",
"return",
"cursor",
"\n",
"}"
] |
// Create cursor position at oldest buffered packet.
|
[
"Create",
"cursor",
"position",
"at",
"oldest",
"buffered",
"packet",
"."
] |
3ddbc8f9d4316ab2bbec2bc9ee98127862e3af02
|
https://github.com/nareix/joy4/blob/3ddbc8f9d4316ab2bbec2bc9ee98127862e3af02/av/pubsub/queue.go#L131-L137
|
21,763
|
nareix/joy4
|
av/pubsub/queue.go
|
DelayedTime
|
func (self *Queue) DelayedTime(dur time.Duration) *QueueCursor {
cursor := self.newCursor()
cursor.init = func(buf *pktque.Buf, videoidx int) pktque.BufPos {
i := buf.Tail - 1
if buf.IsValidPos(i) {
end := buf.Get(i)
for buf.IsValidPos(i) {
if end.Time-buf.Get(i).Time > dur {
break
}
i--
}
}
return i
}
return cursor
}
|
go
|
func (self *Queue) DelayedTime(dur time.Duration) *QueueCursor {
cursor := self.newCursor()
cursor.init = func(buf *pktque.Buf, videoidx int) pktque.BufPos {
i := buf.Tail - 1
if buf.IsValidPos(i) {
end := buf.Get(i)
for buf.IsValidPos(i) {
if end.Time-buf.Get(i).Time > dur {
break
}
i--
}
}
return i
}
return cursor
}
|
[
"func",
"(",
"self",
"*",
"Queue",
")",
"DelayedTime",
"(",
"dur",
"time",
".",
"Duration",
")",
"*",
"QueueCursor",
"{",
"cursor",
":=",
"self",
".",
"newCursor",
"(",
")",
"\n",
"cursor",
".",
"init",
"=",
"func",
"(",
"buf",
"*",
"pktque",
".",
"Buf",
",",
"videoidx",
"int",
")",
"pktque",
".",
"BufPos",
"{",
"i",
":=",
"buf",
".",
"Tail",
"-",
"1",
"\n",
"if",
"buf",
".",
"IsValidPos",
"(",
"i",
")",
"{",
"end",
":=",
"buf",
".",
"Get",
"(",
"i",
")",
"\n",
"for",
"buf",
".",
"IsValidPos",
"(",
"i",
")",
"{",
"if",
"end",
".",
"Time",
"-",
"buf",
".",
"Get",
"(",
"i",
")",
".",
"Time",
">",
"dur",
"{",
"break",
"\n",
"}",
"\n",
"i",
"--",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"i",
"\n",
"}",
"\n",
"return",
"cursor",
"\n",
"}"
] |
// Create cursor position at specific time in buffered packets.
|
[
"Create",
"cursor",
"position",
"at",
"specific",
"time",
"in",
"buffered",
"packets",
"."
] |
3ddbc8f9d4316ab2bbec2bc9ee98127862e3af02
|
https://github.com/nareix/joy4/blob/3ddbc8f9d4316ab2bbec2bc9ee98127862e3af02/av/pubsub/queue.go#L140-L156
|
21,764
|
nareix/joy4
|
av/pubsub/queue.go
|
DelayedGopCount
|
func (self *Queue) DelayedGopCount(n int) *QueueCursor {
cursor := self.newCursor()
cursor.init = func(buf *pktque.Buf, videoidx int) pktque.BufPos {
i := buf.Tail - 1
if videoidx != -1 {
for gop := 0; buf.IsValidPos(i) && gop < n; i-- {
pkt := buf.Get(i)
if pkt.Idx == int8(self.videoidx) && pkt.IsKeyFrame {
gop++
}
}
}
return i
}
return cursor
}
|
go
|
func (self *Queue) DelayedGopCount(n int) *QueueCursor {
cursor := self.newCursor()
cursor.init = func(buf *pktque.Buf, videoidx int) pktque.BufPos {
i := buf.Tail - 1
if videoidx != -1 {
for gop := 0; buf.IsValidPos(i) && gop < n; i-- {
pkt := buf.Get(i)
if pkt.Idx == int8(self.videoidx) && pkt.IsKeyFrame {
gop++
}
}
}
return i
}
return cursor
}
|
[
"func",
"(",
"self",
"*",
"Queue",
")",
"DelayedGopCount",
"(",
"n",
"int",
")",
"*",
"QueueCursor",
"{",
"cursor",
":=",
"self",
".",
"newCursor",
"(",
")",
"\n",
"cursor",
".",
"init",
"=",
"func",
"(",
"buf",
"*",
"pktque",
".",
"Buf",
",",
"videoidx",
"int",
")",
"pktque",
".",
"BufPos",
"{",
"i",
":=",
"buf",
".",
"Tail",
"-",
"1",
"\n",
"if",
"videoidx",
"!=",
"-",
"1",
"{",
"for",
"gop",
":=",
"0",
";",
"buf",
".",
"IsValidPos",
"(",
"i",
")",
"&&",
"gop",
"<",
"n",
";",
"i",
"--",
"{",
"pkt",
":=",
"buf",
".",
"Get",
"(",
"i",
")",
"\n",
"if",
"pkt",
".",
"Idx",
"==",
"int8",
"(",
"self",
".",
"videoidx",
")",
"&&",
"pkt",
".",
"IsKeyFrame",
"{",
"gop",
"++",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"i",
"\n",
"}",
"\n",
"return",
"cursor",
"\n",
"}"
] |
// Create cursor position at specific delayed GOP count in buffered packets.
|
[
"Create",
"cursor",
"position",
"at",
"specific",
"delayed",
"GOP",
"count",
"in",
"buffered",
"packets",
"."
] |
3ddbc8f9d4316ab2bbec2bc9ee98127862e3af02
|
https://github.com/nareix/joy4/blob/3ddbc8f9d4316ab2bbec2bc9ee98127862e3af02/av/pubsub/queue.go#L159-L174
|
21,765
|
nareix/joy4
|
av/pubsub/queue.go
|
ReadPacket
|
func (self *QueueCursor) ReadPacket() (pkt av.Packet, err error) {
self.que.cond.L.Lock()
buf := self.que.buf
if !self.gotpos {
self.pos = self.init(buf, self.que.videoidx)
self.gotpos = true
}
for {
if self.pos.LT(buf.Head) {
self.pos = buf.Head
} else if self.pos.GT(buf.Tail) {
self.pos = buf.Tail
}
if buf.IsValidPos(self.pos) {
pkt = buf.Get(self.pos)
self.pos++
break
}
if self.que.closed {
err = io.EOF
break
}
self.que.cond.Wait()
}
self.que.cond.L.Unlock()
return
}
|
go
|
func (self *QueueCursor) ReadPacket() (pkt av.Packet, err error) {
self.que.cond.L.Lock()
buf := self.que.buf
if !self.gotpos {
self.pos = self.init(buf, self.que.videoidx)
self.gotpos = true
}
for {
if self.pos.LT(buf.Head) {
self.pos = buf.Head
} else if self.pos.GT(buf.Tail) {
self.pos = buf.Tail
}
if buf.IsValidPos(self.pos) {
pkt = buf.Get(self.pos)
self.pos++
break
}
if self.que.closed {
err = io.EOF
break
}
self.que.cond.Wait()
}
self.que.cond.L.Unlock()
return
}
|
[
"func",
"(",
"self",
"*",
"QueueCursor",
")",
"ReadPacket",
"(",
")",
"(",
"pkt",
"av",
".",
"Packet",
",",
"err",
"error",
")",
"{",
"self",
".",
"que",
".",
"cond",
".",
"L",
".",
"Lock",
"(",
")",
"\n",
"buf",
":=",
"self",
".",
"que",
".",
"buf",
"\n",
"if",
"!",
"self",
".",
"gotpos",
"{",
"self",
".",
"pos",
"=",
"self",
".",
"init",
"(",
"buf",
",",
"self",
".",
"que",
".",
"videoidx",
")",
"\n",
"self",
".",
"gotpos",
"=",
"true",
"\n",
"}",
"\n",
"for",
"{",
"if",
"self",
".",
"pos",
".",
"LT",
"(",
"buf",
".",
"Head",
")",
"{",
"self",
".",
"pos",
"=",
"buf",
".",
"Head",
"\n",
"}",
"else",
"if",
"self",
".",
"pos",
".",
"GT",
"(",
"buf",
".",
"Tail",
")",
"{",
"self",
".",
"pos",
"=",
"buf",
".",
"Tail",
"\n",
"}",
"\n",
"if",
"buf",
".",
"IsValidPos",
"(",
"self",
".",
"pos",
")",
"{",
"pkt",
"=",
"buf",
".",
"Get",
"(",
"self",
".",
"pos",
")",
"\n",
"self",
".",
"pos",
"++",
"\n",
"break",
"\n",
"}",
"\n",
"if",
"self",
".",
"que",
".",
"closed",
"{",
"err",
"=",
"io",
".",
"EOF",
"\n",
"break",
"\n",
"}",
"\n",
"self",
".",
"que",
".",
"cond",
".",
"Wait",
"(",
")",
"\n",
"}",
"\n",
"self",
".",
"que",
".",
"cond",
".",
"L",
".",
"Unlock",
"(",
")",
"\n",
"return",
"\n",
"}"
] |
// ReadPacket will not consume packets in Queue, it's just a cursor.
|
[
"ReadPacket",
"will",
"not",
"consume",
"packets",
"in",
"Queue",
"it",
"s",
"just",
"a",
"cursor",
"."
] |
3ddbc8f9d4316ab2bbec2bc9ee98127862e3af02
|
https://github.com/nareix/joy4/blob/3ddbc8f9d4316ab2bbec2bc9ee98127862e3af02/av/pubsub/queue.go#L191-L217
|
21,766
|
go-martini/martini
|
martini.go
|
New
|
func New() *Martini {
m := &Martini{Injector: inject.New(), action: func() {}, logger: log.New(os.Stdout, "[martini] ", 0)}
m.Map(m.logger)
m.Map(defaultReturnHandler())
return m
}
|
go
|
func New() *Martini {
m := &Martini{Injector: inject.New(), action: func() {}, logger: log.New(os.Stdout, "[martini] ", 0)}
m.Map(m.logger)
m.Map(defaultReturnHandler())
return m
}
|
[
"func",
"New",
"(",
")",
"*",
"Martini",
"{",
"m",
":=",
"&",
"Martini",
"{",
"Injector",
":",
"inject",
".",
"New",
"(",
")",
",",
"action",
":",
"func",
"(",
")",
"{",
"}",
",",
"logger",
":",
"log",
".",
"New",
"(",
"os",
".",
"Stdout",
",",
"\"",
"\"",
",",
"0",
")",
"}",
"\n",
"m",
".",
"Map",
"(",
"m",
".",
"logger",
")",
"\n",
"m",
".",
"Map",
"(",
"defaultReturnHandler",
"(",
")",
")",
"\n",
"return",
"m",
"\n",
"}"
] |
// New creates a bare bones Martini instance. Use this method if you want to have full control over the middleware that is used.
|
[
"New",
"creates",
"a",
"bare",
"bones",
"Martini",
"instance",
".",
"Use",
"this",
"method",
"if",
"you",
"want",
"to",
"have",
"full",
"control",
"over",
"the",
"middleware",
"that",
"is",
"used",
"."
] |
22fa46961aabd2665cf3f1343b146d20028f5071
|
https://github.com/go-martini/martini/blob/22fa46961aabd2665cf3f1343b146d20028f5071/martini.go#L38-L43
|
21,767
|
go-martini/martini
|
martini.go
|
Logger
|
func (m *Martini) Logger(logger *log.Logger) {
m.logger = logger
m.Map(m.logger)
}
|
go
|
func (m *Martini) Logger(logger *log.Logger) {
m.logger = logger
m.Map(m.logger)
}
|
[
"func",
"(",
"m",
"*",
"Martini",
")",
"Logger",
"(",
"logger",
"*",
"log",
".",
"Logger",
")",
"{",
"m",
".",
"logger",
"=",
"logger",
"\n",
"m",
".",
"Map",
"(",
"m",
".",
"logger",
")",
"\n",
"}"
] |
// Logger sets the logger
|
[
"Logger",
"sets",
"the",
"logger"
] |
22fa46961aabd2665cf3f1343b146d20028f5071
|
https://github.com/go-martini/martini/blob/22fa46961aabd2665cf3f1343b146d20028f5071/martini.go#L61-L64
|
21,768
|
go-martini/martini
|
martini.go
|
Use
|
func (m *Martini) Use(handler Handler) {
validateHandler(handler)
m.handlers = append(m.handlers, handler)
}
|
go
|
func (m *Martini) Use(handler Handler) {
validateHandler(handler)
m.handlers = append(m.handlers, handler)
}
|
[
"func",
"(",
"m",
"*",
"Martini",
")",
"Use",
"(",
"handler",
"Handler",
")",
"{",
"validateHandler",
"(",
"handler",
")",
"\n\n",
"m",
".",
"handlers",
"=",
"append",
"(",
"m",
".",
"handlers",
",",
"handler",
")",
"\n",
"}"
] |
// Use adds a middleware Handler to the stack. Will panic if the handler is not a callable func. Middleware Handlers are invoked in the order that they are added.
|
[
"Use",
"adds",
"a",
"middleware",
"Handler",
"to",
"the",
"stack",
".",
"Will",
"panic",
"if",
"the",
"handler",
"is",
"not",
"a",
"callable",
"func",
".",
"Middleware",
"Handlers",
"are",
"invoked",
"in",
"the",
"order",
"that",
"they",
"are",
"added",
"."
] |
22fa46961aabd2665cf3f1343b146d20028f5071
|
https://github.com/go-martini/martini/blob/22fa46961aabd2665cf3f1343b146d20028f5071/martini.go#L67-L71
|
21,769
|
go-martini/martini
|
martini.go
|
ServeHTTP
|
func (m *Martini) ServeHTTP(res http.ResponseWriter, req *http.Request) {
m.createContext(res, req).run()
}
|
go
|
func (m *Martini) ServeHTTP(res http.ResponseWriter, req *http.Request) {
m.createContext(res, req).run()
}
|
[
"func",
"(",
"m",
"*",
"Martini",
")",
"ServeHTTP",
"(",
"res",
"http",
".",
"ResponseWriter",
",",
"req",
"*",
"http",
".",
"Request",
")",
"{",
"m",
".",
"createContext",
"(",
"res",
",",
"req",
")",
".",
"run",
"(",
")",
"\n",
"}"
] |
// ServeHTTP is the HTTP Entry point for a Martini instance. Useful if you want to control your own HTTP server.
|
[
"ServeHTTP",
"is",
"the",
"HTTP",
"Entry",
"point",
"for",
"a",
"Martini",
"instance",
".",
"Useful",
"if",
"you",
"want",
"to",
"control",
"your",
"own",
"HTTP",
"server",
"."
] |
22fa46961aabd2665cf3f1343b146d20028f5071
|
https://github.com/go-martini/martini/blob/22fa46961aabd2665cf3f1343b146d20028f5071/martini.go#L74-L76
|
21,770
|
go-martini/martini
|
martini.go
|
RunOnAddr
|
func (m *Martini) RunOnAddr(addr string) {
// TODO: Should probably be implemented using a new instance of http.Server in place of
// calling http.ListenAndServer directly, so that it could be stored in the martini struct for later use.
// This would also allow to improve testing when a custom host and port are passed.
logger := m.Injector.Get(reflect.TypeOf(m.logger)).Interface().(*log.Logger)
logger.Printf("listening on %s (%s)\n", addr, Env)
logger.Fatalln(http.ListenAndServe(addr, m))
}
|
go
|
func (m *Martini) RunOnAddr(addr string) {
// TODO: Should probably be implemented using a new instance of http.Server in place of
// calling http.ListenAndServer directly, so that it could be stored in the martini struct for later use.
// This would also allow to improve testing when a custom host and port are passed.
logger := m.Injector.Get(reflect.TypeOf(m.logger)).Interface().(*log.Logger)
logger.Printf("listening on %s (%s)\n", addr, Env)
logger.Fatalln(http.ListenAndServe(addr, m))
}
|
[
"func",
"(",
"m",
"*",
"Martini",
")",
"RunOnAddr",
"(",
"addr",
"string",
")",
"{",
"// TODO: Should probably be implemented using a new instance of http.Server in place of",
"// calling http.ListenAndServer directly, so that it could be stored in the martini struct for later use.",
"// This would also allow to improve testing when a custom host and port are passed.",
"logger",
":=",
"m",
".",
"Injector",
".",
"Get",
"(",
"reflect",
".",
"TypeOf",
"(",
"m",
".",
"logger",
")",
")",
".",
"Interface",
"(",
")",
".",
"(",
"*",
"log",
".",
"Logger",
")",
"\n",
"logger",
".",
"Printf",
"(",
"\"",
"\\n",
"\"",
",",
"addr",
",",
"Env",
")",
"\n",
"logger",
".",
"Fatalln",
"(",
"http",
".",
"ListenAndServe",
"(",
"addr",
",",
"m",
")",
")",
"\n",
"}"
] |
// Run the http server on a given host and port.
|
[
"Run",
"the",
"http",
"server",
"on",
"a",
"given",
"host",
"and",
"port",
"."
] |
22fa46961aabd2665cf3f1343b146d20028f5071
|
https://github.com/go-martini/martini/blob/22fa46961aabd2665cf3f1343b146d20028f5071/martini.go#L79-L87
|
21,771
|
go-martini/martini
|
martini.go
|
Classic
|
func Classic() *ClassicMartini {
r := NewRouter()
m := New()
m.Use(Logger())
m.Use(Recovery())
m.Use(Static("public"))
m.MapTo(r, (*Routes)(nil))
m.Action(r.Handle)
return &ClassicMartini{m, r}
}
|
go
|
func Classic() *ClassicMartini {
r := NewRouter()
m := New()
m.Use(Logger())
m.Use(Recovery())
m.Use(Static("public"))
m.MapTo(r, (*Routes)(nil))
m.Action(r.Handle)
return &ClassicMartini{m, r}
}
|
[
"func",
"Classic",
"(",
")",
"*",
"ClassicMartini",
"{",
"r",
":=",
"NewRouter",
"(",
")",
"\n",
"m",
":=",
"New",
"(",
")",
"\n",
"m",
".",
"Use",
"(",
"Logger",
"(",
")",
")",
"\n",
"m",
".",
"Use",
"(",
"Recovery",
"(",
")",
")",
"\n",
"m",
".",
"Use",
"(",
"Static",
"(",
"\"",
"\"",
")",
")",
"\n",
"m",
".",
"MapTo",
"(",
"r",
",",
"(",
"*",
"Routes",
")",
"(",
"nil",
")",
")",
"\n",
"m",
".",
"Action",
"(",
"r",
".",
"Handle",
")",
"\n",
"return",
"&",
"ClassicMartini",
"{",
"m",
",",
"r",
"}",
"\n",
"}"
] |
// Classic creates a classic Martini with some basic default middleware - martini.Logger, martini.Recovery and martini.Static.
// Classic also maps martini.Routes as a service.
|
[
"Classic",
"creates",
"a",
"classic",
"Martini",
"with",
"some",
"basic",
"default",
"middleware",
"-",
"martini",
".",
"Logger",
"martini",
".",
"Recovery",
"and",
"martini",
".",
"Static",
".",
"Classic",
"also",
"maps",
"martini",
".",
"Routes",
"as",
"a",
"service",
"."
] |
22fa46961aabd2665cf3f1343b146d20028f5071
|
https://github.com/go-martini/martini/blob/22fa46961aabd2665cf3f1343b146d20028f5071/martini.go#L118-L127
|
21,772
|
go-martini/martini
|
router.go
|
URLWith
|
func (r *route) URLWith(args []string) string {
if len(args) > 0 {
argCount := len(args)
i := 0
url := urlReg.ReplaceAllStringFunc(r.pattern, func(m string) string {
var val interface{}
if i < argCount {
val = args[i]
} else {
val = m
}
i += 1
return fmt.Sprintf(`%v`, val)
})
return url
}
return r.pattern
}
|
go
|
func (r *route) URLWith(args []string) string {
if len(args) > 0 {
argCount := len(args)
i := 0
url := urlReg.ReplaceAllStringFunc(r.pattern, func(m string) string {
var val interface{}
if i < argCount {
val = args[i]
} else {
val = m
}
i += 1
return fmt.Sprintf(`%v`, val)
})
return url
}
return r.pattern
}
|
[
"func",
"(",
"r",
"*",
"route",
")",
"URLWith",
"(",
"args",
"[",
"]",
"string",
")",
"string",
"{",
"if",
"len",
"(",
"args",
")",
">",
"0",
"{",
"argCount",
":=",
"len",
"(",
"args",
")",
"\n",
"i",
":=",
"0",
"\n",
"url",
":=",
"urlReg",
".",
"ReplaceAllStringFunc",
"(",
"r",
".",
"pattern",
",",
"func",
"(",
"m",
"string",
")",
"string",
"{",
"var",
"val",
"interface",
"{",
"}",
"\n",
"if",
"i",
"<",
"argCount",
"{",
"val",
"=",
"args",
"[",
"i",
"]",
"\n",
"}",
"else",
"{",
"val",
"=",
"m",
"\n",
"}",
"\n",
"i",
"+=",
"1",
"\n",
"return",
"fmt",
".",
"Sprintf",
"(",
"`%v`",
",",
"val",
")",
"\n",
"}",
")",
"\n\n",
"return",
"url",
"\n",
"}",
"\n",
"return",
"r",
".",
"pattern",
"\n",
"}"
] |
// URLWith returns the url pattern replacing the parameters for its values
|
[
"URLWith",
"returns",
"the",
"url",
"pattern",
"replacing",
"the",
"parameters",
"for",
"its",
"values"
] |
22fa46961aabd2665cf3f1343b146d20028f5071
|
https://github.com/go-martini/martini/blob/22fa46961aabd2665cf3f1343b146d20028f5071/router.go#L291-L309
|
21,773
|
go-martini/martini
|
router.go
|
URLFor
|
func (r *router) URLFor(name string, params ...interface{}) string {
route := r.findRoute(name)
if route == nil {
panic("route not found")
}
var args []string
for _, param := range params {
switch v := param.(type) {
case int:
args = append(args, strconv.FormatInt(int64(v), 10))
case string:
args = append(args, v)
default:
if v != nil {
panic("Arguments passed to URLFor must be integers or strings")
}
}
}
return route.URLWith(args)
}
|
go
|
func (r *router) URLFor(name string, params ...interface{}) string {
route := r.findRoute(name)
if route == nil {
panic("route not found")
}
var args []string
for _, param := range params {
switch v := param.(type) {
case int:
args = append(args, strconv.FormatInt(int64(v), 10))
case string:
args = append(args, v)
default:
if v != nil {
panic("Arguments passed to URLFor must be integers or strings")
}
}
}
return route.URLWith(args)
}
|
[
"func",
"(",
"r",
"*",
"router",
")",
"URLFor",
"(",
"name",
"string",
",",
"params",
"...",
"interface",
"{",
"}",
")",
"string",
"{",
"route",
":=",
"r",
".",
"findRoute",
"(",
"name",
")",
"\n\n",
"if",
"route",
"==",
"nil",
"{",
"panic",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"var",
"args",
"[",
"]",
"string",
"\n",
"for",
"_",
",",
"param",
":=",
"range",
"params",
"{",
"switch",
"v",
":=",
"param",
".",
"(",
"type",
")",
"{",
"case",
"int",
":",
"args",
"=",
"append",
"(",
"args",
",",
"strconv",
".",
"FormatInt",
"(",
"int64",
"(",
"v",
")",
",",
"10",
")",
")",
"\n",
"case",
"string",
":",
"args",
"=",
"append",
"(",
"args",
",",
"v",
")",
"\n",
"default",
":",
"if",
"v",
"!=",
"nil",
"{",
"panic",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n\n",
"return",
"route",
".",
"URLWith",
"(",
"args",
")",
"\n",
"}"
] |
// URLFor returns the url for the given route name.
|
[
"URLFor",
"returns",
"the",
"url",
"for",
"the",
"given",
"route",
"name",
"."
] |
22fa46961aabd2665cf3f1343b146d20028f5071
|
https://github.com/go-martini/martini/blob/22fa46961aabd2665cf3f1343b146d20028f5071/router.go#L338-L360
|
21,774
|
go-martini/martini
|
router.go
|
MethodsFor
|
func (r *router) MethodsFor(path string) []string {
methods := []string{}
for _, route := range r.getRoutes() {
matches := route.regex.FindStringSubmatch(path)
if len(matches) > 0 && matches[0] == path && !hasMethod(methods, route.method) {
methods = append(methods, route.method)
}
}
return methods
}
|
go
|
func (r *router) MethodsFor(path string) []string {
methods := []string{}
for _, route := range r.getRoutes() {
matches := route.regex.FindStringSubmatch(path)
if len(matches) > 0 && matches[0] == path && !hasMethod(methods, route.method) {
methods = append(methods, route.method)
}
}
return methods
}
|
[
"func",
"(",
"r",
"*",
"router",
")",
"MethodsFor",
"(",
"path",
"string",
")",
"[",
"]",
"string",
"{",
"methods",
":=",
"[",
"]",
"string",
"{",
"}",
"\n",
"for",
"_",
",",
"route",
":=",
"range",
"r",
".",
"getRoutes",
"(",
")",
"{",
"matches",
":=",
"route",
".",
"regex",
".",
"FindStringSubmatch",
"(",
"path",
")",
"\n",
"if",
"len",
"(",
"matches",
")",
">",
"0",
"&&",
"matches",
"[",
"0",
"]",
"==",
"path",
"&&",
"!",
"hasMethod",
"(",
"methods",
",",
"route",
".",
"method",
")",
"{",
"methods",
"=",
"append",
"(",
"methods",
",",
"route",
".",
"method",
")",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"methods",
"\n",
"}"
] |
// MethodsFor returns all methods available for path
|
[
"MethodsFor",
"returns",
"all",
"methods",
"available",
"for",
"path"
] |
22fa46961aabd2665cf3f1343b146d20028f5071
|
https://github.com/go-martini/martini/blob/22fa46961aabd2665cf3f1343b146d20028f5071/router.go#L383-L392
|
21,775
|
go-martini/martini
|
logger.go
|
Logger
|
func Logger() Handler {
return func(res http.ResponseWriter, req *http.Request, c Context, log *log.Logger) {
start := time.Now()
addr := req.Header.Get("X-Real-IP")
if addr == "" {
addr = req.Header.Get("X-Forwarded-For")
if addr == "" {
addr = req.RemoteAddr
}
}
log.Printf("Started %s %s for %s", req.Method, req.URL.Path, addr)
rw := res.(ResponseWriter)
c.Next()
log.Printf("Completed %v %s in %v\n", rw.Status(), http.StatusText(rw.Status()), time.Since(start))
}
}
|
go
|
func Logger() Handler {
return func(res http.ResponseWriter, req *http.Request, c Context, log *log.Logger) {
start := time.Now()
addr := req.Header.Get("X-Real-IP")
if addr == "" {
addr = req.Header.Get("X-Forwarded-For")
if addr == "" {
addr = req.RemoteAddr
}
}
log.Printf("Started %s %s for %s", req.Method, req.URL.Path, addr)
rw := res.(ResponseWriter)
c.Next()
log.Printf("Completed %v %s in %v\n", rw.Status(), http.StatusText(rw.Status()), time.Since(start))
}
}
|
[
"func",
"Logger",
"(",
")",
"Handler",
"{",
"return",
"func",
"(",
"res",
"http",
".",
"ResponseWriter",
",",
"req",
"*",
"http",
".",
"Request",
",",
"c",
"Context",
",",
"log",
"*",
"log",
".",
"Logger",
")",
"{",
"start",
":=",
"time",
".",
"Now",
"(",
")",
"\n\n",
"addr",
":=",
"req",
".",
"Header",
".",
"Get",
"(",
"\"",
"\"",
")",
"\n",
"if",
"addr",
"==",
"\"",
"\"",
"{",
"addr",
"=",
"req",
".",
"Header",
".",
"Get",
"(",
"\"",
"\"",
")",
"\n",
"if",
"addr",
"==",
"\"",
"\"",
"{",
"addr",
"=",
"req",
".",
"RemoteAddr",
"\n",
"}",
"\n",
"}",
"\n\n",
"log",
".",
"Printf",
"(",
"\"",
"\"",
",",
"req",
".",
"Method",
",",
"req",
".",
"URL",
".",
"Path",
",",
"addr",
")",
"\n\n",
"rw",
":=",
"res",
".",
"(",
"ResponseWriter",
")",
"\n",
"c",
".",
"Next",
"(",
")",
"\n\n",
"log",
".",
"Printf",
"(",
"\"",
"\\n",
"\"",
",",
"rw",
".",
"Status",
"(",
")",
",",
"http",
".",
"StatusText",
"(",
"rw",
".",
"Status",
"(",
")",
")",
",",
"time",
".",
"Since",
"(",
"start",
")",
")",
"\n",
"}",
"\n",
"}"
] |
// Logger returns a middleware handler that logs the request as it goes in and the response as it goes out.
|
[
"Logger",
"returns",
"a",
"middleware",
"handler",
"that",
"logs",
"the",
"request",
"as",
"it",
"goes",
"in",
"and",
"the",
"response",
"as",
"it",
"goes",
"out",
"."
] |
22fa46961aabd2665cf3f1343b146d20028f5071
|
https://github.com/go-martini/martini/blob/22fa46961aabd2665cf3f1343b146d20028f5071/logger.go#L10-L29
|
21,776
|
buger/jsonparser
|
escape.go
|
decodeSingleUnicodeEscape
|
func decodeSingleUnicodeEscape(in []byte) (rune, bool) {
// We need at least 6 characters total
if len(in) < 6 {
return utf8.RuneError, false
}
// Convert hex to decimal
h1, h2, h3, h4 := h2I(in[2]), h2I(in[3]), h2I(in[4]), h2I(in[5])
if h1 == badHex || h2 == badHex || h3 == badHex || h4 == badHex {
return utf8.RuneError, false
}
// Compose the hex digits
return rune(h1<<12 + h2<<8 + h3<<4 + h4), true
}
|
go
|
func decodeSingleUnicodeEscape(in []byte) (rune, bool) {
// We need at least 6 characters total
if len(in) < 6 {
return utf8.RuneError, false
}
// Convert hex to decimal
h1, h2, h3, h4 := h2I(in[2]), h2I(in[3]), h2I(in[4]), h2I(in[5])
if h1 == badHex || h2 == badHex || h3 == badHex || h4 == badHex {
return utf8.RuneError, false
}
// Compose the hex digits
return rune(h1<<12 + h2<<8 + h3<<4 + h4), true
}
|
[
"func",
"decodeSingleUnicodeEscape",
"(",
"in",
"[",
"]",
"byte",
")",
"(",
"rune",
",",
"bool",
")",
"{",
"// We need at least 6 characters total",
"if",
"len",
"(",
"in",
")",
"<",
"6",
"{",
"return",
"utf8",
".",
"RuneError",
",",
"false",
"\n",
"}",
"\n\n",
"// Convert hex to decimal",
"h1",
",",
"h2",
",",
"h3",
",",
"h4",
":=",
"h2I",
"(",
"in",
"[",
"2",
"]",
")",
",",
"h2I",
"(",
"in",
"[",
"3",
"]",
")",
",",
"h2I",
"(",
"in",
"[",
"4",
"]",
")",
",",
"h2I",
"(",
"in",
"[",
"5",
"]",
")",
"\n",
"if",
"h1",
"==",
"badHex",
"||",
"h2",
"==",
"badHex",
"||",
"h3",
"==",
"badHex",
"||",
"h4",
"==",
"badHex",
"{",
"return",
"utf8",
".",
"RuneError",
",",
"false",
"\n",
"}",
"\n\n",
"// Compose the hex digits",
"return",
"rune",
"(",
"h1",
"<<",
"12",
"+",
"h2",
"<<",
"8",
"+",
"h3",
"<<",
"4",
"+",
"h4",
")",
",",
"true",
"\n",
"}"
] |
// decodeSingleUnicodeEscape decodes a single \uXXXX escape sequence. The prefix \u is assumed to be present and
// is not checked.
// In JSON, these escapes can either come alone or as part of "UTF16 surrogate pairs" that must be handled together.
// This function only handles one; decodeUnicodeEscape handles this more complex case.
|
[
"decodeSingleUnicodeEscape",
"decodes",
"a",
"single",
"\\",
"uXXXX",
"escape",
"sequence",
".",
"The",
"prefix",
"\\",
"u",
"is",
"assumed",
"to",
"be",
"present",
"and",
"is",
"not",
"checked",
".",
"In",
"JSON",
"these",
"escapes",
"can",
"either",
"come",
"alone",
"or",
"as",
"part",
"of",
"UTF16",
"surrogate",
"pairs",
"that",
"must",
"be",
"handled",
"together",
".",
"This",
"function",
"only",
"handles",
"one",
";",
"decodeUnicodeEscape",
"handles",
"this",
"more",
"complex",
"case",
"."
] |
bf1c66bbce23153d89b23f8960071a680dbef54b
|
https://github.com/buger/jsonparser/blob/bf1c66bbce23153d89b23f8960071a680dbef54b/escape.go#L39-L53
|
21,777
|
buger/jsonparser
|
bytes.go
|
parseInt
|
func parseInt(bytes []byte) (v int64, ok bool, overflow bool) {
if len(bytes) == 0 {
return 0, false, false
}
var neg bool = false
if bytes[0] == '-' {
neg = true
bytes = bytes[1:]
}
var b int64 = 0
for _, c := range bytes {
if c >= '0' && c <= '9' {
b = (10 * v) + int64(c-'0')
} else {
return 0, false, false
}
if overflow = (b < v); overflow {
break
}
v = b
}
if overflow {
if neg && bio.Equal(bytes, []byte(minInt64)) {
return b, true, false
}
return 0, false, true
}
if neg {
return -v, true, false
} else {
return v, true, false
}
}
|
go
|
func parseInt(bytes []byte) (v int64, ok bool, overflow bool) {
if len(bytes) == 0 {
return 0, false, false
}
var neg bool = false
if bytes[0] == '-' {
neg = true
bytes = bytes[1:]
}
var b int64 = 0
for _, c := range bytes {
if c >= '0' && c <= '9' {
b = (10 * v) + int64(c-'0')
} else {
return 0, false, false
}
if overflow = (b < v); overflow {
break
}
v = b
}
if overflow {
if neg && bio.Equal(bytes, []byte(minInt64)) {
return b, true, false
}
return 0, false, true
}
if neg {
return -v, true, false
} else {
return v, true, false
}
}
|
[
"func",
"parseInt",
"(",
"bytes",
"[",
"]",
"byte",
")",
"(",
"v",
"int64",
",",
"ok",
"bool",
",",
"overflow",
"bool",
")",
"{",
"if",
"len",
"(",
"bytes",
")",
"==",
"0",
"{",
"return",
"0",
",",
"false",
",",
"false",
"\n",
"}",
"\n\n",
"var",
"neg",
"bool",
"=",
"false",
"\n",
"if",
"bytes",
"[",
"0",
"]",
"==",
"'-'",
"{",
"neg",
"=",
"true",
"\n",
"bytes",
"=",
"bytes",
"[",
"1",
":",
"]",
"\n",
"}",
"\n\n",
"var",
"b",
"int64",
"=",
"0",
"\n",
"for",
"_",
",",
"c",
":=",
"range",
"bytes",
"{",
"if",
"c",
">=",
"'0'",
"&&",
"c",
"<=",
"'9'",
"{",
"b",
"=",
"(",
"10",
"*",
"v",
")",
"+",
"int64",
"(",
"c",
"-",
"'0'",
")",
"\n",
"}",
"else",
"{",
"return",
"0",
",",
"false",
",",
"false",
"\n",
"}",
"\n",
"if",
"overflow",
"=",
"(",
"b",
"<",
"v",
")",
";",
"overflow",
"{",
"break",
"\n",
"}",
"\n",
"v",
"=",
"b",
"\n",
"}",
"\n\n",
"if",
"overflow",
"{",
"if",
"neg",
"&&",
"bio",
".",
"Equal",
"(",
"bytes",
",",
"[",
"]",
"byte",
"(",
"minInt64",
")",
")",
"{",
"return",
"b",
",",
"true",
",",
"false",
"\n",
"}",
"\n",
"return",
"0",
",",
"false",
",",
"true",
"\n",
"}",
"\n\n",
"if",
"neg",
"{",
"return",
"-",
"v",
",",
"true",
",",
"false",
"\n",
"}",
"else",
"{",
"return",
"v",
",",
"true",
",",
"false",
"\n",
"}",
"\n",
"}"
] |
// About 2x faster then strconv.ParseInt because it only supports base 10, which is enough for JSON
|
[
"About",
"2x",
"faster",
"then",
"strconv",
".",
"ParseInt",
"because",
"it",
"only",
"supports",
"base",
"10",
"which",
"is",
"enough",
"for",
"JSON"
] |
bf1c66bbce23153d89b23f8960071a680dbef54b
|
https://github.com/buger/jsonparser/blob/bf1c66bbce23153d89b23f8960071a680dbef54b/bytes.go#L11-L47
|
21,778
|
buger/jsonparser
|
parser.go
|
lastToken
|
func lastToken(data []byte) int {
for i := len(data) - 1; i >= 0; i-- {
switch data[i] {
case ' ', '\n', '\r', '\t':
continue
default:
return i
}
}
return -1
}
|
go
|
func lastToken(data []byte) int {
for i := len(data) - 1; i >= 0; i-- {
switch data[i] {
case ' ', '\n', '\r', '\t':
continue
default:
return i
}
}
return -1
}
|
[
"func",
"lastToken",
"(",
"data",
"[",
"]",
"byte",
")",
"int",
"{",
"for",
"i",
":=",
"len",
"(",
"data",
")",
"-",
"1",
";",
"i",
">=",
"0",
";",
"i",
"--",
"{",
"switch",
"data",
"[",
"i",
"]",
"{",
"case",
"' '",
",",
"'\\n'",
",",
"'\\r'",
",",
"'\\t'",
":",
"continue",
"\n",
"default",
":",
"return",
"i",
"\n",
"}",
"\n",
"}",
"\n\n",
"return",
"-",
"1",
"\n",
"}"
] |
// Find position of last character which is not whitespace
|
[
"Find",
"position",
"of",
"last",
"character",
"which",
"is",
"not",
"whitespace"
] |
bf1c66bbce23153d89b23f8960071a680dbef54b
|
https://github.com/buger/jsonparser/blob/bf1c66bbce23153d89b23f8960071a680dbef54b/parser.go#L137-L148
|
21,779
|
buger/jsonparser
|
parser.go
|
stringEnd
|
func stringEnd(data []byte) (int, bool) {
escaped := false
for i, c := range data {
if c == '"' {
if !escaped {
return i + 1, false
} else {
j := i - 1
for {
if j < 0 || data[j] != '\\' {
return i + 1, true // even number of backslashes
}
j--
if j < 0 || data[j] != '\\' {
break // odd number of backslashes
}
j--
}
}
} else if c == '\\' {
escaped = true
}
}
return -1, escaped
}
|
go
|
func stringEnd(data []byte) (int, bool) {
escaped := false
for i, c := range data {
if c == '"' {
if !escaped {
return i + 1, false
} else {
j := i - 1
for {
if j < 0 || data[j] != '\\' {
return i + 1, true // even number of backslashes
}
j--
if j < 0 || data[j] != '\\' {
break // odd number of backslashes
}
j--
}
}
} else if c == '\\' {
escaped = true
}
}
return -1, escaped
}
|
[
"func",
"stringEnd",
"(",
"data",
"[",
"]",
"byte",
")",
"(",
"int",
",",
"bool",
")",
"{",
"escaped",
":=",
"false",
"\n",
"for",
"i",
",",
"c",
":=",
"range",
"data",
"{",
"if",
"c",
"==",
"'\"'",
"{",
"if",
"!",
"escaped",
"{",
"return",
"i",
"+",
"1",
",",
"false",
"\n",
"}",
"else",
"{",
"j",
":=",
"i",
"-",
"1",
"\n",
"for",
"{",
"if",
"j",
"<",
"0",
"||",
"data",
"[",
"j",
"]",
"!=",
"'\\\\'",
"{",
"return",
"i",
"+",
"1",
",",
"true",
"// even number of backslashes",
"\n",
"}",
"\n",
"j",
"--",
"\n",
"if",
"j",
"<",
"0",
"||",
"data",
"[",
"j",
"]",
"!=",
"'\\\\'",
"{",
"break",
"// odd number of backslashes",
"\n",
"}",
"\n",
"j",
"--",
"\n\n",
"}",
"\n",
"}",
"\n",
"}",
"else",
"if",
"c",
"==",
"'\\\\'",
"{",
"escaped",
"=",
"true",
"\n",
"}",
"\n",
"}",
"\n\n",
"return",
"-",
"1",
",",
"escaped",
"\n",
"}"
] |
// Tries to find the end of string
// Support if string contains escaped quote symbols.
|
[
"Tries",
"to",
"find",
"the",
"end",
"of",
"string",
"Support",
"if",
"string",
"contains",
"escaped",
"quote",
"symbols",
"."
] |
bf1c66bbce23153d89b23f8960071a680dbef54b
|
https://github.com/buger/jsonparser/blob/bf1c66bbce23153d89b23f8960071a680dbef54b/parser.go#L152-L178
|
21,780
|
buger/jsonparser
|
parser.go
|
ArrayEach
|
func ArrayEach(data []byte, cb func(value []byte, dataType ValueType, offset int, err error), keys ...string) (offset int, err error) {
if len(data) == 0 {
return -1, MalformedObjectError
}
offset = 1
if len(keys) > 0 {
if offset = searchKeys(data, keys...); offset == -1 {
return offset, KeyPathNotFoundError
}
// Go to closest value
nO := nextToken(data[offset:])
if nO == -1 {
return offset, MalformedJsonError
}
offset += nO
if data[offset] != '[' {
return offset, MalformedArrayError
}
offset++
}
nO := nextToken(data[offset:])
if nO == -1 {
return offset, MalformedJsonError
}
offset += nO
if data[offset] == ']' {
return offset, nil
}
for true {
v, t, o, e := Get(data[offset:])
if e != nil {
return offset, e
}
if o == 0 {
break
}
if t != NotExist {
cb(v, t, offset+o-len(v), e)
}
if e != nil {
break
}
offset += o
skipToToken := nextToken(data[offset:])
if skipToToken == -1 {
return offset, MalformedArrayError
}
offset += skipToToken
if data[offset] == ']' {
break
}
if data[offset] != ',' {
return offset, MalformedArrayError
}
offset++
}
return offset, nil
}
|
go
|
func ArrayEach(data []byte, cb func(value []byte, dataType ValueType, offset int, err error), keys ...string) (offset int, err error) {
if len(data) == 0 {
return -1, MalformedObjectError
}
offset = 1
if len(keys) > 0 {
if offset = searchKeys(data, keys...); offset == -1 {
return offset, KeyPathNotFoundError
}
// Go to closest value
nO := nextToken(data[offset:])
if nO == -1 {
return offset, MalformedJsonError
}
offset += nO
if data[offset] != '[' {
return offset, MalformedArrayError
}
offset++
}
nO := nextToken(data[offset:])
if nO == -1 {
return offset, MalformedJsonError
}
offset += nO
if data[offset] == ']' {
return offset, nil
}
for true {
v, t, o, e := Get(data[offset:])
if e != nil {
return offset, e
}
if o == 0 {
break
}
if t != NotExist {
cb(v, t, offset+o-len(v), e)
}
if e != nil {
break
}
offset += o
skipToToken := nextToken(data[offset:])
if skipToToken == -1 {
return offset, MalformedArrayError
}
offset += skipToToken
if data[offset] == ']' {
break
}
if data[offset] != ',' {
return offset, MalformedArrayError
}
offset++
}
return offset, nil
}
|
[
"func",
"ArrayEach",
"(",
"data",
"[",
"]",
"byte",
",",
"cb",
"func",
"(",
"value",
"[",
"]",
"byte",
",",
"dataType",
"ValueType",
",",
"offset",
"int",
",",
"err",
"error",
")",
",",
"keys",
"...",
"string",
")",
"(",
"offset",
"int",
",",
"err",
"error",
")",
"{",
"if",
"len",
"(",
"data",
")",
"==",
"0",
"{",
"return",
"-",
"1",
",",
"MalformedObjectError",
"\n",
"}",
"\n\n",
"offset",
"=",
"1",
"\n\n",
"if",
"len",
"(",
"keys",
")",
">",
"0",
"{",
"if",
"offset",
"=",
"searchKeys",
"(",
"data",
",",
"keys",
"...",
")",
";",
"offset",
"==",
"-",
"1",
"{",
"return",
"offset",
",",
"KeyPathNotFoundError",
"\n",
"}",
"\n\n",
"// Go to closest value",
"nO",
":=",
"nextToken",
"(",
"data",
"[",
"offset",
":",
"]",
")",
"\n",
"if",
"nO",
"==",
"-",
"1",
"{",
"return",
"offset",
",",
"MalformedJsonError",
"\n",
"}",
"\n\n",
"offset",
"+=",
"nO",
"\n\n",
"if",
"data",
"[",
"offset",
"]",
"!=",
"'['",
"{",
"return",
"offset",
",",
"MalformedArrayError",
"\n",
"}",
"\n\n",
"offset",
"++",
"\n",
"}",
"\n\n",
"nO",
":=",
"nextToken",
"(",
"data",
"[",
"offset",
":",
"]",
")",
"\n",
"if",
"nO",
"==",
"-",
"1",
"{",
"return",
"offset",
",",
"MalformedJsonError",
"\n",
"}",
"\n\n",
"offset",
"+=",
"nO",
"\n\n",
"if",
"data",
"[",
"offset",
"]",
"==",
"']'",
"{",
"return",
"offset",
",",
"nil",
"\n",
"}",
"\n\n",
"for",
"true",
"{",
"v",
",",
"t",
",",
"o",
",",
"e",
":=",
"Get",
"(",
"data",
"[",
"offset",
":",
"]",
")",
"\n\n",
"if",
"e",
"!=",
"nil",
"{",
"return",
"offset",
",",
"e",
"\n",
"}",
"\n\n",
"if",
"o",
"==",
"0",
"{",
"break",
"\n",
"}",
"\n\n",
"if",
"t",
"!=",
"NotExist",
"{",
"cb",
"(",
"v",
",",
"t",
",",
"offset",
"+",
"o",
"-",
"len",
"(",
"v",
")",
",",
"e",
")",
"\n",
"}",
"\n\n",
"if",
"e",
"!=",
"nil",
"{",
"break",
"\n",
"}",
"\n\n",
"offset",
"+=",
"o",
"\n\n",
"skipToToken",
":=",
"nextToken",
"(",
"data",
"[",
"offset",
":",
"]",
")",
"\n",
"if",
"skipToToken",
"==",
"-",
"1",
"{",
"return",
"offset",
",",
"MalformedArrayError",
"\n",
"}",
"\n",
"offset",
"+=",
"skipToToken",
"\n\n",
"if",
"data",
"[",
"offset",
"]",
"==",
"']'",
"{",
"break",
"\n",
"}",
"\n\n",
"if",
"data",
"[",
"offset",
"]",
"!=",
"','",
"{",
"return",
"offset",
",",
"MalformedArrayError",
"\n",
"}",
"\n\n",
"offset",
"++",
"\n",
"}",
"\n\n",
"return",
"offset",
",",
"nil",
"\n",
"}"
] |
// ArrayEach is used when iterating arrays, accepts a callback function with the same return arguments as `Get`.
|
[
"ArrayEach",
"is",
"used",
"when",
"iterating",
"arrays",
"accepts",
"a",
"callback",
"function",
"with",
"the",
"same",
"return",
"arguments",
"as",
"Get",
"."
] |
bf1c66bbce23153d89b23f8960071a680dbef54b
|
https://github.com/buger/jsonparser/blob/bf1c66bbce23153d89b23f8960071a680dbef54b/parser.go#L902-L979
|
21,781
|
buger/jsonparser
|
parser.go
|
ObjectEach
|
func ObjectEach(data []byte, callback func(key []byte, value []byte, dataType ValueType, offset int) error, keys ...string) (err error) {
var stackbuf [unescapeStackBufSize]byte // stack-allocated array for allocation-free unescaping of small strings
offset := 0
// Descend to the desired key, if requested
if len(keys) > 0 {
if off := searchKeys(data, keys...); off == -1 {
return KeyPathNotFoundError
} else {
offset = off
}
}
// Validate and skip past opening brace
if off := nextToken(data[offset:]); off == -1 {
return MalformedObjectError
} else if offset += off; data[offset] != '{' {
return MalformedObjectError
} else {
offset++
}
// Skip to the first token inside the object, or stop if we find the ending brace
if off := nextToken(data[offset:]); off == -1 {
return MalformedJsonError
} else if offset += off; data[offset] == '}' {
return nil
}
// Loop pre-condition: data[offset] points to what should be either the next entry's key, or the closing brace (if it's anything else, the JSON is malformed)
for offset < len(data) {
// Step 1: find the next key
var key []byte
// Check what the the next token is: start of string, end of object, or something else (error)
switch data[offset] {
case '"':
offset++ // accept as string and skip opening quote
case '}':
return nil // we found the end of the object; stop and return success
default:
return MalformedObjectError
}
// Find the end of the key string
var keyEscaped bool
if off, esc := stringEnd(data[offset:]); off == -1 {
return MalformedJsonError
} else {
key, keyEscaped = data[offset:offset+off-1], esc
offset += off
}
// Unescape the string if needed
if keyEscaped {
if keyUnescaped, err := Unescape(key, stackbuf[:]); err != nil {
return MalformedStringEscapeError
} else {
key = keyUnescaped
}
}
// Step 2: skip the colon
if off := nextToken(data[offset:]); off == -1 {
return MalformedJsonError
} else if offset += off; data[offset] != ':' {
return MalformedJsonError
} else {
offset++
}
// Step 3: find the associated value, then invoke the callback
if value, valueType, off, err := Get(data[offset:]); err != nil {
return err
} else if err := callback(key, value, valueType, offset+off); err != nil { // Invoke the callback here!
return err
} else {
offset += off
}
// Step 4: skip over the next comma to the following token, or stop if we hit the ending brace
if off := nextToken(data[offset:]); off == -1 {
return MalformedArrayError
} else {
offset += off
switch data[offset] {
case '}':
return nil // Stop if we hit the close brace
case ',':
offset++ // Ignore the comma
default:
return MalformedObjectError
}
}
// Skip to the next token after the comma
if off := nextToken(data[offset:]); off == -1 {
return MalformedArrayError
} else {
offset += off
}
}
return MalformedObjectError // we shouldn't get here; it's expected that we will return via finding the ending brace
}
|
go
|
func ObjectEach(data []byte, callback func(key []byte, value []byte, dataType ValueType, offset int) error, keys ...string) (err error) {
var stackbuf [unescapeStackBufSize]byte // stack-allocated array for allocation-free unescaping of small strings
offset := 0
// Descend to the desired key, if requested
if len(keys) > 0 {
if off := searchKeys(data, keys...); off == -1 {
return KeyPathNotFoundError
} else {
offset = off
}
}
// Validate and skip past opening brace
if off := nextToken(data[offset:]); off == -1 {
return MalformedObjectError
} else if offset += off; data[offset] != '{' {
return MalformedObjectError
} else {
offset++
}
// Skip to the first token inside the object, or stop if we find the ending brace
if off := nextToken(data[offset:]); off == -1 {
return MalformedJsonError
} else if offset += off; data[offset] == '}' {
return nil
}
// Loop pre-condition: data[offset] points to what should be either the next entry's key, or the closing brace (if it's anything else, the JSON is malformed)
for offset < len(data) {
// Step 1: find the next key
var key []byte
// Check what the the next token is: start of string, end of object, or something else (error)
switch data[offset] {
case '"':
offset++ // accept as string and skip opening quote
case '}':
return nil // we found the end of the object; stop and return success
default:
return MalformedObjectError
}
// Find the end of the key string
var keyEscaped bool
if off, esc := stringEnd(data[offset:]); off == -1 {
return MalformedJsonError
} else {
key, keyEscaped = data[offset:offset+off-1], esc
offset += off
}
// Unescape the string if needed
if keyEscaped {
if keyUnescaped, err := Unescape(key, stackbuf[:]); err != nil {
return MalformedStringEscapeError
} else {
key = keyUnescaped
}
}
// Step 2: skip the colon
if off := nextToken(data[offset:]); off == -1 {
return MalformedJsonError
} else if offset += off; data[offset] != ':' {
return MalformedJsonError
} else {
offset++
}
// Step 3: find the associated value, then invoke the callback
if value, valueType, off, err := Get(data[offset:]); err != nil {
return err
} else if err := callback(key, value, valueType, offset+off); err != nil { // Invoke the callback here!
return err
} else {
offset += off
}
// Step 4: skip over the next comma to the following token, or stop if we hit the ending brace
if off := nextToken(data[offset:]); off == -1 {
return MalformedArrayError
} else {
offset += off
switch data[offset] {
case '}':
return nil // Stop if we hit the close brace
case ',':
offset++ // Ignore the comma
default:
return MalformedObjectError
}
}
// Skip to the next token after the comma
if off := nextToken(data[offset:]); off == -1 {
return MalformedArrayError
} else {
offset += off
}
}
return MalformedObjectError // we shouldn't get here; it's expected that we will return via finding the ending brace
}
|
[
"func",
"ObjectEach",
"(",
"data",
"[",
"]",
"byte",
",",
"callback",
"func",
"(",
"key",
"[",
"]",
"byte",
",",
"value",
"[",
"]",
"byte",
",",
"dataType",
"ValueType",
",",
"offset",
"int",
")",
"error",
",",
"keys",
"...",
"string",
")",
"(",
"err",
"error",
")",
"{",
"var",
"stackbuf",
"[",
"unescapeStackBufSize",
"]",
"byte",
"// stack-allocated array for allocation-free unescaping of small strings",
"\n",
"offset",
":=",
"0",
"\n\n",
"// Descend to the desired key, if requested",
"if",
"len",
"(",
"keys",
")",
">",
"0",
"{",
"if",
"off",
":=",
"searchKeys",
"(",
"data",
",",
"keys",
"...",
")",
";",
"off",
"==",
"-",
"1",
"{",
"return",
"KeyPathNotFoundError",
"\n",
"}",
"else",
"{",
"offset",
"=",
"off",
"\n",
"}",
"\n",
"}",
"\n\n",
"// Validate and skip past opening brace",
"if",
"off",
":=",
"nextToken",
"(",
"data",
"[",
"offset",
":",
"]",
")",
";",
"off",
"==",
"-",
"1",
"{",
"return",
"MalformedObjectError",
"\n",
"}",
"else",
"if",
"offset",
"+=",
"off",
";",
"data",
"[",
"offset",
"]",
"!=",
"'{'",
"{",
"return",
"MalformedObjectError",
"\n",
"}",
"else",
"{",
"offset",
"++",
"\n",
"}",
"\n\n",
"// Skip to the first token inside the object, or stop if we find the ending brace",
"if",
"off",
":=",
"nextToken",
"(",
"data",
"[",
"offset",
":",
"]",
")",
";",
"off",
"==",
"-",
"1",
"{",
"return",
"MalformedJsonError",
"\n",
"}",
"else",
"if",
"offset",
"+=",
"off",
";",
"data",
"[",
"offset",
"]",
"==",
"'}'",
"{",
"return",
"nil",
"\n",
"}",
"\n\n",
"// Loop pre-condition: data[offset] points to what should be either the next entry's key, or the closing brace (if it's anything else, the JSON is malformed)",
"for",
"offset",
"<",
"len",
"(",
"data",
")",
"{",
"// Step 1: find the next key",
"var",
"key",
"[",
"]",
"byte",
"\n\n",
"// Check what the the next token is: start of string, end of object, or something else (error)",
"switch",
"data",
"[",
"offset",
"]",
"{",
"case",
"'\"'",
":",
"offset",
"++",
"// accept as string and skip opening quote",
"\n",
"case",
"'}'",
":",
"return",
"nil",
"// we found the end of the object; stop and return success",
"\n",
"default",
":",
"return",
"MalformedObjectError",
"\n",
"}",
"\n\n",
"// Find the end of the key string",
"var",
"keyEscaped",
"bool",
"\n",
"if",
"off",
",",
"esc",
":=",
"stringEnd",
"(",
"data",
"[",
"offset",
":",
"]",
")",
";",
"off",
"==",
"-",
"1",
"{",
"return",
"MalformedJsonError",
"\n",
"}",
"else",
"{",
"key",
",",
"keyEscaped",
"=",
"data",
"[",
"offset",
":",
"offset",
"+",
"off",
"-",
"1",
"]",
",",
"esc",
"\n",
"offset",
"+=",
"off",
"\n",
"}",
"\n\n",
"// Unescape the string if needed",
"if",
"keyEscaped",
"{",
"if",
"keyUnescaped",
",",
"err",
":=",
"Unescape",
"(",
"key",
",",
"stackbuf",
"[",
":",
"]",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"MalformedStringEscapeError",
"\n",
"}",
"else",
"{",
"key",
"=",
"keyUnescaped",
"\n",
"}",
"\n",
"}",
"\n\n",
"// Step 2: skip the colon",
"if",
"off",
":=",
"nextToken",
"(",
"data",
"[",
"offset",
":",
"]",
")",
";",
"off",
"==",
"-",
"1",
"{",
"return",
"MalformedJsonError",
"\n",
"}",
"else",
"if",
"offset",
"+=",
"off",
";",
"data",
"[",
"offset",
"]",
"!=",
"':'",
"{",
"return",
"MalformedJsonError",
"\n",
"}",
"else",
"{",
"offset",
"++",
"\n",
"}",
"\n\n",
"// Step 3: find the associated value, then invoke the callback",
"if",
"value",
",",
"valueType",
",",
"off",
",",
"err",
":=",
"Get",
"(",
"data",
"[",
"offset",
":",
"]",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"else",
"if",
"err",
":=",
"callback",
"(",
"key",
",",
"value",
",",
"valueType",
",",
"offset",
"+",
"off",
")",
";",
"err",
"!=",
"nil",
"{",
"// Invoke the callback here!",
"return",
"err",
"\n",
"}",
"else",
"{",
"offset",
"+=",
"off",
"\n",
"}",
"\n\n",
"// Step 4: skip over the next comma to the following token, or stop if we hit the ending brace",
"if",
"off",
":=",
"nextToken",
"(",
"data",
"[",
"offset",
":",
"]",
")",
";",
"off",
"==",
"-",
"1",
"{",
"return",
"MalformedArrayError",
"\n",
"}",
"else",
"{",
"offset",
"+=",
"off",
"\n",
"switch",
"data",
"[",
"offset",
"]",
"{",
"case",
"'}'",
":",
"return",
"nil",
"// Stop if we hit the close brace",
"\n",
"case",
"','",
":",
"offset",
"++",
"// Ignore the comma",
"\n",
"default",
":",
"return",
"MalformedObjectError",
"\n",
"}",
"\n",
"}",
"\n\n",
"// Skip to the next token after the comma",
"if",
"off",
":=",
"nextToken",
"(",
"data",
"[",
"offset",
":",
"]",
")",
";",
"off",
"==",
"-",
"1",
"{",
"return",
"MalformedArrayError",
"\n",
"}",
"else",
"{",
"offset",
"+=",
"off",
"\n",
"}",
"\n",
"}",
"\n\n",
"return",
"MalformedObjectError",
"// we shouldn't get here; it's expected that we will return via finding the ending brace",
"\n",
"}"
] |
// ObjectEach iterates over the key-value pairs of a JSON object, invoking a given callback for each such entry
|
[
"ObjectEach",
"iterates",
"over",
"the",
"key",
"-",
"value",
"pairs",
"of",
"a",
"JSON",
"object",
"invoking",
"a",
"given",
"callback",
"for",
"each",
"such",
"entry"
] |
bf1c66bbce23153d89b23f8960071a680dbef54b
|
https://github.com/buger/jsonparser/blob/bf1c66bbce23153d89b23f8960071a680dbef54b/parser.go#L982-L1086
|
21,782
|
buger/jsonparser
|
parser.go
|
GetUnsafeString
|
func GetUnsafeString(data []byte, keys ...string) (val string, err error) {
v, _, _, e := Get(data, keys...)
if e != nil {
return "", e
}
return bytesToString(&v), nil
}
|
go
|
func GetUnsafeString(data []byte, keys ...string) (val string, err error) {
v, _, _, e := Get(data, keys...)
if e != nil {
return "", e
}
return bytesToString(&v), nil
}
|
[
"func",
"GetUnsafeString",
"(",
"data",
"[",
"]",
"byte",
",",
"keys",
"...",
"string",
")",
"(",
"val",
"string",
",",
"err",
"error",
")",
"{",
"v",
",",
"_",
",",
"_",
",",
"e",
":=",
"Get",
"(",
"data",
",",
"keys",
"...",
")",
"\n\n",
"if",
"e",
"!=",
"nil",
"{",
"return",
"\"",
"\"",
",",
"e",
"\n",
"}",
"\n\n",
"return",
"bytesToString",
"(",
"&",
"v",
")",
",",
"nil",
"\n",
"}"
] |
// GetUnsafeString returns the value retrieved by `Get`, use creates string without memory allocation by mapping string to slice memory. It does not handle escape symbols.
|
[
"GetUnsafeString",
"returns",
"the",
"value",
"retrieved",
"by",
"Get",
"use",
"creates",
"string",
"without",
"memory",
"allocation",
"by",
"mapping",
"string",
"to",
"slice",
"memory",
".",
"It",
"does",
"not",
"handle",
"escape",
"symbols",
"."
] |
bf1c66bbce23153d89b23f8960071a680dbef54b
|
https://github.com/buger/jsonparser/blob/bf1c66bbce23153d89b23f8960071a680dbef54b/parser.go#L1089-L1097
|
21,783
|
buger/jsonparser
|
parser.go
|
GetString
|
func GetString(data []byte, keys ...string) (val string, err error) {
v, t, _, e := Get(data, keys...)
if e != nil {
return "", e
}
if t != String {
return "", fmt.Errorf("Value is not a string: %s", string(v))
}
// If no escapes return raw conten
if bytes.IndexByte(v, '\\') == -1 {
return string(v), nil
}
return ParseString(v)
}
|
go
|
func GetString(data []byte, keys ...string) (val string, err error) {
v, t, _, e := Get(data, keys...)
if e != nil {
return "", e
}
if t != String {
return "", fmt.Errorf("Value is not a string: %s", string(v))
}
// If no escapes return raw conten
if bytes.IndexByte(v, '\\') == -1 {
return string(v), nil
}
return ParseString(v)
}
|
[
"func",
"GetString",
"(",
"data",
"[",
"]",
"byte",
",",
"keys",
"...",
"string",
")",
"(",
"val",
"string",
",",
"err",
"error",
")",
"{",
"v",
",",
"t",
",",
"_",
",",
"e",
":=",
"Get",
"(",
"data",
",",
"keys",
"...",
")",
"\n\n",
"if",
"e",
"!=",
"nil",
"{",
"return",
"\"",
"\"",
",",
"e",
"\n",
"}",
"\n\n",
"if",
"t",
"!=",
"String",
"{",
"return",
"\"",
"\"",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"string",
"(",
"v",
")",
")",
"\n",
"}",
"\n\n",
"// If no escapes return raw conten",
"if",
"bytes",
".",
"IndexByte",
"(",
"v",
",",
"'\\\\'",
")",
"==",
"-",
"1",
"{",
"return",
"string",
"(",
"v",
")",
",",
"nil",
"\n",
"}",
"\n\n",
"return",
"ParseString",
"(",
"v",
")",
"\n",
"}"
] |
// GetString returns the value retrieved by `Get`, cast to a string if possible, trying to properly handle escape and utf8 symbols
// If key data type do not match, it will return an error.
|
[
"GetString",
"returns",
"the",
"value",
"retrieved",
"by",
"Get",
"cast",
"to",
"a",
"string",
"if",
"possible",
"trying",
"to",
"properly",
"handle",
"escape",
"and",
"utf8",
"symbols",
"If",
"key",
"data",
"type",
"do",
"not",
"match",
"it",
"will",
"return",
"an",
"error",
"."
] |
bf1c66bbce23153d89b23f8960071a680dbef54b
|
https://github.com/buger/jsonparser/blob/bf1c66bbce23153d89b23f8960071a680dbef54b/parser.go#L1101-L1118
|
21,784
|
buger/jsonparser
|
parser.go
|
GetFloat
|
func GetFloat(data []byte, keys ...string) (val float64, err error) {
v, t, _, e := Get(data, keys...)
if e != nil {
return 0, e
}
if t != Number {
return 0, fmt.Errorf("Value is not a number: %s", string(v))
}
return ParseFloat(v)
}
|
go
|
func GetFloat(data []byte, keys ...string) (val float64, err error) {
v, t, _, e := Get(data, keys...)
if e != nil {
return 0, e
}
if t != Number {
return 0, fmt.Errorf("Value is not a number: %s", string(v))
}
return ParseFloat(v)
}
|
[
"func",
"GetFloat",
"(",
"data",
"[",
"]",
"byte",
",",
"keys",
"...",
"string",
")",
"(",
"val",
"float64",
",",
"err",
"error",
")",
"{",
"v",
",",
"t",
",",
"_",
",",
"e",
":=",
"Get",
"(",
"data",
",",
"keys",
"...",
")",
"\n\n",
"if",
"e",
"!=",
"nil",
"{",
"return",
"0",
",",
"e",
"\n",
"}",
"\n\n",
"if",
"t",
"!=",
"Number",
"{",
"return",
"0",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"string",
"(",
"v",
")",
")",
"\n",
"}",
"\n\n",
"return",
"ParseFloat",
"(",
"v",
")",
"\n",
"}"
] |
// GetFloat returns the value retrieved by `Get`, cast to a float64 if possible.
// The offset is the same as in `Get`.
// If key data type do not match, it will return an error.
|
[
"GetFloat",
"returns",
"the",
"value",
"retrieved",
"by",
"Get",
"cast",
"to",
"a",
"float64",
"if",
"possible",
".",
"The",
"offset",
"is",
"the",
"same",
"as",
"in",
"Get",
".",
"If",
"key",
"data",
"type",
"do",
"not",
"match",
"it",
"will",
"return",
"an",
"error",
"."
] |
bf1c66bbce23153d89b23f8960071a680dbef54b
|
https://github.com/buger/jsonparser/blob/bf1c66bbce23153d89b23f8960071a680dbef54b/parser.go#L1123-L1135
|
21,785
|
buger/jsonparser
|
parser.go
|
GetInt
|
func GetInt(data []byte, keys ...string) (val int64, err error) {
v, t, _, e := Get(data, keys...)
if e != nil {
return 0, e
}
if t != Number {
return 0, fmt.Errorf("Value is not a number: %s", string(v))
}
return ParseInt(v)
}
|
go
|
func GetInt(data []byte, keys ...string) (val int64, err error) {
v, t, _, e := Get(data, keys...)
if e != nil {
return 0, e
}
if t != Number {
return 0, fmt.Errorf("Value is not a number: %s", string(v))
}
return ParseInt(v)
}
|
[
"func",
"GetInt",
"(",
"data",
"[",
"]",
"byte",
",",
"keys",
"...",
"string",
")",
"(",
"val",
"int64",
",",
"err",
"error",
")",
"{",
"v",
",",
"t",
",",
"_",
",",
"e",
":=",
"Get",
"(",
"data",
",",
"keys",
"...",
")",
"\n\n",
"if",
"e",
"!=",
"nil",
"{",
"return",
"0",
",",
"e",
"\n",
"}",
"\n\n",
"if",
"t",
"!=",
"Number",
"{",
"return",
"0",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"string",
"(",
"v",
")",
")",
"\n",
"}",
"\n\n",
"return",
"ParseInt",
"(",
"v",
")",
"\n",
"}"
] |
// GetInt returns the value retrieved by `Get`, cast to a int64 if possible.
// If key data type do not match, it will return an error.
|
[
"GetInt",
"returns",
"the",
"value",
"retrieved",
"by",
"Get",
"cast",
"to",
"a",
"int64",
"if",
"possible",
".",
"If",
"key",
"data",
"type",
"do",
"not",
"match",
"it",
"will",
"return",
"an",
"error",
"."
] |
bf1c66bbce23153d89b23f8960071a680dbef54b
|
https://github.com/buger/jsonparser/blob/bf1c66bbce23153d89b23f8960071a680dbef54b/parser.go#L1139-L1151
|
21,786
|
buger/jsonparser
|
parser.go
|
GetBoolean
|
func GetBoolean(data []byte, keys ...string) (val bool, err error) {
v, t, _, e := Get(data, keys...)
if e != nil {
return false, e
}
if t != Boolean {
return false, fmt.Errorf("Value is not a boolean: %s", string(v))
}
return ParseBoolean(v)
}
|
go
|
func GetBoolean(data []byte, keys ...string) (val bool, err error) {
v, t, _, e := Get(data, keys...)
if e != nil {
return false, e
}
if t != Boolean {
return false, fmt.Errorf("Value is not a boolean: %s", string(v))
}
return ParseBoolean(v)
}
|
[
"func",
"GetBoolean",
"(",
"data",
"[",
"]",
"byte",
",",
"keys",
"...",
"string",
")",
"(",
"val",
"bool",
",",
"err",
"error",
")",
"{",
"v",
",",
"t",
",",
"_",
",",
"e",
":=",
"Get",
"(",
"data",
",",
"keys",
"...",
")",
"\n\n",
"if",
"e",
"!=",
"nil",
"{",
"return",
"false",
",",
"e",
"\n",
"}",
"\n\n",
"if",
"t",
"!=",
"Boolean",
"{",
"return",
"false",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"string",
"(",
"v",
")",
")",
"\n",
"}",
"\n\n",
"return",
"ParseBoolean",
"(",
"v",
")",
"\n",
"}"
] |
// GetBoolean returns the value retrieved by `Get`, cast to a bool if possible.
// The offset is the same as in `Get`.
// If key data type do not match, it will return error.
|
[
"GetBoolean",
"returns",
"the",
"value",
"retrieved",
"by",
"Get",
"cast",
"to",
"a",
"bool",
"if",
"possible",
".",
"The",
"offset",
"is",
"the",
"same",
"as",
"in",
"Get",
".",
"If",
"key",
"data",
"type",
"do",
"not",
"match",
"it",
"will",
"return",
"error",
"."
] |
bf1c66bbce23153d89b23f8960071a680dbef54b
|
https://github.com/buger/jsonparser/blob/bf1c66bbce23153d89b23f8960071a680dbef54b/parser.go#L1156-L1168
|
21,787
|
buger/jsonparser
|
parser.go
|
ParseFloat
|
func ParseFloat(b []byte) (float64, error) {
if v, err := parseFloat(&b); err != nil {
return 0, MalformedValueError
} else {
return v, nil
}
}
|
go
|
func ParseFloat(b []byte) (float64, error) {
if v, err := parseFloat(&b); err != nil {
return 0, MalformedValueError
} else {
return v, nil
}
}
|
[
"func",
"ParseFloat",
"(",
"b",
"[",
"]",
"byte",
")",
"(",
"float64",
",",
"error",
")",
"{",
"if",
"v",
",",
"err",
":=",
"parseFloat",
"(",
"&",
"b",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"0",
",",
"MalformedValueError",
"\n",
"}",
"else",
"{",
"return",
"v",
",",
"nil",
"\n",
"}",
"\n",
"}"
] |
// ParseNumber parses a Number ValueType into a Go float64
|
[
"ParseNumber",
"parses",
"a",
"Number",
"ValueType",
"into",
"a",
"Go",
"float64"
] |
bf1c66bbce23153d89b23f8960071a680dbef54b
|
https://github.com/buger/jsonparser/blob/bf1c66bbce23153d89b23f8960071a680dbef54b/parser.go#L1193-L1199
|
21,788
|
buger/jsonparser
|
parser.go
|
ParseInt
|
func ParseInt(b []byte) (int64, error) {
if v, ok, overflow := parseInt(b); !ok {
if overflow {
return 0, OverflowIntegerError
}
return 0, MalformedValueError
} else {
return v, nil
}
}
|
go
|
func ParseInt(b []byte) (int64, error) {
if v, ok, overflow := parseInt(b); !ok {
if overflow {
return 0, OverflowIntegerError
}
return 0, MalformedValueError
} else {
return v, nil
}
}
|
[
"func",
"ParseInt",
"(",
"b",
"[",
"]",
"byte",
")",
"(",
"int64",
",",
"error",
")",
"{",
"if",
"v",
",",
"ok",
",",
"overflow",
":=",
"parseInt",
"(",
"b",
")",
";",
"!",
"ok",
"{",
"if",
"overflow",
"{",
"return",
"0",
",",
"OverflowIntegerError",
"\n",
"}",
"\n",
"return",
"0",
",",
"MalformedValueError",
"\n",
"}",
"else",
"{",
"return",
"v",
",",
"nil",
"\n",
"}",
"\n",
"}"
] |
// ParseInt parses a Number ValueType into a Go int64
|
[
"ParseInt",
"parses",
"a",
"Number",
"ValueType",
"into",
"a",
"Go",
"int64"
] |
bf1c66bbce23153d89b23f8960071a680dbef54b
|
https://github.com/buger/jsonparser/blob/bf1c66bbce23153d89b23f8960071a680dbef54b/parser.go#L1202-L1211
|
21,789
|
jung-kurt/gofpdf
|
fpdf.go
|
SetErrorf
|
func (f *Fpdf) SetErrorf(fmtStr string, args ...interface{}) {
if f.err == nil {
f.err = fmt.Errorf(fmtStr, args...)
}
}
|
go
|
func (f *Fpdf) SetErrorf(fmtStr string, args ...interface{}) {
if f.err == nil {
f.err = fmt.Errorf(fmtStr, args...)
}
}
|
[
"func",
"(",
"f",
"*",
"Fpdf",
")",
"SetErrorf",
"(",
"fmtStr",
"string",
",",
"args",
"...",
"interface",
"{",
"}",
")",
"{",
"if",
"f",
".",
"err",
"==",
"nil",
"{",
"f",
".",
"err",
"=",
"fmt",
".",
"Errorf",
"(",
"fmtStr",
",",
"args",
"...",
")",
"\n",
"}",
"\n",
"}"
] |
// SetErrorf sets the internal Fpdf error with formatted text to halt PDF
// generation; this may facilitate error handling by application. If an error
// condition is already set, this call is ignored.
//
// See the documentation for printing in the standard fmt package for details
// about fmtStr and args.
|
[
"SetErrorf",
"sets",
"the",
"internal",
"Fpdf",
"error",
"with",
"formatted",
"text",
"to",
"halt",
"PDF",
"generation",
";",
"this",
"may",
"facilitate",
"error",
"handling",
"by",
"application",
".",
"If",
"an",
"error",
"condition",
"is",
"already",
"set",
"this",
"call",
"is",
"ignored",
".",
"See",
"the",
"documentation",
"for",
"printing",
"in",
"the",
"standard",
"fmt",
"package",
"for",
"details",
"about",
"fmtStr",
"and",
"args",
"."
] |
8b09ffb30d9a8716107d250631b3c580aa54ba04
|
https://github.com/jung-kurt/gofpdf/blob/8b09ffb30d9a8716107d250631b3c580aa54ba04/fpdf.go#L259-L263
|
21,790
|
jung-kurt/gofpdf
|
fpdf.go
|
SetMargins
|
func (f *Fpdf) SetMargins(left, top, right float64) {
f.lMargin = left
f.tMargin = top
if right < 0 {
right = left
}
f.rMargin = right
}
|
go
|
func (f *Fpdf) SetMargins(left, top, right float64) {
f.lMargin = left
f.tMargin = top
if right < 0 {
right = left
}
f.rMargin = right
}
|
[
"func",
"(",
"f",
"*",
"Fpdf",
")",
"SetMargins",
"(",
"left",
",",
"top",
",",
"right",
"float64",
")",
"{",
"f",
".",
"lMargin",
"=",
"left",
"\n",
"f",
".",
"tMargin",
"=",
"top",
"\n",
"if",
"right",
"<",
"0",
"{",
"right",
"=",
"left",
"\n",
"}",
"\n",
"f",
".",
"rMargin",
"=",
"right",
"\n",
"}"
] |
// SetMargins defines the left, top and right margins. By default, they equal 1
// cm. Call this method to change them. If the value of the right margin is
// less than zero, it is set to the same as the left margin.
|
[
"SetMargins",
"defines",
"the",
"left",
"top",
"and",
"right",
"margins",
".",
"By",
"default",
"they",
"equal",
"1",
"cm",
".",
"Call",
"this",
"method",
"to",
"change",
"them",
".",
"If",
"the",
"value",
"of",
"the",
"right",
"margin",
"is",
"less",
"than",
"zero",
"it",
"is",
"set",
"to",
"the",
"same",
"as",
"the",
"left",
"margin",
"."
] |
8b09ffb30d9a8716107d250631b3c580aa54ba04
|
https://github.com/jung-kurt/gofpdf/blob/8b09ffb30d9a8716107d250631b3c580aa54ba04/fpdf.go#L307-L314
|
21,791
|
jung-kurt/gofpdf
|
fpdf.go
|
SetLeftMargin
|
func (f *Fpdf) SetLeftMargin(margin float64) {
f.lMargin = margin
if f.page > 0 && f.x < margin {
f.x = margin
}
}
|
go
|
func (f *Fpdf) SetLeftMargin(margin float64) {
f.lMargin = margin
if f.page > 0 && f.x < margin {
f.x = margin
}
}
|
[
"func",
"(",
"f",
"*",
"Fpdf",
")",
"SetLeftMargin",
"(",
"margin",
"float64",
")",
"{",
"f",
".",
"lMargin",
"=",
"margin",
"\n",
"if",
"f",
".",
"page",
">",
"0",
"&&",
"f",
".",
"x",
"<",
"margin",
"{",
"f",
".",
"x",
"=",
"margin",
"\n",
"}",
"\n",
"}"
] |
// SetLeftMargin defines the left margin. The method can be called before
// creating the first page. If the current abscissa gets out of page, it is
// brought back to the margin.
|
[
"SetLeftMargin",
"defines",
"the",
"left",
"margin",
".",
"The",
"method",
"can",
"be",
"called",
"before",
"creating",
"the",
"first",
"page",
".",
"If",
"the",
"current",
"abscissa",
"gets",
"out",
"of",
"page",
"it",
"is",
"brought",
"back",
"to",
"the",
"margin",
"."
] |
8b09ffb30d9a8716107d250631b3c580aa54ba04
|
https://github.com/jung-kurt/gofpdf/blob/8b09ffb30d9a8716107d250631b3c580aa54ba04/fpdf.go#L319-L324
|
21,792
|
jung-kurt/gofpdf
|
fpdf.go
|
SetPageBox
|
func (f *Fpdf) SetPageBox(t string, x, y, wd, ht float64) {
f.SetPageBoxRec(t, PageBox{SizeType{Wd: wd, Ht: ht}, PointType{X: x, Y: y}})
}
|
go
|
func (f *Fpdf) SetPageBox(t string, x, y, wd, ht float64) {
f.SetPageBoxRec(t, PageBox{SizeType{Wd: wd, Ht: ht}, PointType{X: x, Y: y}})
}
|
[
"func",
"(",
"f",
"*",
"Fpdf",
")",
"SetPageBox",
"(",
"t",
"string",
",",
"x",
",",
"y",
",",
"wd",
",",
"ht",
"float64",
")",
"{",
"f",
".",
"SetPageBoxRec",
"(",
"t",
",",
"PageBox",
"{",
"SizeType",
"{",
"Wd",
":",
"wd",
",",
"Ht",
":",
"ht",
"}",
",",
"PointType",
"{",
"X",
":",
"x",
",",
"Y",
":",
"y",
"}",
"}",
")",
"\n",
"}"
] |
// SetPageBox sets the page box for the current page, and any following pages.
// Allowable types are trim, trimbox, crop, cropbox, bleed, bleedbox, art and
// artbox box types are case insensitive.
|
[
"SetPageBox",
"sets",
"the",
"page",
"box",
"for",
"the",
"current",
"page",
"and",
"any",
"following",
"pages",
".",
"Allowable",
"types",
"are",
"trim",
"trimbox",
"crop",
"cropbox",
"bleed",
"bleedbox",
"art",
"and",
"artbox",
"box",
"types",
"are",
"case",
"insensitive",
"."
] |
8b09ffb30d9a8716107d250631b3c580aa54ba04
|
https://github.com/jung-kurt/gofpdf/blob/8b09ffb30d9a8716107d250631b3c580aa54ba04/fpdf.go#L383-L385
|
21,793
|
jung-kurt/gofpdf
|
fpdf.go
|
GetAutoPageBreak
|
func (f *Fpdf) GetAutoPageBreak() (auto bool, margin float64) {
auto = f.autoPageBreak
margin = f.bMargin
return
}
|
go
|
func (f *Fpdf) GetAutoPageBreak() (auto bool, margin float64) {
auto = f.autoPageBreak
margin = f.bMargin
return
}
|
[
"func",
"(",
"f",
"*",
"Fpdf",
")",
"GetAutoPageBreak",
"(",
")",
"(",
"auto",
"bool",
",",
"margin",
"float64",
")",
"{",
"auto",
"=",
"f",
".",
"autoPageBreak",
"\n",
"margin",
"=",
"f",
".",
"bMargin",
"\n",
"return",
"\n",
"}"
] |
// GetAutoPageBreak returns true if automatic pages breaks are enabled, false
// otherwise. This is followed by the triggering limit from the bottom of the
// page. This value applies only if automatic page breaks are enabled.
|
[
"GetAutoPageBreak",
"returns",
"true",
"if",
"automatic",
"pages",
"breaks",
"are",
"enabled",
"false",
"otherwise",
".",
"This",
"is",
"followed",
"by",
"the",
"triggering",
"limit",
"from",
"the",
"bottom",
"of",
"the",
"page",
".",
"This",
"value",
"applies",
"only",
"if",
"automatic",
"page",
"breaks",
"are",
"enabled",
"."
] |
8b09ffb30d9a8716107d250631b3c580aa54ba04
|
https://github.com/jung-kurt/gofpdf/blob/8b09ffb30d9a8716107d250631b3c580aa54ba04/fpdf.go#L484-L488
|
21,794
|
jung-kurt/gofpdf
|
fpdf.go
|
SetAutoPageBreak
|
func (f *Fpdf) SetAutoPageBreak(auto bool, margin float64) {
f.autoPageBreak = auto
f.bMargin = margin
f.pageBreakTrigger = f.h - margin
}
|
go
|
func (f *Fpdf) SetAutoPageBreak(auto bool, margin float64) {
f.autoPageBreak = auto
f.bMargin = margin
f.pageBreakTrigger = f.h - margin
}
|
[
"func",
"(",
"f",
"*",
"Fpdf",
")",
"SetAutoPageBreak",
"(",
"auto",
"bool",
",",
"margin",
"float64",
")",
"{",
"f",
".",
"autoPageBreak",
"=",
"auto",
"\n",
"f",
".",
"bMargin",
"=",
"margin",
"\n",
"f",
".",
"pageBreakTrigger",
"=",
"f",
".",
"h",
"-",
"margin",
"\n",
"}"
] |
// SetAutoPageBreak enables or disables the automatic page breaking mode. When
// enabling, the second parameter is the distance from the bottom of the page
// that defines the triggering limit. By default, the mode is on and the margin
// is 2 cm.
|
[
"SetAutoPageBreak",
"enables",
"or",
"disables",
"the",
"automatic",
"page",
"breaking",
"mode",
".",
"When",
"enabling",
"the",
"second",
"parameter",
"is",
"the",
"distance",
"from",
"the",
"bottom",
"of",
"the",
"page",
"that",
"defines",
"the",
"triggering",
"limit",
".",
"By",
"default",
"the",
"mode",
"is",
"on",
"and",
"the",
"margin",
"is",
"2",
"cm",
"."
] |
8b09ffb30d9a8716107d250631b3c580aa54ba04
|
https://github.com/jung-kurt/gofpdf/blob/8b09ffb30d9a8716107d250631b3c580aa54ba04/fpdf.go#L494-L498
|
21,795
|
jung-kurt/gofpdf
|
fpdf.go
|
SetKeywords
|
func (f *Fpdf) SetKeywords(keywordsStr string, isUTF8 bool) {
if isUTF8 {
keywordsStr = utf8toutf16(keywordsStr)
}
f.keywords = keywordsStr
}
|
go
|
func (f *Fpdf) SetKeywords(keywordsStr string, isUTF8 bool) {
if isUTF8 {
keywordsStr = utf8toutf16(keywordsStr)
}
f.keywords = keywordsStr
}
|
[
"func",
"(",
"f",
"*",
"Fpdf",
")",
"SetKeywords",
"(",
"keywordsStr",
"string",
",",
"isUTF8",
"bool",
")",
"{",
"if",
"isUTF8",
"{",
"keywordsStr",
"=",
"utf8toutf16",
"(",
"keywordsStr",
")",
"\n",
"}",
"\n",
"f",
".",
"keywords",
"=",
"keywordsStr",
"\n",
"}"
] |
// SetKeywords defines the keywords of the document. keywordStr is a
// space-delimited string, for example "invoice August". isUTF8 indicates if
// the string is encoded
|
[
"SetKeywords",
"defines",
"the",
"keywords",
"of",
"the",
"document",
".",
"keywordStr",
"is",
"a",
"space",
"-",
"delimited",
"string",
"for",
"example",
"invoice",
"August",
".",
"isUTF8",
"indicates",
"if",
"the",
"string",
"is",
"encoded"
] |
8b09ffb30d9a8716107d250631b3c580aa54ba04
|
https://github.com/jung-kurt/gofpdf/blob/8b09ffb30d9a8716107d250631b3c580aa54ba04/fpdf.go#L588-L593
|
21,796
|
jung-kurt/gofpdf
|
fpdf.go
|
GetStringWidth
|
func (f *Fpdf) GetStringWidth(s string) float64 {
if f.err != nil {
return 0
}
w := 0
for _, ch := range []byte(s) {
if ch == 0 {
break
}
w += f.currentFont.Cw[ch]
}
return float64(w) * f.fontSize / 1000
}
|
go
|
func (f *Fpdf) GetStringWidth(s string) float64 {
if f.err != nil {
return 0
}
w := 0
for _, ch := range []byte(s) {
if ch == 0 {
break
}
w += f.currentFont.Cw[ch]
}
return float64(w) * f.fontSize / 1000
}
|
[
"func",
"(",
"f",
"*",
"Fpdf",
")",
"GetStringWidth",
"(",
"s",
"string",
")",
"float64",
"{",
"if",
"f",
".",
"err",
"!=",
"nil",
"{",
"return",
"0",
"\n",
"}",
"\n",
"w",
":=",
"0",
"\n",
"for",
"_",
",",
"ch",
":=",
"range",
"[",
"]",
"byte",
"(",
"s",
")",
"{",
"if",
"ch",
"==",
"0",
"{",
"break",
"\n",
"}",
"\n",
"w",
"+=",
"f",
".",
"currentFont",
".",
"Cw",
"[",
"ch",
"]",
"\n",
"}",
"\n",
"return",
"float64",
"(",
"w",
")",
"*",
"f",
".",
"fontSize",
"/",
"1000",
"\n",
"}"
] |
// GetStringWidth returns the length of a string in user units. A font must be
// currently selected.
|
[
"GetStringWidth",
"returns",
"the",
"length",
"of",
"a",
"string",
"in",
"user",
"units",
".",
"A",
"font",
"must",
"be",
"currently",
"selected",
"."
] |
8b09ffb30d9a8716107d250631b3c580aa54ba04
|
https://github.com/jung-kurt/gofpdf/blob/8b09ffb30d9a8716107d250631b3c580aa54ba04/fpdf.go#L914-L926
|
21,797
|
jung-kurt/gofpdf
|
fpdf.go
|
SetLineCapStyle
|
func (f *Fpdf) SetLineCapStyle(styleStr string) {
var capStyle int
switch styleStr {
case "round":
capStyle = 1
case "square":
capStyle = 2
default:
capStyle = 0
}
f.capStyle = capStyle
if f.page > 0 {
f.outf("%d J", f.capStyle)
}
}
|
go
|
func (f *Fpdf) SetLineCapStyle(styleStr string) {
var capStyle int
switch styleStr {
case "round":
capStyle = 1
case "square":
capStyle = 2
default:
capStyle = 0
}
f.capStyle = capStyle
if f.page > 0 {
f.outf("%d J", f.capStyle)
}
}
|
[
"func",
"(",
"f",
"*",
"Fpdf",
")",
"SetLineCapStyle",
"(",
"styleStr",
"string",
")",
"{",
"var",
"capStyle",
"int",
"\n",
"switch",
"styleStr",
"{",
"case",
"\"",
"\"",
":",
"capStyle",
"=",
"1",
"\n",
"case",
"\"",
"\"",
":",
"capStyle",
"=",
"2",
"\n",
"default",
":",
"capStyle",
"=",
"0",
"\n",
"}",
"\n",
"f",
".",
"capStyle",
"=",
"capStyle",
"\n",
"if",
"f",
".",
"page",
">",
"0",
"{",
"f",
".",
"outf",
"(",
"\"",
"\"",
",",
"f",
".",
"capStyle",
")",
"\n",
"}",
"\n",
"}"
] |
// SetLineCapStyle defines the line cap style. styleStr should be "butt",
// "round" or "square". A square style projects from the end of the line. The
// method can be called before the first page is created. The value is
// retained from page to page.
|
[
"SetLineCapStyle",
"defines",
"the",
"line",
"cap",
"style",
".",
"styleStr",
"should",
"be",
"butt",
"round",
"or",
"square",
".",
"A",
"square",
"style",
"projects",
"from",
"the",
"end",
"of",
"the",
"line",
".",
"The",
"method",
"can",
"be",
"called",
"before",
"the",
"first",
"page",
"is",
"created",
".",
"The",
"value",
"is",
"retained",
"from",
"page",
"to",
"page",
"."
] |
8b09ffb30d9a8716107d250631b3c580aa54ba04
|
https://github.com/jung-kurt/gofpdf/blob/8b09ffb30d9a8716107d250631b3c580aa54ba04/fpdf.go#L951-L965
|
21,798
|
jung-kurt/gofpdf
|
fpdf.go
|
SetLineJoinStyle
|
func (f *Fpdf) SetLineJoinStyle(styleStr string) {
var joinStyle int
switch styleStr {
case "round":
joinStyle = 1
case "bevel":
joinStyle = 2
default:
joinStyle = 0
}
f.joinStyle = joinStyle
if f.page > 0 {
f.outf("%d j", f.joinStyle)
}
}
|
go
|
func (f *Fpdf) SetLineJoinStyle(styleStr string) {
var joinStyle int
switch styleStr {
case "round":
joinStyle = 1
case "bevel":
joinStyle = 2
default:
joinStyle = 0
}
f.joinStyle = joinStyle
if f.page > 0 {
f.outf("%d j", f.joinStyle)
}
}
|
[
"func",
"(",
"f",
"*",
"Fpdf",
")",
"SetLineJoinStyle",
"(",
"styleStr",
"string",
")",
"{",
"var",
"joinStyle",
"int",
"\n",
"switch",
"styleStr",
"{",
"case",
"\"",
"\"",
":",
"joinStyle",
"=",
"1",
"\n",
"case",
"\"",
"\"",
":",
"joinStyle",
"=",
"2",
"\n",
"default",
":",
"joinStyle",
"=",
"0",
"\n",
"}",
"\n",
"f",
".",
"joinStyle",
"=",
"joinStyle",
"\n",
"if",
"f",
".",
"page",
">",
"0",
"{",
"f",
".",
"outf",
"(",
"\"",
"\"",
",",
"f",
".",
"joinStyle",
")",
"\n",
"}",
"\n",
"}"
] |
// SetLineJoinStyle defines the line cap style. styleStr should be "miter",
// "round" or "bevel". The method can be called before the first page
// is created. The value is retained from page to page.
|
[
"SetLineJoinStyle",
"defines",
"the",
"line",
"cap",
"style",
".",
"styleStr",
"should",
"be",
"miter",
"round",
"or",
"bevel",
".",
"The",
"method",
"can",
"be",
"called",
"before",
"the",
"first",
"page",
"is",
"created",
".",
"The",
"value",
"is",
"retained",
"from",
"page",
"to",
"page",
"."
] |
8b09ffb30d9a8716107d250631b3c580aa54ba04
|
https://github.com/jung-kurt/gofpdf/blob/8b09ffb30d9a8716107d250631b3c580aa54ba04/fpdf.go#L970-L984
|
21,799
|
jung-kurt/gofpdf
|
fpdf.go
|
fillDrawOp
|
func fillDrawOp(styleStr string) (opStr string) {
switch strings.ToUpper(styleStr) {
case "", "D":
// Stroke the path.
opStr = "S"
case "F":
// fill the path, using the nonzero winding number rule
opStr = "f"
case "F*":
// fill the path, using the even-odd rule
opStr = "f*"
case "FD", "DF":
// fill and then stroke the path, using the nonzero winding number rule
opStr = "B"
case "FD*", "DF*":
// fill and then stroke the path, using the even-odd rule
opStr = "B*"
default:
opStr = styleStr
}
return
}
|
go
|
func fillDrawOp(styleStr string) (opStr string) {
switch strings.ToUpper(styleStr) {
case "", "D":
// Stroke the path.
opStr = "S"
case "F":
// fill the path, using the nonzero winding number rule
opStr = "f"
case "F*":
// fill the path, using the even-odd rule
opStr = "f*"
case "FD", "DF":
// fill and then stroke the path, using the nonzero winding number rule
opStr = "B"
case "FD*", "DF*":
// fill and then stroke the path, using the even-odd rule
opStr = "B*"
default:
opStr = styleStr
}
return
}
|
[
"func",
"fillDrawOp",
"(",
"styleStr",
"string",
")",
"(",
"opStr",
"string",
")",
"{",
"switch",
"strings",
".",
"ToUpper",
"(",
"styleStr",
")",
"{",
"case",
"\"",
"\"",
",",
"\"",
"\"",
":",
"// Stroke the path.",
"opStr",
"=",
"\"",
"\"",
"\n",
"case",
"\"",
"\"",
":",
"// fill the path, using the nonzero winding number rule",
"opStr",
"=",
"\"",
"\"",
"\n",
"case",
"\"",
"\"",
":",
"// fill the path, using the even-odd rule",
"opStr",
"=",
"\"",
"\"",
"\n",
"case",
"\"",
"\"",
",",
"\"",
"\"",
":",
"// fill and then stroke the path, using the nonzero winding number rule",
"opStr",
"=",
"\"",
"\"",
"\n",
"case",
"\"",
"\"",
",",
"\"",
"\"",
":",
"// fill and then stroke the path, using the even-odd rule",
"opStr",
"=",
"\"",
"\"",
"\n",
"default",
":",
"opStr",
"=",
"styleStr",
"\n",
"}",
"\n",
"return",
"\n",
"}"
] |
// fillDrawOp corrects path painting operators
|
[
"fillDrawOp",
"corrects",
"path",
"painting",
"operators"
] |
8b09ffb30d9a8716107d250631b3c580aa54ba04
|
https://github.com/jung-kurt/gofpdf/blob/8b09ffb30d9a8716107d250631b3c580aa54ba04/fpdf.go#L1031-L1052
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.