repo stringlengths 5 67 | path stringlengths 4 218 | func_name stringlengths 0 151 | original_string stringlengths 52 373k | language stringclasses 6 values | code stringlengths 52 373k | code_tokens listlengths 10 512 | docstring stringlengths 3 47.2k | docstring_tokens listlengths 3 234 | sha stringlengths 40 40 | url stringlengths 85 339 | partition stringclasses 3 values |
|---|---|---|---|---|---|---|---|---|---|---|---|
sourcegraph/go-langserver | langserver/internal/godef/go/types/types.go | doTypeMembers | func doTypeMembers(t Type, name string, fn func(*ast.Object), q *list.List) {
// strip off single indirection
// TODO: eliminate methods disallowed when indirected.
if u, ok := t.Node.(*ast.StarExpr); ok {
_, t = t.ctxt.exprType(u.X, false, t.Pkg)
}
if id, _ := t.Node.(*ast.Ident); id != nil && id.Obj != nil {
if scope, ok := id.Obj.Type.(*ast.Scope); ok {
doScope(scope, name, fn, t.Pkg)
}
}
u := t.Underlying(true)
switch n := u.Node.(type) {
case *ast.StructType:
t.ctxt.doStructMembers(n.Fields.List, t.Pkg, fn, q)
case *ast.InterfaceType:
t.ctxt.doInterfaceMembers(n.Methods.List, t.Pkg, fn)
}
} | go | func doTypeMembers(t Type, name string, fn func(*ast.Object), q *list.List) {
// strip off single indirection
// TODO: eliminate methods disallowed when indirected.
if u, ok := t.Node.(*ast.StarExpr); ok {
_, t = t.ctxt.exprType(u.X, false, t.Pkg)
}
if id, _ := t.Node.(*ast.Ident); id != nil && id.Obj != nil {
if scope, ok := id.Obj.Type.(*ast.Scope); ok {
doScope(scope, name, fn, t.Pkg)
}
}
u := t.Underlying(true)
switch n := u.Node.(type) {
case *ast.StructType:
t.ctxt.doStructMembers(n.Fields.List, t.Pkg, fn, q)
case *ast.InterfaceType:
t.ctxt.doInterfaceMembers(n.Methods.List, t.Pkg, fn)
}
} | [
"func",
"doTypeMembers",
"(",
"t",
"Type",
",",
"name",
"string",
",",
"fn",
"func",
"(",
"*",
"ast",
".",
"Object",
")",
",",
"q",
"*",
"list",
".",
"List",
")",
"{",
"if",
"u",
",",
"ok",
":=",
"t",
".",
"Node",
".",
"(",
"*",
"ast",
".",
... | // doTypeMembers calls fn for each member of the given type,
// at one level only. Unnamed members are pushed onto the queue. | [
"doTypeMembers",
"calls",
"fn",
"for",
"each",
"member",
"of",
"the",
"given",
"type",
"at",
"one",
"level",
"only",
".",
"Unnamed",
"members",
"are",
"pushed",
"onto",
"the",
"queue",
"."
] | 33d2968a49e1131825a0accdd64bdf9901cf144c | https://github.com/sourcegraph/go-langserver/blob/33d2968a49e1131825a0accdd64bdf9901cf144c/langserver/internal/godef/go/types/types.go#L560-L579 | train |
sourcegraph/go-langserver | langserver/internal/godef/go/types/types.go | unnamedFieldName | func unnamedFieldName(t ast.Node) *ast.Ident {
switch t := t.(type) {
case *ast.Ident:
return t
case *ast.SelectorExpr:
return t.Sel
case *ast.StarExpr:
return unnamedFieldName(t.X)
}
panic("no name found for unnamed field")
} | go | func unnamedFieldName(t ast.Node) *ast.Ident {
switch t := t.(type) {
case *ast.Ident:
return t
case *ast.SelectorExpr:
return t.Sel
case *ast.StarExpr:
return unnamedFieldName(t.X)
}
panic("no name found for unnamed field")
} | [
"func",
"unnamedFieldName",
"(",
"t",
"ast",
".",
"Node",
")",
"*",
"ast",
".",
"Ident",
"{",
"switch",
"t",
":=",
"t",
".",
"(",
"type",
")",
"{",
"case",
"*",
"ast",
".",
"Ident",
":",
"return",
"t",
"\n",
"case",
"*",
"ast",
".",
"SelectorExpr... | // unnamedFieldName returns the field name for
// an unnamed field with its type given by ast node t.
// | [
"unnamedFieldName",
"returns",
"the",
"field",
"name",
"for",
"an",
"unnamed",
"field",
"with",
"its",
"type",
"given",
"by",
"ast",
"node",
"t",
"."
] | 33d2968a49e1131825a0accdd64bdf9901cf144c | https://github.com/sourcegraph/go-langserver/blob/33d2968a49e1131825a0accdd64bdf9901cf144c/langserver/internal/godef/go/types/types.go#L635-L648 | train |
sourcegraph/go-langserver | langserver/internal/godef/go/types/types.go | doScope | func doScope(s *ast.Scope, name string, fn func(*ast.Object), pkg string) {
if s == nil {
return
}
if name != "" {
if obj := s.Lookup(name); obj != nil {
fn(obj)
}
return
}
for _, obj := range s.Objects {
if obj.Kind == ast.Bad || pkg != "" && !ast.IsExported(obj.Name) {
continue
}
fn(obj)
}
} | go | func doScope(s *ast.Scope, name string, fn func(*ast.Object), pkg string) {
if s == nil {
return
}
if name != "" {
if obj := s.Lookup(name); obj != nil {
fn(obj)
}
return
}
for _, obj := range s.Objects {
if obj.Kind == ast.Bad || pkg != "" && !ast.IsExported(obj.Name) {
continue
}
fn(obj)
}
} | [
"func",
"doScope",
"(",
"s",
"*",
"ast",
".",
"Scope",
",",
"name",
"string",
",",
"fn",
"func",
"(",
"*",
"ast",
".",
"Object",
")",
",",
"pkg",
"string",
")",
"{",
"if",
"s",
"==",
"nil",
"{",
"return",
"\n",
"}",
"\n",
"if",
"name",
"!=",
... | // doScope iterates through all the functions in the given scope, at
// the top level only. | [
"doScope",
"iterates",
"through",
"all",
"the",
"functions",
"in",
"the",
"given",
"scope",
"at",
"the",
"top",
"level",
"only",
"."
] | 33d2968a49e1131825a0accdd64bdf9901cf144c | https://github.com/sourcegraph/go-langserver/blob/33d2968a49e1131825a0accdd64bdf9901cf144c/langserver/internal/godef/go/types/types.go#L652-L668 | train |
sourcegraph/go-langserver | langserver/internal/godef/go/types/types.go | Underlying | func (typ Type) Underlying(all bool) Type {
for {
id, _ := typ.Node.(*ast.Ident)
if id == nil || id.Obj == nil {
break
}
_, typNode := splitDecl(id.Obj, id)
_, t := typ.ctxt.exprType(typNode, false, typ.Pkg)
if t.Kind != ast.Typ {
return badType
}
typ.Node = t.Node
typ.Pkg = t.Pkg
if !all {
break
}
}
return typ
} | go | func (typ Type) Underlying(all bool) Type {
for {
id, _ := typ.Node.(*ast.Ident)
if id == nil || id.Obj == nil {
break
}
_, typNode := splitDecl(id.Obj, id)
_, t := typ.ctxt.exprType(typNode, false, typ.Pkg)
if t.Kind != ast.Typ {
return badType
}
typ.Node = t.Node
typ.Pkg = t.Pkg
if !all {
break
}
}
return typ
} | [
"func",
"(",
"typ",
"Type",
")",
"Underlying",
"(",
"all",
"bool",
")",
"Type",
"{",
"for",
"{",
"id",
",",
"_",
":=",
"typ",
".",
"Node",
".",
"(",
"*",
"ast",
".",
"Ident",
")",
"\n",
"if",
"id",
"==",
"nil",
"||",
"id",
".",
"Obj",
"==",
... | // If typ represents a named type, Underlying returns
// the type that it was defined as. If all is true,
// it repeats this process until the type is not
// a named type. | [
"If",
"typ",
"represents",
"a",
"named",
"type",
"Underlying",
"returns",
"the",
"type",
"that",
"it",
"was",
"defined",
"as",
".",
"If",
"all",
"is",
"true",
"it",
"repeats",
"this",
"process",
"until",
"the",
"type",
"is",
"not",
"a",
"named",
"type",
... | 33d2968a49e1131825a0accdd64bdf9901cf144c | https://github.com/sourcegraph/go-langserver/blob/33d2968a49e1131825a0accdd64bdf9901cf144c/langserver/internal/godef/go/types/types.go#L674-L692 | train |
sourcegraph/go-langserver | langserver/internal/godef/go/types/types.go | certify | func (ctxt *exprTypeContext) certify(typ ast.Node, kind ast.ObjKind, pkg string) Type {
_, t := ctxt.exprType(typ, false, pkg)
if t.Kind == ast.Typ {
return ctxt.newType(t.Node, kind, t.Pkg)
}
return badType
} | go | func (ctxt *exprTypeContext) certify(typ ast.Node, kind ast.ObjKind, pkg string) Type {
_, t := ctxt.exprType(typ, false, pkg)
if t.Kind == ast.Typ {
return ctxt.newType(t.Node, kind, t.Pkg)
}
return badType
} | [
"func",
"(",
"ctxt",
"*",
"exprTypeContext",
")",
"certify",
"(",
"typ",
"ast",
".",
"Node",
",",
"kind",
"ast",
".",
"ObjKind",
",",
"pkg",
"string",
")",
"Type",
"{",
"_",
",",
"t",
":=",
"ctxt",
".",
"exprType",
"(",
"typ",
",",
"false",
",",
... | // make sure that the type is really a type expression | [
"make",
"sure",
"that",
"the",
"type",
"is",
"really",
"a",
"type",
"expression"
] | 33d2968a49e1131825a0accdd64bdf9901cf144c | https://github.com/sourcegraph/go-langserver/blob/33d2968a49e1131825a0accdd64bdf9901cf144c/langserver/internal/godef/go/types/types.go#L706-L712 | train |
sourcegraph/go-langserver | langserver/internal/godef/go/types/types.go | exprName | func exprName(typ interface{}) *ast.Object {
switch t := noParens(typ).(type) {
case *ast.Ident:
return t.Obj
case *ast.Object:
return t
}
return nil
} | go | func exprName(typ interface{}) *ast.Object {
switch t := noParens(typ).(type) {
case *ast.Ident:
return t.Obj
case *ast.Object:
return t
}
return nil
} | [
"func",
"exprName",
"(",
"typ",
"interface",
"{",
"}",
")",
"*",
"ast",
".",
"Object",
"{",
"switch",
"t",
":=",
"noParens",
"(",
"typ",
")",
".",
"(",
"type",
")",
"{",
"case",
"*",
"ast",
".",
"Ident",
":",
"return",
"t",
".",
"Obj",
"\n",
"c... | // If n represents a single identifier, exprName returns its object. | [
"If",
"n",
"represents",
"a",
"single",
"identifier",
"exprName",
"returns",
"its",
"object",
"."
] | 33d2968a49e1131825a0accdd64bdf9901cf144c | https://github.com/sourcegraph/go-langserver/blob/33d2968a49e1131825a0accdd64bdf9901cf144c/langserver/internal/godef/go/types/types.go#L715-L723 | train |
sourcegraph/go-langserver | langserver/internal/godef/go/types/types.go | splitDecl | func splitDecl(obj *ast.Object, id *ast.Ident) (expr, typ ast.Node) {
switch decl := obj.Decl.(type) {
case nil:
return nil, nil
case *ast.ValueSpec:
return splitVarDecl(obj.Name, decl.Names, decl.Values, decl.Type)
case *ast.TypeSpec:
return nil, decl.Type
case *ast.FuncDecl:
if decl.Recv != nil {
return decl, decl.Type
}
return decl.Body, decl.Type
case *ast.Field:
return nil, decl.Type
case *ast.LabeledStmt:
return decl, nil
case *ast.ImportSpec:
return nil, decl
case *ast.AssignStmt:
return splitVarDecl(obj.Name, exprsToIdents(decl.Lhs), decl.Rhs, nil)
case *ast.GenDecl:
if decl.Tok == token.CONST {
return splitConstDecl(obj.Name, decl)
}
case *ast.TypeSwitchStmt:
expr := decl.Assign.(*ast.AssignStmt).Rhs[0].(*ast.TypeAssertExpr).X
for _, stmt := range decl.Body.List {
tcase := stmt.(*ast.CaseClause)
for _, stmt := range tcase.Body {
if containsNode(stmt, id) {
if len(tcase.List) == 1 {
return expr, tcase.List[0]
}
return expr, nil
}
}
}
return expr, nil
}
debugp("unknown decl type %T %v", obj.Decl, obj.Decl)
return nil, nil
} | go | func splitDecl(obj *ast.Object, id *ast.Ident) (expr, typ ast.Node) {
switch decl := obj.Decl.(type) {
case nil:
return nil, nil
case *ast.ValueSpec:
return splitVarDecl(obj.Name, decl.Names, decl.Values, decl.Type)
case *ast.TypeSpec:
return nil, decl.Type
case *ast.FuncDecl:
if decl.Recv != nil {
return decl, decl.Type
}
return decl.Body, decl.Type
case *ast.Field:
return nil, decl.Type
case *ast.LabeledStmt:
return decl, nil
case *ast.ImportSpec:
return nil, decl
case *ast.AssignStmt:
return splitVarDecl(obj.Name, exprsToIdents(decl.Lhs), decl.Rhs, nil)
case *ast.GenDecl:
if decl.Tok == token.CONST {
return splitConstDecl(obj.Name, decl)
}
case *ast.TypeSwitchStmt:
expr := decl.Assign.(*ast.AssignStmt).Rhs[0].(*ast.TypeAssertExpr).X
for _, stmt := range decl.Body.List {
tcase := stmt.(*ast.CaseClause)
for _, stmt := range tcase.Body {
if containsNode(stmt, id) {
if len(tcase.List) == 1 {
return expr, tcase.List[0]
}
return expr, nil
}
}
}
return expr, nil
}
debugp("unknown decl type %T %v", obj.Decl, obj.Decl)
return nil, nil
} | [
"func",
"splitDecl",
"(",
"obj",
"*",
"ast",
".",
"Object",
",",
"id",
"*",
"ast",
".",
"Ident",
")",
"(",
"expr",
",",
"typ",
"ast",
".",
"Node",
")",
"{",
"switch",
"decl",
":=",
"obj",
".",
"Decl",
".",
"(",
"type",
")",
"{",
"case",
"nil",
... | // splitDecl splits obj.Decl and returns the expression part and the type part.
// Either may be nil, but not both if the declaration is value.
//
// If id is non-nil, it gives the referring identifier. This is only used
// to determine which node in a type switch is being referred to.
// | [
"splitDecl",
"splits",
"obj",
".",
"Decl",
"and",
"returns",
"the",
"expression",
"part",
"and",
"the",
"type",
"part",
".",
"Either",
"may",
"be",
"nil",
"but",
"not",
"both",
"if",
"the",
"declaration",
"is",
"value",
".",
"If",
"id",
"is",
"non",
"-... | 33d2968a49e1131825a0accdd64bdf9901cf144c | https://github.com/sourcegraph/go-langserver/blob/33d2968a49e1131825a0accdd64bdf9901cf144c/langserver/internal/godef/go/types/types.go#L746-L795 | train |
sourcegraph/go-langserver | langserver/internal/godef/go/types/types.go | splitConstDecl | func splitConstDecl(name string, decl *ast.GenDecl) (expr, typ ast.Node) {
var lastSpec *ast.ValueSpec // last spec with >0 values.
for _, spec := range decl.Specs {
vspec := spec.(*ast.ValueSpec)
if len(vspec.Values) > 0 {
lastSpec = vspec
}
for i, vname := range vspec.Names {
if vname.Name == name {
if i < len(lastSpec.Values) {
return lastSpec.Values[i], lastSpec.Type
}
return nil, lastSpec.Type
}
}
}
return nil, nil
} | go | func splitConstDecl(name string, decl *ast.GenDecl) (expr, typ ast.Node) {
var lastSpec *ast.ValueSpec // last spec with >0 values.
for _, spec := range decl.Specs {
vspec := spec.(*ast.ValueSpec)
if len(vspec.Values) > 0 {
lastSpec = vspec
}
for i, vname := range vspec.Names {
if vname.Name == name {
if i < len(lastSpec.Values) {
return lastSpec.Values[i], lastSpec.Type
}
return nil, lastSpec.Type
}
}
}
return nil, nil
} | [
"func",
"splitConstDecl",
"(",
"name",
"string",
",",
"decl",
"*",
"ast",
".",
"GenDecl",
")",
"(",
"expr",
",",
"typ",
"ast",
".",
"Node",
")",
"{",
"var",
"lastSpec",
"*",
"ast",
".",
"ValueSpec",
"\n",
"for",
"_",
",",
"spec",
":=",
"range",
"de... | // Constant declarations can omit the type, so the declaration for
// a const may be the entire GenDecl - we find the relevant
// clause and infer the type and expression. | [
"Constant",
"declarations",
"can",
"omit",
"the",
"type",
"so",
"the",
"declaration",
"for",
"a",
"const",
"may",
"be",
"the",
"entire",
"GenDecl",
"-",
"we",
"find",
"the",
"relevant",
"clause",
"and",
"infer",
"the",
"type",
"and",
"expression",
"."
] | 33d2968a49e1131825a0accdd64bdf9901cf144c | https://github.com/sourcegraph/go-langserver/blob/33d2968a49e1131825a0accdd64bdf9901cf144c/langserver/internal/godef/go/types/types.go#L830-L847 | train |
sourcegraph/go-langserver | langserver/internal/godef/go/types/types.go | containsNode | func containsNode(node, x ast.Node) (found bool) {
ast.Walk(funcVisitor(func(n ast.Node) bool {
if !found {
found = n == x
}
return !found
}),
node)
return
} | go | func containsNode(node, x ast.Node) (found bool) {
ast.Walk(funcVisitor(func(n ast.Node) bool {
if !found {
found = n == x
}
return !found
}),
node)
return
} | [
"func",
"containsNode",
"(",
"node",
",",
"x",
"ast",
".",
"Node",
")",
"(",
"found",
"bool",
")",
"{",
"ast",
".",
"Walk",
"(",
"funcVisitor",
"(",
"func",
"(",
"n",
"ast",
".",
"Node",
")",
"bool",
"{",
"if",
"!",
"found",
"{",
"found",
"=",
... | // constainsNode returns true if x is found somewhere
// inside node. | [
"constainsNode",
"returns",
"true",
"if",
"x",
"is",
"found",
"somewhere",
"inside",
"node",
"."
] | 33d2968a49e1131825a0accdd64bdf9901cf144c | https://github.com/sourcegraph/go-langserver/blob/33d2968a49e1131825a0accdd64bdf9901cf144c/langserver/internal/godef/go/types/types.go#L862-L871 | train |
sourcegraph/go-langserver | langserver/lint.go | lint | func (h *LangHandler) lint(ctx context.Context, bctx *build.Context, conn jsonrpc2.JSONRPC2, args []string, files []string) error {
if h.linter == nil {
return nil
}
diags, err := h.linter.Lint(ctx, bctx, args...)
if err != nil {
return err
}
return h.publishDiagnostics(ctx, conn, diags, h.config.LintTool, files)
} | go | func (h *LangHandler) lint(ctx context.Context, bctx *build.Context, conn jsonrpc2.JSONRPC2, args []string, files []string) error {
if h.linter == nil {
return nil
}
diags, err := h.linter.Lint(ctx, bctx, args...)
if err != nil {
return err
}
return h.publishDiagnostics(ctx, conn, diags, h.config.LintTool, files)
} | [
"func",
"(",
"h",
"*",
"LangHandler",
")",
"lint",
"(",
"ctx",
"context",
".",
"Context",
",",
"bctx",
"*",
"build",
".",
"Context",
",",
"conn",
"jsonrpc2",
".",
"JSONRPC2",
",",
"args",
"[",
"]",
"string",
",",
"files",
"[",
"]",
"string",
")",
"... | // lint runs the configured lint command with the given arguments then published the
// results as diagnostics. | [
"lint",
"runs",
"the",
"configured",
"lint",
"command",
"with",
"the",
"given",
"arguments",
"then",
"published",
"the",
"results",
"as",
"diagnostics",
"."
] | 33d2968a49e1131825a0accdd64bdf9901cf144c | https://github.com/sourcegraph/go-langserver/blob/33d2968a49e1131825a0accdd64bdf9901cf144c/langserver/lint.go#L34-L45 | train |
sourcegraph/go-langserver | langserver/lint.go | lintPackage | func (h *LangHandler) lintPackage(ctx context.Context, bctx *build.Context, conn jsonrpc2.JSONRPC2, uri lsp.DocumentURI) error {
filename := h.FilePath(uri)
pkg, err := ContainingPackage(h.BuildContext(ctx), filename, h.RootFSPath)
if err != nil {
return err
}
files := make([]string, 0, len(pkg.GoFiles))
for _, f := range pkg.GoFiles {
files = append(files, path.Join(pkg.Dir, f))
}
return h.lint(ctx, bctx, conn, []string{path.Dir(filename)}, files)
} | go | func (h *LangHandler) lintPackage(ctx context.Context, bctx *build.Context, conn jsonrpc2.JSONRPC2, uri lsp.DocumentURI) error {
filename := h.FilePath(uri)
pkg, err := ContainingPackage(h.BuildContext(ctx), filename, h.RootFSPath)
if err != nil {
return err
}
files := make([]string, 0, len(pkg.GoFiles))
for _, f := range pkg.GoFiles {
files = append(files, path.Join(pkg.Dir, f))
}
return h.lint(ctx, bctx, conn, []string{path.Dir(filename)}, files)
} | [
"func",
"(",
"h",
"*",
"LangHandler",
")",
"lintPackage",
"(",
"ctx",
"context",
".",
"Context",
",",
"bctx",
"*",
"build",
".",
"Context",
",",
"conn",
"jsonrpc2",
".",
"JSONRPC2",
",",
"uri",
"lsp",
".",
"DocumentURI",
")",
"error",
"{",
"filename",
... | // lintPackage runs LangHandler.lint for the package containing the uri. | [
"lintPackage",
"runs",
"LangHandler",
".",
"lint",
"for",
"the",
"package",
"containing",
"the",
"uri",
"."
] | 33d2968a49e1131825a0accdd64bdf9901cf144c | https://github.com/sourcegraph/go-langserver/blob/33d2968a49e1131825a0accdd64bdf9901cf144c/langserver/lint.go#L48-L60 | train |
sourcegraph/go-langserver | langserver/lint.go | lintWorkspace | func (h *LangHandler) lintWorkspace(ctx context.Context, bctx *build.Context, conn jsonrpc2.JSONRPC2) error {
var files []string
pkgs := tools.ListPkgsUnderDir(bctx, h.RootFSPath)
find := h.getFindPackageFunc()
for _, pkg := range pkgs {
p, err := find(ctx, bctx, pkg, h.RootFSPath, h.RootFSPath, 0)
if err != nil {
if _, ok := err.(*build.NoGoError); ok {
continue
}
if _, ok := err.(*build.MultiplePackageError); ok {
continue
}
return err
}
for _, f := range p.GoFiles {
files = append(files, path.Join(p.Dir, f))
}
}
return h.lint(ctx, bctx, conn, []string{path.Join(h.RootFSPath, "/...")}, files)
} | go | func (h *LangHandler) lintWorkspace(ctx context.Context, bctx *build.Context, conn jsonrpc2.JSONRPC2) error {
var files []string
pkgs := tools.ListPkgsUnderDir(bctx, h.RootFSPath)
find := h.getFindPackageFunc()
for _, pkg := range pkgs {
p, err := find(ctx, bctx, pkg, h.RootFSPath, h.RootFSPath, 0)
if err != nil {
if _, ok := err.(*build.NoGoError); ok {
continue
}
if _, ok := err.(*build.MultiplePackageError); ok {
continue
}
return err
}
for _, f := range p.GoFiles {
files = append(files, path.Join(p.Dir, f))
}
}
return h.lint(ctx, bctx, conn, []string{path.Join(h.RootFSPath, "/...")}, files)
} | [
"func",
"(",
"h",
"*",
"LangHandler",
")",
"lintWorkspace",
"(",
"ctx",
"context",
".",
"Context",
",",
"bctx",
"*",
"build",
".",
"Context",
",",
"conn",
"jsonrpc2",
".",
"JSONRPC2",
")",
"error",
"{",
"var",
"files",
"[",
"]",
"string",
"\n",
"pkgs",... | // lintWorkspace runs LangHandler.lint for the entire workspace | [
"lintWorkspace",
"runs",
"LangHandler",
".",
"lint",
"for",
"the",
"entire",
"workspace"
] | 33d2968a49e1131825a0accdd64bdf9901cf144c | https://github.com/sourcegraph/go-langserver/blob/33d2968a49e1131825a0accdd64bdf9901cf144c/langserver/lint.go#L63-L84 | train |
sourcegraph/go-langserver | langserver/diagnostics.go | sync | func (p *diagnosticsCache) sync(update func(diagnostics) diagnostics, compare func(oldDiagnostics, newDiagnostics diagnostics) (publish diagnostics)) (publish diagnostics) {
p.mu.Lock()
defer p.mu.Unlock()
if p.cache == nil {
p.cache = diagnostics{}
}
newCache := update(p.cache)
publish = compare(p.cache, newCache)
p.cache = newCache
return publish
} | go | func (p *diagnosticsCache) sync(update func(diagnostics) diagnostics, compare func(oldDiagnostics, newDiagnostics diagnostics) (publish diagnostics)) (publish diagnostics) {
p.mu.Lock()
defer p.mu.Unlock()
if p.cache == nil {
p.cache = diagnostics{}
}
newCache := update(p.cache)
publish = compare(p.cache, newCache)
p.cache = newCache
return publish
} | [
"func",
"(",
"p",
"*",
"diagnosticsCache",
")",
"sync",
"(",
"update",
"func",
"(",
"diagnostics",
")",
"diagnostics",
",",
"compare",
"func",
"(",
"oldDiagnostics",
",",
"newDiagnostics",
"diagnostics",
")",
"(",
"publish",
"diagnostics",
")",
")",
"(",
"pu... | // sync updates the diagnosticsCache and returns diagnostics need to be
// published.
//
// When a file no longer has any diagnostics the file will be removed from
// the cache. The removed file will be included in the returned diagnostics
// in order to clear the client.
//
// sync is thread safe and will only allow one go routine to modify the cache
// at a time. | [
"sync",
"updates",
"the",
"diagnosticsCache",
"and",
"returns",
"diagnostics",
"need",
"to",
"be",
"published",
".",
"When",
"a",
"file",
"no",
"longer",
"has",
"any",
"diagnostics",
"the",
"file",
"will",
"be",
"removed",
"from",
"the",
"cache",
".",
"The",... | 33d2968a49e1131825a0accdd64bdf9901cf144c | https://github.com/sourcegraph/go-langserver/blob/33d2968a49e1131825a0accdd64bdf9901cf144c/langserver/diagnostics.go#L42-L54 | train |
sourcegraph/go-langserver | langserver/diagnostics.go | compareCachedDiagnostics | func compareCachedDiagnostics(oldDiagnostics, newDiagnostics diagnostics, files []string) (publish diagnostics) {
publish = diagnostics{}
for _, f := range files {
_, inOld := oldDiagnostics[f]
diags, inNew := newDiagnostics[f]
if inOld && !inNew {
publish[f] = nil
continue
}
if inNew {
publish[f] = diags
}
}
return publish
} | go | func compareCachedDiagnostics(oldDiagnostics, newDiagnostics diagnostics, files []string) (publish diagnostics) {
publish = diagnostics{}
for _, f := range files {
_, inOld := oldDiagnostics[f]
diags, inNew := newDiagnostics[f]
if inOld && !inNew {
publish[f] = nil
continue
}
if inNew {
publish[f] = diags
}
}
return publish
} | [
"func",
"compareCachedDiagnostics",
"(",
"oldDiagnostics",
",",
"newDiagnostics",
"diagnostics",
",",
"files",
"[",
"]",
"string",
")",
"(",
"publish",
"diagnostics",
")",
"{",
"publish",
"=",
"diagnostics",
"{",
"}",
"\n",
"for",
"_",
",",
"f",
":=",
"range... | // compareCachedDiagnostics compares new and old diagnostics to determine
// what needs to be published. | [
"compareCachedDiagnostics",
"compares",
"new",
"and",
"old",
"diagnostics",
"to",
"determine",
"what",
"needs",
"to",
"be",
"published",
"."
] | 33d2968a49e1131825a0accdd64bdf9901cf144c | https://github.com/sourcegraph/go-langserver/blob/33d2968a49e1131825a0accdd64bdf9901cf144c/langserver/diagnostics.go#L121-L138 | train |
sourcegraph/go-langserver | gituri/uri.go | Parse | func Parse(uriStr string) (*URI, error) {
u, err := url.Parse(uriStr)
if err != nil {
return nil, err
}
if !u.IsAbs() {
return nil, &url.Error{Op: "gituri.Parse", URL: uriStr, Err: errors.New("sourcegraph URI must be absolute")}
}
return &URI{*u}, nil
} | go | func Parse(uriStr string) (*URI, error) {
u, err := url.Parse(uriStr)
if err != nil {
return nil, err
}
if !u.IsAbs() {
return nil, &url.Error{Op: "gituri.Parse", URL: uriStr, Err: errors.New("sourcegraph URI must be absolute")}
}
return &URI{*u}, nil
} | [
"func",
"Parse",
"(",
"uriStr",
"string",
")",
"(",
"*",
"URI",
",",
"error",
")",
"{",
"u",
",",
"err",
":=",
"url",
".",
"Parse",
"(",
"uriStr",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"if",
"... | // Parse parses uriStr to a URI. The uriStr should be an absolute URL. | [
"Parse",
"parses",
"uriStr",
"to",
"a",
"URI",
".",
"The",
"uriStr",
"should",
"be",
"an",
"absolute",
"URL",
"."
] | 33d2968a49e1131825a0accdd64bdf9901cf144c | https://github.com/sourcegraph/go-langserver/blob/33d2968a49e1131825a0accdd64bdf9901cf144c/gituri/uri.go#L35-L44 | train |
sourcegraph/go-langserver | gituri/uri.go | CloneURL | func (u *URI) CloneURL() *url.URL {
return &url.URL{
Scheme: u.Scheme,
Host: u.Host,
Path: u.Path,
}
} | go | func (u *URI) CloneURL() *url.URL {
return &url.URL{
Scheme: u.Scheme,
Host: u.Host,
Path: u.Path,
}
} | [
"func",
"(",
"u",
"*",
"URI",
")",
"CloneURL",
"(",
")",
"*",
"url",
".",
"URL",
"{",
"return",
"&",
"url",
".",
"URL",
"{",
"Scheme",
":",
"u",
".",
"Scheme",
",",
"Host",
":",
"u",
".",
"Host",
",",
"Path",
":",
"u",
".",
"Path",
",",
"}"... | // CloneURL returns the repository clone URL component of the URI. | [
"CloneURL",
"returns",
"the",
"repository",
"clone",
"URL",
"component",
"of",
"the",
"URI",
"."
] | 33d2968a49e1131825a0accdd64bdf9901cf144c | https://github.com/sourcegraph/go-langserver/blob/33d2968a49e1131825a0accdd64bdf9901cf144c/gituri/uri.go#L47-L53 | train |
sourcegraph/go-langserver | langserver/format.go | ComputeTextEdits | func ComputeTextEdits(unformatted string, formatted string) []lsp.TextEdit {
// LSP wants a list of TextEdits. We use difflib to compute a
// non-naive TextEdit. Originally we returned an edit which deleted
// everything followed by inserting everything. This leads to a poor
// experience in vscode.
unformattedLines := strings.Split(unformatted, "\n")
formattedLines := strings.Split(formatted, "\n")
m := difflib.NewMatcher(unformattedLines, formattedLines)
var edits []lsp.TextEdit
for _, op := range m.GetOpCodes() {
switch op.Tag {
case 'r': // 'r' (replace): a[i1:i2] should be replaced by b[j1:j2]
edits = append(edits, lsp.TextEdit{
Range: lsp.Range{
Start: lsp.Position{
Line: op.I1,
},
End: lsp.Position{
Line: op.I2,
},
},
NewText: strings.Join(formattedLines[op.J1:op.J2], "\n") + "\n",
})
case 'd': // 'd' (delete): a[i1:i2] should be deleted, j1==j2 in this case.
edits = append(edits, lsp.TextEdit{
Range: lsp.Range{
Start: lsp.Position{
Line: op.I1,
},
End: lsp.Position{
Line: op.I2,
},
},
})
case 'i': // 'i' (insert): b[j1:j2] should be inserted at a[i1:i1], i1==i2 in this case.
edits = append(edits, lsp.TextEdit{
Range: lsp.Range{
Start: lsp.Position{
Line: op.I1,
},
End: lsp.Position{
Line: op.I1,
},
},
NewText: strings.Join(formattedLines[op.J1:op.J2], "\n") + "\n",
})
}
}
return edits
} | go | func ComputeTextEdits(unformatted string, formatted string) []lsp.TextEdit {
// LSP wants a list of TextEdits. We use difflib to compute a
// non-naive TextEdit. Originally we returned an edit which deleted
// everything followed by inserting everything. This leads to a poor
// experience in vscode.
unformattedLines := strings.Split(unformatted, "\n")
formattedLines := strings.Split(formatted, "\n")
m := difflib.NewMatcher(unformattedLines, formattedLines)
var edits []lsp.TextEdit
for _, op := range m.GetOpCodes() {
switch op.Tag {
case 'r': // 'r' (replace): a[i1:i2] should be replaced by b[j1:j2]
edits = append(edits, lsp.TextEdit{
Range: lsp.Range{
Start: lsp.Position{
Line: op.I1,
},
End: lsp.Position{
Line: op.I2,
},
},
NewText: strings.Join(formattedLines[op.J1:op.J2], "\n") + "\n",
})
case 'd': // 'd' (delete): a[i1:i2] should be deleted, j1==j2 in this case.
edits = append(edits, lsp.TextEdit{
Range: lsp.Range{
Start: lsp.Position{
Line: op.I1,
},
End: lsp.Position{
Line: op.I2,
},
},
})
case 'i': // 'i' (insert): b[j1:j2] should be inserted at a[i1:i1], i1==i2 in this case.
edits = append(edits, lsp.TextEdit{
Range: lsp.Range{
Start: lsp.Position{
Line: op.I1,
},
End: lsp.Position{
Line: op.I1,
},
},
NewText: strings.Join(formattedLines[op.J1:op.J2], "\n") + "\n",
})
}
}
return edits
} | [
"func",
"ComputeTextEdits",
"(",
"unformatted",
"string",
",",
"formatted",
"string",
")",
"[",
"]",
"lsp",
".",
"TextEdit",
"{",
"unformattedLines",
":=",
"strings",
".",
"Split",
"(",
"unformatted",
",",
"\"\\n\"",
")",
"\n",
"\\n",
"\n",
"formattedLines",
... | // ComputeTextEdits computes text edits that are required to
// change the `unformatted` to the `formatted` text. | [
"ComputeTextEdits",
"computes",
"text",
"edits",
"that",
"are",
"required",
"to",
"change",
"the",
"unformatted",
"to",
"the",
"formatted",
"text",
"."
] | 33d2968a49e1131825a0accdd64bdf9901cf144c | https://github.com/sourcegraph/go-langserver/blob/33d2968a49e1131825a0accdd64bdf9901cf144c/langserver/format.go#L79-L129 | train |
sourcegraph/go-langserver | langserver/signature.go | callExpr | func callExpr(fset *token.FileSet, nodes []ast.Node) *ast.CallExpr {
for _, node := range nodes {
callExpr, ok := node.(*ast.CallExpr)
if ok {
return callExpr
}
}
return nil
} | go | func callExpr(fset *token.FileSet, nodes []ast.Node) *ast.CallExpr {
for _, node := range nodes {
callExpr, ok := node.(*ast.CallExpr)
if ok {
return callExpr
}
}
return nil
} | [
"func",
"callExpr",
"(",
"fset",
"*",
"token",
".",
"FileSet",
",",
"nodes",
"[",
"]",
"ast",
".",
"Node",
")",
"*",
"ast",
".",
"CallExpr",
"{",
"for",
"_",
",",
"node",
":=",
"range",
"nodes",
"{",
"callExpr",
",",
"ok",
":=",
"node",
".",
"(",... | // callExpr climbs AST tree up until call expression | [
"callExpr",
"climbs",
"AST",
"tree",
"up",
"until",
"call",
"expression"
] | 33d2968a49e1131825a0accdd64bdf9901cf144c | https://github.com/sourcegraph/go-langserver/blob/33d2968a49e1131825a0accdd64bdf9901cf144c/langserver/signature.go#L77-L85 | train |
sourcegraph/go-langserver | langserver/signature.go | shortType | func shortType(t types.Type) string {
return types.TypeString(t, func(*types.Package) string {
return ""
})
} | go | func shortType(t types.Type) string {
return types.TypeString(t, func(*types.Package) string {
return ""
})
} | [
"func",
"shortType",
"(",
"t",
"types",
".",
"Type",
")",
"string",
"{",
"return",
"types",
".",
"TypeString",
"(",
"t",
",",
"func",
"(",
"*",
"types",
".",
"Package",
")",
"string",
"{",
"return",
"\"\"",
"\n",
"}",
")",
"\n",
"}"
] | // shortTyoe returns shorthand type notation without specifying type's import path | [
"shortTyoe",
"returns",
"shorthand",
"type",
"notation",
"without",
"specifying",
"type",
"s",
"import",
"path"
] | 33d2968a49e1131825a0accdd64bdf9901cf144c | https://github.com/sourcegraph/go-langserver/blob/33d2968a49e1131825a0accdd64bdf9901cf144c/langserver/signature.go#L88-L92 | train |
sourcegraph/go-langserver | langserver/signature.go | shortParam | func shortParam(param *types.Var) string {
ret := param.Name()
if ret != "" {
ret += " "
}
return ret + shortType(param.Type())
} | go | func shortParam(param *types.Var) string {
ret := param.Name()
if ret != "" {
ret += " "
}
return ret + shortType(param.Type())
} | [
"func",
"shortParam",
"(",
"param",
"*",
"types",
".",
"Var",
")",
"string",
"{",
"ret",
":=",
"param",
".",
"Name",
"(",
")",
"\n",
"if",
"ret",
"!=",
"\"\"",
"{",
"ret",
"+=",
"\" \"",
"\n",
"}",
"\n",
"return",
"ret",
"+",
"shortType",
"(",
"p... | // shortParam returns shorthand parameter notation in form "name type" without specifying type's import path | [
"shortParam",
"returns",
"shorthand",
"parameter",
"notation",
"in",
"form",
"name",
"type",
"without",
"specifying",
"type",
"s",
"import",
"path"
] | 33d2968a49e1131825a0accdd64bdf9901cf144c | https://github.com/sourcegraph/go-langserver/blob/33d2968a49e1131825a0accdd64bdf9901cf144c/langserver/signature.go#L95-L101 | train |
sourcegraph/go-langserver | langserver/ast.go | goRangeToLSPLocation | func goRangeToLSPLocation(fset *token.FileSet, pos token.Pos, end token.Pos) lsp.Location {
return lsp.Location{
URI: util.PathToURI(fset.Position(pos).Filename),
Range: rangeForNode(fset, fakeNode{p: pos, e: end}),
}
} | go | func goRangeToLSPLocation(fset *token.FileSet, pos token.Pos, end token.Pos) lsp.Location {
return lsp.Location{
URI: util.PathToURI(fset.Position(pos).Filename),
Range: rangeForNode(fset, fakeNode{p: pos, e: end}),
}
} | [
"func",
"goRangeToLSPLocation",
"(",
"fset",
"*",
"token",
".",
"FileSet",
",",
"pos",
"token",
".",
"Pos",
",",
"end",
"token",
".",
"Pos",
")",
"lsp",
".",
"Location",
"{",
"return",
"lsp",
".",
"Location",
"{",
"URI",
":",
"util",
".",
"PathToURI",
... | // goRangeToLSPLocation converts a token.Pos range into a lsp.Location. end is
// exclusive. | [
"goRangeToLSPLocation",
"converts",
"a",
"token",
".",
"Pos",
"range",
"into",
"a",
"lsp",
".",
"Location",
".",
"end",
"is",
"exclusive",
"."
] | 33d2968a49e1131825a0accdd64bdf9901cf144c | https://github.com/sourcegraph/go-langserver/blob/33d2968a49e1131825a0accdd64bdf9901cf144c/langserver/ast.go#L69-L75 | train |
sourcegraph/go-langserver | langserver/lsp.go | Contains | func (a *symbolDescriptor) Contains(b lspext.SymbolDescriptor) bool {
for k, v := range b {
switch k {
case "package":
if s, ok := v.(string); !ok || s != a.Package {
return false
}
case "packageName":
if s, ok := v.(string); !ok || s != a.PackageName {
return false
}
case "recv":
if s, ok := v.(string); !ok || s != a.Recv {
return false
}
case "name":
if s, ok := v.(string); !ok || s != a.Name {
return false
}
case "id":
if s, ok := v.(string); !ok || s != a.ID {
return false
}
case "vendor":
if s, ok := v.(bool); !ok || s != a.Vendor {
return false
}
default:
return false
}
}
return true
} | go | func (a *symbolDescriptor) Contains(b lspext.SymbolDescriptor) bool {
for k, v := range b {
switch k {
case "package":
if s, ok := v.(string); !ok || s != a.Package {
return false
}
case "packageName":
if s, ok := v.(string); !ok || s != a.PackageName {
return false
}
case "recv":
if s, ok := v.(string); !ok || s != a.Recv {
return false
}
case "name":
if s, ok := v.(string); !ok || s != a.Name {
return false
}
case "id":
if s, ok := v.(string); !ok || s != a.ID {
return false
}
case "vendor":
if s, ok := v.(bool); !ok || s != a.Vendor {
return false
}
default:
return false
}
}
return true
} | [
"func",
"(",
"a",
"*",
"symbolDescriptor",
")",
"Contains",
"(",
"b",
"lspext",
".",
"SymbolDescriptor",
")",
"bool",
"{",
"for",
"k",
",",
"v",
":=",
"range",
"b",
"{",
"switch",
"k",
"{",
"case",
"\"package\"",
":",
"if",
"s",
",",
"ok",
":=",
"v... | // Contains ensures that b is a subset of our symbolDescriptor | [
"Contains",
"ensures",
"that",
"b",
"is",
"a",
"subset",
"of",
"our",
"symbolDescriptor"
] | 33d2968a49e1131825a0accdd64bdf9901cf144c | https://github.com/sourcegraph/go-langserver/blob/33d2968a49e1131825a0accdd64bdf9901cf144c/langserver/lsp.go#L24-L56 | train |
sourcegraph/go-langserver | langserver/references.go | reverseImportGraph | func (h *LangHandler) reverseImportGraph(ctx context.Context, conn jsonrpc2.JSONRPC2) <-chan importgraph.Graph {
// Ensure our buffer is big enough to prevent deadlock
c := make(chan importgraph.Graph, 2)
go func() {
// This should always be related to the go import path for
// this repo. For sourcegraph.com this means we share the
// import graph across commits. We want this behaviour since
// we assume that they don't change drastically across
// commits.
cacheKey := "importgraph:" + string(h.init.Root())
h.mu.Lock()
tryCache := h.importGraph == nil
once := h.importGraphOnce
h.mu.Unlock()
if tryCache {
g := make(importgraph.Graph)
if hit := h.cacheGet(ctx, conn, cacheKey, g); hit {
// \o/
c <- g
}
}
parentCtx := ctx
once.Do(func() {
// Note: We use a background context since this
// operation should not be cancelled due to an
// individual request.
span := startSpanFollowsFromContext(parentCtx, "BuildReverseImportGraph")
ctx := opentracing.ContextWithSpan(context.Background(), span)
defer span.Finish()
bctx := h.BuildContext(ctx)
findPackageWithCtx := h.getFindPackageFunc()
findPackage := func(bctx *build.Context, importPath, fromDir string, mode build.ImportMode) (*build.Package, error) {
return findPackageWithCtx(ctx, bctx, importPath, fromDir, h.RootFSPath, mode)
}
g := tools.BuildReverseImportGraph(bctx, findPackage, h.FilePath(h.init.Root()))
h.mu.Lock()
h.importGraph = g
h.mu.Unlock()
// Update cache in background
go h.cacheSet(ctx, conn, cacheKey, g)
})
h.mu.Lock()
// TODO(keegancsmith) h.importGraph may have been reset after once
importGraph := h.importGraph
h.mu.Unlock()
c <- importGraph
close(c)
}()
return c
} | go | func (h *LangHandler) reverseImportGraph(ctx context.Context, conn jsonrpc2.JSONRPC2) <-chan importgraph.Graph {
// Ensure our buffer is big enough to prevent deadlock
c := make(chan importgraph.Graph, 2)
go func() {
// This should always be related to the go import path for
// this repo. For sourcegraph.com this means we share the
// import graph across commits. We want this behaviour since
// we assume that they don't change drastically across
// commits.
cacheKey := "importgraph:" + string(h.init.Root())
h.mu.Lock()
tryCache := h.importGraph == nil
once := h.importGraphOnce
h.mu.Unlock()
if tryCache {
g := make(importgraph.Graph)
if hit := h.cacheGet(ctx, conn, cacheKey, g); hit {
// \o/
c <- g
}
}
parentCtx := ctx
once.Do(func() {
// Note: We use a background context since this
// operation should not be cancelled due to an
// individual request.
span := startSpanFollowsFromContext(parentCtx, "BuildReverseImportGraph")
ctx := opentracing.ContextWithSpan(context.Background(), span)
defer span.Finish()
bctx := h.BuildContext(ctx)
findPackageWithCtx := h.getFindPackageFunc()
findPackage := func(bctx *build.Context, importPath, fromDir string, mode build.ImportMode) (*build.Package, error) {
return findPackageWithCtx(ctx, bctx, importPath, fromDir, h.RootFSPath, mode)
}
g := tools.BuildReverseImportGraph(bctx, findPackage, h.FilePath(h.init.Root()))
h.mu.Lock()
h.importGraph = g
h.mu.Unlock()
// Update cache in background
go h.cacheSet(ctx, conn, cacheKey, g)
})
h.mu.Lock()
// TODO(keegancsmith) h.importGraph may have been reset after once
importGraph := h.importGraph
h.mu.Unlock()
c <- importGraph
close(c)
}()
return c
} | [
"func",
"(",
"h",
"*",
"LangHandler",
")",
"reverseImportGraph",
"(",
"ctx",
"context",
".",
"Context",
",",
"conn",
"jsonrpc2",
".",
"JSONRPC2",
")",
"<-",
"chan",
"importgraph",
".",
"Graph",
"{",
"c",
":=",
"make",
"(",
"chan",
"importgraph",
".",
"Gr... | // reverseImportGraph returns the reversed import graph for the workspace
// under the RootPath. Computing the reverse import graph is IO intensive, as
// such we may send down more than one import graph. The later a graph is
// sent, the more accurate it is. The channel will be closed, and the last
// graph sent is accurate. The reader does not have to read all the values. | [
"reverseImportGraph",
"returns",
"the",
"reversed",
"import",
"graph",
"for",
"the",
"workspace",
"under",
"the",
"RootPath",
".",
"Computing",
"the",
"reverse",
"import",
"graph",
"is",
"IO",
"intensive",
"as",
"such",
"we",
"may",
"send",
"down",
"more",
"th... | 33d2968a49e1131825a0accdd64bdf9901cf144c | https://github.com/sourcegraph/go-langserver/blob/33d2968a49e1131825a0accdd64bdf9901cf144c/langserver/references.go#L215-L271 | train |
sourcegraph/go-langserver | langserver/references.go | refStreamAndCollect | func refStreamAndCollect(ctx context.Context, conn jsonrpc2.JSONRPC2, req *jsonrpc2.Request, fset *token.FileSet, refs <-chan *ast.Ident, limit int, stop func()) []lsp.Location {
if limit == 0 {
// If we don't have a limit, just set it to a value we should never exceed
limit = math.MaxInt32
}
id := lsp.ID{
Num: req.ID.Num,
Str: req.ID.Str,
IsString: req.ID.IsString,
}
initial := json.RawMessage(`[{"op":"replace","path":"","value":[]}]`)
_ = conn.Notify(ctx, "$/partialResult", &lspext.PartialResultParams{
ID: id,
Patch: &initial,
})
var (
locs []lsp.Location
pos int
)
send := func() {
if pos >= len(locs) {
return
}
patch := make([]referenceAddOp, 0, len(locs)-pos)
for _, l := range locs[pos:] {
patch = append(patch, referenceAddOp{
OP: "add",
Path: "/-",
Value: l,
})
}
pos = len(locs)
_ = conn.Notify(ctx, "$/partialResult", &lspext.PartialResultParams{
ID: id,
// We use referencePatch so the build server can rewrite URIs
Patch: referencePatch(patch),
})
}
tick := time.NewTicker(100 * time.Millisecond)
defer tick.Stop()
for {
select {
case n, ok := <-refs:
if !ok {
// send a final update
send()
return locs
}
if len(locs) >= limit {
stop()
continue
}
locs = append(locs, goRangeToLSPLocation(fset, n.Pos(), n.End()))
case <-tick.C:
send()
}
}
} | go | func refStreamAndCollect(ctx context.Context, conn jsonrpc2.JSONRPC2, req *jsonrpc2.Request, fset *token.FileSet, refs <-chan *ast.Ident, limit int, stop func()) []lsp.Location {
if limit == 0 {
// If we don't have a limit, just set it to a value we should never exceed
limit = math.MaxInt32
}
id := lsp.ID{
Num: req.ID.Num,
Str: req.ID.Str,
IsString: req.ID.IsString,
}
initial := json.RawMessage(`[{"op":"replace","path":"","value":[]}]`)
_ = conn.Notify(ctx, "$/partialResult", &lspext.PartialResultParams{
ID: id,
Patch: &initial,
})
var (
locs []lsp.Location
pos int
)
send := func() {
if pos >= len(locs) {
return
}
patch := make([]referenceAddOp, 0, len(locs)-pos)
for _, l := range locs[pos:] {
patch = append(patch, referenceAddOp{
OP: "add",
Path: "/-",
Value: l,
})
}
pos = len(locs)
_ = conn.Notify(ctx, "$/partialResult", &lspext.PartialResultParams{
ID: id,
// We use referencePatch so the build server can rewrite URIs
Patch: referencePatch(patch),
})
}
tick := time.NewTicker(100 * time.Millisecond)
defer tick.Stop()
for {
select {
case n, ok := <-refs:
if !ok {
// send a final update
send()
return locs
}
if len(locs) >= limit {
stop()
continue
}
locs = append(locs, goRangeToLSPLocation(fset, n.Pos(), n.End()))
case <-tick.C:
send()
}
}
} | [
"func",
"refStreamAndCollect",
"(",
"ctx",
"context",
".",
"Context",
",",
"conn",
"jsonrpc2",
".",
"JSONRPC2",
",",
"req",
"*",
"jsonrpc2",
".",
"Request",
",",
"fset",
"*",
"token",
".",
"FileSet",
",",
"refs",
"<-",
"chan",
"*",
"ast",
".",
"Ident",
... | // refStreamAndCollect returns all refs read in from chan until it is
// closed. While it is reading, it will also occasionally stream out updates of
// the refs received so far. | [
"refStreamAndCollect",
"returns",
"all",
"refs",
"read",
"in",
"from",
"chan",
"until",
"it",
"is",
"closed",
".",
"While",
"it",
"is",
"reading",
"it",
"will",
"also",
"occasionally",
"stream",
"out",
"updates",
"of",
"the",
"refs",
"received",
"so",
"far",... | 33d2968a49e1131825a0accdd64bdf9901cf144c | https://github.com/sourcegraph/go-langserver/blob/33d2968a49e1131825a0accdd64bdf9901cf144c/langserver/references.go#L276-L337 | train |
sourcegraph/go-langserver | langserver/references.go | classify | func classify(obj types.Object) (global, pkglevel bool) {
if obj.Exported() {
if obj.Parent() == nil {
// selectable object (field or method)
return true, false
}
if obj.Parent() == obj.Pkg().Scope() {
// lexical object (package-level var/const/func/type)
return true, true
}
}
// object with unexported named or defined in local scope
return false, false
} | go | func classify(obj types.Object) (global, pkglevel bool) {
if obj.Exported() {
if obj.Parent() == nil {
// selectable object (field or method)
return true, false
}
if obj.Parent() == obj.Pkg().Scope() {
// lexical object (package-level var/const/func/type)
return true, true
}
}
// object with unexported named or defined in local scope
return false, false
} | [
"func",
"classify",
"(",
"obj",
"types",
".",
"Object",
")",
"(",
"global",
",",
"pkglevel",
"bool",
")",
"{",
"if",
"obj",
".",
"Exported",
"(",
")",
"{",
"if",
"obj",
".",
"Parent",
"(",
")",
"==",
"nil",
"{",
"return",
"true",
",",
"false",
"\... | // classify classifies objects by how far
// we have to look to find references to them. | [
"classify",
"classifies",
"objects",
"by",
"how",
"far",
"we",
"have",
"to",
"look",
"to",
"find",
"references",
"to",
"them",
"."
] | 33d2968a49e1131825a0accdd64bdf9901cf144c | https://github.com/sourcegraph/go-langserver/blob/33d2968a49e1131825a0accdd64bdf9901cf144c/langserver/references.go#L730-L743 | train |
sourcegraph/go-langserver | langserver/references.go | findObject | func findObject(fset *token.FileSet, info *types.Info, objposn token.Position) types.Object {
good := func(obj types.Object) bool {
if obj == nil {
return false
}
posn := fset.Position(obj.Pos())
return posn.Filename == objposn.Filename && posn.Offset == objposn.Offset
}
for _, obj := range info.Defs {
if good(obj) {
return obj
}
}
for _, obj := range info.Implicits {
if good(obj) {
return obj
}
}
return nil
} | go | func findObject(fset *token.FileSet, info *types.Info, objposn token.Position) types.Object {
good := func(obj types.Object) bool {
if obj == nil {
return false
}
posn := fset.Position(obj.Pos())
return posn.Filename == objposn.Filename && posn.Offset == objposn.Offset
}
for _, obj := range info.Defs {
if good(obj) {
return obj
}
}
for _, obj := range info.Implicits {
if good(obj) {
return obj
}
}
return nil
} | [
"func",
"findObject",
"(",
"fset",
"*",
"token",
".",
"FileSet",
",",
"info",
"*",
"types",
".",
"Info",
",",
"objposn",
"token",
".",
"Position",
")",
"types",
".",
"Object",
"{",
"good",
":=",
"func",
"(",
"obj",
"types",
".",
"Object",
")",
"bool"... | // findObject returns the object defined at the specified position. | [
"findObject",
"returns",
"the",
"object",
"defined",
"at",
"the",
"specified",
"position",
"."
] | 33d2968a49e1131825a0accdd64bdf9901cf144c | https://github.com/sourcegraph/go-langserver/blob/33d2968a49e1131825a0accdd64bdf9901cf144c/langserver/references.go#L761-L780 | train |
sourcegraph/go-langserver | langserver/references.go | sameObj | func sameObj(x, y types.Object) bool {
if x == y {
return true
}
if x, ok := x.(*types.PkgName); ok {
if y, ok := y.(*types.PkgName); ok {
return x.Imported() == y.Imported()
}
}
return false
} | go | func sameObj(x, y types.Object) bool {
if x == y {
return true
}
if x, ok := x.(*types.PkgName); ok {
if y, ok := y.(*types.PkgName); ok {
return x.Imported() == y.Imported()
}
}
return false
} | [
"func",
"sameObj",
"(",
"x",
",",
"y",
"types",
".",
"Object",
")",
"bool",
"{",
"if",
"x",
"==",
"y",
"{",
"return",
"true",
"\n",
"}",
"\n",
"if",
"x",
",",
"ok",
":=",
"x",
".",
"(",
"*",
"types",
".",
"PkgName",
")",
";",
"ok",
"{",
"if... | // same reports whether x and y are identical, or both are PkgNames
// that import the same Package. | [
"same",
"reports",
"whether",
"x",
"and",
"y",
"are",
"identical",
"or",
"both",
"are",
"PkgNames",
"that",
"import",
"the",
"same",
"Package",
"."
] | 33d2968a49e1131825a0accdd64bdf9901cf144c | https://github.com/sourcegraph/go-langserver/blob/33d2968a49e1131825a0accdd64bdf9901cf144c/langserver/references.go#L794-L804 | train |
sourcegraph/go-langserver | langserver/references.go | readFile | func readFile(ctxt *build.Context, filename string, buf *bytes.Buffer) ([]byte, error) {
rc, err := buildutil.OpenFile(ctxt, filename)
if err != nil {
return nil, err
}
defer rc.Close()
if buf == nil {
buf = new(bytes.Buffer)
}
if _, err := io.Copy(buf, rc); err != nil {
return nil, err
}
return buf.Bytes(), nil
} | go | func readFile(ctxt *build.Context, filename string, buf *bytes.Buffer) ([]byte, error) {
rc, err := buildutil.OpenFile(ctxt, filename)
if err != nil {
return nil, err
}
defer rc.Close()
if buf == nil {
buf = new(bytes.Buffer)
}
if _, err := io.Copy(buf, rc); err != nil {
return nil, err
}
return buf.Bytes(), nil
} | [
"func",
"readFile",
"(",
"ctxt",
"*",
"build",
".",
"Context",
",",
"filename",
"string",
",",
"buf",
"*",
"bytes",
".",
"Buffer",
")",
"(",
"[",
"]",
"byte",
",",
"error",
")",
"{",
"rc",
",",
"err",
":=",
"buildutil",
".",
"OpenFile",
"(",
"ctxt"... | // readFile is like ioutil.ReadFile, but
// it goes through the virtualized build.Context.
// If non-nil, buf must have been reset. | [
"readFile",
"is",
"like",
"ioutil",
".",
"ReadFile",
"but",
"it",
"goes",
"through",
"the",
"virtualized",
"build",
".",
"Context",
".",
"If",
"non",
"-",
"nil",
"buf",
"must",
"have",
"been",
"reset",
"."
] | 33d2968a49e1131825a0accdd64bdf9901cf144c | https://github.com/sourcegraph/go-langserver/blob/33d2968a49e1131825a0accdd64bdf9901cf144c/langserver/references.go#L809-L822 | train |
sourcegraph/go-langserver | langserver/handler_common.go | ShutDown | func (h *HandlerCommon) ShutDown() {
h.mu.Lock()
if h.shutdown {
log.Printf("Warning: server received a shutdown request after it was already shut down.")
}
h.shutdown = true
h.mu.Unlock()
} | go | func (h *HandlerCommon) ShutDown() {
h.mu.Lock()
if h.shutdown {
log.Printf("Warning: server received a shutdown request after it was already shut down.")
}
h.shutdown = true
h.mu.Unlock()
} | [
"func",
"(",
"h",
"*",
"HandlerCommon",
")",
"ShutDown",
"(",
")",
"{",
"h",
".",
"mu",
".",
"Lock",
"(",
")",
"\n",
"if",
"h",
".",
"shutdown",
"{",
"log",
".",
"Printf",
"(",
"\"Warning: server received a shutdown request after it was already shut down.\"",
... | // ShutDown marks this server as being shut down and causes all future calls to checkReady to return an error. | [
"ShutDown",
"marks",
"this",
"server",
"as",
"being",
"shut",
"down",
"and",
"causes",
"all",
"future",
"calls",
"to",
"checkReady",
"to",
"return",
"an",
"error",
"."
] | 33d2968a49e1131825a0accdd64bdf9901cf144c | https://github.com/sourcegraph/go-langserver/blob/33d2968a49e1131825a0accdd64bdf9901cf144c/langserver/handler_common.go#L40-L47 | train |
sourcegraph/go-langserver | langserver/handler_common.go | CheckReady | func (h *HandlerCommon) CheckReady() error {
h.mu.Lock()
defer h.mu.Unlock()
if h.shutdown {
return errors.New("server is shutting down")
}
return nil
} | go | func (h *HandlerCommon) CheckReady() error {
h.mu.Lock()
defer h.mu.Unlock()
if h.shutdown {
return errors.New("server is shutting down")
}
return nil
} | [
"func",
"(",
"h",
"*",
"HandlerCommon",
")",
"CheckReady",
"(",
")",
"error",
"{",
"h",
".",
"mu",
".",
"Lock",
"(",
")",
"\n",
"defer",
"h",
".",
"mu",
".",
"Unlock",
"(",
")",
"\n",
"if",
"h",
".",
"shutdown",
"{",
"return",
"errors",
".",
"N... | // CheckReady returns an error if the handler has been shut
// down. | [
"CheckReady",
"returns",
"an",
"error",
"if",
"the",
"handler",
"has",
"been",
"shut",
"down",
"."
] | 33d2968a49e1131825a0accdd64bdf9901cf144c | https://github.com/sourcegraph/go-langserver/blob/33d2968a49e1131825a0accdd64bdf9901cf144c/langserver/handler_common.go#L51-L58 | train |
sourcegraph/go-langserver | langserver/fs.go | FS | func (h *overlay) FS() ctxvfs.FileSystem {
return ctxvfs.Sync(&h.mu, ctxvfs.Map(h.m))
} | go | func (h *overlay) FS() ctxvfs.FileSystem {
return ctxvfs.Sync(&h.mu, ctxvfs.Map(h.m))
} | [
"func",
"(",
"h",
"*",
"overlay",
")",
"FS",
"(",
")",
"ctxvfs",
".",
"FileSystem",
"{",
"return",
"ctxvfs",
".",
"Sync",
"(",
"&",
"h",
".",
"mu",
",",
"ctxvfs",
".",
"Map",
"(",
"h",
".",
"m",
")",
")",
"\n",
"}"
] | // FS returns a vfs for the overlay. | [
"FS",
"returns",
"a",
"vfs",
"for",
"the",
"overlay",
"."
] | 33d2968a49e1131825a0accdd64bdf9901cf144c | https://github.com/sourcegraph/go-langserver/blob/33d2968a49e1131825a0accdd64bdf9901cf144c/langserver/fs.go#L117-L119 | train |
sourcegraph/go-langserver | langserver/fs.go | applyContentChanges | func applyContentChanges(uri lsp.DocumentURI, contents []byte, changes []lsp.TextDocumentContentChangeEvent) ([]byte, error) {
for _, change := range changes {
if change.Range == nil && change.RangeLength == 0 {
contents = []byte(change.Text) // new full content
continue
}
start, ok, why := offsetForPosition(contents, change.Range.Start)
if !ok {
return nil, fmt.Errorf("received textDocument/didChange for invalid position %q on %q: %s", change.Range.Start, uri, why)
}
var end int
if change.RangeLength != 0 {
end = start + int(change.RangeLength)
} else {
// RangeLength not specified, work it out from Range.End
end, ok, why = offsetForPosition(contents, change.Range.End)
if !ok {
return nil, fmt.Errorf("received textDocument/didChange for invalid position %q on %q: %s", change.Range.Start, uri, why)
}
}
if start < 0 || end > len(contents) || end < start {
return nil, fmt.Errorf("received textDocument/didChange for out of range position %q on %q", change.Range, uri)
}
// Try avoid doing too many allocations, so use bytes.Buffer
b := &bytes.Buffer{}
b.Grow(start + len(change.Text) + len(contents) - end)
b.Write(contents[:start])
b.WriteString(change.Text)
b.Write(contents[end:])
contents = b.Bytes()
}
return contents, nil
} | go | func applyContentChanges(uri lsp.DocumentURI, contents []byte, changes []lsp.TextDocumentContentChangeEvent) ([]byte, error) {
for _, change := range changes {
if change.Range == nil && change.RangeLength == 0 {
contents = []byte(change.Text) // new full content
continue
}
start, ok, why := offsetForPosition(contents, change.Range.Start)
if !ok {
return nil, fmt.Errorf("received textDocument/didChange for invalid position %q on %q: %s", change.Range.Start, uri, why)
}
var end int
if change.RangeLength != 0 {
end = start + int(change.RangeLength)
} else {
// RangeLength not specified, work it out from Range.End
end, ok, why = offsetForPosition(contents, change.Range.End)
if !ok {
return nil, fmt.Errorf("received textDocument/didChange for invalid position %q on %q: %s", change.Range.Start, uri, why)
}
}
if start < 0 || end > len(contents) || end < start {
return nil, fmt.Errorf("received textDocument/didChange for out of range position %q on %q", change.Range, uri)
}
// Try avoid doing too many allocations, so use bytes.Buffer
b := &bytes.Buffer{}
b.Grow(start + len(change.Text) + len(contents) - end)
b.Write(contents[:start])
b.WriteString(change.Text)
b.Write(contents[end:])
contents = b.Bytes()
}
return contents, nil
} | [
"func",
"applyContentChanges",
"(",
"uri",
"lsp",
".",
"DocumentURI",
",",
"contents",
"[",
"]",
"byte",
",",
"changes",
"[",
"]",
"lsp",
".",
"TextDocumentContentChangeEvent",
")",
"(",
"[",
"]",
"byte",
",",
"error",
")",
"{",
"for",
"_",
",",
"change"... | // applyContentChanges updates `contents` based on `changes` | [
"applyContentChanges",
"updates",
"contents",
"based",
"on",
"changes"
] | 33d2968a49e1131825a0accdd64bdf9901cf144c | https://github.com/sourcegraph/go-langserver/blob/33d2968a49e1131825a0accdd64bdf9901cf144c/langserver/fs.go#L141-L173 | train |
sourcegraph/go-langserver | langserver/fs.go | NewAtomicFS | func NewAtomicFS() *AtomicFS {
fs := &AtomicFS{}
fs.v.Store(make(ctxvfs.NameSpace))
return fs
} | go | func NewAtomicFS() *AtomicFS {
fs := &AtomicFS{}
fs.v.Store(make(ctxvfs.NameSpace))
return fs
} | [
"func",
"NewAtomicFS",
"(",
")",
"*",
"AtomicFS",
"{",
"fs",
":=",
"&",
"AtomicFS",
"{",
"}",
"\n",
"fs",
".",
"v",
".",
"Store",
"(",
"make",
"(",
"ctxvfs",
".",
"NameSpace",
")",
")",
"\n",
"return",
"fs",
"\n",
"}"
] | // NewAtomicFS returns an AtomicFS with an empty wrapped ctxvfs.NameSpace | [
"NewAtomicFS",
"returns",
"an",
"AtomicFS",
"with",
"an",
"empty",
"wrapped",
"ctxvfs",
".",
"NameSpace"
] | 33d2968a49e1131825a0accdd64bdf9901cf144c | https://github.com/sourcegraph/go-langserver/blob/33d2968a49e1131825a0accdd64bdf9901cf144c/langserver/fs.go#L242-L246 | train |
sourcegraph/go-langserver | langserver/fs.go | Bind | func (a *AtomicFS) Bind(old string, newfs ctxvfs.FileSystem, new string, mode ctxvfs.BindMode) {
// We do copy-on-write
a.mu.Lock()
defer a.mu.Unlock()
fs1 := a.v.Load().(ctxvfs.NameSpace)
fs2 := make(ctxvfs.NameSpace)
for k, v := range fs1 {
fs2[k] = v
}
fs2.Bind(old, newfs, new, mode)
a.v.Store(fs2)
} | go | func (a *AtomicFS) Bind(old string, newfs ctxvfs.FileSystem, new string, mode ctxvfs.BindMode) {
// We do copy-on-write
a.mu.Lock()
defer a.mu.Unlock()
fs1 := a.v.Load().(ctxvfs.NameSpace)
fs2 := make(ctxvfs.NameSpace)
for k, v := range fs1 {
fs2[k] = v
}
fs2.Bind(old, newfs, new, mode)
a.v.Store(fs2)
} | [
"func",
"(",
"a",
"*",
"AtomicFS",
")",
"Bind",
"(",
"old",
"string",
",",
"newfs",
"ctxvfs",
".",
"FileSystem",
",",
"new",
"string",
",",
"mode",
"ctxvfs",
".",
"BindMode",
")",
"{",
"a",
".",
"mu",
".",
"Lock",
"(",
")",
"\n",
"defer",
"a",
".... | // Bind wraps ctxvfs.NameSpace.Bind | [
"Bind",
"wraps",
"ctxvfs",
".",
"NameSpace",
".",
"Bind"
] | 33d2968a49e1131825a0accdd64bdf9901cf144c | https://github.com/sourcegraph/go-langserver/blob/33d2968a49e1131825a0accdd64bdf9901cf144c/langserver/fs.go#L249-L261 | train |
sourcegraph/go-langserver | langserver/fs.go | Open | func (a *AtomicFS) Open(ctx context.Context, path string) (ctxvfs.ReadSeekCloser, error) {
fs := a.v.Load().(ctxvfs.NameSpace)
return fs.Open(ctx, path)
} | go | func (a *AtomicFS) Open(ctx context.Context, path string) (ctxvfs.ReadSeekCloser, error) {
fs := a.v.Load().(ctxvfs.NameSpace)
return fs.Open(ctx, path)
} | [
"func",
"(",
"a",
"*",
"AtomicFS",
")",
"Open",
"(",
"ctx",
"context",
".",
"Context",
",",
"path",
"string",
")",
"(",
"ctxvfs",
".",
"ReadSeekCloser",
",",
"error",
")",
"{",
"fs",
":=",
"a",
".",
"v",
".",
"Load",
"(",
")",
".",
"(",
"ctxvfs",... | // Open wraps ctxvfs.NameSpace.Open | [
"Open",
"wraps",
"ctxvfs",
".",
"NameSpace",
".",
"Open"
] | 33d2968a49e1131825a0accdd64bdf9901cf144c | https://github.com/sourcegraph/go-langserver/blob/33d2968a49e1131825a0accdd64bdf9901cf144c/langserver/fs.go#L268-L271 | train |
sourcegraph/go-langserver | langserver/fs.go | Stat | func (a *AtomicFS) Stat(ctx context.Context, path string) (os.FileInfo, error) {
fs := a.v.Load().(ctxvfs.NameSpace)
return fs.Stat(ctx, path)
} | go | func (a *AtomicFS) Stat(ctx context.Context, path string) (os.FileInfo, error) {
fs := a.v.Load().(ctxvfs.NameSpace)
return fs.Stat(ctx, path)
} | [
"func",
"(",
"a",
"*",
"AtomicFS",
")",
"Stat",
"(",
"ctx",
"context",
".",
"Context",
",",
"path",
"string",
")",
"(",
"os",
".",
"FileInfo",
",",
"error",
")",
"{",
"fs",
":=",
"a",
".",
"v",
".",
"Load",
"(",
")",
".",
"(",
"ctxvfs",
".",
... | // Stat wraps ctxvfs.NameSpace.Stat | [
"Stat",
"wraps",
"ctxvfs",
".",
"NameSpace",
".",
"Stat"
] | 33d2968a49e1131825a0accdd64bdf9901cf144c | https://github.com/sourcegraph/go-langserver/blob/33d2968a49e1131825a0accdd64bdf9901cf144c/langserver/fs.go#L274-L277 | train |
sourcegraph/go-langserver | langserver/cache.go | newLRU | func newLRU(env string, defaultSize int) *lru.Cache {
size := defaultSize
if i, err := strconv.Atoi(os.Getenv(env)); err == nil && i > 0 {
size = i
}
c, err := lru.New(size)
if err != nil {
// This should never happen since our size is always > 0
panic(err)
}
return c
} | go | func newLRU(env string, defaultSize int) *lru.Cache {
size := defaultSize
if i, err := strconv.Atoi(os.Getenv(env)); err == nil && i > 0 {
size = i
}
c, err := lru.New(size)
if err != nil {
// This should never happen since our size is always > 0
panic(err)
}
return c
} | [
"func",
"newLRU",
"(",
"env",
"string",
",",
"defaultSize",
"int",
")",
"*",
"lru",
".",
"Cache",
"{",
"size",
":=",
"defaultSize",
"\n",
"if",
"i",
",",
"err",
":=",
"strconv",
".",
"Atoi",
"(",
"os",
".",
"Getenv",
"(",
"env",
")",
")",
";",
"e... | // newLRU returns an LRU based cache. | [
"newLRU",
"returns",
"an",
"LRU",
"based",
"cache",
"."
] | 33d2968a49e1131825a0accdd64bdf9901cf144c | https://github.com/sourcegraph/go-langserver/blob/33d2968a49e1131825a0accdd64bdf9901cf144c/langserver/cache.go#L142-L153 | train |
sourcegraph/go-langserver | buildserver/util.go | add | func (e *errorList) add(err error) {
e.mu.Lock()
e.errors = append(e.errors, err)
e.mu.Unlock()
} | go | func (e *errorList) add(err error) {
e.mu.Lock()
e.errors = append(e.errors, err)
e.mu.Unlock()
} | [
"func",
"(",
"e",
"*",
"errorList",
")",
"add",
"(",
"err",
"error",
")",
"{",
"e",
".",
"mu",
".",
"Lock",
"(",
")",
"\n",
"e",
".",
"errors",
"=",
"append",
"(",
"e",
".",
"errors",
",",
"err",
")",
"\n",
"e",
".",
"mu",
".",
"Unlock",
"(... | // add adds err to the list of errors. It is safe to call it from
// concurrent goroutines. | [
"add",
"adds",
"err",
"to",
"the",
"list",
"of",
"errors",
".",
"It",
"is",
"safe",
"to",
"call",
"it",
"from",
"concurrent",
"goroutines",
"."
] | 33d2968a49e1131825a0accdd64bdf9901cf144c | https://github.com/sourcegraph/go-langserver/blob/33d2968a49e1131825a0accdd64bdf9901cf144c/buildserver/util.go#L15-L19 | train |
sourcegraph/go-langserver | buildserver/util.go | error | func (e *errorList) error() error {
switch len(e.errors) {
case 0:
return nil
case 1:
return e.errors[0]
default:
return fmt.Errorf("%s [and %d more errors]", e.errors[0], len(e.errors)-1)
}
} | go | func (e *errorList) error() error {
switch len(e.errors) {
case 0:
return nil
case 1:
return e.errors[0]
default:
return fmt.Errorf("%s [and %d more errors]", e.errors[0], len(e.errors)-1)
}
} | [
"func",
"(",
"e",
"*",
"errorList",
")",
"error",
"(",
")",
"error",
"{",
"switch",
"len",
"(",
"e",
".",
"errors",
")",
"{",
"case",
"0",
":",
"return",
"nil",
"\n",
"case",
"1",
":",
"return",
"e",
".",
"errors",
"[",
"0",
"]",
"\n",
"default... | // errors returns the list of errors as a single error. It is NOT safe
// to call from concurrent goroutines. | [
"errors",
"returns",
"the",
"list",
"of",
"errors",
"as",
"a",
"single",
"error",
".",
"It",
"is",
"NOT",
"safe",
"to",
"call",
"from",
"concurrent",
"goroutines",
"."
] | 33d2968a49e1131825a0accdd64bdf9901cf144c | https://github.com/sourcegraph/go-langserver/blob/33d2968a49e1131825a0accdd64bdf9901cf144c/buildserver/util.go#L23-L32 | train |
sourcegraph/go-langserver | langserver/handler_shared.go | getFindPackageFunc | func (h *HandlerShared) getFindPackageFunc() FindPackageFunc {
if h.FindPackage != nil {
return h.FindPackage
}
return defaultFindPackageFunc
} | go | func (h *HandlerShared) getFindPackageFunc() FindPackageFunc {
if h.FindPackage != nil {
return h.FindPackage
}
return defaultFindPackageFunc
} | [
"func",
"(",
"h",
"*",
"HandlerShared",
")",
"getFindPackageFunc",
"(",
")",
"FindPackageFunc",
"{",
"if",
"h",
".",
"FindPackage",
"!=",
"nil",
"{",
"return",
"h",
".",
"FindPackage",
"\n",
"}",
"\n",
"return",
"defaultFindPackageFunc",
"\n",
"}"
] | // getFindPackageFunc is a helper which returns h.FindPackage if non-nil, otherwise defaultFindPackageFunc | [
"getFindPackageFunc",
"is",
"a",
"helper",
"which",
"returns",
"h",
".",
"FindPackage",
"if",
"non",
"-",
"nil",
"otherwise",
"defaultFindPackageFunc"
] | 33d2968a49e1131825a0accdd64bdf9901cf144c | https://github.com/sourcegraph/go-langserver/blob/33d2968a49e1131825a0accdd64bdf9901cf144c/langserver/handler_shared.go#L93-L98 | train |
sourcegraph/go-langserver | vfsutil/cache.go | Evict | func (f *cachedFile) Evict() {
// Best-effort. Ignore error
_ = os.Remove(f.path)
cachedFileEvict.Inc()
} | go | func (f *cachedFile) Evict() {
// Best-effort. Ignore error
_ = os.Remove(f.path)
cachedFileEvict.Inc()
} | [
"func",
"(",
"f",
"*",
"cachedFile",
")",
"Evict",
"(",
")",
"{",
"_",
"=",
"os",
".",
"Remove",
"(",
"f",
".",
"path",
")",
"\n",
"cachedFileEvict",
".",
"Inc",
"(",
")",
"\n",
"}"
] | // Evict will remove the file from the cache. It does not close File. It also
// does not protect against other open readers or concurrent fetches. | [
"Evict",
"will",
"remove",
"the",
"file",
"from",
"the",
"cache",
".",
"It",
"does",
"not",
"close",
"File",
".",
"It",
"also",
"does",
"not",
"protect",
"against",
"other",
"open",
"readers",
"or",
"concurrent",
"fetches",
"."
] | 33d2968a49e1131825a0accdd64bdf9901cf144c | https://github.com/sourcegraph/go-langserver/blob/33d2968a49e1131825a0accdd64bdf9901cf144c/vfsutil/cache.go#L38-L42 | train |
sourcegraph/go-langserver | vfsutil/cache.go | cachedFetch | func cachedFetch(ctx context.Context, key string, s *diskcache.Store, fetcher func(context.Context) (io.ReadCloser, error)) (ff *cachedFile, err error) {
f, err := s.Open(ctx, key, fetcher)
if err != nil {
return nil, err
}
return &cachedFile{
File: f.File,
path: f.Path,
}, nil
} | go | func cachedFetch(ctx context.Context, key string, s *diskcache.Store, fetcher func(context.Context) (io.ReadCloser, error)) (ff *cachedFile, err error) {
f, err := s.Open(ctx, key, fetcher)
if err != nil {
return nil, err
}
return &cachedFile{
File: f.File,
path: f.Path,
}, nil
} | [
"func",
"cachedFetch",
"(",
"ctx",
"context",
".",
"Context",
",",
"key",
"string",
",",
"s",
"*",
"diskcache",
".",
"Store",
",",
"fetcher",
"func",
"(",
"context",
".",
"Context",
")",
"(",
"io",
".",
"ReadCloser",
",",
"error",
")",
")",
"(",
"ff"... | // cachedFetch will open a file from the local cache with key. If missing,
// fetcher will fill the cache first. cachedFetch also performs
// single-flighting. | [
"cachedFetch",
"will",
"open",
"a",
"file",
"from",
"the",
"local",
"cache",
"with",
"key",
".",
"If",
"missing",
"fetcher",
"will",
"fill",
"the",
"cache",
"first",
".",
"cachedFetch",
"also",
"performs",
"single",
"-",
"flighting",
"."
] | 33d2968a49e1131825a0accdd64bdf9901cf144c | https://github.com/sourcegraph/go-langserver/blob/33d2968a49e1131825a0accdd64bdf9901cf144c/vfsutil/cache.go#L47-L56 | train |
sourcegraph/go-langserver | buildserver/environment.go | determineEnvironment | func determineEnvironment(ctx context.Context, fs ctxvfs.FileSystem, params lspext.InitializeParams) (*langserver.InitializeParams, error) {
rootImportPath, err := determineRootImportPath(ctx, params.OriginalRootURI, fs)
if err != nil {
return nil, fmt.Errorf("unable to determine workspace's root Go import path: %s (original rootPath is %q)", err, params.OriginalRootURI)
}
// Sanity-check the import path.
if rootImportPath == "" || rootImportPath != path.Clean(rootImportPath) || strings.Contains(rootImportPath, "..") || strings.HasPrefix(rootImportPath, string(os.PathSeparator)) || strings.HasPrefix(rootImportPath, "/") || strings.HasPrefix(rootImportPath, ".") {
return nil, fmt.Errorf("empty or suspicious import path: %q", rootImportPath)
}
// Put all files in the workspace under a /src/IMPORTPATH
// directory, such as /src/github.com/foo/bar, so that Go can
// build it in GOPATH=/.
var rootPath string
if rootImportPath == "github.com/golang/go" {
// stdlib means our rootpath is the GOPATH
rootPath = goroot
rootImportPath = ""
} else {
rootPath = "/src/" + rootImportPath
}
GOPATH := gopath
if customGOPATH := detectCustomGOPATH(ctx, fs); len(customGOPATH) > 0 {
// Convert list of relative GOPATHs into absolute. We can have
// more than one so we root ourselves at /workspace. We still
// append the default GOPATH of `/` at the end. Fetched
// dependencies will be mounted at that location.
rootPath = "/workspace"
rootImportPath = ""
for i := range customGOPATH {
customGOPATH[i] = rootPath + customGOPATH[i]
}
customGOPATH = append(customGOPATH, gopath)
GOPATH = strings.Join(customGOPATH, ":")
}
// Send "initialize" to the wrapped lang server.
langInitParams := &langserver.InitializeParams{
InitializeParams: params.InitializeParams,
NoOSFileSystemAccess: true,
BuildContext: &langserver.InitializeBuildContextParams{
GOOS: goos,
GOARCH: goarch,
GOPATH: GOPATH,
GOROOT: goroot,
CgoEnabled: false,
Compiler: gocompiler,
// TODO(sqs): We'd like to set this to true only for
// the package we're analyzing (or for the whole
// repo), but go/loader is insufficiently
// configurable, so it applies it to the entire
// program, which takes a lot longer and causes weird
// error messages in the runtime package, etc. Disable
// it for now.
UseAllFiles: false,
},
}
langInitParams.RootURI = lsp.DocumentURI("file://" + rootPath)
langInitParams.RootImportPath = rootImportPath
return langInitParams, nil
} | go | func determineEnvironment(ctx context.Context, fs ctxvfs.FileSystem, params lspext.InitializeParams) (*langserver.InitializeParams, error) {
rootImportPath, err := determineRootImportPath(ctx, params.OriginalRootURI, fs)
if err != nil {
return nil, fmt.Errorf("unable to determine workspace's root Go import path: %s (original rootPath is %q)", err, params.OriginalRootURI)
}
// Sanity-check the import path.
if rootImportPath == "" || rootImportPath != path.Clean(rootImportPath) || strings.Contains(rootImportPath, "..") || strings.HasPrefix(rootImportPath, string(os.PathSeparator)) || strings.HasPrefix(rootImportPath, "/") || strings.HasPrefix(rootImportPath, ".") {
return nil, fmt.Errorf("empty or suspicious import path: %q", rootImportPath)
}
// Put all files in the workspace under a /src/IMPORTPATH
// directory, such as /src/github.com/foo/bar, so that Go can
// build it in GOPATH=/.
var rootPath string
if rootImportPath == "github.com/golang/go" {
// stdlib means our rootpath is the GOPATH
rootPath = goroot
rootImportPath = ""
} else {
rootPath = "/src/" + rootImportPath
}
GOPATH := gopath
if customGOPATH := detectCustomGOPATH(ctx, fs); len(customGOPATH) > 0 {
// Convert list of relative GOPATHs into absolute. We can have
// more than one so we root ourselves at /workspace. We still
// append the default GOPATH of `/` at the end. Fetched
// dependencies will be mounted at that location.
rootPath = "/workspace"
rootImportPath = ""
for i := range customGOPATH {
customGOPATH[i] = rootPath + customGOPATH[i]
}
customGOPATH = append(customGOPATH, gopath)
GOPATH = strings.Join(customGOPATH, ":")
}
// Send "initialize" to the wrapped lang server.
langInitParams := &langserver.InitializeParams{
InitializeParams: params.InitializeParams,
NoOSFileSystemAccess: true,
BuildContext: &langserver.InitializeBuildContextParams{
GOOS: goos,
GOARCH: goarch,
GOPATH: GOPATH,
GOROOT: goroot,
CgoEnabled: false,
Compiler: gocompiler,
// TODO(sqs): We'd like to set this to true only for
// the package we're analyzing (or for the whole
// repo), but go/loader is insufficiently
// configurable, so it applies it to the entire
// program, which takes a lot longer and causes weird
// error messages in the runtime package, etc. Disable
// it for now.
UseAllFiles: false,
},
}
langInitParams.RootURI = lsp.DocumentURI("file://" + rootPath)
langInitParams.RootImportPath = rootImportPath
return langInitParams, nil
} | [
"func",
"determineEnvironment",
"(",
"ctx",
"context",
".",
"Context",
",",
"fs",
"ctxvfs",
".",
"FileSystem",
",",
"params",
"lspext",
".",
"InitializeParams",
")",
"(",
"*",
"langserver",
".",
"InitializeParams",
",",
"error",
")",
"{",
"rootImportPath",
","... | // determineEnvironment will setup the language server InitializeParams based
// what it can detect from the filesystem and what it received from the client's
// InitializeParams.
//
// It is expected that fs will be mounted at InitializeParams.RootURI. | [
"determineEnvironment",
"will",
"setup",
"the",
"language",
"server",
"InitializeParams",
"based",
"what",
"it",
"can",
"detect",
"from",
"the",
"filesystem",
"and",
"what",
"it",
"received",
"from",
"the",
"client",
"s",
"InitializeParams",
".",
"It",
"is",
"ex... | 33d2968a49e1131825a0accdd64bdf9901cf144c | https://github.com/sourcegraph/go-langserver/blob/33d2968a49e1131825a0accdd64bdf9901cf144c/buildserver/environment.go#L44-L108 | train |
sourcegraph/go-langserver | buildserver/environment.go | detectCustomGOPATH | func detectCustomGOPATH(ctx context.Context, fs ctxvfs.FileSystem) (gopaths []string) {
// If we detect any .sorucegraph/config.json GOPATHs then they take
// absolute precedence and override all others.
if paths := detectSourcegraphGOPATH(ctx, fs); len(paths) > 0 {
return paths
}
// Check .vscode/config.json and .envrc files, giving them equal precedence.
if paths := detectVSCodeGOPATH(ctx, fs); len(paths) > 0 {
gopaths = append(gopaths, paths...)
}
if paths := detectEnvRCGOPATH(ctx, fs); len(paths) > 0 {
gopaths = append(gopaths, paths...)
}
return
} | go | func detectCustomGOPATH(ctx context.Context, fs ctxvfs.FileSystem) (gopaths []string) {
// If we detect any .sorucegraph/config.json GOPATHs then they take
// absolute precedence and override all others.
if paths := detectSourcegraphGOPATH(ctx, fs); len(paths) > 0 {
return paths
}
// Check .vscode/config.json and .envrc files, giving them equal precedence.
if paths := detectVSCodeGOPATH(ctx, fs); len(paths) > 0 {
gopaths = append(gopaths, paths...)
}
if paths := detectEnvRCGOPATH(ctx, fs); len(paths) > 0 {
gopaths = append(gopaths, paths...)
}
return
} | [
"func",
"detectCustomGOPATH",
"(",
"ctx",
"context",
".",
"Context",
",",
"fs",
"ctxvfs",
".",
"FileSystem",
")",
"(",
"gopaths",
"[",
"]",
"string",
")",
"{",
"if",
"paths",
":=",
"detectSourcegraphGOPATH",
"(",
"ctx",
",",
"fs",
")",
";",
"len",
"(",
... | // detectCustomGOPATH tries to detect monorepos which require their own custom
// GOPATH.
//
// This is best-effort. If any errors occur or we do not detect a custom
// gopath, an empty result is returned. | [
"detectCustomGOPATH",
"tries",
"to",
"detect",
"monorepos",
"which",
"require",
"their",
"own",
"custom",
"GOPATH",
".",
"This",
"is",
"best",
"-",
"effort",
".",
"If",
"any",
"errors",
"occur",
"or",
"we",
"do",
"not",
"detect",
"a",
"custom",
"gopath",
"... | 33d2968a49e1131825a0accdd64bdf9901cf144c | https://github.com/sourcegraph/go-langserver/blob/33d2968a49e1131825a0accdd64bdf9901cf144c/buildserver/environment.go#L115-L130 | train |
sourcegraph/go-langserver | buildserver/environment.go | unmarshalJSONC | func unmarshalJSONC(text string, v interface{}) error {
data, errs := jsonx.Parse(text, jsonx.ParseOptions{Comments: true, TrailingCommas: true})
if len(errs) > 0 {
return fmt.Errorf("failed to parse JSON: %v", errs)
}
return json.Unmarshal(data, v)
} | go | func unmarshalJSONC(text string, v interface{}) error {
data, errs := jsonx.Parse(text, jsonx.ParseOptions{Comments: true, TrailingCommas: true})
if len(errs) > 0 {
return fmt.Errorf("failed to parse JSON: %v", errs)
}
return json.Unmarshal(data, v)
} | [
"func",
"unmarshalJSONC",
"(",
"text",
"string",
",",
"v",
"interface",
"{",
"}",
")",
"error",
"{",
"data",
",",
"errs",
":=",
"jsonx",
".",
"Parse",
"(",
"text",
",",
"jsonx",
".",
"ParseOptions",
"{",
"Comments",
":",
"true",
",",
"TrailingCommas",
... | // unmarshalJSONC unmarshals the JSON using a fault-tolerant parser that allows comments
// and trailing commas. If any unrecoverable faults are found, an error is returned. | [
"unmarshalJSONC",
"unmarshals",
"the",
"JSON",
"using",
"a",
"fault",
"-",
"tolerant",
"parser",
"that",
"allows",
"comments",
"and",
"trailing",
"commas",
".",
"If",
"any",
"unrecoverable",
"faults",
"are",
"found",
"an",
"error",
"is",
"returned",
"."
] | 33d2968a49e1131825a0accdd64bdf9901cf144c | https://github.com/sourcegraph/go-langserver/blob/33d2968a49e1131825a0accdd64bdf9901cf144c/buildserver/environment.go#L165-L171 | train |
sourcegraph/go-langserver | langserver/types.go | deref | func deref(typ types.Type) types.Type {
if p, ok := typ.Underlying().(*types.Pointer); ok {
return p.Elem()
}
return typ
} | go | func deref(typ types.Type) types.Type {
if p, ok := typ.Underlying().(*types.Pointer); ok {
return p.Elem()
}
return typ
} | [
"func",
"deref",
"(",
"typ",
"types",
".",
"Type",
")",
"types",
".",
"Type",
"{",
"if",
"p",
",",
"ok",
":=",
"typ",
".",
"Underlying",
"(",
")",
".",
"(",
"*",
"types",
".",
"Pointer",
")",
";",
"ok",
"{",
"return",
"p",
".",
"Elem",
"(",
"... | // deref returns a pointer's element type; otherwise it returns typ. | [
"deref",
"returns",
"a",
"pointer",
"s",
"element",
"type",
";",
"otherwise",
"it",
"returns",
"typ",
"."
] | 33d2968a49e1131825a0accdd64bdf9901cf144c | https://github.com/sourcegraph/go-langserver/blob/33d2968a49e1131825a0accdd64bdf9901cf144c/langserver/types.go#L6-L11 | train |
sourcegraph/go-langserver | buildserver/deps.go | get | func (k *keyMutex) get(key string) *sync.Mutex {
k.mu.Lock()
mu, ok := k.mus[key]
if !ok {
mu = &sync.Mutex{}
k.mus[key] = mu
}
k.mu.Unlock()
return mu
} | go | func (k *keyMutex) get(key string) *sync.Mutex {
k.mu.Lock()
mu, ok := k.mus[key]
if !ok {
mu = &sync.Mutex{}
k.mus[key] = mu
}
k.mu.Unlock()
return mu
} | [
"func",
"(",
"k",
"*",
"keyMutex",
")",
"get",
"(",
"key",
"string",
")",
"*",
"sync",
".",
"Mutex",
"{",
"k",
".",
"mu",
".",
"Lock",
"(",
")",
"\n",
"mu",
",",
"ok",
":=",
"k",
".",
"mus",
"[",
"key",
"]",
"\n",
"if",
"!",
"ok",
"{",
"m... | // get returns a mutex unique to the given key. | [
"get",
"returns",
"a",
"mutex",
"unique",
"to",
"the",
"given",
"key",
"."
] | 33d2968a49e1131825a0accdd64bdf9901cf144c | https://github.com/sourcegraph/go-langserver/blob/33d2968a49e1131825a0accdd64bdf9901cf144c/buildserver/deps.go#L34-L43 | train |
sourcegraph/go-langserver | buildserver/deps.go | fetchTransitiveDepsOfFile | func (h *BuildHandler) fetchTransitiveDepsOfFile(ctx context.Context, fileURI lsp.DocumentURI, dc *depCache) (err error) {
parentSpan := opentracing.SpanFromContext(ctx)
span := parentSpan.Tracer().StartSpan("go-langserver-go: fetch transitive dependencies",
opentracing.Tags{"fileURI": fileURI},
opentracing.ChildOf(parentSpan.Context()),
)
ctx = opentracing.ContextWithSpan(ctx, span)
defer func() {
if err != nil {
ext.Error.Set(span, true)
span.LogFields(otlog.Error(err))
}
span.Finish()
}()
bctx := h.lang.BuildContext(ctx)
filename := h.FilePath(fileURI)
bpkg, err := langserver.ContainingPackage(bctx, filename, h.RootFSPath)
if err != nil && !isMultiplePackageError(err) {
return err
}
err = doDeps(bpkg, 0, dc, func(path, srcDir string, mode build.ImportMode) (*build.Package, error) {
return h.doFindPackage(ctx, bctx, path, srcDir, mode, dc)
})
return err
} | go | func (h *BuildHandler) fetchTransitiveDepsOfFile(ctx context.Context, fileURI lsp.DocumentURI, dc *depCache) (err error) {
parentSpan := opentracing.SpanFromContext(ctx)
span := parentSpan.Tracer().StartSpan("go-langserver-go: fetch transitive dependencies",
opentracing.Tags{"fileURI": fileURI},
opentracing.ChildOf(parentSpan.Context()),
)
ctx = opentracing.ContextWithSpan(ctx, span)
defer func() {
if err != nil {
ext.Error.Set(span, true)
span.LogFields(otlog.Error(err))
}
span.Finish()
}()
bctx := h.lang.BuildContext(ctx)
filename := h.FilePath(fileURI)
bpkg, err := langserver.ContainingPackage(bctx, filename, h.RootFSPath)
if err != nil && !isMultiplePackageError(err) {
return err
}
err = doDeps(bpkg, 0, dc, func(path, srcDir string, mode build.ImportMode) (*build.Package, error) {
return h.doFindPackage(ctx, bctx, path, srcDir, mode, dc)
})
return err
} | [
"func",
"(",
"h",
"*",
"BuildHandler",
")",
"fetchTransitiveDepsOfFile",
"(",
"ctx",
"context",
".",
"Context",
",",
"fileURI",
"lsp",
".",
"DocumentURI",
",",
"dc",
"*",
"depCache",
")",
"(",
"err",
"error",
")",
"{",
"parentSpan",
":=",
"opentracing",
".... | // fetchTransitiveDepsOfFile fetches the transitive dependencies of
// the named Go file. A Go file's dependencies are the imports of its
// own package, plus all of its imports' imports, and so on.
//
// It adds fetched dependencies to its own file system overlay, and
// the returned depFiles should be passed onto the language server to
// add to its overlay. | [
"fetchTransitiveDepsOfFile",
"fetches",
"the",
"transitive",
"dependencies",
"of",
"the",
"named",
"Go",
"file",
".",
"A",
"Go",
"file",
"s",
"dependencies",
"are",
"the",
"imports",
"of",
"its",
"own",
"package",
"plus",
"all",
"of",
"its",
"imports",
"import... | 33d2968a49e1131825a0accdd64bdf9901cf144c | https://github.com/sourcegraph/go-langserver/blob/33d2968a49e1131825a0accdd64bdf9901cf144c/buildserver/deps.go#L86-L112 | train |
sourcegraph/go-langserver | buildserver/deps.go | findPackage | func (h *BuildHandler) findPackage(ctx context.Context, bctx *build.Context, path, srcDir string, mode build.ImportMode) (*build.Package, error) {
return h.doFindPackage(ctx, bctx, path, srcDir, mode, newDepCache())
} | go | func (h *BuildHandler) findPackage(ctx context.Context, bctx *build.Context, path, srcDir string, mode build.ImportMode) (*build.Package, error) {
return h.doFindPackage(ctx, bctx, path, srcDir, mode, newDepCache())
} | [
"func",
"(",
"h",
"*",
"BuildHandler",
")",
"findPackage",
"(",
"ctx",
"context",
".",
"Context",
",",
"bctx",
"*",
"build",
".",
"Context",
",",
"path",
",",
"srcDir",
"string",
",",
"mode",
"build",
".",
"ImportMode",
")",
"(",
"*",
"build",
".",
"... | // findPackage is a langserver.FindPackageFunc which integrates with the build
// server. It will fetch dependencies just in time. | [
"findPackage",
"is",
"a",
"langserver",
".",
"FindPackageFunc",
"which",
"integrates",
"with",
"the",
"build",
"server",
".",
"It",
"will",
"fetch",
"dependencies",
"just",
"in",
"time",
"."
] | 33d2968a49e1131825a0accdd64bdf9901cf144c | https://github.com/sourcegraph/go-langserver/blob/33d2968a49e1131825a0accdd64bdf9901cf144c/buildserver/deps.go#L194-L196 | train |
sourcegraph/go-langserver | buildserver/deps.go | isUnderRootImportPath | func isUnderRootImportPath(rootImportPath, path string) bool {
return rootImportPath != "" && util.PathHasPrefix(path, rootImportPath)
} | go | func isUnderRootImportPath(rootImportPath, path string) bool {
return rootImportPath != "" && util.PathHasPrefix(path, rootImportPath)
} | [
"func",
"isUnderRootImportPath",
"(",
"rootImportPath",
",",
"path",
"string",
")",
"bool",
"{",
"return",
"rootImportPath",
"!=",
"\"\"",
"&&",
"util",
".",
"PathHasPrefix",
"(",
"path",
",",
"rootImportPath",
")",
"\n",
"}"
] | // isUnderCanonicalImportPath tells if the given path is under the given root import path. | [
"isUnderCanonicalImportPath",
"tells",
"if",
"the",
"given",
"path",
"is",
"under",
"the",
"given",
"root",
"import",
"path",
"."
] | 33d2968a49e1131825a0accdd64bdf9901cf144c | https://github.com/sourcegraph/go-langserver/blob/33d2968a49e1131825a0accdd64bdf9901cf144c/buildserver/deps.go#L199-L201 | train |
sourcegraph/go-langserver | buildserver/deps.go | FetchCommonDeps | func FetchCommonDeps() {
// github.com/golang/go
d, _ := gosrc.ResolveImportPath(http.DefaultClient, "time")
u, _ := url.Parse(d.CloneURL)
_, _ = NewDepRepoVFS(context.Background(), u, d.Rev, nil)
} | go | func FetchCommonDeps() {
// github.com/golang/go
d, _ := gosrc.ResolveImportPath(http.DefaultClient, "time")
u, _ := url.Parse(d.CloneURL)
_, _ = NewDepRepoVFS(context.Background(), u, d.Rev, nil)
} | [
"func",
"FetchCommonDeps",
"(",
")",
"{",
"d",
",",
"_",
":=",
"gosrc",
".",
"ResolveImportPath",
"(",
"http",
".",
"DefaultClient",
",",
"\"time\"",
")",
"\n",
"u",
",",
"_",
":=",
"url",
".",
"Parse",
"(",
"d",
".",
"CloneURL",
")",
"\n",
"_",
",... | // FetchCommonDeps will fetch our common used dependencies. This is to avoid
// impacting the first ever typecheck we do in a repo since it will have to
// fetch the dependency from the internet. | [
"FetchCommonDeps",
"will",
"fetch",
"our",
"common",
"used",
"dependencies",
".",
"This",
"is",
"to",
"avoid",
"impacting",
"the",
"first",
"ever",
"typecheck",
"we",
"do",
"in",
"a",
"repo",
"since",
"it",
"will",
"have",
"to",
"fetch",
"the",
"dependency",... | 33d2968a49e1131825a0accdd64bdf9901cf144c | https://github.com/sourcegraph/go-langserver/blob/33d2968a49e1131825a0accdd64bdf9901cf144c/buildserver/deps.go#L479-L484 | train |
sourcegraph/go-langserver | langserver/hover.go | maybeAddComments | func maybeAddComments(comments string, contents []lsp.MarkedString) []lsp.MarkedString {
if comments == "" {
return contents
}
var b bytes.Buffer
doc.ToMarkdown(&b, comments, nil)
return append(contents, lsp.RawMarkedString(b.String()))
} | go | func maybeAddComments(comments string, contents []lsp.MarkedString) []lsp.MarkedString {
if comments == "" {
return contents
}
var b bytes.Buffer
doc.ToMarkdown(&b, comments, nil)
return append(contents, lsp.RawMarkedString(b.String()))
} | [
"func",
"maybeAddComments",
"(",
"comments",
"string",
",",
"contents",
"[",
"]",
"lsp",
".",
"MarkedString",
")",
"[",
"]",
"lsp",
".",
"MarkedString",
"{",
"if",
"comments",
"==",
"\"\"",
"{",
"return",
"contents",
"\n",
"}",
"\n",
"var",
"b",
"bytes",... | // maybeAddComments appends the specified comments converted to Markdown godoc
// form to the specified contents slice, if the comments string is not empty. | [
"maybeAddComments",
"appends",
"the",
"specified",
"comments",
"converted",
"to",
"Markdown",
"godoc",
"form",
"to",
"the",
"specified",
"contents",
"slice",
"if",
"the",
"comments",
"string",
"is",
"not",
"empty",
"."
] | 33d2968a49e1131825a0accdd64bdf9901cf144c | https://github.com/sourcegraph/go-langserver/blob/33d2968a49e1131825a0accdd64bdf9901cf144c/langserver/hover.go#L179-L186 | train |
sourcegraph/go-langserver | langserver/hover.go | joinCommentGroups | func joinCommentGroups(a, b *ast.CommentGroup) string {
aText := a.Text()
bText := b.Text()
if aText == "" {
return bText
} else if bText == "" {
return aText
} else {
return aText + "\n" + bText
}
} | go | func joinCommentGroups(a, b *ast.CommentGroup) string {
aText := a.Text()
bText := b.Text()
if aText == "" {
return bText
} else if bText == "" {
return aText
} else {
return aText + "\n" + bText
}
} | [
"func",
"joinCommentGroups",
"(",
"a",
",",
"b",
"*",
"ast",
".",
"CommentGroup",
")",
"string",
"{",
"aText",
":=",
"a",
".",
"Text",
"(",
")",
"\n",
"bText",
":=",
"b",
".",
"Text",
"(",
")",
"\n",
"if",
"aText",
"==",
"\"\"",
"{",
"return",
"b... | // joinCommentGroups joins the resultant non-empty comment text from two
// CommentGroups with a newline. | [
"joinCommentGroups",
"joins",
"the",
"resultant",
"non",
"-",
"empty",
"comment",
"text",
"from",
"two",
"CommentGroups",
"with",
"a",
"newline",
"."
] | 33d2968a49e1131825a0accdd64bdf9901cf144c | https://github.com/sourcegraph/go-langserver/blob/33d2968a49e1131825a0accdd64bdf9901cf144c/langserver/hover.go#L190-L200 | train |
sourcegraph/go-langserver | langserver/hover.go | packageDoc | func packageDoc(files []*ast.File, pkgName string) string {
for _, f := range files {
if f.Name.Name == pkgName {
txt := f.Doc.Text()
if strings.TrimSpace(txt) != "" {
return txt
}
}
}
return ""
} | go | func packageDoc(files []*ast.File, pkgName string) string {
for _, f := range files {
if f.Name.Name == pkgName {
txt := f.Doc.Text()
if strings.TrimSpace(txt) != "" {
return txt
}
}
}
return ""
} | [
"func",
"packageDoc",
"(",
"files",
"[",
"]",
"*",
"ast",
".",
"File",
",",
"pkgName",
"string",
")",
"string",
"{",
"for",
"_",
",",
"f",
":=",
"range",
"files",
"{",
"if",
"f",
".",
"Name",
".",
"Name",
"==",
"pkgName",
"{",
"txt",
":=",
"f",
... | // packageDoc finds the documentation for the named package from its files or
// additional files. | [
"packageDoc",
"finds",
"the",
"documentation",
"for",
"the",
"named",
"package",
"from",
"its",
"files",
"or",
"additional",
"files",
"."
] | 33d2968a49e1131825a0accdd64bdf9901cf144c | https://github.com/sourcegraph/go-langserver/blob/33d2968a49e1131825a0accdd64bdf9901cf144c/langserver/hover.go#L204-L214 | train |
sourcegraph/go-langserver | langserver/hover.go | builtinDoc | func builtinDoc(ident string) []lsp.MarkedString {
// Grab files from builtin package
pkgs, err := packages.Load(
&packages.Config{
Mode: packages.LoadFiles,
},
"builtin",
)
if err != nil {
return nil
}
// Parse the files into ASTs
pkg := pkgs[0]
fs := token.NewFileSet()
asts := &ast.Package{
Name: "builtin",
Files: make(map[string]*ast.File),
}
for _, filename := range pkg.GoFiles {
file, err := parser.ParseFile(fs, filename, nil, parser.ParseComments)
if err != nil {
fmt.Println(err.Error())
}
asts.Files[filename] = file
}
// Extract documentation and declaration from the ASTs
docs := doc.New(asts, "builtin", doc.AllDecls)
node, pos := findDocIdent(docs, ident)
contents, _ := fmtDocObject(fs, node, fs.Position(pos))
return contents
} | go | func builtinDoc(ident string) []lsp.MarkedString {
// Grab files from builtin package
pkgs, err := packages.Load(
&packages.Config{
Mode: packages.LoadFiles,
},
"builtin",
)
if err != nil {
return nil
}
// Parse the files into ASTs
pkg := pkgs[0]
fs := token.NewFileSet()
asts := &ast.Package{
Name: "builtin",
Files: make(map[string]*ast.File),
}
for _, filename := range pkg.GoFiles {
file, err := parser.ParseFile(fs, filename, nil, parser.ParseComments)
if err != nil {
fmt.Println(err.Error())
}
asts.Files[filename] = file
}
// Extract documentation and declaration from the ASTs
docs := doc.New(asts, "builtin", doc.AllDecls)
node, pos := findDocIdent(docs, ident)
contents, _ := fmtDocObject(fs, node, fs.Position(pos))
return contents
} | [
"func",
"builtinDoc",
"(",
"ident",
"string",
")",
"[",
"]",
"lsp",
".",
"MarkedString",
"{",
"pkgs",
",",
"err",
":=",
"packages",
".",
"Load",
"(",
"&",
"packages",
".",
"Config",
"{",
"Mode",
":",
"packages",
".",
"LoadFiles",
",",
"}",
",",
"\"bu... | // builtinDoc finds the documentation for a builtin node. | [
"builtinDoc",
"finds",
"the",
"documentation",
"for",
"a",
"builtin",
"node",
"."
] | 33d2968a49e1131825a0accdd64bdf9901cf144c | https://github.com/sourcegraph/go-langserver/blob/33d2968a49e1131825a0accdd64bdf9901cf144c/langserver/hover.go#L217-L249 | train |
sourcegraph/go-langserver | langserver/hover.go | packageForFile | func packageForFile(pkgs map[string]*ast.Package, filename string) (string, *ast.Package, error) {
for path, pkg := range pkgs {
for pkgFile := range pkg.Files {
if pkgFile == filename {
return path, pkg, nil
}
}
}
return "", nil, fmt.Errorf("failed to find %q in packages %q", filename, pkgs)
} | go | func packageForFile(pkgs map[string]*ast.Package, filename string) (string, *ast.Package, error) {
for path, pkg := range pkgs {
for pkgFile := range pkg.Files {
if pkgFile == filename {
return path, pkg, nil
}
}
}
return "", nil, fmt.Errorf("failed to find %q in packages %q", filename, pkgs)
} | [
"func",
"packageForFile",
"(",
"pkgs",
"map",
"[",
"string",
"]",
"*",
"ast",
".",
"Package",
",",
"filename",
"string",
")",
"(",
"string",
",",
"*",
"ast",
".",
"Package",
",",
"error",
")",
"{",
"for",
"path",
",",
"pkg",
":=",
"range",
"pkgs",
... | // packageForFile returns the import path and pkg from pkgs that contains the
// named file. | [
"packageForFile",
"returns",
"the",
"import",
"path",
"and",
"pkg",
"from",
"pkgs",
"that",
"contains",
"the",
"named",
"file",
"."
] | 33d2968a49e1131825a0accdd64bdf9901cf144c | https://github.com/sourcegraph/go-langserver/blob/33d2968a49e1131825a0accdd64bdf9901cf144c/langserver/hover.go#L495-L504 | train |
sourcegraph/go-langserver | langserver/hover.go | inRange | func inRange(x, a, b token.Position) bool {
if !util.PathEqual(x.Filename, a.Filename) || !util.PathEqual(x.Filename, b.Filename) {
return false
}
return x.Offset >= a.Offset && x.Offset <= b.Offset
} | go | func inRange(x, a, b token.Position) bool {
if !util.PathEqual(x.Filename, a.Filename) || !util.PathEqual(x.Filename, b.Filename) {
return false
}
return x.Offset >= a.Offset && x.Offset <= b.Offset
} | [
"func",
"inRange",
"(",
"x",
",",
"a",
",",
"b",
"token",
".",
"Position",
")",
"bool",
"{",
"if",
"!",
"util",
".",
"PathEqual",
"(",
"x",
".",
"Filename",
",",
"a",
".",
"Filename",
")",
"||",
"!",
"util",
".",
"PathEqual",
"(",
"x",
".",
"Fi... | // inRange tells if x is in the range of a-b inclusive. | [
"inRange",
"tells",
"if",
"x",
"is",
"in",
"the",
"range",
"of",
"a",
"-",
"b",
"inclusive",
"."
] | 33d2968a49e1131825a0accdd64bdf9901cf144c | https://github.com/sourcegraph/go-langserver/blob/33d2968a49e1131825a0accdd64bdf9901cf144c/langserver/hover.go#L507-L512 | train |
sourcegraph/go-langserver | langserver/hover.go | fmtNode | func fmtNode(fset *token.FileSet, n ast.Node) string {
var buf bytes.Buffer
err := format.Node(&buf, fset, n)
if err != nil {
panic("unreachable")
}
return buf.String()
} | go | func fmtNode(fset *token.FileSet, n ast.Node) string {
var buf bytes.Buffer
err := format.Node(&buf, fset, n)
if err != nil {
panic("unreachable")
}
return buf.String()
} | [
"func",
"fmtNode",
"(",
"fset",
"*",
"token",
".",
"FileSet",
",",
"n",
"ast",
".",
"Node",
")",
"string",
"{",
"var",
"buf",
"bytes",
".",
"Buffer",
"\n",
"err",
":=",
"format",
".",
"Node",
"(",
"&",
"buf",
",",
"fset",
",",
"n",
")",
"\n",
"... | // fmtNode formats the given node as a string. | [
"fmtNode",
"formats",
"the",
"given",
"node",
"as",
"a",
"string",
"."
] | 33d2968a49e1131825a0accdd64bdf9901cf144c | https://github.com/sourcegraph/go-langserver/blob/33d2968a49e1131825a0accdd64bdf9901cf144c/langserver/hover.go#L671-L678 | train |
sourcegraph/go-langserver | langserver/internal/refs/refs.go | dereferenceType | func dereferenceType(otyp types.Type) types.Type {
for {
switch typ := otyp.(type) {
case *types.Map:
return otyp
case dereferencable:
otyp = typ.Elem()
default:
return otyp
}
}
} | go | func dereferenceType(otyp types.Type) types.Type {
for {
switch typ := otyp.(type) {
case *types.Map:
return otyp
case dereferencable:
otyp = typ.Elem()
default:
return otyp
}
}
} | [
"func",
"dereferenceType",
"(",
"otyp",
"types",
".",
"Type",
")",
"types",
".",
"Type",
"{",
"for",
"{",
"switch",
"typ",
":=",
"otyp",
".",
"(",
"type",
")",
"{",
"case",
"*",
"types",
".",
"Map",
":",
"return",
"otyp",
"\n",
"case",
"dereferencabl... | // dereferenceType finds the "root" type of a thing, meaning
// the type pointed-to by a pointer, the element type of
// a slice or array, or the object type of a chan. The special
// case for Map is because a Map would also have a key, and
// you might be interested in either of those. | [
"dereferenceType",
"finds",
"the",
"root",
"type",
"of",
"a",
"thing",
"meaning",
"the",
"type",
"pointed",
"-",
"to",
"by",
"a",
"pointer",
"the",
"element",
"type",
"of",
"a",
"slice",
"or",
"array",
"or",
"the",
"object",
"type",
"of",
"a",
"chan",
... | 33d2968a49e1131825a0accdd64bdf9901cf144c | https://github.com/sourcegraph/go-langserver/blob/33d2968a49e1131825a0accdd64bdf9901cf144c/langserver/internal/refs/refs.go#L316-L327 | train |
sourcegraph/go-langserver | langserver/workspace_refs.go | workspaceRefsFromPkg | func (h *LangHandler) workspaceRefsFromPkg(ctx context.Context, bctx *build.Context, conn jsonrpc2.JSONRPC2, params lspext.WorkspaceReferencesParams, fs *token.FileSet, pkg *loader.PackageInfo, files []*ast.File, rootPath string, results *refResult) (err error) {
if err := ctx.Err(); err != nil {
return err
}
span, ctx := opentracing.StartSpanFromContext(ctx, "workspaceRefsFromPkg")
defer func() {
if err != nil {
ext.Error.Set(span, true)
span.SetTag("err", err.Error())
}
span.Finish()
}()
span.SetTag("pkg", pkg)
// Compute workspace references.
findPackage := h.getFindPackageFunc()
cfg := &refs.Config{
FileSet: fs,
Pkg: pkg.Pkg,
PkgFiles: files,
Info: &pkg.Info,
}
refsErr := cfg.Refs(func(r *refs.Ref) {
symDesc, err := defSymbolDescriptor(ctx, bctx, rootPath, r.Def, findPackage)
if err != nil {
// Log the error, and flag it as one in the trace -- but do not
// halt execution (hopefully, it is limited to a small subset of
// the data).
ext.Error.Set(span, true)
err := fmt.Errorf("workspaceRefsFromPkg: failed to import %v: %v", r.Def.ImportPath, err)
log.Println(err)
span.SetTag("error", err.Error())
return
}
if !symDesc.Contains(params.Query) {
return
}
results.resultsMu.Lock()
results.results = append(results.results, referenceInformation{
Reference: goRangeToLSPLocation(fs, r.Start, r.End),
Symbol: symDesc,
})
results.resultsMu.Unlock()
})
if refsErr != nil {
// Trace the error, but do not consider it a true error. In many cases
// it is a problem with the user's code, not our workspace reference
// finding code.
span.SetTag("err", fmt.Sprintf("workspaceRefsFromPkg: workspace refs failed: %v: %v", pkg, refsErr))
}
return nil
} | go | func (h *LangHandler) workspaceRefsFromPkg(ctx context.Context, bctx *build.Context, conn jsonrpc2.JSONRPC2, params lspext.WorkspaceReferencesParams, fs *token.FileSet, pkg *loader.PackageInfo, files []*ast.File, rootPath string, results *refResult) (err error) {
if err := ctx.Err(); err != nil {
return err
}
span, ctx := opentracing.StartSpanFromContext(ctx, "workspaceRefsFromPkg")
defer func() {
if err != nil {
ext.Error.Set(span, true)
span.SetTag("err", err.Error())
}
span.Finish()
}()
span.SetTag("pkg", pkg)
// Compute workspace references.
findPackage := h.getFindPackageFunc()
cfg := &refs.Config{
FileSet: fs,
Pkg: pkg.Pkg,
PkgFiles: files,
Info: &pkg.Info,
}
refsErr := cfg.Refs(func(r *refs.Ref) {
symDesc, err := defSymbolDescriptor(ctx, bctx, rootPath, r.Def, findPackage)
if err != nil {
// Log the error, and flag it as one in the trace -- but do not
// halt execution (hopefully, it is limited to a small subset of
// the data).
ext.Error.Set(span, true)
err := fmt.Errorf("workspaceRefsFromPkg: failed to import %v: %v", r.Def.ImportPath, err)
log.Println(err)
span.SetTag("error", err.Error())
return
}
if !symDesc.Contains(params.Query) {
return
}
results.resultsMu.Lock()
results.results = append(results.results, referenceInformation{
Reference: goRangeToLSPLocation(fs, r.Start, r.End),
Symbol: symDesc,
})
results.resultsMu.Unlock()
})
if refsErr != nil {
// Trace the error, but do not consider it a true error. In many cases
// it is a problem with the user's code, not our workspace reference
// finding code.
span.SetTag("err", fmt.Sprintf("workspaceRefsFromPkg: workspace refs failed: %v: %v", pkg, refsErr))
}
return nil
} | [
"func",
"(",
"h",
"*",
"LangHandler",
")",
"workspaceRefsFromPkg",
"(",
"ctx",
"context",
".",
"Context",
",",
"bctx",
"*",
"build",
".",
"Context",
",",
"conn",
"jsonrpc2",
".",
"JSONRPC2",
",",
"params",
"lspext",
".",
"WorkspaceReferencesParams",
",",
"fs... | // workspaceRefsFromPkg collects all the references made to dependencies from
// the specified package and returns the results. | [
"workspaceRefsFromPkg",
"collects",
"all",
"the",
"references",
"made",
"to",
"dependencies",
"from",
"the",
"specified",
"package",
"and",
"returns",
"the",
"results",
"."
] | 33d2968a49e1131825a0accdd64bdf9901cf144c | https://github.com/sourcegraph/go-langserver/blob/33d2968a49e1131825a0accdd64bdf9901cf144c/langserver/workspace_refs.go#L282-L334 | train |
sourcegraph/go-langserver | langserver/internal/godef/godef.go | parseLocalPackage | func parseLocalPackage(fset *token.FileSet, filename string, src *ast.File, pkgScope *ast.Scope, pathToName parser.ImportPathToName) (*ast.Package, error) {
pkg := &ast.Package{src.Name.Name, pkgScope, nil, map[string]*ast.File{filename: src}}
d, f := filepath.Split(filename)
if d == "" {
d = "./"
}
fd, err := os.Open(d)
if err != nil {
return nil, err
}
defer fd.Close()
list, err := fd.Readdirnames(-1)
if err != nil {
return nil, errNoPkgFiles
}
for _, pf := range list {
file := filepath.Join(d, pf)
if !strings.HasSuffix(pf, ".go") ||
pf == f ||
pkgName(fset, file) != pkg.Name {
continue
}
src, err := parser.ParseFile(fset, file, nil, 0, pkg.Scope, types.DefaultImportPathToName)
if err == nil {
pkg.Files[file] = src
}
}
if len(pkg.Files) == 1 {
return nil, errNoPkgFiles
}
return pkg, nil
} | go | func parseLocalPackage(fset *token.FileSet, filename string, src *ast.File, pkgScope *ast.Scope, pathToName parser.ImportPathToName) (*ast.Package, error) {
pkg := &ast.Package{src.Name.Name, pkgScope, nil, map[string]*ast.File{filename: src}}
d, f := filepath.Split(filename)
if d == "" {
d = "./"
}
fd, err := os.Open(d)
if err != nil {
return nil, err
}
defer fd.Close()
list, err := fd.Readdirnames(-1)
if err != nil {
return nil, errNoPkgFiles
}
for _, pf := range list {
file := filepath.Join(d, pf)
if !strings.HasSuffix(pf, ".go") ||
pf == f ||
pkgName(fset, file) != pkg.Name {
continue
}
src, err := parser.ParseFile(fset, file, nil, 0, pkg.Scope, types.DefaultImportPathToName)
if err == nil {
pkg.Files[file] = src
}
}
if len(pkg.Files) == 1 {
return nil, errNoPkgFiles
}
return pkg, nil
} | [
"func",
"parseLocalPackage",
"(",
"fset",
"*",
"token",
".",
"FileSet",
",",
"filename",
"string",
",",
"src",
"*",
"ast",
".",
"File",
",",
"pkgScope",
"*",
"ast",
".",
"Scope",
",",
"pathToName",
"parser",
".",
"ImportPathToName",
")",
"(",
"*",
"ast",... | // parseLocalPackage reads and parses all go files from the
// current directory that implement the same package name
// the principal source file, except the original source file
// itself, which will already have been parsed.
// | [
"parseLocalPackage",
"reads",
"and",
"parses",
"all",
"go",
"files",
"from",
"the",
"current",
"directory",
"that",
"implement",
"the",
"same",
"package",
"name",
"the",
"principal",
"source",
"file",
"except",
"the",
"original",
"source",
"file",
"itself",
"whi... | 33d2968a49e1131825a0accdd64bdf9901cf144c | https://github.com/sourcegraph/go-langserver/blob/33d2968a49e1131825a0accdd64bdf9901cf144c/langserver/internal/godef/godef.go#L197-L230 | train |
sourcegraph/go-langserver | langserver/internal/godef/godef.go | pkgName | func pkgName(fset *token.FileSet, filename string) string {
prog, _ := parser.ParseFile(fset, filename, nil, parser.PackageClauseOnly, nil, types.DefaultImportPathToName)
if prog != nil {
return prog.Name.Name
}
return ""
} | go | func pkgName(fset *token.FileSet, filename string) string {
prog, _ := parser.ParseFile(fset, filename, nil, parser.PackageClauseOnly, nil, types.DefaultImportPathToName)
if prog != nil {
return prog.Name.Name
}
return ""
} | [
"func",
"pkgName",
"(",
"fset",
"*",
"token",
".",
"FileSet",
",",
"filename",
"string",
")",
"string",
"{",
"prog",
",",
"_",
":=",
"parser",
".",
"ParseFile",
"(",
"fset",
",",
"filename",
",",
"nil",
",",
"parser",
".",
"PackageClauseOnly",
",",
"ni... | // pkgName returns the package name implemented by the
// go source filename.
// | [
"pkgName",
"returns",
"the",
"package",
"name",
"implemented",
"by",
"the",
"go",
"source",
"filename",
"."
] | 33d2968a49e1131825a0accdd64bdf9901cf144c | https://github.com/sourcegraph/go-langserver/blob/33d2968a49e1131825a0accdd64bdf9901cf144c/langserver/internal/godef/godef.go#L235-L241 | train |
sourcegraph/go-langserver | langserver/internal/godef/go/parser/interface.go | ParseExpr | func ParseExpr(fset *token.FileSet, filename string, src interface{}, scope *ast.Scope, pathToName ImportPathToName) (ast.Expr, error) {
data, err := readSource(filename, src)
if err != nil {
return nil, err
}
var p parser
p.init(fset, filename, data, 0, scope, pathToName)
x := p.parseExpr()
if p.tok == token.SEMICOLON {
p.next() // consume automatically inserted semicolon, if any
}
return x, p.parseEOF()
} | go | func ParseExpr(fset *token.FileSet, filename string, src interface{}, scope *ast.Scope, pathToName ImportPathToName) (ast.Expr, error) {
data, err := readSource(filename, src)
if err != nil {
return nil, err
}
var p parser
p.init(fset, filename, data, 0, scope, pathToName)
x := p.parseExpr()
if p.tok == token.SEMICOLON {
p.next() // consume automatically inserted semicolon, if any
}
return x, p.parseEOF()
} | [
"func",
"ParseExpr",
"(",
"fset",
"*",
"token",
".",
"FileSet",
",",
"filename",
"string",
",",
"src",
"interface",
"{",
"}",
",",
"scope",
"*",
"ast",
".",
"Scope",
",",
"pathToName",
"ImportPathToName",
")",
"(",
"ast",
".",
"Expr",
",",
"error",
")"... | // ParseExpr parses a Go expression and returns the corresponding
// AST node. The fset, filename, and src arguments have the same interpretation
// as for ParseFile. If there is an error, the result expression
// may be nil or contain a partial AST.
//
// if scope is non-nil, it will be used as the scope for the expression.
// | [
"ParseExpr",
"parses",
"a",
"Go",
"expression",
"and",
"returns",
"the",
"corresponding",
"AST",
"node",
".",
"The",
"fset",
"filename",
"and",
"src",
"arguments",
"have",
"the",
"same",
"interpretation",
"as",
"for",
"ParseFile",
".",
"If",
"there",
"is",
"... | 33d2968a49e1131825a0accdd64bdf9901cf144c | https://github.com/sourcegraph/go-langserver/blob/33d2968a49e1131825a0accdd64bdf9901cf144c/langserver/internal/godef/go/parser/interface.go#L72-L85 | train |
sourcegraph/go-langserver | langserver/internal/godef/go/parser/interface.go | ParseDir | func ParseDir(fset *token.FileSet, path string, filter func(os.FileInfo) bool, mode uint, pathToName ImportPathToName) (map[string]*ast.Package, error) {
fd, err := os.Open(path)
if err != nil {
return nil, err
}
defer fd.Close()
list, err := fd.Readdir(-1)
if err != nil {
return nil, err
}
filenames := make([]string, len(list))
n := 0
for i := 0; i < len(list); i++ {
d := list[i]
if filter == nil || filter(d) {
filenames[n] = filepath.Join(path, d.Name())
n++
}
}
filenames = filenames[0:n]
return ParseFiles(fset, filenames, mode, pathToName)
} | go | func ParseDir(fset *token.FileSet, path string, filter func(os.FileInfo) bool, mode uint, pathToName ImportPathToName) (map[string]*ast.Package, error) {
fd, err := os.Open(path)
if err != nil {
return nil, err
}
defer fd.Close()
list, err := fd.Readdir(-1)
if err != nil {
return nil, err
}
filenames := make([]string, len(list))
n := 0
for i := 0; i < len(list); i++ {
d := list[i]
if filter == nil || filter(d) {
filenames[n] = filepath.Join(path, d.Name())
n++
}
}
filenames = filenames[0:n]
return ParseFiles(fset, filenames, mode, pathToName)
} | [
"func",
"ParseDir",
"(",
"fset",
"*",
"token",
".",
"FileSet",
",",
"path",
"string",
",",
"filter",
"func",
"(",
"os",
".",
"FileInfo",
")",
"bool",
",",
"mode",
"uint",
",",
"pathToName",
"ImportPathToName",
")",
"(",
"map",
"[",
"string",
"]",
"*",
... | // ParseDir calls ParseFile for the files in the directory specified by path and
// returns a map of package name -> package AST with all the packages found. If
// filter != nil, only the files with os.FileInfo entries passing through the filter
// are considered. The mode bits are passed to ParseFile unchanged. Position
// information is recorded in the file set fset.
//
// If the directory couldn't be read, a nil map and the respective error are
// returned. If a parse error occurred, a non-nil but incomplete map and the
// error are returned.
// | [
"ParseDir",
"calls",
"ParseFile",
"for",
"the",
"files",
"in",
"the",
"directory",
"specified",
"by",
"path",
"and",
"returns",
"a",
"map",
"of",
"package",
"name",
"-",
">",
"package",
"AST",
"with",
"all",
"the",
"packages",
"found",
".",
"If",
"filter",... | 33d2968a49e1131825a0accdd64bdf9901cf144c | https://github.com/sourcegraph/go-langserver/blob/33d2968a49e1131825a0accdd64bdf9901cf144c/langserver/internal/godef/go/parser/interface.go#L176-L200 | train |
sourcegraph/go-langserver | vfsutil/github_archive.go | NewGitHubRepoVFS | func NewGitHubRepoVFS(ctx context.Context, repo, rev string) (*ArchiveFS, error) {
if !githubRepoRx.MatchString(repo) {
return nil, fmt.Errorf(`invalid GitHub repo %q: must be "github.com/user/repo"`, repo)
}
url := fmt.Sprintf("https://codeload.%s/zip/%s", repo, rev)
return NewZipVFS(ctx, url, ghFetch.Inc, ghFetchFailed.Inc, false)
} | go | func NewGitHubRepoVFS(ctx context.Context, repo, rev string) (*ArchiveFS, error) {
if !githubRepoRx.MatchString(repo) {
return nil, fmt.Errorf(`invalid GitHub repo %q: must be "github.com/user/repo"`, repo)
}
url := fmt.Sprintf("https://codeload.%s/zip/%s", repo, rev)
return NewZipVFS(ctx, url, ghFetch.Inc, ghFetchFailed.Inc, false)
} | [
"func",
"NewGitHubRepoVFS",
"(",
"ctx",
"context",
".",
"Context",
",",
"repo",
",",
"rev",
"string",
")",
"(",
"*",
"ArchiveFS",
",",
"error",
")",
"{",
"if",
"!",
"githubRepoRx",
".",
"MatchString",
"(",
"repo",
")",
"{",
"return",
"nil",
",",
"fmt",... | // NewGitHubRepoVFS creates a new VFS backed by a GitHub downloadable
// repository archive. | [
"NewGitHubRepoVFS",
"creates",
"a",
"new",
"VFS",
"backed",
"by",
"a",
"GitHub",
"downloadable",
"repository",
"archive",
"."
] | 33d2968a49e1131825a0accdd64bdf9901cf144c | https://github.com/sourcegraph/go-langserver/blob/33d2968a49e1131825a0accdd64bdf9901cf144c/vfsutil/github_archive.go#L13-L20 | train |
sourcegraph/go-langserver | langserver/build_context.go | BuildContext | func (h *LangHandler) BuildContext(ctx context.Context) *build.Context {
var bctx *build.Context
if override := h.init.BuildContext; override != nil {
bctx = &build.Context{
GOOS: override.GOOS,
GOARCH: override.GOARCH,
GOPATH: override.GOPATH,
GOROOT: override.GOROOT,
CgoEnabled: override.CgoEnabled,
UseAllFiles: override.UseAllFiles,
Compiler: override.Compiler,
BuildTags: override.BuildTags,
// Enable analysis of all go version build tags that
// our compiler should understand.
ReleaseTags: build.Default.ReleaseTags,
}
} else {
// make a copy since we will mutate it
copy := build.Default
bctx = ©
}
h.Mu.Lock()
fs := h.FS
h.Mu.Unlock()
util.PrepareContext(bctx, ctx, fs)
return bctx
} | go | func (h *LangHandler) BuildContext(ctx context.Context) *build.Context {
var bctx *build.Context
if override := h.init.BuildContext; override != nil {
bctx = &build.Context{
GOOS: override.GOOS,
GOARCH: override.GOARCH,
GOPATH: override.GOPATH,
GOROOT: override.GOROOT,
CgoEnabled: override.CgoEnabled,
UseAllFiles: override.UseAllFiles,
Compiler: override.Compiler,
BuildTags: override.BuildTags,
// Enable analysis of all go version build tags that
// our compiler should understand.
ReleaseTags: build.Default.ReleaseTags,
}
} else {
// make a copy since we will mutate it
copy := build.Default
bctx = ©
}
h.Mu.Lock()
fs := h.FS
h.Mu.Unlock()
util.PrepareContext(bctx, ctx, fs)
return bctx
} | [
"func",
"(",
"h",
"*",
"LangHandler",
")",
"BuildContext",
"(",
"ctx",
"context",
".",
"Context",
")",
"*",
"build",
".",
"Context",
"{",
"var",
"bctx",
"*",
"build",
".",
"Context",
"\n",
"if",
"override",
":=",
"h",
".",
"init",
".",
"BuildContext",
... | // BuildContext creates a build.Context which uses the overlay FS and the InitializeParams.BuildContext overrides. | [
"BuildContext",
"creates",
"a",
"build",
".",
"Context",
"which",
"uses",
"the",
"overlay",
"FS",
"and",
"the",
"InitializeParams",
".",
"BuildContext",
"overrides",
"."
] | 33d2968a49e1131825a0accdd64bdf9901cf144c | https://github.com/sourcegraph/go-langserver/blob/33d2968a49e1131825a0accdd64bdf9901cf144c/langserver/build_context.go#L18-L47 | train |
sourcegraph/go-langserver | buildserver/deps_refs.go | references | func (d *depCache) references(emitRef func(path string, r goDependencyReference), depthLimit int) {
// Example import graph with edge cases:
//
// '/' (root)
// |
// a
// |\
// b c
// \|
// .>. d <<<<<<.
// | \ / \ | |
// .<< e f >>^ |
// | |
// f >>>>>>>>^
//
// Although Go does not allow such cyclic import graphs, we must handle
// them here due to the fact that we aggregate imports for all packages in
// a directory (e.g. including xtest files, which can import the package
// path itself).
// orderedEmit emits the dependency references found in m as being
// referenced by the given path. The only difference from emitRef is that
// the emissions are in a sorted order rather than in random map order.
orderedEmit := func(path string, m map[string]goDependencyReference) {
keys := make([]string, 0, len(m))
for k := range m {
keys = append(keys, k)
}
sort.Strings(keys)
for _, k := range keys {
emitRef(path, m[k])
}
}
// Prepare a function to walk every package node in the above example graph.
beganWalk := map[string]struct{}{}
var walk func(rootDir, pkgDir string, parentDirs []string, emissions map[string]goDependencyReference, depth int)
walk = func(rootDir, pkgDir string, parentDirs []string, emissions map[string]goDependencyReference, depth int) {
if depth >= depthLimit {
return
}
// The imports are recorded in parallel by goroutines in doDeps, so we
// must sort them in order to get a stable output order.
imports := d.seen[pkgDir]
sort.Sort(sortedImportRecord(imports))
for _, imp := range imports {
// At this point we know that `imp.pkg.ImportPath` has imported
// `imp.imports.ImportPath`.
// If the package being referenced is the package itself, i.e. the
// package tried to import itself, do not walk any further.
if imp.pkg.Dir == imp.imports.Dir {
continue
}
// If the package being referenced is itself one of our parent
// packages, then we have hit a cyclic dependency and should not
// walk any further.
cyclic := false
for _, parentDir := range parentDirs {
if parentDir == imp.imports.Dir {
cyclic = true
break
}
}
if cyclic {
continue
}
// Walk the referenced dependency so that we emit transitive
// dependencies.
walk(rootDir, imp.imports.Dir, append(parentDirs, pkgDir), emissions, depth+1)
// If the dependency being referenced has not already been walked
// individually / on its own, do so now.
_, began := beganWalk[imp.imports.Dir]
if !began {
beganWalk[imp.imports.Dir] = struct{}{}
childEmissions := map[string]goDependencyReference{}
walk(imp.imports.Dir, imp.imports.Dir, append(parentDirs, pkgDir), childEmissions, 0)
orderedEmit(imp.imports.Dir, childEmissions)
}
// If the new emissions for the import path would have a greater
// depth, then do not overwrite the old emission. This ensures that
// for a single package which is referenced we always get the
// closest (smallest) depth value.
if existing, ok := emissions[imp.imports.ImportPath]; ok {
if existing.depth < depth {
return
}
}
emissions[imp.imports.ImportPath] = goDependencyReference{
pkg: unvendoredPath(imp.imports.ImportPath),
absolute: imp.imports.ImportPath,
vendor: util.IsVendorDir(imp.imports.Dir),
depth: depth,
}
}
}
sort.Strings(d.entryPackageDirs)
for _, entryDir := range d.entryPackageDirs {
emissions := map[string]goDependencyReference{}
walk(entryDir, entryDir, nil, emissions, 0)
orderedEmit(entryDir, emissions)
}
} | go | func (d *depCache) references(emitRef func(path string, r goDependencyReference), depthLimit int) {
// Example import graph with edge cases:
//
// '/' (root)
// |
// a
// |\
// b c
// \|
// .>. d <<<<<<.
// | \ / \ | |
// .<< e f >>^ |
// | |
// f >>>>>>>>^
//
// Although Go does not allow such cyclic import graphs, we must handle
// them here due to the fact that we aggregate imports for all packages in
// a directory (e.g. including xtest files, which can import the package
// path itself).
// orderedEmit emits the dependency references found in m as being
// referenced by the given path. The only difference from emitRef is that
// the emissions are in a sorted order rather than in random map order.
orderedEmit := func(path string, m map[string]goDependencyReference) {
keys := make([]string, 0, len(m))
for k := range m {
keys = append(keys, k)
}
sort.Strings(keys)
for _, k := range keys {
emitRef(path, m[k])
}
}
// Prepare a function to walk every package node in the above example graph.
beganWalk := map[string]struct{}{}
var walk func(rootDir, pkgDir string, parentDirs []string, emissions map[string]goDependencyReference, depth int)
walk = func(rootDir, pkgDir string, parentDirs []string, emissions map[string]goDependencyReference, depth int) {
if depth >= depthLimit {
return
}
// The imports are recorded in parallel by goroutines in doDeps, so we
// must sort them in order to get a stable output order.
imports := d.seen[pkgDir]
sort.Sort(sortedImportRecord(imports))
for _, imp := range imports {
// At this point we know that `imp.pkg.ImportPath` has imported
// `imp.imports.ImportPath`.
// If the package being referenced is the package itself, i.e. the
// package tried to import itself, do not walk any further.
if imp.pkg.Dir == imp.imports.Dir {
continue
}
// If the package being referenced is itself one of our parent
// packages, then we have hit a cyclic dependency and should not
// walk any further.
cyclic := false
for _, parentDir := range parentDirs {
if parentDir == imp.imports.Dir {
cyclic = true
break
}
}
if cyclic {
continue
}
// Walk the referenced dependency so that we emit transitive
// dependencies.
walk(rootDir, imp.imports.Dir, append(parentDirs, pkgDir), emissions, depth+1)
// If the dependency being referenced has not already been walked
// individually / on its own, do so now.
_, began := beganWalk[imp.imports.Dir]
if !began {
beganWalk[imp.imports.Dir] = struct{}{}
childEmissions := map[string]goDependencyReference{}
walk(imp.imports.Dir, imp.imports.Dir, append(parentDirs, pkgDir), childEmissions, 0)
orderedEmit(imp.imports.Dir, childEmissions)
}
// If the new emissions for the import path would have a greater
// depth, then do not overwrite the old emission. This ensures that
// for a single package which is referenced we always get the
// closest (smallest) depth value.
if existing, ok := emissions[imp.imports.ImportPath]; ok {
if existing.depth < depth {
return
}
}
emissions[imp.imports.ImportPath] = goDependencyReference{
pkg: unvendoredPath(imp.imports.ImportPath),
absolute: imp.imports.ImportPath,
vendor: util.IsVendorDir(imp.imports.Dir),
depth: depth,
}
}
}
sort.Strings(d.entryPackageDirs)
for _, entryDir := range d.entryPackageDirs {
emissions := map[string]goDependencyReference{}
walk(entryDir, entryDir, nil, emissions, 0)
orderedEmit(entryDir, emissions)
}
} | [
"func",
"(",
"d",
"*",
"depCache",
")",
"references",
"(",
"emitRef",
"func",
"(",
"path",
"string",
",",
"r",
"goDependencyReference",
")",
",",
"depthLimit",
"int",
")",
"{",
"orderedEmit",
":=",
"func",
"(",
"path",
"string",
",",
"m",
"map",
"[",
"... | // references calls emitRef on each transitive package that has been seen by
// the dependency cache. The parameters say that the Go package directory `path`
// has imported the Go package described by r. | [
"references",
"calls",
"emitRef",
"on",
"each",
"transitive",
"package",
"that",
"has",
"been",
"seen",
"by",
"the",
"dependency",
"cache",
".",
"The",
"parameters",
"say",
"that",
"the",
"Go",
"package",
"directory",
"path",
"has",
"imported",
"the",
"Go",
... | 33d2968a49e1131825a0accdd64bdf9901cf144c | https://github.com/sourcegraph/go-langserver/blob/33d2968a49e1131825a0accdd64bdf9901cf144c/buildserver/deps_refs.go#L60-L168 | train |
sourcegraph/go-langserver | langserver/internal/godef/go/parser/parser.go | resolve | func (p *parser) resolve(ident *ast.Ident) {
if ident.Name == "_" {
return
}
// try to resolve the identifier
for s := p.topScope; s != nil; s = s.Outer {
if obj := s.Lookup(ident.Name); obj != nil {
ident.Obj = obj
return
}
}
if p.pkgScope == nil {
return
}
ident.Obj = ast.NewObj(ast.Bad, ident.Name)
p.pkgScope.Insert(ident.Obj)
} | go | func (p *parser) resolve(ident *ast.Ident) {
if ident.Name == "_" {
return
}
// try to resolve the identifier
for s := p.topScope; s != nil; s = s.Outer {
if obj := s.Lookup(ident.Name); obj != nil {
ident.Obj = obj
return
}
}
if p.pkgScope == nil {
return
}
ident.Obj = ast.NewObj(ast.Bad, ident.Name)
p.pkgScope.Insert(ident.Obj)
} | [
"func",
"(",
"p",
"*",
"parser",
")",
"resolve",
"(",
"ident",
"*",
"ast",
".",
"Ident",
")",
"{",
"if",
"ident",
".",
"Name",
"==",
"\"_\"",
"{",
"return",
"\n",
"}",
"\n",
"for",
"s",
":=",
"p",
".",
"topScope",
";",
"s",
"!=",
"nil",
";",
... | // newIdent returns a new identifier with attached Object.
// If no Object currently exists for the identifier, it is
// created in package scope. | [
"newIdent",
"returns",
"a",
"new",
"identifier",
"with",
"attached",
"Object",
".",
"If",
"no",
"Object",
"currently",
"exists",
"for",
"the",
"identifier",
"it",
"is",
"created",
"in",
"package",
"scope",
"."
] | 33d2968a49e1131825a0accdd64bdf9901cf144c | https://github.com/sourcegraph/go-langserver/blob/33d2968a49e1131825a0accdd64bdf9901cf144c/langserver/internal/godef/go/parser/parser.go#L280-L296 | train |
sourcegraph/go-langserver | langserver/internal/godef/go/parser/parser.go | next0 | func (p *parser) next0() {
// Because of one-token look-ahead, print the previous token
// when tracing as it provides a more readable output. The
// very first token (!p.pos.IsValid()) is not initialized
// (it is token.ILLEGAL), so don't print it .
if p.trace && p.pos.IsValid() {
s := p.tok.String()
switch {
case p.tok.IsLiteral():
p.printTrace(s, string(p.lit))
case p.tok.IsOperator(), p.tok.IsKeyword():
p.printTrace("\"" + s + "\"")
default:
p.printTrace(s)
}
}
p.pos, p.tok, p.lit = p.scanner.Scan()
} | go | func (p *parser) next0() {
// Because of one-token look-ahead, print the previous token
// when tracing as it provides a more readable output. The
// very first token (!p.pos.IsValid()) is not initialized
// (it is token.ILLEGAL), so don't print it .
if p.trace && p.pos.IsValid() {
s := p.tok.String()
switch {
case p.tok.IsLiteral():
p.printTrace(s, string(p.lit))
case p.tok.IsOperator(), p.tok.IsKeyword():
p.printTrace("\"" + s + "\"")
default:
p.printTrace(s)
}
}
p.pos, p.tok, p.lit = p.scanner.Scan()
} | [
"func",
"(",
"p",
"*",
"parser",
")",
"next0",
"(",
")",
"{",
"if",
"p",
".",
"trace",
"&&",
"p",
".",
"pos",
".",
"IsValid",
"(",
")",
"{",
"s",
":=",
"p",
".",
"tok",
".",
"String",
"(",
")",
"\n",
"switch",
"{",
"case",
"p",
".",
"tok",
... | // Advance to the next token. | [
"Advance",
"to",
"the",
"next",
"token",
"."
] | 33d2968a49e1131825a0accdd64bdf9901cf144c | https://github.com/sourcegraph/go-langserver/blob/33d2968a49e1131825a0accdd64bdf9901cf144c/langserver/internal/godef/go/parser/parser.go#L328-L346 | train |
sourcegraph/go-langserver | langserver/internal/godef/go/parser/parser.go | consumeComment | func (p *parser) consumeComment() (comment *ast.Comment, endline int) {
// /*-style comments may end on a different line than where they start.
// Scan the comment for '\n' chars and adjust endline accordingly.
endline = p.file.Line(p.pos)
if p.lit[1] == '*' {
for _, b := range p.lit {
if b == '\n' {
endline++
}
}
}
comment = &ast.Comment{p.pos, p.lit}
p.next0()
return
} | go | func (p *parser) consumeComment() (comment *ast.Comment, endline int) {
// /*-style comments may end on a different line than where they start.
// Scan the comment for '\n' chars and adjust endline accordingly.
endline = p.file.Line(p.pos)
if p.lit[1] == '*' {
for _, b := range p.lit {
if b == '\n' {
endline++
}
}
}
comment = &ast.Comment{p.pos, p.lit}
p.next0()
return
} | [
"func",
"(",
"p",
"*",
"parser",
")",
"consumeComment",
"(",
")",
"(",
"comment",
"*",
"ast",
".",
"Comment",
",",
"endline",
"int",
")",
"{",
"endline",
"=",
"p",
".",
"file",
".",
"Line",
"(",
"p",
".",
"pos",
")",
"\n",
"if",
"p",
".",
"lit"... | // Consume a comment and return it and the line on which it ends. | [
"Consume",
"a",
"comment",
"and",
"return",
"it",
"and",
"the",
"line",
"on",
"which",
"it",
"ends",
"."
] | 33d2968a49e1131825a0accdd64bdf9901cf144c | https://github.com/sourcegraph/go-langserver/blob/33d2968a49e1131825a0accdd64bdf9901cf144c/langserver/internal/godef/go/parser/parser.go#L349-L365 | train |
sourcegraph/go-langserver | langserver/internal/godef/go/parser/parser.go | consumeCommentGroup | func (p *parser) consumeCommentGroup() (comments *ast.CommentGroup, endline int) {
var list []*ast.Comment
endline = p.file.Line(p.pos)
for p.tok == token.COMMENT && endline+1 >= p.file.Line(p.pos) {
var comment *ast.Comment
comment, endline = p.consumeComment()
list = append(list, comment)
}
// add comment group to the comments list
comments = &ast.CommentGroup{list}
p.comments = append(p.comments, comments)
return
} | go | func (p *parser) consumeCommentGroup() (comments *ast.CommentGroup, endline int) {
var list []*ast.Comment
endline = p.file.Line(p.pos)
for p.tok == token.COMMENT && endline+1 >= p.file.Line(p.pos) {
var comment *ast.Comment
comment, endline = p.consumeComment()
list = append(list, comment)
}
// add comment group to the comments list
comments = &ast.CommentGroup{list}
p.comments = append(p.comments, comments)
return
} | [
"func",
"(",
"p",
"*",
"parser",
")",
"consumeCommentGroup",
"(",
")",
"(",
"comments",
"*",
"ast",
".",
"CommentGroup",
",",
"endline",
"int",
")",
"{",
"var",
"list",
"[",
"]",
"*",
"ast",
".",
"Comment",
"\n",
"endline",
"=",
"p",
".",
"file",
"... | // Consume a group of adjacent comments, add it to the parser's
// comments list, and return it together with the line at which
// the last comment in the group ends. An empty line or non-comment
// token terminates a comment group.
// | [
"Consume",
"a",
"group",
"of",
"adjacent",
"comments",
"add",
"it",
"to",
"the",
"parser",
"s",
"comments",
"list",
"and",
"return",
"it",
"together",
"with",
"the",
"line",
"at",
"which",
"the",
"last",
"comment",
"in",
"the",
"group",
"ends",
".",
"An"... | 33d2968a49e1131825a0accdd64bdf9901cf144c | https://github.com/sourcegraph/go-langserver/blob/33d2968a49e1131825a0accdd64bdf9901cf144c/langserver/internal/godef/go/parser/parser.go#L372-L386 | train |
sourcegraph/go-langserver | langserver/internal/godef/go/parser/parser.go | next | func (p *parser) next() {
p.leadComment = nil
p.lineComment = nil
line := p.file.Line(p.pos) // current line
p.next0()
if p.tok == token.COMMENT {
var comment *ast.CommentGroup
var endline int
if p.file.Line(p.pos) == line {
// The comment is on same line as previous token; it
// cannot be a lead comment but may be a line comment.
comment, endline = p.consumeCommentGroup()
if p.file.Line(p.pos) != endline {
// The next token is on a different line, thus
// the last comment group is a line comment.
p.lineComment = comment
}
}
// consume successor comments, if any
endline = -1
for p.tok == token.COMMENT {
comment, endline = p.consumeCommentGroup()
}
if endline+1 == p.file.Line(p.pos) {
// The next token is following on the line immediately after the
// comment group, thus the last comment group is a lead comment.
p.leadComment = comment
}
}
} | go | func (p *parser) next() {
p.leadComment = nil
p.lineComment = nil
line := p.file.Line(p.pos) // current line
p.next0()
if p.tok == token.COMMENT {
var comment *ast.CommentGroup
var endline int
if p.file.Line(p.pos) == line {
// The comment is on same line as previous token; it
// cannot be a lead comment but may be a line comment.
comment, endline = p.consumeCommentGroup()
if p.file.Line(p.pos) != endline {
// The next token is on a different line, thus
// the last comment group is a line comment.
p.lineComment = comment
}
}
// consume successor comments, if any
endline = -1
for p.tok == token.COMMENT {
comment, endline = p.consumeCommentGroup()
}
if endline+1 == p.file.Line(p.pos) {
// The next token is following on the line immediately after the
// comment group, thus the last comment group is a lead comment.
p.leadComment = comment
}
}
} | [
"func",
"(",
"p",
"*",
"parser",
")",
"next",
"(",
")",
"{",
"p",
".",
"leadComment",
"=",
"nil",
"\n",
"p",
".",
"lineComment",
"=",
"nil",
"\n",
"line",
":=",
"p",
".",
"file",
".",
"Line",
"(",
"p",
".",
"pos",
")",
"\n",
"p",
".",
"next0"... | // Advance to the next non-comment token. In the process, collect
// any comment groups encountered, and remember the last lead and
// and line comments.
//
// A lead comment is a comment group that starts and ends in a
// line without any other tokens and that is followed by a non-comment
// token on the line immediately after the comment group.
//
// A line comment is a comment group that follows a non-comment
// token on the same line, and that has no tokens after it on the line
// where it ends.
//
// Lead and line comments may be considered documentation that is
// stored in the AST.
// | [
"Advance",
"to",
"the",
"next",
"non",
"-",
"comment",
"token",
".",
"In",
"the",
"process",
"collect",
"any",
"comment",
"groups",
"encountered",
"and",
"remember",
"the",
"last",
"lead",
"and",
"and",
"line",
"comments",
".",
"A",
"lead",
"comment",
"is"... | 33d2968a49e1131825a0accdd64bdf9901cf144c | https://github.com/sourcegraph/go-langserver/blob/33d2968a49e1131825a0accdd64bdf9901cf144c/langserver/internal/godef/go/parser/parser.go#L403-L436 | train |
sourcegraph/go-langserver | langserver/internal/godef/go/parser/parser.go | makeAnonField | func makeAnonField(t, declType ast.Expr) ast.Expr {
switch t := t.(type) {
case *ast.Ident:
id := new(ast.Ident)
*id = *t
id.Obj = ast.NewObj(ast.Var, id.Name)
id.Obj.Decl = &ast.Field{nil, []*ast.Ident{id}, declType, nil, nil}
return id
case *ast.SelectorExpr:
return &ast.SelectorExpr{t.X, makeAnonField(t.Sel, declType).(*ast.Ident)}
case *ast.StarExpr:
return &ast.StarExpr{t.Star, makeAnonField(t.X, declType)}
}
return t
} | go | func makeAnonField(t, declType ast.Expr) ast.Expr {
switch t := t.(type) {
case *ast.Ident:
id := new(ast.Ident)
*id = *t
id.Obj = ast.NewObj(ast.Var, id.Name)
id.Obj.Decl = &ast.Field{nil, []*ast.Ident{id}, declType, nil, nil}
return id
case *ast.SelectorExpr:
return &ast.SelectorExpr{t.X, makeAnonField(t.Sel, declType).(*ast.Ident)}
case *ast.StarExpr:
return &ast.StarExpr{t.Star, makeAnonField(t.X, declType)}
}
return t
} | [
"func",
"makeAnonField",
"(",
"t",
",",
"declType",
"ast",
".",
"Expr",
")",
"ast",
".",
"Expr",
"{",
"switch",
"t",
":=",
"t",
".",
"(",
"type",
")",
"{",
"case",
"*",
"ast",
".",
"Ident",
":",
"id",
":=",
"new",
"(",
"ast",
".",
"Ident",
")",... | // The object for the identifier in an anonymous
// field must point to the original type because
// the object has its own identity as a field member.
// | [
"The",
"object",
"for",
"the",
"identifier",
"in",
"an",
"anonymous",
"field",
"must",
"point",
"to",
"the",
"original",
"type",
"because",
"the",
"object",
"has",
"its",
"own",
"identity",
"as",
"a",
"field",
"member",
"."
] | 33d2968a49e1131825a0accdd64bdf9901cf144c | https://github.com/sourcegraph/go-langserver/blob/33d2968a49e1131825a0accdd64bdf9901cf144c/langserver/internal/godef/go/parser/parser.go#L664-L680 | train |
sourcegraph/go-langserver | langserver/internal/godef/go/parser/parser.go | isLiteralType | func isLiteralType(x ast.Expr) bool {
switch t := x.(type) {
case *ast.BadExpr:
case *ast.Ident:
case *ast.SelectorExpr:
_, isIdent := t.X.(*ast.Ident)
return isIdent
case *ast.ArrayType:
case *ast.StructType:
case *ast.MapType:
default:
return false // all other nodes are not legal composite literal types
}
return true
} | go | func isLiteralType(x ast.Expr) bool {
switch t := x.(type) {
case *ast.BadExpr:
case *ast.Ident:
case *ast.SelectorExpr:
_, isIdent := t.X.(*ast.Ident)
return isIdent
case *ast.ArrayType:
case *ast.StructType:
case *ast.MapType:
default:
return false // all other nodes are not legal composite literal types
}
return true
} | [
"func",
"isLiteralType",
"(",
"x",
"ast",
".",
"Expr",
")",
"bool",
"{",
"switch",
"t",
":=",
"x",
".",
"(",
"type",
")",
"{",
"case",
"*",
"ast",
".",
"BadExpr",
":",
"case",
"*",
"ast",
".",
"Ident",
":",
"case",
"*",
"ast",
".",
"SelectorExpr"... | // isLiteralType returns true iff x is a legal composite literal type. | [
"isLiteralType",
"returns",
"true",
"iff",
"x",
"is",
"a",
"legal",
"composite",
"literal",
"type",
"."
] | 33d2968a49e1131825a0accdd64bdf9901cf144c | https://github.com/sourcegraph/go-langserver/blob/33d2968a49e1131825a0accdd64bdf9901cf144c/langserver/internal/godef/go/parser/parser.go#L1272-L1286 | train |
sourcegraph/go-langserver | langserver/internal/godef/go/parser/parser.go | newScope | func (p *parser) newScope(outer *ast.Scope) *ast.Scope {
if p.topScope == nil {
return nil
}
return ast.NewScope(outer)
} | go | func (p *parser) newScope(outer *ast.Scope) *ast.Scope {
if p.topScope == nil {
return nil
}
return ast.NewScope(outer)
} | [
"func",
"(",
"p",
"*",
"parser",
")",
"newScope",
"(",
"outer",
"*",
"ast",
".",
"Scope",
")",
"*",
"ast",
".",
"Scope",
"{",
"if",
"p",
".",
"topScope",
"==",
"nil",
"{",
"return",
"nil",
"\n",
"}",
"\n",
"return",
"ast",
".",
"NewScope",
"(",
... | // newScope creates a new scope only if we're using scopes. | [
"newScope",
"creates",
"a",
"new",
"scope",
"only",
"if",
"we",
"re",
"using",
"scopes",
"."
] | 33d2968a49e1131825a0accdd64bdf9901cf144c | https://github.com/sourcegraph/go-langserver/blob/33d2968a49e1131825a0accdd64bdf9901cf144c/langserver/internal/godef/go/parser/parser.go#L2200-L2205 | train |
sourcegraph/go-langserver | langserver/internal/gocode/suggest/suggest.go | Suggest | func (c *Config) Suggest(filename string, data []byte, cursor int) ([]Candidate, int, error) {
if cursor < 0 {
return nil, 0, nil
}
a, err := c.analyzePackage(filename, data, cursor)
if err != nil {
return nil, 0, err
}
fset := a.fset
pos := a.pos
pkg := a.pkg
if pkg == nil {
return nil, 0, nil
}
scope := pkg.Scope().Innermost(pos)
ctx, expr, partial := deduceCursorContext(data, cursor)
b := candidateCollector{
localpkg: pkg,
partial: partial,
filter: objectFilters[partial],
builtin: ctx != selectContext && c.Builtin,
}
switch ctx {
case selectContext:
tv, _ := types.Eval(fset, pkg, pos, expr)
if lookdot.Walk(&tv, b.appendObject) {
break
}
_, obj := scope.LookupParent(expr, pos)
if pkgName, isPkg := obj.(*types.PkgName); isPkg {
c.packageCandidates(pkgName.Imported(), &b)
break
}
return nil, 0, nil
case compositeLiteralContext:
tv, _ := types.Eval(fset, pkg, pos, expr)
if tv.IsType() {
if _, isStruct := tv.Type.Underlying().(*types.Struct); isStruct {
c.fieldNameCandidates(tv.Type, &b)
break
}
}
fallthrough
default:
c.scopeCandidates(scope, pos, &b)
}
res := b.getCandidates()
if len(res) == 0 {
return nil, 0, nil
}
return res, len(partial), nil
} | go | func (c *Config) Suggest(filename string, data []byte, cursor int) ([]Candidate, int, error) {
if cursor < 0 {
return nil, 0, nil
}
a, err := c.analyzePackage(filename, data, cursor)
if err != nil {
return nil, 0, err
}
fset := a.fset
pos := a.pos
pkg := a.pkg
if pkg == nil {
return nil, 0, nil
}
scope := pkg.Scope().Innermost(pos)
ctx, expr, partial := deduceCursorContext(data, cursor)
b := candidateCollector{
localpkg: pkg,
partial: partial,
filter: objectFilters[partial],
builtin: ctx != selectContext && c.Builtin,
}
switch ctx {
case selectContext:
tv, _ := types.Eval(fset, pkg, pos, expr)
if lookdot.Walk(&tv, b.appendObject) {
break
}
_, obj := scope.LookupParent(expr, pos)
if pkgName, isPkg := obj.(*types.PkgName); isPkg {
c.packageCandidates(pkgName.Imported(), &b)
break
}
return nil, 0, nil
case compositeLiteralContext:
tv, _ := types.Eval(fset, pkg, pos, expr)
if tv.IsType() {
if _, isStruct := tv.Type.Underlying().(*types.Struct); isStruct {
c.fieldNameCandidates(tv.Type, &b)
break
}
}
fallthrough
default:
c.scopeCandidates(scope, pos, &b)
}
res := b.getCandidates()
if len(res) == 0 {
return nil, 0, nil
}
return res, len(partial), nil
} | [
"func",
"(",
"c",
"*",
"Config",
")",
"Suggest",
"(",
"filename",
"string",
",",
"data",
"[",
"]",
"byte",
",",
"cursor",
"int",
")",
"(",
"[",
"]",
"Candidate",
",",
"int",
",",
"error",
")",
"{",
"if",
"cursor",
"<",
"0",
"{",
"return",
"nil",
... | // Suggest returns a list of suggestion candidates and the length of
// the text that should be replaced, if any. | [
"Suggest",
"returns",
"a",
"list",
"of",
"suggestion",
"candidates",
"and",
"the",
"length",
"of",
"the",
"text",
"that",
"should",
"be",
"replaced",
"if",
"any",
"."
] | 33d2968a49e1131825a0accdd64bdf9901cf144c | https://github.com/sourcegraph/go-langserver/blob/33d2968a49e1131825a0accdd64bdf9901cf144c/langserver/internal/gocode/suggest/suggest.go#L32-L91 | train |
sourcegraph/go-langserver | diskcache/cache.go | Open | func (s *Store) Open(ctx context.Context, key string, fetcher Fetcher) (file *File, err error) {
span, ctx := opentracing.StartSpanFromContext(ctx, "Cached Fetch")
if s.Component != "" {
ext.Component.Set(span, s.Component)
}
defer func() {
if err != nil {
ext.Error.Set(span, true)
span.SetTag("err", err.Error())
}
if file != nil {
// Update modified time. Modified time is used to decide which
// files to evict from the cache.
touch(file.Path)
}
span.Finish()
}()
if s.Dir == "" {
return nil, errors.New("diskcache.Store.Dir must be set")
}
// path uses a sha256 hash of the key since we want to use it for the
// disk name.
h := sha256.Sum256([]byte(key))
path := filepath.Join(s.Dir, hex.EncodeToString(h[:])) + ".zip"
span.LogKV("key", key, "path", path)
// First do a fast-path, assume already on disk
f, err := os.Open(path)
if err == nil {
span.SetTag("source", "fast")
return &File{File: f, Path: path}, nil
}
// We (probably) have to fetch
span.SetTag("source", "fetch")
// Do the fetch in another goroutine so we can respect ctx cancellation.
type result struct {
f *File
err error
}
ch := make(chan result, 1)
go func(ctx context.Context) {
if s.BackgroundTimeout != 0 {
var cancel context.CancelFunc
ctx, cancel = context.WithTimeout(context.Background(), s.BackgroundTimeout)
defer cancel()
}
f, err := doFetch(ctx, path, fetcher)
ch <- result{f, err}
}(ctx)
select {
case <-ctx.Done():
// *os.File sets a finalizer to close the file when no longer used, so
// we don't need to worry about closing the file in the case of context
// cancellation.
return nil, ctx.Err()
case r := <-ch:
return r.f, r.err
}
} | go | func (s *Store) Open(ctx context.Context, key string, fetcher Fetcher) (file *File, err error) {
span, ctx := opentracing.StartSpanFromContext(ctx, "Cached Fetch")
if s.Component != "" {
ext.Component.Set(span, s.Component)
}
defer func() {
if err != nil {
ext.Error.Set(span, true)
span.SetTag("err", err.Error())
}
if file != nil {
// Update modified time. Modified time is used to decide which
// files to evict from the cache.
touch(file.Path)
}
span.Finish()
}()
if s.Dir == "" {
return nil, errors.New("diskcache.Store.Dir must be set")
}
// path uses a sha256 hash of the key since we want to use it for the
// disk name.
h := sha256.Sum256([]byte(key))
path := filepath.Join(s.Dir, hex.EncodeToString(h[:])) + ".zip"
span.LogKV("key", key, "path", path)
// First do a fast-path, assume already on disk
f, err := os.Open(path)
if err == nil {
span.SetTag("source", "fast")
return &File{File: f, Path: path}, nil
}
// We (probably) have to fetch
span.SetTag("source", "fetch")
// Do the fetch in another goroutine so we can respect ctx cancellation.
type result struct {
f *File
err error
}
ch := make(chan result, 1)
go func(ctx context.Context) {
if s.BackgroundTimeout != 0 {
var cancel context.CancelFunc
ctx, cancel = context.WithTimeout(context.Background(), s.BackgroundTimeout)
defer cancel()
}
f, err := doFetch(ctx, path, fetcher)
ch <- result{f, err}
}(ctx)
select {
case <-ctx.Done():
// *os.File sets a finalizer to close the file when no longer used, so
// we don't need to worry about closing the file in the case of context
// cancellation.
return nil, ctx.Err()
case r := <-ch:
return r.f, r.err
}
} | [
"func",
"(",
"s",
"*",
"Store",
")",
"Open",
"(",
"ctx",
"context",
".",
"Context",
",",
"key",
"string",
",",
"fetcher",
"Fetcher",
")",
"(",
"file",
"*",
"File",
",",
"err",
"error",
")",
"{",
"span",
",",
"ctx",
":=",
"opentracing",
".",
"StartS... | // Open will open a file from the local cache with key. If missing, fetcher
// will fill the cache first. Open also performs single-flighting for fetcher. | [
"Open",
"will",
"open",
"a",
"file",
"from",
"the",
"local",
"cache",
"with",
"key",
".",
"If",
"missing",
"fetcher",
"will",
"fill",
"the",
"cache",
"first",
".",
"Open",
"also",
"performs",
"single",
"-",
"flighting",
"for",
"fetcher",
"."
] | 33d2968a49e1131825a0accdd64bdf9901cf144c | https://github.com/sourcegraph/go-langserver/blob/33d2968a49e1131825a0accdd64bdf9901cf144c/diskcache/cache.go#L58-L121 | train |
sourcegraph/go-langserver | diskcache/cache.go | EvictMaxSize | func (s *Store) EvictMaxSize(maxCacheSizeBytes int64) (stats EvictStats, err error) {
isZip := func(fi os.FileInfo) bool {
return strings.HasSuffix(fi.Name(), ".zip")
}
list, err := ioutil.ReadDir(s.Dir)
if err != nil {
if os.IsNotExist(err) {
return EvictStats{
CacheSize: 0,
Evicted: 0,
}, nil
}
return stats, errors.Wrapf(err, "failed to ReadDir %s", s.Dir)
}
// Sum up the total size of all zips
var size int64
for _, fi := range list {
if isZip(fi) {
size += fi.Size()
}
}
stats.CacheSize = size
// Nothing to evict
if size <= maxCacheSizeBytes {
return stats, nil
}
// Keep removing files until we are under the cache size. Remove the
// oldest first.
sort.Slice(list, func(i, j int) bool {
return list[i].ModTime().Before(list[j].ModTime())
})
for _, fi := range list {
if size <= maxCacheSizeBytes {
break
}
if !isZip(fi) {
continue
}
path := filepath.Join(s.Dir, fi.Name())
if s.BeforeEvict != nil {
s.BeforeEvict(path)
}
err = os.Remove(path)
if err != nil {
log.Printf("failed to remove %s: %s", path, err)
continue
}
stats.Evicted++
size -= fi.Size()
}
return stats, nil
} | go | func (s *Store) EvictMaxSize(maxCacheSizeBytes int64) (stats EvictStats, err error) {
isZip := func(fi os.FileInfo) bool {
return strings.HasSuffix(fi.Name(), ".zip")
}
list, err := ioutil.ReadDir(s.Dir)
if err != nil {
if os.IsNotExist(err) {
return EvictStats{
CacheSize: 0,
Evicted: 0,
}, nil
}
return stats, errors.Wrapf(err, "failed to ReadDir %s", s.Dir)
}
// Sum up the total size of all zips
var size int64
for _, fi := range list {
if isZip(fi) {
size += fi.Size()
}
}
stats.CacheSize = size
// Nothing to evict
if size <= maxCacheSizeBytes {
return stats, nil
}
// Keep removing files until we are under the cache size. Remove the
// oldest first.
sort.Slice(list, func(i, j int) bool {
return list[i].ModTime().Before(list[j].ModTime())
})
for _, fi := range list {
if size <= maxCacheSizeBytes {
break
}
if !isZip(fi) {
continue
}
path := filepath.Join(s.Dir, fi.Name())
if s.BeforeEvict != nil {
s.BeforeEvict(path)
}
err = os.Remove(path)
if err != nil {
log.Printf("failed to remove %s: %s", path, err)
continue
}
stats.Evicted++
size -= fi.Size()
}
return stats, nil
} | [
"func",
"(",
"s",
"*",
"Store",
")",
"EvictMaxSize",
"(",
"maxCacheSizeBytes",
"int64",
")",
"(",
"stats",
"EvictStats",
",",
"err",
"error",
")",
"{",
"isZip",
":=",
"func",
"(",
"fi",
"os",
".",
"FileInfo",
")",
"bool",
"{",
"return",
"strings",
".",... | // Evict will remove files from Store.Dir until it is smaller than
// maxCacheSizeBytes. It evicts files with the oldest modification time first. | [
"Evict",
"will",
"remove",
"files",
"from",
"Store",
".",
"Dir",
"until",
"it",
"is",
"smaller",
"than",
"maxCacheSizeBytes",
".",
"It",
"evicts",
"files",
"with",
"the",
"oldest",
"modification",
"time",
"first",
"."
] | 33d2968a49e1131825a0accdd64bdf9901cf144c | https://github.com/sourcegraph/go-langserver/blob/33d2968a49e1131825a0accdd64bdf9901cf144c/diskcache/cache.go#L199-L255 | train |
sourcegraph/go-langserver | langserver/util/util.go | PathHasPrefix | func PathHasPrefix(s, prefix string) bool {
s = normalizePath(s)
prefix = normalizePath(prefix)
if s == prefix {
return true
}
if !strings.HasSuffix(prefix, "/") {
prefix += "/"
}
return s == prefix || strings.HasPrefix(s, prefix)
} | go | func PathHasPrefix(s, prefix string) bool {
s = normalizePath(s)
prefix = normalizePath(prefix)
if s == prefix {
return true
}
if !strings.HasSuffix(prefix, "/") {
prefix += "/"
}
return s == prefix || strings.HasPrefix(s, prefix)
} | [
"func",
"PathHasPrefix",
"(",
"s",
",",
"prefix",
"string",
")",
"bool",
"{",
"s",
"=",
"normalizePath",
"(",
"s",
")",
"\n",
"prefix",
"=",
"normalizePath",
"(",
"prefix",
")",
"\n",
"if",
"s",
"==",
"prefix",
"{",
"return",
"true",
"\n",
"}",
"\n",... | // PathHasPrefix returns true if s is starts with the given prefix | [
"PathHasPrefix",
"returns",
"true",
"if",
"s",
"is",
"starts",
"with",
"the",
"given",
"prefix"
] | 33d2968a49e1131825a0accdd64bdf9901cf144c | https://github.com/sourcegraph/go-langserver/blob/33d2968a49e1131825a0accdd64bdf9901cf144c/langserver/util/util.go#L31-L41 | train |
sourcegraph/go-langserver | langserver/util/util.go | PathTrimPrefix | func PathTrimPrefix(s, prefix string) string {
s = normalizePath(s)
prefix = normalizePath(prefix)
if s == prefix {
return ""
}
if !strings.HasSuffix(prefix, "/") {
prefix += "/"
}
return strings.TrimPrefix(s, prefix)
} | go | func PathTrimPrefix(s, prefix string) string {
s = normalizePath(s)
prefix = normalizePath(prefix)
if s == prefix {
return ""
}
if !strings.HasSuffix(prefix, "/") {
prefix += "/"
}
return strings.TrimPrefix(s, prefix)
} | [
"func",
"PathTrimPrefix",
"(",
"s",
",",
"prefix",
"string",
")",
"string",
"{",
"s",
"=",
"normalizePath",
"(",
"s",
")",
"\n",
"prefix",
"=",
"normalizePath",
"(",
"prefix",
")",
"\n",
"if",
"s",
"==",
"prefix",
"{",
"return",
"\"\"",
"\n",
"}",
"\... | // PathTrimPrefix removes the prefix from s | [
"PathTrimPrefix",
"removes",
"the",
"prefix",
"from",
"s"
] | 33d2968a49e1131825a0accdd64bdf9901cf144c | https://github.com/sourcegraph/go-langserver/blob/33d2968a49e1131825a0accdd64bdf9901cf144c/langserver/util/util.go#L44-L54 | train |
sourcegraph/go-langserver | langserver/util/util.go | IsVendorDir | func IsVendorDir(dir string) bool {
return strings.HasPrefix(dir, "vendor/") || strings.Contains(dir, "/vendor/")
} | go | func IsVendorDir(dir string) bool {
return strings.HasPrefix(dir, "vendor/") || strings.Contains(dir, "/vendor/")
} | [
"func",
"IsVendorDir",
"(",
"dir",
"string",
")",
"bool",
"{",
"return",
"strings",
".",
"HasPrefix",
"(",
"dir",
",",
"\"vendor/\"",
")",
"||",
"strings",
".",
"Contains",
"(",
"dir",
",",
"\"/vendor/\"",
")",
"\n",
"}"
] | // IsVendorDir tells if the specified directory is a vendor directory. | [
"IsVendorDir",
"tells",
"if",
"the",
"specified",
"directory",
"is",
"a",
"vendor",
"directory",
"."
] | 33d2968a49e1131825a0accdd64bdf9901cf144c | https://github.com/sourcegraph/go-langserver/blob/33d2968a49e1131825a0accdd64bdf9901cf144c/langserver/util/util.go#L62-L64 | train |
sourcegraph/go-langserver | langserver/util/util.go | PathToURI | func PathToURI(path string) lsp.DocumentURI {
path = filepath.ToSlash(path)
parts := strings.SplitN(path, "/", 2)
// If the first segment is a Windows drive letter, prefix with a slash and skip encoding
head := parts[0]
if head != "" {
head = "/" + head
}
rest := ""
if len(parts) > 1 {
rest = "/" + parts[1]
}
return lsp.DocumentURI("file://" + head + rest)
} | go | func PathToURI(path string) lsp.DocumentURI {
path = filepath.ToSlash(path)
parts := strings.SplitN(path, "/", 2)
// If the first segment is a Windows drive letter, prefix with a slash and skip encoding
head := parts[0]
if head != "" {
head = "/" + head
}
rest := ""
if len(parts) > 1 {
rest = "/" + parts[1]
}
return lsp.DocumentURI("file://" + head + rest)
} | [
"func",
"PathToURI",
"(",
"path",
"string",
")",
"lsp",
".",
"DocumentURI",
"{",
"path",
"=",
"filepath",
".",
"ToSlash",
"(",
"path",
")",
"\n",
"parts",
":=",
"strings",
".",
"SplitN",
"(",
"path",
",",
"\"/\"",
",",
"2",
")",
"\n",
"head",
":=",
... | // PathToURI converts given absolute path to file URI | [
"PathToURI",
"converts",
"given",
"absolute",
"path",
"to",
"file",
"URI"
] | 33d2968a49e1131825a0accdd64bdf9901cf144c | https://github.com/sourcegraph/go-langserver/blob/33d2968a49e1131825a0accdd64bdf9901cf144c/langserver/util/util.go#L76-L92 | train |
sourcegraph/go-langserver | langserver/util/util.go | UriToPath | func UriToPath(uri lsp.DocumentURI) string {
u, err := url.Parse(string(uri))
if err != nil {
return trimFilePrefix(string(uri))
}
return u.Path
} | go | func UriToPath(uri lsp.DocumentURI) string {
u, err := url.Parse(string(uri))
if err != nil {
return trimFilePrefix(string(uri))
}
return u.Path
} | [
"func",
"UriToPath",
"(",
"uri",
"lsp",
".",
"DocumentURI",
")",
"string",
"{",
"u",
",",
"err",
":=",
"url",
".",
"Parse",
"(",
"string",
"(",
"uri",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"trimFilePrefix",
"(",
"string",
"(",
"u... | // UriToPath converts given file URI to path | [
"UriToPath",
"converts",
"given",
"file",
"URI",
"to",
"path"
] | 33d2968a49e1131825a0accdd64bdf9901cf144c | https://github.com/sourcegraph/go-langserver/blob/33d2968a49e1131825a0accdd64bdf9901cf144c/langserver/util/util.go#L95-L101 | train |
sourcegraph/go-langserver | langserver/util/util.go | UriToRealPath | func UriToRealPath(uri lsp.DocumentURI) string {
path := UriToPath(uri)
if regDriveLetter.MatchString(path) {
// remove the leading slash if it starts with a drive letter
// and convert to back slashes
path = filepath.FromSlash(path[1:])
}
return path
} | go | func UriToRealPath(uri lsp.DocumentURI) string {
path := UriToPath(uri)
if regDriveLetter.MatchString(path) {
// remove the leading slash if it starts with a drive letter
// and convert to back slashes
path = filepath.FromSlash(path[1:])
}
return path
} | [
"func",
"UriToRealPath",
"(",
"uri",
"lsp",
".",
"DocumentURI",
")",
"string",
"{",
"path",
":=",
"UriToPath",
"(",
"uri",
")",
"\n",
"if",
"regDriveLetter",
".",
"MatchString",
"(",
"path",
")",
"{",
"path",
"=",
"filepath",
".",
"FromSlash",
"(",
"path... | // UriToRealPath converts the given file URI to the platform specific path | [
"UriToRealPath",
"converts",
"the",
"given",
"file",
"URI",
"to",
"the",
"platform",
"specific",
"path"
] | 33d2968a49e1131825a0accdd64bdf9901cf144c | https://github.com/sourcegraph/go-langserver/blob/33d2968a49e1131825a0accdd64bdf9901cf144c/langserver/util/util.go#L106-L116 | train |
sourcegraph/go-langserver | langserver/util/util.go | IsAbs | func IsAbs(path string) bool {
// Windows implementation accepts path-like and filepath-like arguments
return strings.HasPrefix(path, "/") || filepath.IsAbs(path)
} | go | func IsAbs(path string) bool {
// Windows implementation accepts path-like and filepath-like arguments
return strings.HasPrefix(path, "/") || filepath.IsAbs(path)
} | [
"func",
"IsAbs",
"(",
"path",
"string",
")",
"bool",
"{",
"return",
"strings",
".",
"HasPrefix",
"(",
"path",
",",
"\"/\"",
")",
"||",
"filepath",
".",
"IsAbs",
"(",
"path",
")",
"\n",
"}"
] | // IsAbs returns true if the given path is absolute | [
"IsAbs",
"returns",
"true",
"if",
"the",
"given",
"path",
"is",
"absolute"
] | 33d2968a49e1131825a0accdd64bdf9901cf144c | https://github.com/sourcegraph/go-langserver/blob/33d2968a49e1131825a0accdd64bdf9901cf144c/langserver/util/util.go#L119-L122 | train |
sourcegraph/go-langserver | langserver/tracing.go | InitTracer | func (h *HandlerCommon) InitTracer(conn *jsonrpc2.Conn) {
h.mu.Lock()
defer h.mu.Unlock()
if h.tracer != nil {
return
}
if _, isNoopTracer := opentracing.GlobalTracer().(opentracing.NoopTracer); !isNoopTracer {
// We have configured a tracer, use that instead of telemetry/event
h.tracer = opentracing.GlobalTracer()
return
}
t := tracer{conn: conn}
opt := basictracer.DefaultOptions()
opt.Recorder = &t
h.tracer = basictracer.NewWithOptions(opt)
go func() {
<-conn.DisconnectNotify()
t.mu.Lock()
t.conn = nil
t.mu.Unlock()
}()
} | go | func (h *HandlerCommon) InitTracer(conn *jsonrpc2.Conn) {
h.mu.Lock()
defer h.mu.Unlock()
if h.tracer != nil {
return
}
if _, isNoopTracer := opentracing.GlobalTracer().(opentracing.NoopTracer); !isNoopTracer {
// We have configured a tracer, use that instead of telemetry/event
h.tracer = opentracing.GlobalTracer()
return
}
t := tracer{conn: conn}
opt := basictracer.DefaultOptions()
opt.Recorder = &t
h.tracer = basictracer.NewWithOptions(opt)
go func() {
<-conn.DisconnectNotify()
t.mu.Lock()
t.conn = nil
t.mu.Unlock()
}()
} | [
"func",
"(",
"h",
"*",
"HandlerCommon",
")",
"InitTracer",
"(",
"conn",
"*",
"jsonrpc2",
".",
"Conn",
")",
"{",
"h",
".",
"mu",
".",
"Lock",
"(",
")",
"\n",
"defer",
"h",
".",
"mu",
".",
"Unlock",
"(",
")",
"\n",
"if",
"h",
".",
"tracer",
"!=",... | // InitTracer initializes the tracer for the connection if it has not
// already been initialized.
//
// It assumes that h is only ever called for this conn. | [
"InitTracer",
"initializes",
"the",
"tracer",
"for",
"the",
"connection",
"if",
"it",
"has",
"not",
"already",
"been",
"initialized",
".",
"It",
"assumes",
"that",
"h",
"is",
"only",
"ever",
"called",
"for",
"this",
"conn",
"."
] | 33d2968a49e1131825a0accdd64bdf9901cf144c | https://github.com/sourcegraph/go-langserver/blob/33d2968a49e1131825a0accdd64bdf9901cf144c/langserver/tracing.go#L19-L42 | train |
sourcegraph/go-langserver | langserver/tracing.go | startSpanFollowsFromContext | func startSpanFollowsFromContext(ctx context.Context, operationName string, opts ...opentracing.StartSpanOption) opentracing.Span {
if parentSpan := opentracing.SpanFromContext(ctx); parentSpan != nil {
opts = append(opts, opentracing.FollowsFrom(parentSpan.Context()))
return parentSpan.Tracer().StartSpan(operationName, opts...)
}
return opentracing.GlobalTracer().StartSpan(operationName, opts...)
} | go | func startSpanFollowsFromContext(ctx context.Context, operationName string, opts ...opentracing.StartSpanOption) opentracing.Span {
if parentSpan := opentracing.SpanFromContext(ctx); parentSpan != nil {
opts = append(opts, opentracing.FollowsFrom(parentSpan.Context()))
return parentSpan.Tracer().StartSpan(operationName, opts...)
}
return opentracing.GlobalTracer().StartSpan(operationName, opts...)
} | [
"func",
"startSpanFollowsFromContext",
"(",
"ctx",
"context",
".",
"Context",
",",
"operationName",
"string",
",",
"opts",
"...",
"opentracing",
".",
"StartSpanOption",
")",
"opentracing",
".",
"Span",
"{",
"if",
"parentSpan",
":=",
"opentracing",
".",
"SpanFromCo... | // FollowsFrom means the parent span does not depend on the child span, but
// caused it to start. | [
"FollowsFrom",
"means",
"the",
"parent",
"span",
"does",
"not",
"depend",
"on",
"the",
"child",
"span",
"but",
"caused",
"it",
"to",
"start",
"."
] | 33d2968a49e1131825a0accdd64bdf9901cf144c | https://github.com/sourcegraph/go-langserver/blob/33d2968a49e1131825a0accdd64bdf9901cf144c/langserver/tracing.go#L109-L115 | train |
radovskyb/watcher | watcher.go | String | func (e Op) String() string {
if op, found := ops[e]; found {
return op
}
return "???"
} | go | func (e Op) String() string {
if op, found := ops[e]; found {
return op
}
return "???"
} | [
"func",
"(",
"e",
"Op",
")",
"String",
"(",
")",
"string",
"{",
"if",
"op",
",",
"found",
":=",
"ops",
"[",
"e",
"]",
";",
"found",
"{",
"return",
"op",
"\n",
"}",
"\n",
"return",
"\"???\"",
"\n",
"}"
] | // String prints the string version of the Op consts | [
"String",
"prints",
"the",
"string",
"version",
"of",
"the",
"Op",
"consts"
] | f33c874a09dcfac90f008abeee9171d88431e212 | https://github.com/radovskyb/watcher/blob/f33c874a09dcfac90f008abeee9171d88431e212/watcher.go#L58-L63 | train |
radovskyb/watcher | watcher.go | String | func (e Event) String() string {
if e.FileInfo == nil {
return "???"
}
pathType := "FILE"
if e.IsDir() {
pathType = "DIRECTORY"
}
return fmt.Sprintf("%s %q %s [%s]", pathType, e.Name(), e.Op, e.Path)
} | go | func (e Event) String() string {
if e.FileInfo == nil {
return "???"
}
pathType := "FILE"
if e.IsDir() {
pathType = "DIRECTORY"
}
return fmt.Sprintf("%s %q %s [%s]", pathType, e.Name(), e.Op, e.Path)
} | [
"func",
"(",
"e",
"Event",
")",
"String",
"(",
")",
"string",
"{",
"if",
"e",
".",
"FileInfo",
"==",
"nil",
"{",
"return",
"\"???\"",
"\n",
"}",
"\n",
"pathType",
":=",
"\"FILE\"",
"\n",
"if",
"e",
".",
"IsDir",
"(",
")",
"{",
"pathType",
"=",
"\... | // String returns a string depending on what type of event occurred and the
// file name associated with the event. | [
"String",
"returns",
"a",
"string",
"depending",
"on",
"what",
"type",
"of",
"event",
"occurred",
"and",
"the",
"file",
"name",
"associated",
"with",
"the",
"event",
"."
] | f33c874a09dcfac90f008abeee9171d88431e212 | https://github.com/radovskyb/watcher/blob/f33c874a09dcfac90f008abeee9171d88431e212/watcher.go#L76-L86 | train |
radovskyb/watcher | watcher.go | RegexFilterHook | func RegexFilterHook(r *regexp.Regexp, useFullPath bool) FilterFileHookFunc {
return func(info os.FileInfo, fullPath string) error {
str := info.Name()
if useFullPath {
str = fullPath
}
// Match
if r.MatchString(str) {
return nil
}
// No match.
return ErrSkip
}
} | go | func RegexFilterHook(r *regexp.Regexp, useFullPath bool) FilterFileHookFunc {
return func(info os.FileInfo, fullPath string) error {
str := info.Name()
if useFullPath {
str = fullPath
}
// Match
if r.MatchString(str) {
return nil
}
// No match.
return ErrSkip
}
} | [
"func",
"RegexFilterHook",
"(",
"r",
"*",
"regexp",
".",
"Regexp",
",",
"useFullPath",
"bool",
")",
"FilterFileHookFunc",
"{",
"return",
"func",
"(",
"info",
"os",
".",
"FileInfo",
",",
"fullPath",
"string",
")",
"error",
"{",
"str",
":=",
"info",
".",
"... | // RegexFilterHook is a function that accepts or rejects a file
// for listing based on whether it's filename or full path matches
// a regular expression. | [
"RegexFilterHook",
"is",
"a",
"function",
"that",
"accepts",
"or",
"rejects",
"a",
"file",
"for",
"listing",
"based",
"on",
"whether",
"it",
"s",
"filename",
"or",
"full",
"path",
"matches",
"a",
"regular",
"expression",
"."
] | f33c874a09dcfac90f008abeee9171d88431e212 | https://github.com/radovskyb/watcher/blob/f33c874a09dcfac90f008abeee9171d88431e212/watcher.go#L95-L111 | train |
radovskyb/watcher | watcher.go | New | func New() *Watcher {
// Set up the WaitGroup for w.Wait().
var wg sync.WaitGroup
wg.Add(1)
return &Watcher{
Event: make(chan Event),
Error: make(chan error),
Closed: make(chan struct{}),
close: make(chan struct{}),
mu: new(sync.Mutex),
wg: &wg,
files: make(map[string]os.FileInfo),
ignored: make(map[string]struct{}),
names: make(map[string]bool),
}
} | go | func New() *Watcher {
// Set up the WaitGroup for w.Wait().
var wg sync.WaitGroup
wg.Add(1)
return &Watcher{
Event: make(chan Event),
Error: make(chan error),
Closed: make(chan struct{}),
close: make(chan struct{}),
mu: new(sync.Mutex),
wg: &wg,
files: make(map[string]os.FileInfo),
ignored: make(map[string]struct{}),
names: make(map[string]bool),
}
} | [
"func",
"New",
"(",
")",
"*",
"Watcher",
"{",
"var",
"wg",
"sync",
".",
"WaitGroup",
"\n",
"wg",
".",
"Add",
"(",
"1",
")",
"\n",
"return",
"&",
"Watcher",
"{",
"Event",
":",
"make",
"(",
"chan",
"Event",
")",
",",
"Error",
":",
"make",
"(",
"c... | // New creates a new Watcher. | [
"New",
"creates",
"a",
"new",
"Watcher",
"."
] | f33c874a09dcfac90f008abeee9171d88431e212 | https://github.com/radovskyb/watcher/blob/f33c874a09dcfac90f008abeee9171d88431e212/watcher.go#L134-L150 | train |
radovskyb/watcher | watcher.go | SetMaxEvents | func (w *Watcher) SetMaxEvents(delta int) {
w.mu.Lock()
w.maxEvents = delta
w.mu.Unlock()
} | go | func (w *Watcher) SetMaxEvents(delta int) {
w.mu.Lock()
w.maxEvents = delta
w.mu.Unlock()
} | [
"func",
"(",
"w",
"*",
"Watcher",
")",
"SetMaxEvents",
"(",
"delta",
"int",
")",
"{",
"w",
".",
"mu",
".",
"Lock",
"(",
")",
"\n",
"w",
".",
"maxEvents",
"=",
"delta",
"\n",
"w",
".",
"mu",
".",
"Unlock",
"(",
")",
"\n",
"}"
] | // SetMaxEvents controls the maximum amount of events that are sent on
// the Event channel per watching cycle. If max events is less than 1, there is
// no limit, which is the default. | [
"SetMaxEvents",
"controls",
"the",
"maximum",
"amount",
"of",
"events",
"that",
"are",
"sent",
"on",
"the",
"Event",
"channel",
"per",
"watching",
"cycle",
".",
"If",
"max",
"events",
"is",
"less",
"than",
"1",
"there",
"is",
"no",
"limit",
"which",
"is",
... | f33c874a09dcfac90f008abeee9171d88431e212 | https://github.com/radovskyb/watcher/blob/f33c874a09dcfac90f008abeee9171d88431e212/watcher.go#L155-L159 | train |
radovskyb/watcher | watcher.go | IgnoreHiddenFiles | func (w *Watcher) IgnoreHiddenFiles(ignore bool) {
w.mu.Lock()
w.ignoreHidden = ignore
w.mu.Unlock()
} | go | func (w *Watcher) IgnoreHiddenFiles(ignore bool) {
w.mu.Lock()
w.ignoreHidden = ignore
w.mu.Unlock()
} | [
"func",
"(",
"w",
"*",
"Watcher",
")",
"IgnoreHiddenFiles",
"(",
"ignore",
"bool",
")",
"{",
"w",
".",
"mu",
".",
"Lock",
"(",
")",
"\n",
"w",
".",
"ignoreHidden",
"=",
"ignore",
"\n",
"w",
".",
"mu",
".",
"Unlock",
"(",
")",
"\n",
"}"
] | // IgnoreHiddenFiles sets the watcher to ignore any file or directory
// that starts with a dot. | [
"IgnoreHiddenFiles",
"sets",
"the",
"watcher",
"to",
"ignore",
"any",
"file",
"or",
"directory",
"that",
"starts",
"with",
"a",
"dot",
"."
] | f33c874a09dcfac90f008abeee9171d88431e212 | https://github.com/radovskyb/watcher/blob/f33c874a09dcfac90f008abeee9171d88431e212/watcher.go#L170-L174 | train |
radovskyb/watcher | watcher.go | FilterOps | func (w *Watcher) FilterOps(ops ...Op) {
w.mu.Lock()
w.ops = make(map[Op]struct{})
for _, op := range ops {
w.ops[op] = struct{}{}
}
w.mu.Unlock()
} | go | func (w *Watcher) FilterOps(ops ...Op) {
w.mu.Lock()
w.ops = make(map[Op]struct{})
for _, op := range ops {
w.ops[op] = struct{}{}
}
w.mu.Unlock()
} | [
"func",
"(",
"w",
"*",
"Watcher",
")",
"FilterOps",
"(",
"ops",
"...",
"Op",
")",
"{",
"w",
".",
"mu",
".",
"Lock",
"(",
")",
"\n",
"w",
".",
"ops",
"=",
"make",
"(",
"map",
"[",
"Op",
"]",
"struct",
"{",
"}",
")",
"\n",
"for",
"_",
",",
... | // FilterOps filters which event op types should be returned
// when an event occurs. | [
"FilterOps",
"filters",
"which",
"event",
"op",
"types",
"should",
"be",
"returned",
"when",
"an",
"event",
"occurs",
"."
] | f33c874a09dcfac90f008abeee9171d88431e212 | https://github.com/radovskyb/watcher/blob/f33c874a09dcfac90f008abeee9171d88431e212/watcher.go#L178-L185 | train |
radovskyb/watcher | watcher.go | Add | func (w *Watcher) Add(name string) (err error) {
w.mu.Lock()
defer w.mu.Unlock()
name, err = filepath.Abs(name)
if err != nil {
return err
}
// If name is on the ignored list or if hidden files are
// ignored and name is a hidden file or directory, simply return.
_, ignored := w.ignored[name]
isHidden, err := isHiddenFile(name)
if err != nil {
return err
}
if ignored || (w.ignoreHidden && isHidden) {
return nil
}
// Add the directory's contents to the files list.
fileList, err := w.list(name)
if err != nil {
return err
}
for k, v := range fileList {
w.files[k] = v
}
// Add the name to the names list.
w.names[name] = false
return nil
} | go | func (w *Watcher) Add(name string) (err error) {
w.mu.Lock()
defer w.mu.Unlock()
name, err = filepath.Abs(name)
if err != nil {
return err
}
// If name is on the ignored list or if hidden files are
// ignored and name is a hidden file or directory, simply return.
_, ignored := w.ignored[name]
isHidden, err := isHiddenFile(name)
if err != nil {
return err
}
if ignored || (w.ignoreHidden && isHidden) {
return nil
}
// Add the directory's contents to the files list.
fileList, err := w.list(name)
if err != nil {
return err
}
for k, v := range fileList {
w.files[k] = v
}
// Add the name to the names list.
w.names[name] = false
return nil
} | [
"func",
"(",
"w",
"*",
"Watcher",
")",
"Add",
"(",
"name",
"string",
")",
"(",
"err",
"error",
")",
"{",
"w",
".",
"mu",
".",
"Lock",
"(",
")",
"\n",
"defer",
"w",
".",
"mu",
".",
"Unlock",
"(",
")",
"\n",
"name",
",",
"err",
"=",
"filepath",... | // Add adds either a single file or directory to the file list. | [
"Add",
"adds",
"either",
"a",
"single",
"file",
"or",
"directory",
"to",
"the",
"file",
"list",
"."
] | f33c874a09dcfac90f008abeee9171d88431e212 | https://github.com/radovskyb/watcher/blob/f33c874a09dcfac90f008abeee9171d88431e212/watcher.go#L188-L223 | train |
radovskyb/watcher | watcher.go | AddRecursive | func (w *Watcher) AddRecursive(name string) (err error) {
w.mu.Lock()
defer w.mu.Unlock()
name, err = filepath.Abs(name)
if err != nil {
return err
}
fileList, err := w.listRecursive(name)
if err != nil {
return err
}
for k, v := range fileList {
w.files[k] = v
}
// Add the name to the names list.
w.names[name] = true
return nil
} | go | func (w *Watcher) AddRecursive(name string) (err error) {
w.mu.Lock()
defer w.mu.Unlock()
name, err = filepath.Abs(name)
if err != nil {
return err
}
fileList, err := w.listRecursive(name)
if err != nil {
return err
}
for k, v := range fileList {
w.files[k] = v
}
// Add the name to the names list.
w.names[name] = true
return nil
} | [
"func",
"(",
"w",
"*",
"Watcher",
")",
"AddRecursive",
"(",
"name",
"string",
")",
"(",
"err",
"error",
")",
"{",
"w",
".",
"mu",
".",
"Lock",
"(",
")",
"\n",
"defer",
"w",
".",
"mu",
".",
"Unlock",
"(",
")",
"\n",
"name",
",",
"err",
"=",
"f... | // AddRecursive adds either a single file or directory recursively to the file list. | [
"AddRecursive",
"adds",
"either",
"a",
"single",
"file",
"or",
"directory",
"recursively",
"to",
"the",
"file",
"list",
"."
] | f33c874a09dcfac90f008abeee9171d88431e212 | https://github.com/radovskyb/watcher/blob/f33c874a09dcfac90f008abeee9171d88431e212/watcher.go#L279-L300 | train |
radovskyb/watcher | watcher.go | Remove | func (w *Watcher) Remove(name string) (err error) {
w.mu.Lock()
defer w.mu.Unlock()
name, err = filepath.Abs(name)
if err != nil {
return err
}
// Remove the name from w's names list.
delete(w.names, name)
// If name is a single file, remove it and return.
info, found := w.files[name]
if !found {
return nil // Doesn't exist, just return.
}
if !info.IsDir() {
delete(w.files, name)
return nil
}
// Delete the actual directory from w.files
delete(w.files, name)
// If it's a directory, delete all of it's contents from w.files.
for path := range w.files {
if filepath.Dir(path) == name {
delete(w.files, path)
}
}
return nil
} | go | func (w *Watcher) Remove(name string) (err error) {
w.mu.Lock()
defer w.mu.Unlock()
name, err = filepath.Abs(name)
if err != nil {
return err
}
// Remove the name from w's names list.
delete(w.names, name)
// If name is a single file, remove it and return.
info, found := w.files[name]
if !found {
return nil // Doesn't exist, just return.
}
if !info.IsDir() {
delete(w.files, name)
return nil
}
// Delete the actual directory from w.files
delete(w.files, name)
// If it's a directory, delete all of it's contents from w.files.
for path := range w.files {
if filepath.Dir(path) == name {
delete(w.files, path)
}
}
return nil
} | [
"func",
"(",
"w",
"*",
"Watcher",
")",
"Remove",
"(",
"name",
"string",
")",
"(",
"err",
"error",
")",
"{",
"w",
".",
"mu",
".",
"Lock",
"(",
")",
"\n",
"defer",
"w",
".",
"mu",
".",
"Unlock",
"(",
")",
"\n",
"name",
",",
"err",
"=",
"filepat... | // Remove removes either a single file or directory from the file's list. | [
"Remove",
"removes",
"either",
"a",
"single",
"file",
"or",
"directory",
"from",
"the",
"file",
"s",
"list",
"."
] | f33c874a09dcfac90f008abeee9171d88431e212 | https://github.com/radovskyb/watcher/blob/f33c874a09dcfac90f008abeee9171d88431e212/watcher.go#L342-L374 | train |
radovskyb/watcher | watcher.go | RemoveRecursive | func (w *Watcher) RemoveRecursive(name string) (err error) {
w.mu.Lock()
defer w.mu.Unlock()
name, err = filepath.Abs(name)
if err != nil {
return err
}
// Remove the name from w's names list.
delete(w.names, name)
// If name is a single file, remove it and return.
info, found := w.files[name]
if !found {
return nil // Doesn't exist, just return.
}
if !info.IsDir() {
delete(w.files, name)
return nil
}
// If it's a directory, delete all of it's contents recursively
// from w.files.
for path := range w.files {
if strings.HasPrefix(path, name) {
delete(w.files, path)
}
}
return nil
} | go | func (w *Watcher) RemoveRecursive(name string) (err error) {
w.mu.Lock()
defer w.mu.Unlock()
name, err = filepath.Abs(name)
if err != nil {
return err
}
// Remove the name from w's names list.
delete(w.names, name)
// If name is a single file, remove it and return.
info, found := w.files[name]
if !found {
return nil // Doesn't exist, just return.
}
if !info.IsDir() {
delete(w.files, name)
return nil
}
// If it's a directory, delete all of it's contents recursively
// from w.files.
for path := range w.files {
if strings.HasPrefix(path, name) {
delete(w.files, path)
}
}
return nil
} | [
"func",
"(",
"w",
"*",
"Watcher",
")",
"RemoveRecursive",
"(",
"name",
"string",
")",
"(",
"err",
"error",
")",
"{",
"w",
".",
"mu",
".",
"Lock",
"(",
")",
"\n",
"defer",
"w",
".",
"mu",
".",
"Unlock",
"(",
")",
"\n",
"name",
",",
"err",
"=",
... | // RemoveRecursive removes either a single file or a directory recursively from
// the file's list. | [
"RemoveRecursive",
"removes",
"either",
"a",
"single",
"file",
"or",
"a",
"directory",
"recursively",
"from",
"the",
"file",
"s",
"list",
"."
] | f33c874a09dcfac90f008abeee9171d88431e212 | https://github.com/radovskyb/watcher/blob/f33c874a09dcfac90f008abeee9171d88431e212/watcher.go#L378-L408 | train |
radovskyb/watcher | watcher.go | Ignore | func (w *Watcher) Ignore(paths ...string) (err error) {
for _, path := range paths {
path, err = filepath.Abs(path)
if err != nil {
return err
}
// Remove any of the paths that were already added.
if err := w.RemoveRecursive(path); err != nil {
return err
}
w.mu.Lock()
w.ignored[path] = struct{}{}
w.mu.Unlock()
}
return nil
} | go | func (w *Watcher) Ignore(paths ...string) (err error) {
for _, path := range paths {
path, err = filepath.Abs(path)
if err != nil {
return err
}
// Remove any of the paths that were already added.
if err := w.RemoveRecursive(path); err != nil {
return err
}
w.mu.Lock()
w.ignored[path] = struct{}{}
w.mu.Unlock()
}
return nil
} | [
"func",
"(",
"w",
"*",
"Watcher",
")",
"Ignore",
"(",
"paths",
"...",
"string",
")",
"(",
"err",
"error",
")",
"{",
"for",
"_",
",",
"path",
":=",
"range",
"paths",
"{",
"path",
",",
"err",
"=",
"filepath",
".",
"Abs",
"(",
"path",
")",
"\n",
"... | // Ignore adds paths that should be ignored.
//
// For files that are already added, Ignore removes them. | [
"Ignore",
"adds",
"paths",
"that",
"should",
"be",
"ignored",
".",
"For",
"files",
"that",
"are",
"already",
"added",
"Ignore",
"removes",
"them",
"."
] | f33c874a09dcfac90f008abeee9171d88431e212 | https://github.com/radovskyb/watcher/blob/f33c874a09dcfac90f008abeee9171d88431e212/watcher.go#L413-L428 | train |
radovskyb/watcher | watcher.go | WatchedFiles | func (w *Watcher) WatchedFiles() map[string]os.FileInfo {
w.mu.Lock()
defer w.mu.Unlock()
files := make(map[string]os.FileInfo)
for k, v := range w.files {
files[k] = v
}
return files
} | go | func (w *Watcher) WatchedFiles() map[string]os.FileInfo {
w.mu.Lock()
defer w.mu.Unlock()
files := make(map[string]os.FileInfo)
for k, v := range w.files {
files[k] = v
}
return files
} | [
"func",
"(",
"w",
"*",
"Watcher",
")",
"WatchedFiles",
"(",
")",
"map",
"[",
"string",
"]",
"os",
".",
"FileInfo",
"{",
"w",
".",
"mu",
".",
"Lock",
"(",
")",
"\n",
"defer",
"w",
".",
"mu",
".",
"Unlock",
"(",
")",
"\n",
"files",
":=",
"make",
... | // WatchedFiles returns a map of files added to a Watcher. | [
"WatchedFiles",
"returns",
"a",
"map",
"of",
"files",
"added",
"to",
"a",
"Watcher",
"."
] | f33c874a09dcfac90f008abeee9171d88431e212 | https://github.com/radovskyb/watcher/blob/f33c874a09dcfac90f008abeee9171d88431e212/watcher.go#L431-L441 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.