repo
stringlengths
5
54
path
stringlengths
4
155
func_name
stringlengths
1
118
original_string
stringlengths
52
85.5k
language
stringclasses
1 value
code
stringlengths
52
85.5k
code_tokens
list
docstring
stringlengths
6
2.61k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
85
252
partition
stringclasses
1 value
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", "{", "// Ensure our buffer is big enough to prevent deadlock", "c", ":=", "make", "(", "chan", "importgraph", ".", "Graph", ",", "2", ")", "\n\n", "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", ":=", "\"", "\"", "+", "string", "(", "h", ".", "init", ".", "Root", "(", ")", ")", "\n\n", "h", ".", "mu", ".", "Lock", "(", ")", "\n", "tryCache", ":=", "h", ".", "importGraph", "==", "nil", "\n", "once", ":=", "h", ".", "importGraphOnce", "\n", "h", ".", "mu", ".", "Unlock", "(", ")", "\n", "if", "tryCache", "{", "g", ":=", "make", "(", "importgraph", ".", "Graph", ")", "\n", "if", "hit", ":=", "h", ".", "cacheGet", "(", "ctx", ",", "conn", ",", "cacheKey", ",", "g", ")", ";", "hit", "{", "// \\o/", "c", "<-", "g", "\n", "}", "\n", "}", "\n\n", "parentCtx", ":=", "ctx", "\n", "once", ".", "Do", "(", "func", "(", ")", "{", "// Note: We use a background context since this", "// operation should not be cancelled due to an", "// individual request.", "span", ":=", "startSpanFollowsFromContext", "(", "parentCtx", ",", "\"", "\"", ")", "\n", "ctx", ":=", "opentracing", ".", "ContextWithSpan", "(", "context", ".", "Background", "(", ")", ",", "span", ")", "\n", "defer", "span", ".", "Finish", "(", ")", "\n\n", "bctx", ":=", "h", ".", "BuildContext", "(", "ctx", ")", "\n", "findPackageWithCtx", ":=", "h", ".", "getFindPackageFunc", "(", ")", "\n", "findPackage", ":=", "func", "(", "bctx", "*", "build", ".", "Context", ",", "importPath", ",", "fromDir", "string", ",", "mode", "build", ".", "ImportMode", ")", "(", "*", "build", ".", "Package", ",", "error", ")", "{", "return", "findPackageWithCtx", "(", "ctx", ",", "bctx", ",", "importPath", ",", "fromDir", ",", "h", ".", "RootFSPath", ",", "mode", ")", "\n", "}", "\n", "g", ":=", "tools", ".", "BuildReverseImportGraph", "(", "bctx", ",", "findPackage", ",", "h", ".", "FilePath", "(", "h", ".", "init", ".", "Root", "(", ")", ")", ")", "\n", "h", ".", "mu", ".", "Lock", "(", ")", "\n", "h", ".", "importGraph", "=", "g", "\n", "h", ".", "mu", ".", "Unlock", "(", ")", "\n\n", "// Update cache in background", "go", "h", ".", "cacheSet", "(", "ctx", ",", "conn", ",", "cacheKey", ",", "g", ")", "\n", "}", ")", "\n", "h", ".", "mu", ".", "Lock", "(", ")", "\n", "// TODO(keegancsmith) h.importGraph may have been reset after once", "importGraph", ":=", "h", ".", "importGraph", "\n", "h", ".", "mu", ".", "Unlock", "(", ")", "\n", "c", "<-", "importGraph", "\n\n", "close", "(", "c", ")", "\n", "}", "(", ")", "\n\n", "return", "c", "\n", "}" ]
// 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", "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", "." ]
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", ",", "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", "\n", "}", "\n\n", "id", ":=", "lsp", ".", "ID", "{", "Num", ":", "req", ".", "ID", ".", "Num", ",", "Str", ":", "req", ".", "ID", ".", "Str", ",", "IsString", ":", "req", ".", "ID", ".", "IsString", ",", "}", "\n", "initial", ":=", "json", ".", "RawMessage", "(", "`[{\"op\":\"replace\",\"path\":\"\",\"value\":[]}]`", ")", "\n", "_", "=", "conn", ".", "Notify", "(", "ctx", ",", "\"", "\"", ",", "&", "lspext", ".", "PartialResultParams", "{", "ID", ":", "id", ",", "Patch", ":", "&", "initial", ",", "}", ")", "\n\n", "var", "(", "locs", "[", "]", "lsp", ".", "Location", "\n", "pos", "int", "\n", ")", "\n", "send", ":=", "func", "(", ")", "{", "if", "pos", ">=", "len", "(", "locs", ")", "{", "return", "\n", "}", "\n", "patch", ":=", "make", "(", "[", "]", "referenceAddOp", ",", "0", ",", "len", "(", "locs", ")", "-", "pos", ")", "\n", "for", "_", ",", "l", ":=", "range", "locs", "[", "pos", ":", "]", "{", "patch", "=", "append", "(", "patch", ",", "referenceAddOp", "{", "OP", ":", "\"", "\"", ",", "Path", ":", "\"", "\"", ",", "Value", ":", "l", ",", "}", ")", "\n", "}", "\n", "pos", "=", "len", "(", "locs", ")", "\n", "_", "=", "conn", ".", "Notify", "(", "ctx", ",", "\"", "\"", ",", "&", "lspext", ".", "PartialResultParams", "{", "ID", ":", "id", ",", "// We use referencePatch so the build server can rewrite URIs", "Patch", ":", "referencePatch", "(", "patch", ")", ",", "}", ")", "\n", "}", "\n\n", "tick", ":=", "time", ".", "NewTicker", "(", "100", "*", "time", ".", "Millisecond", ")", "\n", "defer", "tick", ".", "Stop", "(", ")", "\n\n", "for", "{", "select", "{", "case", "n", ",", "ok", ":=", "<-", "refs", ":", "if", "!", "ok", "{", "// send a final update", "send", "(", ")", "\n", "return", "locs", "\n", "}", "\n", "if", "len", "(", "locs", ")", ">=", "limit", "{", "stop", "(", ")", "\n", "continue", "\n", "}", "\n", "locs", "=", "append", "(", "locs", ",", "goRangeToLSPLocation", "(", "fset", ",", "n", ".", "Pos", "(", ")", ",", "n", ".", "End", "(", ")", ")", ")", "\n", "case", "<-", "tick", ".", "C", ":", "send", "(", ")", "\n", "}", "\n", "}", "\n", "}" ]
// 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", "{", "// selectable object (field or method)", "return", "true", ",", "false", "\n", "}", "\n", "if", "obj", ".", "Parent", "(", ")", "==", "obj", ".", "Pkg", "(", ")", ".", "Scope", "(", ")", "{", "// lexical object (package-level var/const/func/type)", "return", "true", ",", "true", "\n", "}", "\n", "}", "\n", "// object with unexported named or defined in local scope", "return", "false", ",", "false", "\n", "}" ]
// 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", "{", "if", "obj", "==", "nil", "{", "return", "false", "\n", "}", "\n", "posn", ":=", "fset", ".", "Position", "(", "obj", ".", "Pos", "(", ")", ")", "\n", "return", "posn", ".", "Filename", "==", "objposn", ".", "Filename", "&&", "posn", ".", "Offset", "==", "objposn", ".", "Offset", "\n", "}", "\n", "for", "_", ",", "obj", ":=", "range", "info", ".", "Defs", "{", "if", "good", "(", "obj", ")", "{", "return", "obj", "\n", "}", "\n", "}", "\n", "for", "_", ",", "obj", ":=", "range", "info", ".", "Implicits", "{", "if", "good", "(", "obj", ")", "{", "return", "obj", "\n", "}", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// 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", "y", ",", "ok", ":=", "y", ".", "(", "*", "types", ".", "PkgName", ")", ";", "ok", "{", "return", "x", ".", "Imported", "(", ")", "==", "y", ".", "Imported", "(", ")", "\n", "}", "\n", "}", "\n", "return", "false", "\n", "}" ]
// 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", ",", "filename", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "defer", "rc", ".", "Close", "(", ")", "\n", "if", "buf", "==", "nil", "{", "buf", "=", "new", "(", "bytes", ".", "Buffer", ")", "\n", "}", "\n", "if", "_", ",", "err", ":=", "io", ".", "Copy", "(", "buf", ",", "rc", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "return", "buf", ".", "Bytes", "(", ")", ",", "nil", "\n", "}" ]
// 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", "(", "\"", "\"", ")", "\n", "}", "\n", "h", ".", "shutdown", "=", "true", "\n", "h", ".", "mu", ".", "Unlock", "(", ")", "\n", "}" ]
// 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", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n", "return", "nil", "\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", ":=", "range", "changes", "{", "if", "change", ".", "Range", "==", "nil", "&&", "change", ".", "RangeLength", "==", "0", "{", "contents", "=", "[", "]", "byte", "(", "change", ".", "Text", ")", "// new full content", "\n", "continue", "\n", "}", "\n", "start", ",", "ok", ",", "why", ":=", "offsetForPosition", "(", "contents", ",", "change", ".", "Range", ".", "Start", ")", "\n", "if", "!", "ok", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "change", ".", "Range", ".", "Start", ",", "uri", ",", "why", ")", "\n", "}", "\n", "var", "end", "int", "\n", "if", "change", ".", "RangeLength", "!=", "0", "{", "end", "=", "start", "+", "int", "(", "change", ".", "RangeLength", ")", "\n", "}", "else", "{", "// RangeLength not specified, work it out from Range.End", "end", ",", "ok", ",", "why", "=", "offsetForPosition", "(", "contents", ",", "change", ".", "Range", ".", "End", ")", "\n", "if", "!", "ok", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "change", ".", "Range", ".", "Start", ",", "uri", ",", "why", ")", "\n", "}", "\n", "}", "\n", "if", "start", "<", "0", "||", "end", ">", "len", "(", "contents", ")", "||", "end", "<", "start", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "change", ".", "Range", ",", "uri", ")", "\n", "}", "\n", "// Try avoid doing too many allocations, so use bytes.Buffer", "b", ":=", "&", "bytes", ".", "Buffer", "{", "}", "\n", "b", ".", "Grow", "(", "start", "+", "len", "(", "change", ".", "Text", ")", "+", "len", "(", "contents", ")", "-", "end", ")", "\n", "b", ".", "Write", "(", "contents", "[", ":", "start", "]", ")", "\n", "b", ".", "WriteString", "(", "change", ".", "Text", ")", "\n", "b", ".", "Write", "(", "contents", "[", "end", ":", "]", ")", "\n", "contents", "=", "b", ".", "Bytes", "(", ")", "\n", "}", "\n", "return", "contents", ",", "nil", "\n", "}" ]
// 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", ")", "{", "// We do copy-on-write", "a", ".", "mu", ".", "Lock", "(", ")", "\n", "defer", "a", ".", "mu", ".", "Unlock", "(", ")", "\n\n", "fs1", ":=", "a", ".", "v", ".", "Load", "(", ")", ".", "(", "ctxvfs", ".", "NameSpace", ")", "\n", "fs2", ":=", "make", "(", "ctxvfs", ".", "NameSpace", ")", "\n", "for", "k", ",", "v", ":=", "range", "fs1", "{", "fs2", "[", "k", "]", "=", "v", "\n", "}", "\n", "fs2", ".", "Bind", "(", "old", ",", "newfs", ",", "new", ",", "mode", ")", "\n", "a", ".", "v", ".", "Store", "(", "fs2", ")", "\n", "}" ]
// 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", ".", "NameSpace", ")", "\n", "return", "fs", ".", "Open", "(", "ctx", ",", "path", ")", "\n", "}" ]
// 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", ".", "NameSpace", ")", "\n", "return", "fs", ".", "Stat", "(", "ctx", ",", "path", ")", "\n", "}" ]
// 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", ")", ")", ";", "err", "==", "nil", "&&", "i", ">", "0", "{", "size", "=", "i", "\n", "}", "\n", "c", ",", "err", ":=", "lru", ".", "New", "(", "size", ")", "\n", "if", "err", "!=", "nil", "{", "// This should never happen since our size is always > 0", "panic", "(", "err", ")", "\n", "}", "\n", "return", "c", "\n", "}" ]
// 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", "(", ")", "\n", "}" ]
// 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", ":", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "e", ".", "errors", "[", "0", "]", ",", "len", "(", "e", ".", "errors", ")", "-", "1", ")", "\n", "}", "\n", "}" ]
// 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", "(", ")", "{", "// Best-effort. Ignore error", "_", "=", "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", "*", "cachedFile", ",", "err", "error", ")", "{", "f", ",", "err", ":=", "s", ".", "Open", "(", "ctx", ",", "key", ",", "fetcher", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "return", "&", "cachedFile", "{", "File", ":", "f", ".", "File", ",", "path", ":", "f", ".", "Path", ",", "}", ",", "nil", "\n", "}" ]
// 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", ",", "err", ":=", "determineRootImportPath", "(", "ctx", ",", "params", ".", "OriginalRootURI", ",", "fs", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ",", "params", ".", "OriginalRootURI", ")", "\n", "}", "\n", "// 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", "(", "\"", "\"", ",", "rootImportPath", ")", "\n", "}", "\n\n", "// 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", "\n", "if", "rootImportPath", "==", "\"", "\"", "{", "// stdlib means our rootpath is the GOPATH", "rootPath", "=", "goroot", "\n", "rootImportPath", "=", "\"", "\"", "\n", "}", "else", "{", "rootPath", "=", "\"", "\"", "+", "rootImportPath", "\n", "}", "\n\n", "GOPATH", ":=", "gopath", "\n", "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", "=", "\"", "\"", "\n", "rootImportPath", "=", "\"", "\"", "\n", "for", "i", ":=", "range", "customGOPATH", "{", "customGOPATH", "[", "i", "]", "=", "rootPath", "+", "customGOPATH", "[", "i", "]", "\n", "}", "\n", "customGOPATH", "=", "append", "(", "customGOPATH", ",", "gopath", ")", "\n", "GOPATH", "=", "strings", ".", "Join", "(", "customGOPATH", ",", "\"", "\"", ")", "\n", "}", "\n\n", "// 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", ",", "}", ",", "}", "\n\n", "langInitParams", ".", "RootURI", "=", "lsp", ".", "DocumentURI", "(", "\"", "\"", "+", "rootPath", ")", "\n", "langInitParams", ".", "RootImportPath", "=", "rootImportPath", "\n\n", "return", "langInitParams", ",", "nil", "\n", "}" ]
// 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", "expected", "that", "fs", "will", "be", "mounted", "at", "InitializeParams", ".", "RootURI", "." ]
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 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", "\n", "}", "\n\n", "// Check .vscode/config.json and .envrc files, giving them equal precedence.", "if", "paths", ":=", "detectVSCodeGOPATH", "(", "ctx", ",", "fs", ")", ";", "len", "(", "paths", ")", ">", "0", "{", "gopaths", "=", "append", "(", "gopaths", ",", "paths", "...", ")", "\n", "}", "\n", "if", "paths", ":=", "detectEnvRCGOPATH", "(", "ctx", ",", "fs", ")", ";", "len", "(", "paths", ")", ">", "0", "{", "gopaths", "=", "append", "(", "gopaths", ",", "paths", "...", ")", "\n", "}", "\n", "return", "\n", "}" ]
// 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", "an", "empty", "result", "is", "returned", "." ]
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", ":", "true", "}", ")", "\n", "if", "len", "(", "errs", ")", ">", "0", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "errs", ")", "\n", "}", "\n", "return", "json", ".", "Unmarshal", "(", "data", ",", "v", ")", "\n", "}" ]
// 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", "(", ")", "\n", "}", "\n", "return", "typ", "\n", "}" ]
// 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", "{", "mu", "=", "&", "sync", ".", "Mutex", "{", "}", "\n", "k", ".", "mus", "[", "key", "]", "=", "mu", "\n", "}", "\n", "k", ".", "mu", ".", "Unlock", "(", ")", "\n", "return", "mu", "\n", "}" ]
// 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", ".", "SpanFromContext", "(", "ctx", ")", "\n", "span", ":=", "parentSpan", ".", "Tracer", "(", ")", ".", "StartSpan", "(", "\"", "\"", ",", "opentracing", ".", "Tags", "{", "\"", "\"", ":", "fileURI", "}", ",", "opentracing", ".", "ChildOf", "(", "parentSpan", ".", "Context", "(", ")", ")", ",", ")", "\n", "ctx", "=", "opentracing", ".", "ContextWithSpan", "(", "ctx", ",", "span", ")", "\n", "defer", "func", "(", ")", "{", "if", "err", "!=", "nil", "{", "ext", ".", "Error", ".", "Set", "(", "span", ",", "true", ")", "\n", "span", ".", "LogFields", "(", "otlog", ".", "Error", "(", "err", ")", ")", "\n", "}", "\n", "span", ".", "Finish", "(", ")", "\n", "}", "(", ")", "\n\n", "bctx", ":=", "h", ".", "lang", ".", "BuildContext", "(", "ctx", ")", "\n", "filename", ":=", "h", ".", "FilePath", "(", "fileURI", ")", "\n", "bpkg", ",", "err", ":=", "langserver", ".", "ContainingPackage", "(", "bctx", ",", "filename", ",", "h", ".", "RootFSPath", ")", "\n", "if", "err", "!=", "nil", "&&", "!", "isMultiplePackageError", "(", "err", ")", "{", "return", "err", "\n", "}", "\n\n", "err", "=", "doDeps", "(", "bpkg", ",", "0", ",", "dc", ",", "func", "(", "path", ",", "srcDir", "string", ",", "mode", "build", ".", "ImportMode", ")", "(", "*", "build", ".", "Package", ",", "error", ")", "{", "return", "h", ".", "doFindPackage", "(", "ctx", ",", "bctx", ",", "path", ",", "srcDir", ",", "mode", ",", "dc", ")", "\n", "}", ")", "\n", "return", "err", "\n", "}" ]
// 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", "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", "." ]
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", ".", "Package", ",", "error", ")", "{", "return", "h", ".", "doFindPackage", "(", "ctx", ",", "bctx", ",", "path", ",", "srcDir", ",", "mode", ",", "newDepCache", "(", ")", ")", "\n", "}" ]
// 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", "(", ")", "{", "// github.com/golang/go", "d", ",", "_", ":=", "gosrc", ".", "ResolveImportPath", "(", "http", ".", "DefaultClient", ",", "\"", "\"", ")", "\n", "u", ",", "_", ":=", "url", ".", "Parse", "(", "d", ".", "CloneURL", ")", "\n", "_", ",", "_", "=", "NewDepRepoVFS", "(", "context", ".", "Background", "(", ")", ",", "u", ",", "d", ".", "Rev", ",", "nil", ")", "\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", "from", "the", "internet", "." ]
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", ".", "Buffer", "\n", "doc", ".", "ToMarkdown", "(", "&", "b", ",", "comments", ",", "nil", ")", "\n", "return", "append", "(", "contents", ",", "lsp", ".", "RawMarkedString", "(", "b", ".", "String", "(", ")", ")", ")", "\n", "}" ]
// 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", "bText", "\n", "}", "else", "if", "bText", "==", "\"", "\"", "{", "return", "aText", "\n", "}", "else", "{", "return", "aText", "+", "\"", "\\n", "\"", "+", "bText", "\n", "}", "\n", "}" ]
// 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", ".", "Doc", ".", "Text", "(", ")", "\n", "if", "strings", ".", "TrimSpace", "(", "txt", ")", "!=", "\"", "\"", "{", "return", "txt", "\n", "}", "\n", "}", "\n", "}", "\n", "return", "\"", "\"", "\n", "}" ]
// 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", "{", "// Grab files from builtin package", "pkgs", ",", "err", ":=", "packages", ".", "Load", "(", "&", "packages", ".", "Config", "{", "Mode", ":", "packages", ".", "LoadFiles", ",", "}", ",", "\"", "\"", ",", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", "\n", "}", "\n\n", "// Parse the files into ASTs", "pkg", ":=", "pkgs", "[", "0", "]", "\n", "fs", ":=", "token", ".", "NewFileSet", "(", ")", "\n", "asts", ":=", "&", "ast", ".", "Package", "{", "Name", ":", "\"", "\"", ",", "Files", ":", "make", "(", "map", "[", "string", "]", "*", "ast", ".", "File", ")", ",", "}", "\n", "for", "_", ",", "filename", ":=", "range", "pkg", ".", "GoFiles", "{", "file", ",", "err", ":=", "parser", ".", "ParseFile", "(", "fs", ",", "filename", ",", "nil", ",", "parser", ".", "ParseComments", ")", "\n", "if", "err", "!=", "nil", "{", "fmt", ".", "Println", "(", "err", ".", "Error", "(", ")", ")", "\n", "}", "\n", "asts", ".", "Files", "[", "filename", "]", "=", "file", "\n", "}", "\n\n", "// Extract documentation and declaration from the ASTs", "docs", ":=", "doc", ".", "New", "(", "asts", ",", "\"", "\"", ",", "doc", ".", "AllDecls", ")", "\n", "node", ",", "pos", ":=", "findDocIdent", "(", "docs", ",", "ident", ")", "\n", "contents", ",", "_", ":=", "fmtDocObject", "(", "fs", ",", "node", ",", "fs", ".", "Position", "(", "pos", ")", ")", "\n", "return", "contents", "\n", "}" ]
// 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", "{", "for", "pkgFile", ":=", "range", "pkg", ".", "Files", "{", "if", "pkgFile", "==", "filename", "{", "return", "path", ",", "pkg", ",", "nil", "\n", "}", "\n", "}", "\n", "}", "\n", "return", "\"", "\"", ",", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "filename", ",", "pkgs", ")", "\n", "}" ]
// 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", ".", "Filename", ",", "b", ".", "Filename", ")", "{", "return", "false", "\n", "}", "\n", "return", "x", ".", "Offset", ">=", "a", ".", "Offset", "&&", "x", ".", "Offset", "<=", "b", ".", "Offset", "\n", "}" ]
// 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", "if", "err", "!=", "nil", "{", "panic", "(", "\"", "\"", ")", "\n", "}", "\n", "return", "buf", ".", "String", "(", ")", "\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", "dereferencable", ":", "otyp", "=", "typ", ".", "Elem", "(", ")", "\n", "default", ":", "return", "otyp", "\n", "}", "\n", "}", "\n", "}" ]
// 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", ".", "The", "special", "case", "for", "Map", "is", "because", "a", "Map", "would", "also", "have", "a", "key", "and", "you", "might", "be", "interested", "in", "either", "of", "those", "." ]
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", "*", "token", ".", "FileSet", ",", "pkg", "*", "loader", ".", "PackageInfo", ",", "files", "[", "]", "*", "ast", ".", "File", ",", "rootPath", "string", ",", "results", "*", "refResult", ")", "(", "err", "error", ")", "{", "if", "err", ":=", "ctx", ".", "Err", "(", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "span", ",", "ctx", ":=", "opentracing", ".", "StartSpanFromContext", "(", "ctx", ",", "\"", "\"", ")", "\n", "defer", "func", "(", ")", "{", "if", "err", "!=", "nil", "{", "ext", ".", "Error", ".", "Set", "(", "span", ",", "true", ")", "\n", "span", ".", "SetTag", "(", "\"", "\"", ",", "err", ".", "Error", "(", ")", ")", "\n", "}", "\n", "span", ".", "Finish", "(", ")", "\n", "}", "(", ")", "\n", "span", ".", "SetTag", "(", "\"", "\"", ",", "pkg", ")", "\n\n", "// Compute workspace references.", "findPackage", ":=", "h", ".", "getFindPackageFunc", "(", ")", "\n", "cfg", ":=", "&", "refs", ".", "Config", "{", "FileSet", ":", "fs", ",", "Pkg", ":", "pkg", ".", "Pkg", ",", "PkgFiles", ":", "files", ",", "Info", ":", "&", "pkg", ".", "Info", ",", "}", "\n", "refsErr", ":=", "cfg", ".", "Refs", "(", "func", "(", "r", "*", "refs", ".", "Ref", ")", "{", "symDesc", ",", "err", ":=", "defSymbolDescriptor", "(", "ctx", ",", "bctx", ",", "rootPath", ",", "r", ".", "Def", ",", "findPackage", ")", "\n", "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", ")", "\n", "err", ":=", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "r", ".", "Def", ".", "ImportPath", ",", "err", ")", "\n", "log", ".", "Println", "(", "err", ")", "\n", "span", ".", "SetTag", "(", "\"", "\"", ",", "err", ".", "Error", "(", ")", ")", "\n", "return", "\n", "}", "\n", "if", "!", "symDesc", ".", "Contains", "(", "params", ".", "Query", ")", "{", "return", "\n", "}", "\n\n", "results", ".", "resultsMu", ".", "Lock", "(", ")", "\n", "results", ".", "results", "=", "append", "(", "results", ".", "results", ",", "referenceInformation", "{", "Reference", ":", "goRangeToLSPLocation", "(", "fs", ",", "r", ".", "Start", ",", "r", ".", "End", ")", ",", "Symbol", ":", "symDesc", ",", "}", ")", "\n", "results", ".", "resultsMu", ".", "Unlock", "(", ")", "\n", "}", ")", "\n", "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", "(", "\"", "\"", ",", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "pkg", ",", "refsErr", ")", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// 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", ".", "Package", ",", "error", ")", "{", "pkg", ":=", "&", "ast", ".", "Package", "{", "src", ".", "Name", ".", "Name", ",", "pkgScope", ",", "nil", ",", "map", "[", "string", "]", "*", "ast", ".", "File", "{", "filename", ":", "src", "}", "}", "\n", "d", ",", "f", ":=", "filepath", ".", "Split", "(", "filename", ")", "\n", "if", "d", "==", "\"", "\"", "{", "d", "=", "\"", "\"", "\n", "}", "\n", "fd", ",", "err", ":=", "os", ".", "Open", "(", "d", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "defer", "fd", ".", "Close", "(", ")", "\n\n", "list", ",", "err", ":=", "fd", ".", "Readdirnames", "(", "-", "1", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errNoPkgFiles", "\n", "}", "\n\n", "for", "_", ",", "pf", ":=", "range", "list", "{", "file", ":=", "filepath", ".", "Join", "(", "d", ",", "pf", ")", "\n", "if", "!", "strings", ".", "HasSuffix", "(", "pf", ",", "\"", "\"", ")", "||", "pf", "==", "f", "||", "pkgName", "(", "fset", ",", "file", ")", "!=", "pkg", ".", "Name", "{", "continue", "\n", "}", "\n", "src", ",", "err", ":=", "parser", ".", "ParseFile", "(", "fset", ",", "file", ",", "nil", ",", "0", ",", "pkg", ".", "Scope", ",", "types", ".", "DefaultImportPathToName", ")", "\n", "if", "err", "==", "nil", "{", "pkg", ".", "Files", "[", "file", "]", "=", "src", "\n", "}", "\n", "}", "\n", "if", "len", "(", "pkg", ".", "Files", ")", "==", "1", "{", "return", "nil", ",", "errNoPkgFiles", "\n", "}", "\n", "return", "pkg", ",", "nil", "\n", "}" ]
// 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", "which", "will", "already", "have", "been", "parsed", "." ]
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", ",", "nil", ",", "types", ".", "DefaultImportPathToName", ")", "\n", "if", "prog", "!=", "nil", "{", "return", "prog", ".", "Name", ".", "Name", "\n", "}", "\n", "return", "\"", "\"", "\n", "}" ]
// 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", ")", "{", "data", ",", "err", ":=", "readSource", "(", "filename", ",", "src", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "var", "p", "parser", "\n", "p", ".", "init", "(", "fset", ",", "filename", ",", "data", ",", "0", ",", "scope", ",", "pathToName", ")", "\n", "x", ":=", "p", ".", "parseExpr", "(", ")", "\n", "if", "p", ".", "tok", "==", "token", ".", "SEMICOLON", "{", "p", ".", "next", "(", ")", "// consume automatically inserted semicolon, if any", "\n", "}", "\n", "return", "x", ",", "p", ".", "parseEOF", "(", ")", "\n", "}" ]
// 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", "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", "." ]
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", "]", "*", "ast", ".", "Package", ",", "error", ")", "{", "fd", ",", "err", ":=", "os", ".", "Open", "(", "path", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "defer", "fd", ".", "Close", "(", ")", "\n\n", "list", ",", "err", ":=", "fd", ".", "Readdir", "(", "-", "1", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "filenames", ":=", "make", "(", "[", "]", "string", ",", "len", "(", "list", ")", ")", "\n", "n", ":=", "0", "\n", "for", "i", ":=", "0", ";", "i", "<", "len", "(", "list", ")", ";", "i", "++", "{", "d", ":=", "list", "[", "i", "]", "\n", "if", "filter", "==", "nil", "||", "filter", "(", "d", ")", "{", "filenames", "[", "n", "]", "=", "filepath", ".", "Join", "(", "path", ",", "d", ".", "Name", "(", ")", ")", "\n", "n", "++", "\n", "}", "\n", "}", "\n", "filenames", "=", "filenames", "[", "0", ":", "n", "]", "\n\n", "return", "ParseFiles", "(", "fset", ",", "filenames", ",", "mode", ",", "pathToName", ")", "\n", "}" ]
// 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", "!", "=", "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", "." ]
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", ".", "Errorf", "(", "`invalid GitHub repo %q: must be \"github.com/user/repo\"`", ",", "repo", ")", "\n", "}", "\n\n", "url", ":=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "repo", ",", "rev", ")", "\n", "return", "NewZipVFS", "(", "ctx", ",", "url", ",", "ghFetch", ".", "Inc", ",", "ghFetchFailed", ".", "Inc", ",", "false", ")", "\n", "}" ]
// 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 = &copy } 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 = &copy } 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", ";", "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", ",", "}", "\n", "}", "else", "{", "// make a copy since we will mutate it", "copy", ":=", "build", ".", "Default", "\n", "bctx", "=", "&", "copy", "\n", "}", "\n\n", "h", ".", "Mu", ".", "Lock", "(", ")", "\n", "fs", ":=", "h", ".", "FS", "\n", "h", ".", "Mu", ".", "Unlock", "(", ")", "\n\n", "util", ".", "PrepareContext", "(", "bctx", ",", "ctx", ",", "fs", ")", "\n", "return", "bctx", "\n", "}" ]
// 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", ")", "{", "// 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", ")", ")", "\n", "for", "k", ":=", "range", "m", "{", "keys", "=", "append", "(", "keys", ",", "k", ")", "\n", "}", "\n", "sort", ".", "Strings", "(", "keys", ")", "\n", "for", "_", ",", "k", ":=", "range", "keys", "{", "emitRef", "(", "path", ",", "m", "[", "k", "]", ")", "\n", "}", "\n", "}", "\n\n", "// Prepare a function to walk every package node in the above example graph.", "beganWalk", ":=", "map", "[", "string", "]", "struct", "{", "}", "{", "}", "\n", "var", "walk", "func", "(", "rootDir", ",", "pkgDir", "string", ",", "parentDirs", "[", "]", "string", ",", "emissions", "map", "[", "string", "]", "goDependencyReference", ",", "depth", "int", ")", "\n", "walk", "=", "func", "(", "rootDir", ",", "pkgDir", "string", ",", "parentDirs", "[", "]", "string", ",", "emissions", "map", "[", "string", "]", "goDependencyReference", ",", "depth", "int", ")", "{", "if", "depth", ">=", "depthLimit", "{", "return", "\n", "}", "\n\n", "// 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", "]", "\n", "sort", ".", "Sort", "(", "sortedImportRecord", "(", "imports", ")", ")", "\n\n", "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", "\n", "}", "\n\n", "// 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", "\n", "for", "_", ",", "parentDir", ":=", "range", "parentDirs", "{", "if", "parentDir", "==", "imp", ".", "imports", ".", "Dir", "{", "cyclic", "=", "true", "\n", "break", "\n", "}", "\n", "}", "\n", "if", "cyclic", "{", "continue", "\n", "}", "\n\n", "// Walk the referenced dependency so that we emit transitive", "// dependencies.", "walk", "(", "rootDir", ",", "imp", ".", "imports", ".", "Dir", ",", "append", "(", "parentDirs", ",", "pkgDir", ")", ",", "emissions", ",", "depth", "+", "1", ")", "\n\n", "// If the dependency being referenced has not already been walked", "// individually / on its own, do so now.", "_", ",", "began", ":=", "beganWalk", "[", "imp", ".", "imports", ".", "Dir", "]", "\n", "if", "!", "began", "{", "beganWalk", "[", "imp", ".", "imports", ".", "Dir", "]", "=", "struct", "{", "}", "{", "}", "\n", "childEmissions", ":=", "map", "[", "string", "]", "goDependencyReference", "{", "}", "\n", "walk", "(", "imp", ".", "imports", ".", "Dir", ",", "imp", ".", "imports", ".", "Dir", ",", "append", "(", "parentDirs", ",", "pkgDir", ")", ",", "childEmissions", ",", "0", ")", "\n", "orderedEmit", "(", "imp", ".", "imports", ".", "Dir", ",", "childEmissions", ")", "\n", "}", "\n\n", "// 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", "\n", "}", "\n", "}", "\n", "emissions", "[", "imp", ".", "imports", ".", "ImportPath", "]", "=", "goDependencyReference", "{", "pkg", ":", "unvendoredPath", "(", "imp", ".", "imports", ".", "ImportPath", ")", ",", "absolute", ":", "imp", ".", "imports", ".", "ImportPath", ",", "vendor", ":", "util", ".", "IsVendorDir", "(", "imp", ".", "imports", ".", "Dir", ")", ",", "depth", ":", "depth", ",", "}", "\n", "}", "\n", "}", "\n", "sort", ".", "Strings", "(", "d", ".", "entryPackageDirs", ")", "\n", "for", "_", ",", "entryDir", ":=", "range", "d", ".", "entryPackageDirs", "{", "emissions", ":=", "map", "[", "string", "]", "goDependencyReference", "{", "}", "\n", "walk", "(", "entryDir", ",", "entryDir", ",", "nil", ",", "emissions", ",", "0", ")", "\n", "orderedEmit", "(", "entryDir", ",", "emissions", ")", "\n", "}", "\n", "}" ]
// 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", "package", "described", "by", "r", "." ]
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", "// 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", "\n", "return", "\n", "}", "\n", "}", "\n", "if", "p", ".", "pkgScope", "==", "nil", "{", "return", "\n", "}", "\n", "ident", ".", "Obj", "=", "ast", ".", "NewObj", "(", "ast", ".", "Bad", ",", "ident", ".", "Name", ")", "\n", "p", ".", "pkgScope", ".", "Insert", "(", "ident", ".", "Obj", ")", "\n", "}" ]
// 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", "(", ")", "{", "// 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", "(", ")", "\n", "switch", "{", "case", "p", ".", "tok", ".", "IsLiteral", "(", ")", ":", "p", ".", "printTrace", "(", "s", ",", "string", "(", "p", ".", "lit", ")", ")", "\n", "case", "p", ".", "tok", ".", "IsOperator", "(", ")", ",", "p", ".", "tok", ".", "IsKeyword", "(", ")", ":", "p", ".", "printTrace", "(", "\"", "\\\"", "\"", "+", "s", "+", "\"", "\\\"", "\"", ")", "\n", "default", ":", "p", ".", "printTrace", "(", "s", ")", "\n", "}", "\n", "}", "\n\n", "p", ".", "pos", ",", "p", ".", "tok", ",", "p", ".", "lit", "=", "p", ".", "scanner", ".", "Scan", "(", ")", "\n", "}" ]
// 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", ")", "{", "// /*-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", ")", "\n", "if", "p", ".", "lit", "[", "1", "]", "==", "'*'", "{", "for", "_", ",", "b", ":=", "range", "p", ".", "lit", "{", "if", "b", "==", "'\\n'", "{", "endline", "++", "\n", "}", "\n", "}", "\n", "}", "\n\n", "comment", "=", "&", "ast", ".", "Comment", "{", "p", ".", "pos", ",", "p", ".", "lit", "}", "\n", "p", ".", "next0", "(", ")", "\n\n", "return", "\n", "}" ]
// 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", ".", "Line", "(", "p", ".", "pos", ")", "\n", "for", "p", ".", "tok", "==", "token", ".", "COMMENT", "&&", "endline", "+", "1", ">=", "p", ".", "file", ".", "Line", "(", "p", ".", "pos", ")", "{", "var", "comment", "*", "ast", ".", "Comment", "\n", "comment", ",", "endline", "=", "p", ".", "consumeComment", "(", ")", "\n", "list", "=", "append", "(", "list", ",", "comment", ")", "\n", "}", "\n\n", "// add comment group to the comments list", "comments", "=", "&", "ast", ".", "CommentGroup", "{", "list", "}", "\n", "p", ".", "comments", "=", "append", "(", "p", ".", "comments", ",", "comments", ")", "\n\n", "return", "\n", "}" ]
// 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", "empty", "line", "or", "non", "-", "comment", "token", "terminates", "a", "comment", "group", "." ]
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", ")", "// current line", "\n", "p", ".", "next0", "(", ")", "\n\n", "if", "p", ".", "tok", "==", "token", ".", "COMMENT", "{", "var", "comment", "*", "ast", ".", "CommentGroup", "\n", "var", "endline", "int", "\n\n", "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", "(", ")", "\n", "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", "\n", "}", "\n", "}", "\n\n", "// consume successor comments, if any", "endline", "=", "-", "1", "\n", "for", "p", ".", "tok", "==", "token", ".", "COMMENT", "{", "comment", ",", "endline", "=", "p", ".", "consumeCommentGroup", "(", ")", "\n", "}", "\n\n", "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", "\n", "}", "\n", "}", "\n", "}" ]
// 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", "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", "." ]
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", ")", "\n", "*", "id", "=", "*", "t", "\n", "id", ".", "Obj", "=", "ast", ".", "NewObj", "(", "ast", ".", "Var", ",", "id", ".", "Name", ")", "\n", "id", ".", "Obj", ".", "Decl", "=", "&", "ast", ".", "Field", "{", "nil", ",", "[", "]", "*", "ast", ".", "Ident", "{", "id", "}", ",", "declType", ",", "nil", ",", "nil", "}", "\n", "return", "id", "\n\n", "case", "*", "ast", ".", "SelectorExpr", ":", "return", "&", "ast", ".", "SelectorExpr", "{", "t", ".", "X", ",", "makeAnonField", "(", "t", ".", "Sel", ",", "declType", ")", ".", "(", "*", "ast", ".", "Ident", ")", "}", "\n\n", "case", "*", "ast", ".", "StarExpr", ":", "return", "&", "ast", ".", "StarExpr", "{", "t", ".", "Star", ",", "makeAnonField", "(", "t", ".", "X", ",", "declType", ")", "}", "\n", "}", "\n", "return", "t", "\n", "}" ]
// 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", ":", "_", ",", "isIdent", ":=", "t", ".", "X", ".", "(", "*", "ast", ".", "Ident", ")", "\n", "return", "isIdent", "\n", "case", "*", "ast", ".", "ArrayType", ":", "case", "*", "ast", ".", "StructType", ":", "case", "*", "ast", ".", "MapType", ":", "default", ":", "return", "false", "// all other nodes are not legal composite literal types", "\n", "}", "\n", "return", "true", "\n", "}" ]
// 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", "(", "outer", ")", "\n", "}" ]
// 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", ",", "0", ",", "nil", "\n", "}", "\n\n", "a", ",", "err", ":=", "c", ".", "analyzePackage", "(", "filename", ",", "data", ",", "cursor", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "0", ",", "err", "\n", "}", "\n", "fset", ":=", "a", ".", "fset", "\n", "pos", ":=", "a", ".", "pos", "\n", "pkg", ":=", "a", ".", "pkg", "\n", "if", "pkg", "==", "nil", "{", "return", "nil", ",", "0", ",", "nil", "\n", "}", "\n", "scope", ":=", "pkg", ".", "Scope", "(", ")", ".", "Innermost", "(", "pos", ")", "\n\n", "ctx", ",", "expr", ",", "partial", ":=", "deduceCursorContext", "(", "data", ",", "cursor", ")", "\n", "b", ":=", "candidateCollector", "{", "localpkg", ":", "pkg", ",", "partial", ":", "partial", ",", "filter", ":", "objectFilters", "[", "partial", "]", ",", "builtin", ":", "ctx", "!=", "selectContext", "&&", "c", ".", "Builtin", ",", "}", "\n\n", "switch", "ctx", "{", "case", "selectContext", ":", "tv", ",", "_", ":=", "types", ".", "Eval", "(", "fset", ",", "pkg", ",", "pos", ",", "expr", ")", "\n", "if", "lookdot", ".", "Walk", "(", "&", "tv", ",", "b", ".", "appendObject", ")", "{", "break", "\n", "}", "\n\n", "_", ",", "obj", ":=", "scope", ".", "LookupParent", "(", "expr", ",", "pos", ")", "\n", "if", "pkgName", ",", "isPkg", ":=", "obj", ".", "(", "*", "types", ".", "PkgName", ")", ";", "isPkg", "{", "c", ".", "packageCandidates", "(", "pkgName", ".", "Imported", "(", ")", ",", "&", "b", ")", "\n", "break", "\n", "}", "\n\n", "return", "nil", ",", "0", ",", "nil", "\n\n", "case", "compositeLiteralContext", ":", "tv", ",", "_", ":=", "types", ".", "Eval", "(", "fset", ",", "pkg", ",", "pos", ",", "expr", ")", "\n", "if", "tv", ".", "IsType", "(", ")", "{", "if", "_", ",", "isStruct", ":=", "tv", ".", "Type", ".", "Underlying", "(", ")", ".", "(", "*", "types", ".", "Struct", ")", ";", "isStruct", "{", "c", ".", "fieldNameCandidates", "(", "tv", ".", "Type", ",", "&", "b", ")", "\n", "break", "\n", "}", "\n", "}", "\n\n", "fallthrough", "\n", "default", ":", "c", ".", "scopeCandidates", "(", "scope", ",", "pos", ",", "&", "b", ")", "\n", "}", "\n\n", "res", ":=", "b", ".", "getCandidates", "(", ")", "\n", "if", "len", "(", "res", ")", "==", "0", "{", "return", "nil", ",", "0", ",", "nil", "\n", "}", "\n", "return", "res", ",", "len", "(", "partial", ")", ",", "nil", "\n", "}" ]
// 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", ".", "StartSpanFromContext", "(", "ctx", ",", "\"", "\"", ")", "\n", "if", "s", ".", "Component", "!=", "\"", "\"", "{", "ext", ".", "Component", ".", "Set", "(", "span", ",", "s", ".", "Component", ")", "\n", "}", "\n", "defer", "func", "(", ")", "{", "if", "err", "!=", "nil", "{", "ext", ".", "Error", ".", "Set", "(", "span", ",", "true", ")", "\n", "span", ".", "SetTag", "(", "\"", "\"", ",", "err", ".", "Error", "(", ")", ")", "\n", "}", "\n", "if", "file", "!=", "nil", "{", "// Update modified time. Modified time is used to decide which", "// files to evict from the cache.", "touch", "(", "file", ".", "Path", ")", "\n", "}", "\n", "span", ".", "Finish", "(", ")", "\n", "}", "(", ")", "\n\n", "if", "s", ".", "Dir", "==", "\"", "\"", "{", "return", "nil", ",", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n\n", "// path uses a sha256 hash of the key since we want to use it for the", "// disk name.", "h", ":=", "sha256", ".", "Sum256", "(", "[", "]", "byte", "(", "key", ")", ")", "\n", "path", ":=", "filepath", ".", "Join", "(", "s", ".", "Dir", ",", "hex", ".", "EncodeToString", "(", "h", "[", ":", "]", ")", ")", "+", "\"", "\"", "\n", "span", ".", "LogKV", "(", "\"", "\"", ",", "key", ",", "\"", "\"", ",", "path", ")", "\n\n", "// First do a fast-path, assume already on disk", "f", ",", "err", ":=", "os", ".", "Open", "(", "path", ")", "\n", "if", "err", "==", "nil", "{", "span", ".", "SetTag", "(", "\"", "\"", ",", "\"", "\"", ")", "\n", "return", "&", "File", "{", "File", ":", "f", ",", "Path", ":", "path", "}", ",", "nil", "\n", "}", "\n\n", "// We (probably) have to fetch", "span", ".", "SetTag", "(", "\"", "\"", ",", "\"", "\"", ")", "\n\n", "// Do the fetch in another goroutine so we can respect ctx cancellation.", "type", "result", "struct", "{", "f", "*", "File", "\n", "err", "error", "\n", "}", "\n", "ch", ":=", "make", "(", "chan", "result", ",", "1", ")", "\n", "go", "func", "(", "ctx", "context", ".", "Context", ")", "{", "if", "s", ".", "BackgroundTimeout", "!=", "0", "{", "var", "cancel", "context", ".", "CancelFunc", "\n", "ctx", ",", "cancel", "=", "context", ".", "WithTimeout", "(", "context", ".", "Background", "(", ")", ",", "s", ".", "BackgroundTimeout", ")", "\n", "defer", "cancel", "(", ")", "\n", "}", "\n", "f", ",", "err", ":=", "doFetch", "(", "ctx", ",", "path", ",", "fetcher", ")", "\n", "ch", "<-", "result", "{", "f", ",", "err", "}", "\n", "}", "(", "ctx", ")", "\n\n", "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", "(", ")", "\n", "case", "r", ":=", "<-", "ch", ":", "return", "r", ".", "f", ",", "r", ".", "err", "\n", "}", "\n", "}" ]
// 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", ".", "HasSuffix", "(", "fi", ".", "Name", "(", ")", ",", "\"", "\"", ")", "\n", "}", "\n\n", "list", ",", "err", ":=", "ioutil", ".", "ReadDir", "(", "s", ".", "Dir", ")", "\n", "if", "err", "!=", "nil", "{", "if", "os", ".", "IsNotExist", "(", "err", ")", "{", "return", "EvictStats", "{", "CacheSize", ":", "0", ",", "Evicted", ":", "0", ",", "}", ",", "nil", "\n", "}", "\n", "return", "stats", ",", "errors", ".", "Wrapf", "(", "err", ",", "\"", "\"", ",", "s", ".", "Dir", ")", "\n", "}", "\n\n", "// Sum up the total size of all zips", "var", "size", "int64", "\n", "for", "_", ",", "fi", ":=", "range", "list", "{", "if", "isZip", "(", "fi", ")", "{", "size", "+=", "fi", ".", "Size", "(", ")", "\n", "}", "\n", "}", "\n", "stats", ".", "CacheSize", "=", "size", "\n\n", "// Nothing to evict", "if", "size", "<=", "maxCacheSizeBytes", "{", "return", "stats", ",", "nil", "\n", "}", "\n\n", "// 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", "(", ")", ")", "\n", "}", ")", "\n", "for", "_", ",", "fi", ":=", "range", "list", "{", "if", "size", "<=", "maxCacheSizeBytes", "{", "break", "\n", "}", "\n", "if", "!", "isZip", "(", "fi", ")", "{", "continue", "\n", "}", "\n", "path", ":=", "filepath", ".", "Join", "(", "s", ".", "Dir", ",", "fi", ".", "Name", "(", ")", ")", "\n", "if", "s", ".", "BeforeEvict", "!=", "nil", "{", "s", ".", "BeforeEvict", "(", "path", ")", "\n", "}", "\n", "err", "=", "os", ".", "Remove", "(", "path", ")", "\n", "if", "err", "!=", "nil", "{", "log", ".", "Printf", "(", "\"", "\"", ",", "path", ",", "err", ")", "\n", "continue", "\n", "}", "\n", "stats", ".", "Evicted", "++", "\n", "size", "-=", "fi", ".", "Size", "(", ")", "\n", "}", "\n\n", "return", "stats", ",", "nil", "\n", "}" ]
// 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", "if", "!", "strings", ".", "HasSuffix", "(", "prefix", ",", "\"", "\"", ")", "{", "prefix", "+=", "\"", "\"", "\n", "}", "\n", "return", "s", "==", "prefix", "||", "strings", ".", "HasPrefix", "(", "s", ",", "prefix", ")", "\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", "}", "\n", "if", "!", "strings", ".", "HasSuffix", "(", "prefix", ",", "\"", "\"", ")", "{", "prefix", "+=", "\"", "\"", "\n", "}", "\n", "return", "strings", ".", "TrimPrefix", "(", "s", ",", "prefix", ")", "\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", ",", "\"", "\"", ")", "||", "strings", ".", "Contains", "(", "dir", ",", "\"", "\"", ")", "\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\n", "// If the first segment is a Windows drive letter, prefix with a slash and skip encoding", "head", ":=", "parts", "[", "0", "]", "\n", "if", "head", "!=", "\"", "\"", "{", "head", "=", "\"", "\"", "+", "head", "\n", "}", "\n\n", "rest", ":=", "\"", "\"", "\n", "if", "len", "(", "parts", ")", ">", "1", "{", "rest", "=", "\"", "\"", "+", "parts", "[", "1", "]", "\n", "}", "\n\n", "return", "lsp", ".", "DocumentURI", "(", "\"", "\"", "+", "head", "+", "rest", ")", "\n", "}" ]
// 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", "(", "uri", ")", ")", "\n", "}", "\n", "return", "u", ".", "Path", "\n", "}" ]
// 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\n", "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", ":", "]", ")", "\n", "}", "\n\n", "return", "path", "\n", "}" ]
// 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", "{", "// Windows implementation accepts path-like and filepath-like arguments", "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", "!=", "nil", "{", "return", "\n", "}", "\n\n", "if", "_", ",", "isNoopTracer", ":=", "opentracing", ".", "GlobalTracer", "(", ")", ".", "(", "opentracing", ".", "NoopTracer", ")", ";", "!", "isNoopTracer", "{", "// We have configured a tracer, use that instead of telemetry/event", "h", ".", "tracer", "=", "opentracing", ".", "GlobalTracer", "(", ")", "\n", "return", "\n", "}", "\n\n", "t", ":=", "tracer", "{", "conn", ":", "conn", "}", "\n", "opt", ":=", "basictracer", ".", "DefaultOptions", "(", ")", "\n", "opt", ".", "Recorder", "=", "&", "t", "\n", "h", ".", "tracer", "=", "basictracer", ".", "NewWithOptions", "(", "opt", ")", "\n", "go", "func", "(", ")", "{", "<-", "conn", ".", "DisconnectNotify", "(", ")", "\n", "t", ".", "mu", ".", "Lock", "(", ")", "\n", "t", ".", "conn", "=", "nil", "\n", "t", ".", "mu", ".", "Unlock", "(", ")", "\n", "}", "(", ")", "\n", "}" ]
// 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", ".", "SpanFromContext", "(", "ctx", ")", ";", "parentSpan", "!=", "nil", "{", "opts", "=", "append", "(", "opts", ",", "opentracing", ".", "FollowsFrom", "(", "parentSpan", ".", "Context", "(", ")", ")", ")", "\n", "return", "parentSpan", ".", "Tracer", "(", ")", ".", "StartSpan", "(", "operationName", ",", "opts", "...", ")", "\n", "}", "\n", "return", "opentracing", ".", "GlobalTracer", "(", ")", ".", "StartSpan", "(", "operationName", ",", "opts", "...", ")", "\n", "}" ]
// 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\n", "pathType", ":=", "\"", "\"", "\n", "if", "e", ".", "IsDir", "(", ")", "{", "pathType", "=", "\"", "\"", "\n", "}", "\n", "return", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "pathType", ",", "e", ".", "Name", "(", ")", ",", "e", ".", "Op", ",", "e", ".", "Path", ")", "\n", "}" ]
// 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", ".", "Name", "(", ")", "\n\n", "if", "useFullPath", "{", "str", "=", "fullPath", "\n", "}", "\n\n", "// Match", "if", "r", ".", "MatchString", "(", "str", ")", "{", "return", "nil", "\n", "}", "\n\n", "// No match.", "return", "ErrSkip", "\n", "}", "\n", "}" ]
// 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", "{", "// Set up the WaitGroup for w.Wait().", "var", "wg", "sync", ".", "WaitGroup", "\n", "wg", ".", "Add", "(", "1", ")", "\n\n", "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", ")", ",", "}", "\n", "}" ]
// 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", "the", "default", "." ]
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", "_", ",", "op", ":=", "range", "ops", "{", "w", ".", "ops", "[", "op", "]", "=", "struct", "{", "}", "{", "}", "\n", "}", "\n", "w", ".", "mu", ".", "Unlock", "(", ")", "\n", "}" ]
// 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\n", "name", ",", "err", "=", "filepath", ".", "Abs", "(", "name", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "// 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", "]", "\n\n", "isHidden", ",", "err", ":=", "isHiddenFile", "(", "name", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "if", "ignored", "||", "(", "w", ".", "ignoreHidden", "&&", "isHidden", ")", "{", "return", "nil", "\n", "}", "\n\n", "// Add the directory's contents to the files list.", "fileList", ",", "err", ":=", "w", ".", "list", "(", "name", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "for", "k", ",", "v", ":=", "range", "fileList", "{", "w", ".", "files", "[", "k", "]", "=", "v", "\n", "}", "\n\n", "// Add the name to the names list.", "w", ".", "names", "[", "name", "]", "=", "false", "\n\n", "return", "nil", "\n", "}" ]
// 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\n", "name", ",", "err", "=", "filepath", ".", "Abs", "(", "name", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "fileList", ",", "err", ":=", "w", ".", "listRecursive", "(", "name", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "for", "k", ",", "v", ":=", "range", "fileList", "{", "w", ".", "files", "[", "k", "]", "=", "v", "\n", "}", "\n\n", "// Add the name to the names list.", "w", ".", "names", "[", "name", "]", "=", "true", "\n\n", "return", "nil", "\n", "}" ]
// 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\n", "name", ",", "err", "=", "filepath", ".", "Abs", "(", "name", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "// Remove the name from w's names list.", "delete", "(", "w", ".", "names", ",", "name", ")", "\n\n", "// If name is a single file, remove it and return.", "info", ",", "found", ":=", "w", ".", "files", "[", "name", "]", "\n", "if", "!", "found", "{", "return", "nil", "// Doesn't exist, just return.", "\n", "}", "\n", "if", "!", "info", ".", "IsDir", "(", ")", "{", "delete", "(", "w", ".", "files", ",", "name", ")", "\n", "return", "nil", "\n", "}", "\n\n", "// Delete the actual directory from w.files", "delete", "(", "w", ".", "files", ",", "name", ")", "\n\n", "// 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", ")", "\n", "}", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// 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\n", "name", ",", "err", "=", "filepath", ".", "Abs", "(", "name", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "// Remove the name from w's names list.", "delete", "(", "w", ".", "names", ",", "name", ")", "\n\n", "// If name is a single file, remove it and return.", "info", ",", "found", ":=", "w", ".", "files", "[", "name", "]", "\n", "if", "!", "found", "{", "return", "nil", "// Doesn't exist, just return.", "\n", "}", "\n", "if", "!", "info", ".", "IsDir", "(", ")", "{", "delete", "(", "w", ".", "files", ",", "name", ")", "\n", "return", "nil", "\n", "}", "\n\n", "// 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", ")", "\n", "}", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// 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", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "// Remove any of the paths that were already added.", "if", "err", ":=", "w", ".", "RemoveRecursive", "(", "path", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "w", ".", "mu", ".", "Lock", "(", ")", "\n", "w", ".", "ignored", "[", "path", "]", "=", "struct", "{", "}", "{", "}", "\n", "w", ".", "mu", ".", "Unlock", "(", ")", "\n", "}", "\n", "return", "nil", "\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\n", "files", ":=", "make", "(", "map", "[", "string", "]", "os", ".", "FileInfo", ")", "\n", "for", "k", ",", "v", ":=", "range", "w", ".", "files", "{", "files", "[", "k", "]", "=", "v", "\n", "}", "\n\n", "return", "files", "\n", "}" ]
// 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
radovskyb/watcher
watcher.go
TriggerEvent
func (w *Watcher) TriggerEvent(eventType Op, file os.FileInfo) { w.Wait() if file == nil { file = &fileInfo{name: "triggered event", modTime: time.Now()} } w.Event <- Event{Op: eventType, Path: "-", FileInfo: file} }
go
func (w *Watcher) TriggerEvent(eventType Op, file os.FileInfo) { w.Wait() if file == nil { file = &fileInfo{name: "triggered event", modTime: time.Now()} } w.Event <- Event{Op: eventType, Path: "-", FileInfo: file} }
[ "func", "(", "w", "*", "Watcher", ")", "TriggerEvent", "(", "eventType", "Op", ",", "file", "os", ".", "FileInfo", ")", "{", "w", ".", "Wait", "(", ")", "\n", "if", "file", "==", "nil", "{", "file", "=", "&", "fileInfo", "{", "name", ":", "\"", "\"", ",", "modTime", ":", "time", ".", "Now", "(", ")", "}", "\n", "}", "\n", "w", ".", "Event", "<-", "Event", "{", "Op", ":", "eventType", ",", "Path", ":", "\"", "\"", ",", "FileInfo", ":", "file", "}", "\n", "}" ]
// TriggerEvent is a method that can be used to trigger an event, separate to // the file watching process.
[ "TriggerEvent", "is", "a", "method", "that", "can", "be", "used", "to", "trigger", "an", "event", "separate", "to", "the", "file", "watching", "process", "." ]
f33c874a09dcfac90f008abeee9171d88431e212
https://github.com/radovskyb/watcher/blob/f33c874a09dcfac90f008abeee9171d88431e212/watcher.go#L476-L482
train
radovskyb/watcher
watcher.go
Start
func (w *Watcher) Start(d time.Duration) error { // Return an error if d is less than 1 nanosecond. if d < time.Nanosecond { return ErrDurationTooShort } // Make sure the Watcher is not already running. w.mu.Lock() if w.running { w.mu.Unlock() return ErrWatcherRunning } w.running = true w.mu.Unlock() // Unblock w.Wait(). w.wg.Done() for { // done lets the inner polling cycle loop know when the // current cycle's method has finished executing. done := make(chan struct{}) // Any events that are found are first piped to evt before // being sent to the main Event channel. evt := make(chan Event) // Retrieve the file list for all watched file's and dirs. fileList := w.retrieveFileList() // cancel can be used to cancel the current event polling function. cancel := make(chan struct{}) // Look for events. go func() { w.pollEvents(fileList, evt, cancel) done <- struct{}{} }() // numEvents holds the number of events for the current cycle. numEvents := 0 inner: for { select { case <-w.close: close(cancel) close(w.Closed) return nil case event := <-evt: if len(w.ops) > 0 { // Filter Ops. _, found := w.ops[event.Op] if !found { continue } } numEvents++ if w.maxEvents > 0 && numEvents > w.maxEvents { close(cancel) break inner } w.Event <- event case <-done: // Current cycle is finished. break inner } } // Update the file's list. w.mu.Lock() w.files = fileList w.mu.Unlock() // Sleep and then continue to the next loop iteration. time.Sleep(d) } }
go
func (w *Watcher) Start(d time.Duration) error { // Return an error if d is less than 1 nanosecond. if d < time.Nanosecond { return ErrDurationTooShort } // Make sure the Watcher is not already running. w.mu.Lock() if w.running { w.mu.Unlock() return ErrWatcherRunning } w.running = true w.mu.Unlock() // Unblock w.Wait(). w.wg.Done() for { // done lets the inner polling cycle loop know when the // current cycle's method has finished executing. done := make(chan struct{}) // Any events that are found are first piped to evt before // being sent to the main Event channel. evt := make(chan Event) // Retrieve the file list for all watched file's and dirs. fileList := w.retrieveFileList() // cancel can be used to cancel the current event polling function. cancel := make(chan struct{}) // Look for events. go func() { w.pollEvents(fileList, evt, cancel) done <- struct{}{} }() // numEvents holds the number of events for the current cycle. numEvents := 0 inner: for { select { case <-w.close: close(cancel) close(w.Closed) return nil case event := <-evt: if len(w.ops) > 0 { // Filter Ops. _, found := w.ops[event.Op] if !found { continue } } numEvents++ if w.maxEvents > 0 && numEvents > w.maxEvents { close(cancel) break inner } w.Event <- event case <-done: // Current cycle is finished. break inner } } // Update the file's list. w.mu.Lock() w.files = fileList w.mu.Unlock() // Sleep and then continue to the next loop iteration. time.Sleep(d) } }
[ "func", "(", "w", "*", "Watcher", ")", "Start", "(", "d", "time", ".", "Duration", ")", "error", "{", "// Return an error if d is less than 1 nanosecond.", "if", "d", "<", "time", ".", "Nanosecond", "{", "return", "ErrDurationTooShort", "\n", "}", "\n\n", "// Make sure the Watcher is not already running.", "w", ".", "mu", ".", "Lock", "(", ")", "\n", "if", "w", ".", "running", "{", "w", ".", "mu", ".", "Unlock", "(", ")", "\n", "return", "ErrWatcherRunning", "\n", "}", "\n", "w", ".", "running", "=", "true", "\n", "w", ".", "mu", ".", "Unlock", "(", ")", "\n\n", "// Unblock w.Wait().", "w", ".", "wg", ".", "Done", "(", ")", "\n\n", "for", "{", "// done lets the inner polling cycle loop know when the", "// current cycle's method has finished executing.", "done", ":=", "make", "(", "chan", "struct", "{", "}", ")", "\n\n", "// Any events that are found are first piped to evt before", "// being sent to the main Event channel.", "evt", ":=", "make", "(", "chan", "Event", ")", "\n\n", "// Retrieve the file list for all watched file's and dirs.", "fileList", ":=", "w", ".", "retrieveFileList", "(", ")", "\n\n", "// cancel can be used to cancel the current event polling function.", "cancel", ":=", "make", "(", "chan", "struct", "{", "}", ")", "\n\n", "// Look for events.", "go", "func", "(", ")", "{", "w", ".", "pollEvents", "(", "fileList", ",", "evt", ",", "cancel", ")", "\n", "done", "<-", "struct", "{", "}", "{", "}", "\n", "}", "(", ")", "\n\n", "// numEvents holds the number of events for the current cycle.", "numEvents", ":=", "0", "\n\n", "inner", ":", "for", "{", "select", "{", "case", "<-", "w", ".", "close", ":", "close", "(", "cancel", ")", "\n", "close", "(", "w", ".", "Closed", ")", "\n", "return", "nil", "\n", "case", "event", ":=", "<-", "evt", ":", "if", "len", "(", "w", ".", "ops", ")", ">", "0", "{", "// Filter Ops.", "_", ",", "found", ":=", "w", ".", "ops", "[", "event", ".", "Op", "]", "\n", "if", "!", "found", "{", "continue", "\n", "}", "\n", "}", "\n", "numEvents", "++", "\n", "if", "w", ".", "maxEvents", ">", "0", "&&", "numEvents", ">", "w", ".", "maxEvents", "{", "close", "(", "cancel", ")", "\n", "break", "inner", "\n", "}", "\n", "w", ".", "Event", "<-", "event", "\n", "case", "<-", "done", ":", "// Current cycle is finished.", "break", "inner", "\n", "}", "\n", "}", "\n\n", "// Update the file's list.", "w", ".", "mu", ".", "Lock", "(", ")", "\n", "w", ".", "files", "=", "fileList", "\n", "w", ".", "mu", ".", "Unlock", "(", ")", "\n\n", "// Sleep and then continue to the next loop iteration.", "time", ".", "Sleep", "(", "d", ")", "\n", "}", "\n", "}" ]
// Start begins the polling cycle which repeats every specified // duration until Close is called.
[ "Start", "begins", "the", "polling", "cycle", "which", "repeats", "every", "specified", "duration", "until", "Close", "is", "called", "." ]
f33c874a09dcfac90f008abeee9171d88431e212
https://github.com/radovskyb/watcher/blob/f33c874a09dcfac90f008abeee9171d88431e212/watcher.go#L534-L609
train
radovskyb/watcher
watcher.go
Close
func (w *Watcher) Close() { w.mu.Lock() if !w.running { w.mu.Unlock() return } w.running = false w.files = make(map[string]os.FileInfo) w.names = make(map[string]bool) w.mu.Unlock() // Send a close signal to the Start method. w.close <- struct{}{} }
go
func (w *Watcher) Close() { w.mu.Lock() if !w.running { w.mu.Unlock() return } w.running = false w.files = make(map[string]os.FileInfo) w.names = make(map[string]bool) w.mu.Unlock() // Send a close signal to the Start method. w.close <- struct{}{} }
[ "func", "(", "w", "*", "Watcher", ")", "Close", "(", ")", "{", "w", ".", "mu", ".", "Lock", "(", ")", "\n", "if", "!", "w", ".", "running", "{", "w", ".", "mu", ".", "Unlock", "(", ")", "\n", "return", "\n", "}", "\n", "w", ".", "running", "=", "false", "\n", "w", ".", "files", "=", "make", "(", "map", "[", "string", "]", "os", ".", "FileInfo", ")", "\n", "w", ".", "names", "=", "make", "(", "map", "[", "string", "]", "bool", ")", "\n", "w", ".", "mu", ".", "Unlock", "(", ")", "\n", "// Send a close signal to the Start method.", "w", ".", "close", "<-", "struct", "{", "}", "{", "}", "\n", "}" ]
// Close stops a Watcher and unlocks its mutex, then sends a close signal.
[ "Close", "stops", "a", "Watcher", "and", "unlocks", "its", "mutex", "then", "sends", "a", "close", "signal", "." ]
f33c874a09dcfac90f008abeee9171d88431e212
https://github.com/radovskyb/watcher/blob/f33c874a09dcfac90f008abeee9171d88431e212/watcher.go#L701-L713
train
canthefason/go-watcher
common.go
NewParams
func NewParams() *Params { return &Params{ Package: make([]string, 0), Watcher: make(map[string]string), } }
go
func NewParams() *Params { return &Params{ Package: make([]string, 0), Watcher: make(map[string]string), } }
[ "func", "NewParams", "(", ")", "*", "Params", "{", "return", "&", "Params", "{", "Package", ":", "make", "(", "[", "]", "string", ",", "0", ")", ",", "Watcher", ":", "make", "(", "map", "[", "string", "]", "string", ")", ",", "}", "\n", "}" ]
// NewParams creates a new Params instance
[ "NewParams", "creates", "a", "new", "Params", "instance" ]
59980168ee35c24b8dc3c3bb3dec2ed749fa5c44
https://github.com/canthefason/go-watcher/blob/59980168ee35c24b8dc3c3bb3dec2ed749fa5c44/common.go#L28-L33
train
canthefason/go-watcher
common.go
generateBinaryName
func (p *Params) generateBinaryName() string { rand.Seed(time.Now().UnixNano()) randName := rand.Int31n(999999) packageName := strings.Replace(p.packagePath(), "/", "-", -1) return fmt.Sprintf("%s-%s-%d", generateBinaryPrefix(), packageName, randName) }
go
func (p *Params) generateBinaryName() string { rand.Seed(time.Now().UnixNano()) randName := rand.Int31n(999999) packageName := strings.Replace(p.packagePath(), "/", "-", -1) return fmt.Sprintf("%s-%s-%d", generateBinaryPrefix(), packageName, randName) }
[ "func", "(", "p", "*", "Params", ")", "generateBinaryName", "(", ")", "string", "{", "rand", ".", "Seed", "(", "time", ".", "Now", "(", ")", ".", "UnixNano", "(", ")", ")", "\n", "randName", ":=", "rand", ".", "Int31n", "(", "999999", ")", "\n", "packageName", ":=", "strings", ".", "Replace", "(", "p", ".", "packagePath", "(", ")", ",", "\"", "\"", ",", "\"", "\"", ",", "-", "1", ")", "\n\n", "return", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "generateBinaryPrefix", "(", ")", ",", "packageName", ",", "randName", ")", "\n", "}" ]
// generateBinaryName generates a new binary name for each rebuild, for preventing any sorts of conflicts
[ "generateBinaryName", "generates", "a", "new", "binary", "name", "for", "each", "rebuild", "for", "preventing", "any", "sorts", "of", "conflicts" ]
59980168ee35c24b8dc3c3bb3dec2ed749fa5c44
https://github.com/canthefason/go-watcher/blob/59980168ee35c24b8dc3c3bb3dec2ed749fa5c44/common.go#L56-L62
train
canthefason/go-watcher
common.go
runCommand
func runCommand(name string, args ...string) (*exec.Cmd, error) { cmd := exec.Command(name, args...) stderr, err := cmd.StderrPipe() if err != nil { return cmd, err } stdout, err := cmd.StdoutPipe() if err != nil { return cmd, err } if err := cmd.Start(); err != nil { return cmd, err } go io.Copy(os.Stdout, stdout) go io.Copy(os.Stderr, stderr) return cmd, nil }
go
func runCommand(name string, args ...string) (*exec.Cmd, error) { cmd := exec.Command(name, args...) stderr, err := cmd.StderrPipe() if err != nil { return cmd, err } stdout, err := cmd.StdoutPipe() if err != nil { return cmd, err } if err := cmd.Start(); err != nil { return cmd, err } go io.Copy(os.Stdout, stdout) go io.Copy(os.Stderr, stderr) return cmd, nil }
[ "func", "runCommand", "(", "name", "string", ",", "args", "...", "string", ")", "(", "*", "exec", ".", "Cmd", ",", "error", ")", "{", "cmd", ":=", "exec", ".", "Command", "(", "name", ",", "args", "...", ")", "\n", "stderr", ",", "err", ":=", "cmd", ".", "StderrPipe", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "cmd", ",", "err", "\n", "}", "\n\n", "stdout", ",", "err", ":=", "cmd", ".", "StdoutPipe", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "cmd", ",", "err", "\n", "}", "\n\n", "if", "err", ":=", "cmd", ".", "Start", "(", ")", ";", "err", "!=", "nil", "{", "return", "cmd", ",", "err", "\n", "}", "\n\n", "go", "io", ".", "Copy", "(", "os", ".", "Stdout", ",", "stdout", ")", "\n", "go", "io", ".", "Copy", "(", "os", ".", "Stderr", ",", "stderr", ")", "\n\n", "return", "cmd", ",", "nil", "\n", "}" ]
// runCommand runs the command with given name and arguments. It copies the // logs to standard output
[ "runCommand", "runs", "the", "command", "with", "given", "name", "and", "arguments", ".", "It", "copies", "the", "logs", "to", "standard", "output" ]
59980168ee35c24b8dc3c3bb3dec2ed749fa5c44
https://github.com/canthefason/go-watcher/blob/59980168ee35c24b8dc3c3bb3dec2ed749fa5c44/common.go#L75-L95
train
canthefason/go-watcher
common.go
ParseArgs
func ParseArgs(args []string) *Params { params := NewParams() // remove the command argument args = args[1:len(args)] for i := 0; i < len(args); i++ { arg := args[i] arg = stripDash(arg) if existIn(arg, watcherFlags) { // used for fetching the value of the given parameter if len(args) <= i+1 { log.Fatalf("missing parameter value: %s", arg) } if strings.HasPrefix(args[i+1], "-") { log.Fatalf("missing parameter value: %s", arg) } params.Watcher[arg] = args[i+1] i++ continue } params.Package = append(params.Package, args[i]) } params.cloneRunFlag() return params }
go
func ParseArgs(args []string) *Params { params := NewParams() // remove the command argument args = args[1:len(args)] for i := 0; i < len(args); i++ { arg := args[i] arg = stripDash(arg) if existIn(arg, watcherFlags) { // used for fetching the value of the given parameter if len(args) <= i+1 { log.Fatalf("missing parameter value: %s", arg) } if strings.HasPrefix(args[i+1], "-") { log.Fatalf("missing parameter value: %s", arg) } params.Watcher[arg] = args[i+1] i++ continue } params.Package = append(params.Package, args[i]) } params.cloneRunFlag() return params }
[ "func", "ParseArgs", "(", "args", "[", "]", "string", ")", "*", "Params", "{", "params", ":=", "NewParams", "(", ")", "\n\n", "// remove the command argument", "args", "=", "args", "[", "1", ":", "len", "(", "args", ")", "]", "\n\n", "for", "i", ":=", "0", ";", "i", "<", "len", "(", "args", ")", ";", "i", "++", "{", "arg", ":=", "args", "[", "i", "]", "\n", "arg", "=", "stripDash", "(", "arg", ")", "\n\n", "if", "existIn", "(", "arg", ",", "watcherFlags", ")", "{", "// used for fetching the value of the given parameter", "if", "len", "(", "args", ")", "<=", "i", "+", "1", "{", "log", ".", "Fatalf", "(", "\"", "\"", ",", "arg", ")", "\n", "}", "\n\n", "if", "strings", ".", "HasPrefix", "(", "args", "[", "i", "+", "1", "]", ",", "\"", "\"", ")", "{", "log", ".", "Fatalf", "(", "\"", "\"", ",", "arg", ")", "\n", "}", "\n\n", "params", ".", "Watcher", "[", "arg", "]", "=", "args", "[", "i", "+", "1", "]", "\n", "i", "++", "\n", "continue", "\n", "}", "\n\n", "params", ".", "Package", "=", "append", "(", "params", ".", "Package", ",", "args", "[", "i", "]", ")", "\n", "}", "\n\n", "params", ".", "cloneRunFlag", "(", ")", "\n\n", "return", "params", "\n", "}" ]
// ParseArgs extracts the application parameters from args and returns // Params instance with separated watcher and application parameters
[ "ParseArgs", "extracts", "the", "application", "parameters", "from", "args", "and", "returns", "Params", "instance", "with", "separated", "watcher", "and", "application", "parameters" ]
59980168ee35c24b8dc3c3bb3dec2ed749fa5c44
https://github.com/canthefason/go-watcher/blob/59980168ee35c24b8dc3c3bb3dec2ed749fa5c44/common.go#L99-L131
train
canthefason/go-watcher
common.go
stripDash
func stripDash(arg string) string { if len(arg) > 1 { if arg[1] == '-' { return arg[2:] } else if arg[0] == '-' { return arg[1:] } } return arg }
go
func stripDash(arg string) string { if len(arg) > 1 { if arg[1] == '-' { return arg[2:] } else if arg[0] == '-' { return arg[1:] } } return arg }
[ "func", "stripDash", "(", "arg", "string", ")", "string", "{", "if", "len", "(", "arg", ")", ">", "1", "{", "if", "arg", "[", "1", "]", "==", "'-'", "{", "return", "arg", "[", "2", ":", "]", "\n", "}", "else", "if", "arg", "[", "0", "]", "==", "'-'", "{", "return", "arg", "[", "1", ":", "]", "\n", "}", "\n", "}", "\n\n", "return", "arg", "\n", "}" ]
// stripDash removes the both single and double dash chars and returns // the actual parameter name
[ "stripDash", "removes", "the", "both", "single", "and", "double", "dash", "chars", "and", "returns", "the", "actual", "parameter", "name" ]
59980168ee35c24b8dc3c3bb3dec2ed749fa5c44
https://github.com/canthefason/go-watcher/blob/59980168ee35c24b8dc3c3bb3dec2ed749fa5c44/common.go#L135-L145
train
canthefason/go-watcher
build.go
NewBuilder
func NewBuilder(w *Watcher, r *Runner) *Builder { return &Builder{watcher: w, runner: r} }
go
func NewBuilder(w *Watcher, r *Runner) *Builder { return &Builder{watcher: w, runner: r} }
[ "func", "NewBuilder", "(", "w", "*", "Watcher", ",", "r", "*", "Runner", ")", "*", "Builder", "{", "return", "&", "Builder", "{", "watcher", ":", "w", ",", "runner", ":", "r", "}", "\n", "}" ]
// NewBuilder constructs the Builder instance
[ "NewBuilder", "constructs", "the", "Builder", "instance" ]
59980168ee35c24b8dc3c3bb3dec2ed749fa5c44
https://github.com/canthefason/go-watcher/blob/59980168ee35c24b8dc3c3bb3dec2ed749fa5c44/build.go#L20-L22
train
canthefason/go-watcher
build.go
Build
func (b *Builder) Build(p *Params) { go b.registerSignalHandler() go func() { // used for triggering the first build b.watcher.update <- struct{}{} }() for range b.watcher.Wait() { fileName := p.generateBinaryName() pkg := p.packagePath() log.Println("build started") color.Cyan("Building %s...\n", pkg) // build package cmd, err := runCommand("go", "build", "-i", "-o", fileName, pkg) if err != nil { log.Fatalf("Could not run 'go build' command: %s", err) continue } if err := cmd.Wait(); err != nil { if err := interpretError(err); err != nil { color.Red("An error occurred while building: %s", err) } else { color.Red("A build error occurred. Please update your code...") } continue } log.Println("build completed") // and start the new process b.runner.restart(fileName) } }
go
func (b *Builder) Build(p *Params) { go b.registerSignalHandler() go func() { // used for triggering the first build b.watcher.update <- struct{}{} }() for range b.watcher.Wait() { fileName := p.generateBinaryName() pkg := p.packagePath() log.Println("build started") color.Cyan("Building %s...\n", pkg) // build package cmd, err := runCommand("go", "build", "-i", "-o", fileName, pkg) if err != nil { log.Fatalf("Could not run 'go build' command: %s", err) continue } if err := cmd.Wait(); err != nil { if err := interpretError(err); err != nil { color.Red("An error occurred while building: %s", err) } else { color.Red("A build error occurred. Please update your code...") } continue } log.Println("build completed") // and start the new process b.runner.restart(fileName) } }
[ "func", "(", "b", "*", "Builder", ")", "Build", "(", "p", "*", "Params", ")", "{", "go", "b", ".", "registerSignalHandler", "(", ")", "\n", "go", "func", "(", ")", "{", "// used for triggering the first build", "b", ".", "watcher", ".", "update", "<-", "struct", "{", "}", "{", "}", "\n", "}", "(", ")", "\n\n", "for", "range", "b", ".", "watcher", ".", "Wait", "(", ")", "{", "fileName", ":=", "p", ".", "generateBinaryName", "(", ")", "\n\n", "pkg", ":=", "p", ".", "packagePath", "(", ")", "\n\n", "log", ".", "Println", "(", "\"", "\"", ")", "\n", "color", ".", "Cyan", "(", "\"", "\\n", "\"", ",", "pkg", ")", "\n\n", "// build package", "cmd", ",", "err", ":=", "runCommand", "(", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ",", "fileName", ",", "pkg", ")", "\n", "if", "err", "!=", "nil", "{", "log", ".", "Fatalf", "(", "\"", "\"", ",", "err", ")", "\n", "continue", "\n", "}", "\n\n", "if", "err", ":=", "cmd", ".", "Wait", "(", ")", ";", "err", "!=", "nil", "{", "if", "err", ":=", "interpretError", "(", "err", ")", ";", "err", "!=", "nil", "{", "color", ".", "Red", "(", "\"", "\"", ",", "err", ")", "\n", "}", "else", "{", "color", ".", "Red", "(", "\"", "\"", ")", "\n", "}", "\n\n", "continue", "\n", "}", "\n", "log", ".", "Println", "(", "\"", "\"", ")", "\n\n", "// and start the new process", "b", ".", "runner", ".", "restart", "(", "fileName", ")", "\n", "}", "\n", "}" ]
// Build listens watch events from Watcher and sends messages to Runner // when new changes are built.
[ "Build", "listens", "watch", "events", "from", "Watcher", "and", "sends", "messages", "to", "Runner", "when", "new", "changes", "are", "built", "." ]
59980168ee35c24b8dc3c3bb3dec2ed749fa5c44
https://github.com/canthefason/go-watcher/blob/59980168ee35c24b8dc3c3bb3dec2ed749fa5c44/build.go#L26-L62
train
canthefason/go-watcher
watch.go
MustRegisterWatcher
func MustRegisterWatcher(params *Params) *Watcher { watchVendorStr := params.Get("watch-vendor") var watchVendor bool var err error if watchVendorStr != "" { watchVendor, err = strconv.ParseBool(watchVendorStr) if err != nil { log.Println("Wrong watch-vendor value: %s (default=false)", watchVendorStr) } } w := &Watcher{ update: make(chan struct{}), rootdir: params.Get("watch"), watchVendor: watchVendor, } w.watcher, err = fsnotify.NewWatcher() if err != nil { log.Fatalf("Could not register watcher: %s", err) } // add folders that will be watched w.watchFolders() return w }
go
func MustRegisterWatcher(params *Params) *Watcher { watchVendorStr := params.Get("watch-vendor") var watchVendor bool var err error if watchVendorStr != "" { watchVendor, err = strconv.ParseBool(watchVendorStr) if err != nil { log.Println("Wrong watch-vendor value: %s (default=false)", watchVendorStr) } } w := &Watcher{ update: make(chan struct{}), rootdir: params.Get("watch"), watchVendor: watchVendor, } w.watcher, err = fsnotify.NewWatcher() if err != nil { log.Fatalf("Could not register watcher: %s", err) } // add folders that will be watched w.watchFolders() return w }
[ "func", "MustRegisterWatcher", "(", "params", "*", "Params", ")", "*", "Watcher", "{", "watchVendorStr", ":=", "params", ".", "Get", "(", "\"", "\"", ")", "\n", "var", "watchVendor", "bool", "\n", "var", "err", "error", "\n", "if", "watchVendorStr", "!=", "\"", "\"", "{", "watchVendor", ",", "err", "=", "strconv", ".", "ParseBool", "(", "watchVendorStr", ")", "\n", "if", "err", "!=", "nil", "{", "log", ".", "Println", "(", "\"", "\"", ",", "watchVendorStr", ")", "\n", "}", "\n", "}", "\n\n", "w", ":=", "&", "Watcher", "{", "update", ":", "make", "(", "chan", "struct", "{", "}", ")", ",", "rootdir", ":", "params", ".", "Get", "(", "\"", "\"", ")", ",", "watchVendor", ":", "watchVendor", ",", "}", "\n\n", "w", ".", "watcher", ",", "err", "=", "fsnotify", ".", "NewWatcher", "(", ")", "\n", "if", "err", "!=", "nil", "{", "log", ".", "Fatalf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n\n", "// add folders that will be watched", "w", ".", "watchFolders", "(", ")", "\n\n", "return", "w", "\n", "}" ]
// MustRegisterWatcher creates a new Watcher and starts listening to // given folders
[ "MustRegisterWatcher", "creates", "a", "new", "Watcher", "and", "starts", "listening", "to", "given", "folders" ]
59980168ee35c24b8dc3c3bb3dec2ed749fa5c44
https://github.com/canthefason/go-watcher/blob/59980168ee35c24b8dc3c3bb3dec2ed749fa5c44/watch.go#L37-L63
train
canthefason/go-watcher
watch.go
Watch
func (w *Watcher) Watch() { eventSent := false for { select { case event := <-w.watcher.Events: // discard chmod events if event.Op&fsnotify.Chmod != fsnotify.Chmod { // test files do not need a rebuild if isTestFile(event.Name) { continue } if !isWatchedFileType(event.Name) { continue } if eventSent { continue } eventSent = true // prevent consequent builds go func() { w.update <- struct{}{} time.Sleep(watchDelta) eventSent = false }() } case err := <-w.watcher.Errors: if err != nil { log.Fatalf("Watcher error: %s", err) } return } } }
go
func (w *Watcher) Watch() { eventSent := false for { select { case event := <-w.watcher.Events: // discard chmod events if event.Op&fsnotify.Chmod != fsnotify.Chmod { // test files do not need a rebuild if isTestFile(event.Name) { continue } if !isWatchedFileType(event.Name) { continue } if eventSent { continue } eventSent = true // prevent consequent builds go func() { w.update <- struct{}{} time.Sleep(watchDelta) eventSent = false }() } case err := <-w.watcher.Errors: if err != nil { log.Fatalf("Watcher error: %s", err) } return } } }
[ "func", "(", "w", "*", "Watcher", ")", "Watch", "(", ")", "{", "eventSent", ":=", "false", "\n\n", "for", "{", "select", "{", "case", "event", ":=", "<-", "w", ".", "watcher", ".", "Events", ":", "// discard chmod events", "if", "event", ".", "Op", "&", "fsnotify", ".", "Chmod", "!=", "fsnotify", ".", "Chmod", "{", "// test files do not need a rebuild", "if", "isTestFile", "(", "event", ".", "Name", ")", "{", "continue", "\n", "}", "\n", "if", "!", "isWatchedFileType", "(", "event", ".", "Name", ")", "{", "continue", "\n", "}", "\n", "if", "eventSent", "{", "continue", "\n", "}", "\n", "eventSent", "=", "true", "\n", "// prevent consequent builds", "go", "func", "(", ")", "{", "w", ".", "update", "<-", "struct", "{", "}", "{", "}", "\n", "time", ".", "Sleep", "(", "watchDelta", ")", "\n", "eventSent", "=", "false", "\n", "}", "(", ")", "\n\n", "}", "\n", "case", "err", ":=", "<-", "w", ".", "watcher", ".", "Errors", ":", "if", "err", "!=", "nil", "{", "log", ".", "Fatalf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n", "return", "\n", "}", "\n", "}", "\n", "}" ]
// Watch listens file updates, and sends signal to // update channel when .go and .tmpl files are updated
[ "Watch", "listens", "file", "updates", "and", "sends", "signal", "to", "update", "channel", "when", ".", "go", "and", ".", "tmpl", "files", "are", "updated" ]
59980168ee35c24b8dc3c3bb3dec2ed749fa5c44
https://github.com/canthefason/go-watcher/blob/59980168ee35c24b8dc3c3bb3dec2ed749fa5c44/watch.go#L67-L101
train
canthefason/go-watcher
watch.go
watchFolders
func (w *Watcher) watchFolders() { wd, err := w.prepareRootDir() if err != nil { log.Fatalf("Could not get root working directory: %s", err) } filepath.Walk(wd, func(path string, info os.FileInfo, err error) error { // skip files if info == nil { log.Fatalf("wrong watcher package: %s", path) } if !info.IsDir() { return nil } if !w.watchVendor { // skip vendor directory vendor := fmt.Sprintf("%s/vendor", wd) if strings.HasPrefix(path, vendor) { return filepath.SkipDir } } // skip hidden folders if len(path) > 1 && strings.HasPrefix(filepath.Base(path), ".") { return filepath.SkipDir } w.addFolder(path) return err }) }
go
func (w *Watcher) watchFolders() { wd, err := w.prepareRootDir() if err != nil { log.Fatalf("Could not get root working directory: %s", err) } filepath.Walk(wd, func(path string, info os.FileInfo, err error) error { // skip files if info == nil { log.Fatalf("wrong watcher package: %s", path) } if !info.IsDir() { return nil } if !w.watchVendor { // skip vendor directory vendor := fmt.Sprintf("%s/vendor", wd) if strings.HasPrefix(path, vendor) { return filepath.SkipDir } } // skip hidden folders if len(path) > 1 && strings.HasPrefix(filepath.Base(path), ".") { return filepath.SkipDir } w.addFolder(path) return err }) }
[ "func", "(", "w", "*", "Watcher", ")", "watchFolders", "(", ")", "{", "wd", ",", "err", ":=", "w", ".", "prepareRootDir", "(", ")", "\n\n", "if", "err", "!=", "nil", "{", "log", ".", "Fatalf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n\n", "filepath", ".", "Walk", "(", "wd", ",", "func", "(", "path", "string", ",", "info", "os", ".", "FileInfo", ",", "err", "error", ")", "error", "{", "// skip files", "if", "info", "==", "nil", "{", "log", ".", "Fatalf", "(", "\"", "\"", ",", "path", ")", "\n", "}", "\n\n", "if", "!", "info", ".", "IsDir", "(", ")", "{", "return", "nil", "\n", "}", "\n\n", "if", "!", "w", ".", "watchVendor", "{", "// skip vendor directory", "vendor", ":=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "wd", ")", "\n", "if", "strings", ".", "HasPrefix", "(", "path", ",", "vendor", ")", "{", "return", "filepath", ".", "SkipDir", "\n", "}", "\n", "}", "\n\n", "// skip hidden folders", "if", "len", "(", "path", ")", ">", "1", "&&", "strings", ".", "HasPrefix", "(", "filepath", ".", "Base", "(", "path", ")", ",", "\"", "\"", ")", "{", "return", "filepath", ".", "SkipDir", "\n", "}", "\n\n", "w", ".", "addFolder", "(", "path", ")", "\n\n", "return", "err", "\n", "}", ")", "\n", "}" ]
// watchFolders recursively adds folders that will be watched against the changes, // starting from the working directory
[ "watchFolders", "recursively", "adds", "folders", "that", "will", "be", "watched", "against", "the", "changes", "starting", "from", "the", "working", "directory" ]
59980168ee35c24b8dc3c3bb3dec2ed749fa5c44
https://github.com/canthefason/go-watcher/blob/59980168ee35c24b8dc3c3bb3dec2ed749fa5c44/watch.go#L126-L160
train
canthefason/go-watcher
watch.go
addFolder
func (w *Watcher) addFolder(name string) { if err := w.watcher.Add(name); err != nil { log.Fatalf("Could not watch folder: %s", err) } }
go
func (w *Watcher) addFolder(name string) { if err := w.watcher.Add(name); err != nil { log.Fatalf("Could not watch folder: %s", err) } }
[ "func", "(", "w", "*", "Watcher", ")", "addFolder", "(", "name", "string", ")", "{", "if", "err", ":=", "w", ".", "watcher", ".", "Add", "(", "name", ")", ";", "err", "!=", "nil", "{", "log", ".", "Fatalf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n", "}" ]
// addFolder adds given folder name to the watched folders, and starts // watching it for further changes
[ "addFolder", "adds", "given", "folder", "name", "to", "the", "watched", "folders", "and", "starts", "watching", "it", "for", "further", "changes" ]
59980168ee35c24b8dc3c3bb3dec2ed749fa5c44
https://github.com/canthefason/go-watcher/blob/59980168ee35c24b8dc3c3bb3dec2ed749fa5c44/watch.go#L164-L168
train
canthefason/go-watcher
watch.go
prepareRootDir
func (w *Watcher) prepareRootDir() (string, error) { if w.rootdir == "" { return os.Getwd() } path := os.Getenv("GOPATH") if path == "" { return "", ErrPathNotSet } root := fmt.Sprintf("%s/src/%s", path, w.rootdir) return root, nil }
go
func (w *Watcher) prepareRootDir() (string, error) { if w.rootdir == "" { return os.Getwd() } path := os.Getenv("GOPATH") if path == "" { return "", ErrPathNotSet } root := fmt.Sprintf("%s/src/%s", path, w.rootdir) return root, nil }
[ "func", "(", "w", "*", "Watcher", ")", "prepareRootDir", "(", ")", "(", "string", ",", "error", ")", "{", "if", "w", ".", "rootdir", "==", "\"", "\"", "{", "return", "os", ".", "Getwd", "(", ")", "\n", "}", "\n\n", "path", ":=", "os", ".", "Getenv", "(", "\"", "\"", ")", "\n", "if", "path", "==", "\"", "\"", "{", "return", "\"", "\"", ",", "ErrPathNotSet", "\n", "}", "\n\n", "root", ":=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "path", ",", "w", ".", "rootdir", ")", "\n\n", "return", "root", ",", "nil", "\n", "}" ]
// prepareRootDir prepares working directory depending on root directory
[ "prepareRootDir", "prepares", "working", "directory", "depending", "on", "root", "directory" ]
59980168ee35c24b8dc3c3bb3dec2ed749fa5c44
https://github.com/canthefason/go-watcher/blob/59980168ee35c24b8dc3c3bb3dec2ed749fa5c44/watch.go#L171-L184
train
canthefason/go-watcher
run.go
Run
func (r *Runner) Run(p *Params) { for fileName := range r.start { color.Green("Running %s...\n", p.Get("run")) cmd, err := runCommand(fileName, p.Package...) if err != nil { log.Printf("Could not run the go binary: %s \n", err) r.kill(cmd) continue } r.cmd = cmd removeFile(fileName) go func(cmd *exec.Cmd) { if err := cmd.Wait(); err != nil { log.Printf("process interrupted: %s \n", err) r.kill(cmd) } }(r.cmd) } }
go
func (r *Runner) Run(p *Params) { for fileName := range r.start { color.Green("Running %s...\n", p.Get("run")) cmd, err := runCommand(fileName, p.Package...) if err != nil { log.Printf("Could not run the go binary: %s \n", err) r.kill(cmd) continue } r.cmd = cmd removeFile(fileName) go func(cmd *exec.Cmd) { if err := cmd.Wait(); err != nil { log.Printf("process interrupted: %s \n", err) r.kill(cmd) } }(r.cmd) } }
[ "func", "(", "r", "*", "Runner", ")", "Run", "(", "p", "*", "Params", ")", "{", "for", "fileName", ":=", "range", "r", ".", "start", "{", "color", ".", "Green", "(", "\"", "\\n", "\"", ",", "p", ".", "Get", "(", "\"", "\"", ")", ")", "\n\n", "cmd", ",", "err", ":=", "runCommand", "(", "fileName", ",", "p", ".", "Package", "...", ")", "\n", "if", "err", "!=", "nil", "{", "log", ".", "Printf", "(", "\"", "\\n", "\"", ",", "err", ")", "\n", "r", ".", "kill", "(", "cmd", ")", "\n\n", "continue", "\n", "}", "\n\n", "r", ".", "cmd", "=", "cmd", "\n", "removeFile", "(", "fileName", ")", "\n\n", "go", "func", "(", "cmd", "*", "exec", ".", "Cmd", ")", "{", "if", "err", ":=", "cmd", ".", "Wait", "(", ")", ";", "err", "!=", "nil", "{", "log", ".", "Printf", "(", "\"", "\\n", "\"", ",", "err", ")", "\n", "r", ".", "kill", "(", "cmd", ")", "\n", "}", "\n", "}", "(", "r", ".", "cmd", ")", "\n", "}", "\n", "}" ]
// Run initializes runner with given parameters.
[ "Run", "initializes", "runner", "with", "given", "parameters", "." ]
59980168ee35c24b8dc3c3bb3dec2ed749fa5c44
https://github.com/canthefason/go-watcher/blob/59980168ee35c24b8dc3c3bb3dec2ed749fa5c44/run.go#L31-L54
train
canthefason/go-watcher
run.go
restart
func (r *Runner) restart(fileName string) { r.kill(r.cmd) r.start <- fileName }
go
func (r *Runner) restart(fileName string) { r.kill(r.cmd) r.start <- fileName }
[ "func", "(", "r", "*", "Runner", ")", "restart", "(", "fileName", "string", ")", "{", "r", ".", "kill", "(", "r", ".", "cmd", ")", "\n\n", "r", ".", "start", "<-", "fileName", "\n", "}" ]
// Restart kills the process, removes the old binary and // restarts the new process
[ "Restart", "kills", "the", "process", "removes", "the", "old", "binary", "and", "restarts", "the", "new", "process" ]
59980168ee35c24b8dc3c3bb3dec2ed749fa5c44
https://github.com/canthefason/go-watcher/blob/59980168ee35c24b8dc3c3bb3dec2ed749fa5c44/run.go#L58-L62
train
sony/sonyflake
sonyflake.go
NextID
func (sf *Sonyflake) NextID() (uint64, error) { const maskSequence = uint16(1<<BitLenSequence - 1) sf.mutex.Lock() defer sf.mutex.Unlock() current := currentElapsedTime(sf.startTime) if sf.elapsedTime < current { sf.elapsedTime = current sf.sequence = 0 } else { // sf.elapsedTime >= current sf.sequence = (sf.sequence + 1) & maskSequence if sf.sequence == 0 { sf.elapsedTime++ overtime := sf.elapsedTime - current time.Sleep(sleepTime((overtime))) } } return sf.toID() }
go
func (sf *Sonyflake) NextID() (uint64, error) { const maskSequence = uint16(1<<BitLenSequence - 1) sf.mutex.Lock() defer sf.mutex.Unlock() current := currentElapsedTime(sf.startTime) if sf.elapsedTime < current { sf.elapsedTime = current sf.sequence = 0 } else { // sf.elapsedTime >= current sf.sequence = (sf.sequence + 1) & maskSequence if sf.sequence == 0 { sf.elapsedTime++ overtime := sf.elapsedTime - current time.Sleep(sleepTime((overtime))) } } return sf.toID() }
[ "func", "(", "sf", "*", "Sonyflake", ")", "NextID", "(", ")", "(", "uint64", ",", "error", ")", "{", "const", "maskSequence", "=", "uint16", "(", "1", "<<", "BitLenSequence", "-", "1", ")", "\n\n", "sf", ".", "mutex", ".", "Lock", "(", ")", "\n", "defer", "sf", ".", "mutex", ".", "Unlock", "(", ")", "\n\n", "current", ":=", "currentElapsedTime", "(", "sf", ".", "startTime", ")", "\n", "if", "sf", ".", "elapsedTime", "<", "current", "{", "sf", ".", "elapsedTime", "=", "current", "\n", "sf", ".", "sequence", "=", "0", "\n", "}", "else", "{", "// sf.elapsedTime >= current", "sf", ".", "sequence", "=", "(", "sf", ".", "sequence", "+", "1", ")", "&", "maskSequence", "\n", "if", "sf", ".", "sequence", "==", "0", "{", "sf", ".", "elapsedTime", "++", "\n", "overtime", ":=", "sf", ".", "elapsedTime", "-", "current", "\n", "time", ".", "Sleep", "(", "sleepTime", "(", "(", "overtime", ")", ")", ")", "\n", "}", "\n", "}", "\n\n", "return", "sf", ".", "toID", "(", ")", "\n", "}" ]
// NextID generates a next unique ID. // After the Sonyflake time overflows, NextID returns an error.
[ "NextID", "generates", "a", "next", "unique", "ID", ".", "After", "the", "Sonyflake", "time", "overflows", "NextID", "returns", "an", "error", "." ]
6d5bd61810093eae37d7d605d0cbdd845969b5b2
https://github.com/sony/sonyflake/blob/6d5bd61810093eae37d7d605d0cbdd845969b5b2/sonyflake.go#L86-L106
train
sony/sonyflake
sonyflake.go
Decompose
func Decompose(id uint64) map[string]uint64 { const maskSequence = uint64((1<<BitLenSequence - 1) << BitLenMachineID) const maskMachineID = uint64(1<<BitLenMachineID - 1) msb := id >> 63 time := id >> (BitLenSequence + BitLenMachineID) sequence := id & maskSequence >> BitLenMachineID machineID := id & maskMachineID return map[string]uint64{ "id": id, "msb": msb, "time": time, "sequence": sequence, "machine-id": machineID, } }
go
func Decompose(id uint64) map[string]uint64 { const maskSequence = uint64((1<<BitLenSequence - 1) << BitLenMachineID) const maskMachineID = uint64(1<<BitLenMachineID - 1) msb := id >> 63 time := id >> (BitLenSequence + BitLenMachineID) sequence := id & maskSequence >> BitLenMachineID machineID := id & maskMachineID return map[string]uint64{ "id": id, "msb": msb, "time": time, "sequence": sequence, "machine-id": machineID, } }
[ "func", "Decompose", "(", "id", "uint64", ")", "map", "[", "string", "]", "uint64", "{", "const", "maskSequence", "=", "uint64", "(", "(", "1", "<<", "BitLenSequence", "-", "1", ")", "<<", "BitLenMachineID", ")", "\n", "const", "maskMachineID", "=", "uint64", "(", "1", "<<", "BitLenMachineID", "-", "1", ")", "\n\n", "msb", ":=", "id", ">>", "63", "\n", "time", ":=", "id", ">>", "(", "BitLenSequence", "+", "BitLenMachineID", ")", "\n", "sequence", ":=", "id", "&", "maskSequence", ">>", "BitLenMachineID", "\n", "machineID", ":=", "id", "&", "maskMachineID", "\n", "return", "map", "[", "string", "]", "uint64", "{", "\"", "\"", ":", "id", ",", "\"", "\"", ":", "msb", ",", "\"", "\"", ":", "time", ",", "\"", "\"", ":", "sequence", ",", "\"", "\"", ":", "machineID", ",", "}", "\n", "}" ]
// Decompose returns a set of Sonyflake ID parts.
[ "Decompose", "returns", "a", "set", "of", "Sonyflake", "ID", "parts", "." ]
6d5bd61810093eae37d7d605d0cbdd845969b5b2
https://github.com/sony/sonyflake/blob/6d5bd61810093eae37d7d605d0cbdd845969b5b2/sonyflake.go#L168-L183
train
sony/sonyflake
awsutil/awsutil.go
AmazonEC2MachineID
func AmazonEC2MachineID() (uint16, error) { ip, err := amazonEC2PrivateIPv4() if err != nil { return 0, err } return uint16(ip[2])<<8 + uint16(ip[3]), nil }
go
func AmazonEC2MachineID() (uint16, error) { ip, err := amazonEC2PrivateIPv4() if err != nil { return 0, err } return uint16(ip[2])<<8 + uint16(ip[3]), nil }
[ "func", "AmazonEC2MachineID", "(", ")", "(", "uint16", ",", "error", ")", "{", "ip", ",", "err", ":=", "amazonEC2PrivateIPv4", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "0", ",", "err", "\n", "}", "\n\n", "return", "uint16", "(", "ip", "[", "2", "]", ")", "<<", "8", "+", "uint16", "(", "ip", "[", "3", "]", ")", ",", "nil", "\n", "}" ]
// AmazonEC2MachineID retrieves the private IP address of the Amazon EC2 instance // and returns its lower 16 bits. // It works correctly on Docker as well.
[ "AmazonEC2MachineID", "retrieves", "the", "private", "IP", "address", "of", "the", "Amazon", "EC2", "instance", "and", "returns", "its", "lower", "16", "bits", ".", "It", "works", "correctly", "on", "Docker", "as", "well", "." ]
6d5bd61810093eae37d7d605d0cbdd845969b5b2
https://github.com/sony/sonyflake/blob/6d5bd61810093eae37d7d605d0cbdd845969b5b2/awsutil/awsutil.go#L37-L44
train
sony/sonyflake
awsutil/awsutil.go
TimeDifference
func TimeDifference(server string) (time.Duration, error) { output, err := exec.Command("/usr/sbin/ntpdate", "-q", server).CombinedOutput() if err != nil { return time.Duration(0), err } re, _ := regexp.Compile("offset (.*) sec") submatched := re.FindSubmatch(output) if len(submatched) != 2 { return time.Duration(0), errors.New("invalid ntpdate output") } f, err := strconv.ParseFloat(string(submatched[1]), 64) if err != nil { return time.Duration(0), err } return time.Duration(f*1000) * time.Millisecond, nil }
go
func TimeDifference(server string) (time.Duration, error) { output, err := exec.Command("/usr/sbin/ntpdate", "-q", server).CombinedOutput() if err != nil { return time.Duration(0), err } re, _ := regexp.Compile("offset (.*) sec") submatched := re.FindSubmatch(output) if len(submatched) != 2 { return time.Duration(0), errors.New("invalid ntpdate output") } f, err := strconv.ParseFloat(string(submatched[1]), 64) if err != nil { return time.Duration(0), err } return time.Duration(f*1000) * time.Millisecond, nil }
[ "func", "TimeDifference", "(", "server", "string", ")", "(", "time", ".", "Duration", ",", "error", ")", "{", "output", ",", "err", ":=", "exec", ".", "Command", "(", "\"", "\"", ",", "\"", "\"", ",", "server", ")", ".", "CombinedOutput", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "time", ".", "Duration", "(", "0", ")", ",", "err", "\n", "}", "\n\n", "re", ",", "_", ":=", "regexp", ".", "Compile", "(", "\"", "\"", ")", "\n", "submatched", ":=", "re", ".", "FindSubmatch", "(", "output", ")", "\n", "if", "len", "(", "submatched", ")", "!=", "2", "{", "return", "time", ".", "Duration", "(", "0", ")", ",", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n\n", "f", ",", "err", ":=", "strconv", ".", "ParseFloat", "(", "string", "(", "submatched", "[", "1", "]", ")", ",", "64", ")", "\n", "if", "err", "!=", "nil", "{", "return", "time", ".", "Duration", "(", "0", ")", ",", "err", "\n", "}", "\n", "return", "time", ".", "Duration", "(", "f", "*", "1000", ")", "*", "time", ".", "Millisecond", ",", "nil", "\n", "}" ]
// TimeDifference returns the time difference between the localhost and the given NTP server.
[ "TimeDifference", "returns", "the", "time", "difference", "between", "the", "localhost", "and", "the", "given", "NTP", "server", "." ]
6d5bd61810093eae37d7d605d0cbdd845969b5b2
https://github.com/sony/sonyflake/blob/6d5bd61810093eae37d7d605d0cbdd845969b5b2/awsutil/awsutil.go#L47-L64
train
terraform-providers/terraform-provider-openstack
openstack/dns_zone_v2.go
ToZoneCreateMap
func (opts ZoneCreateOpts) ToZoneCreateMap() (map[string]interface{}, error) { b, err := BuildRequest(opts, "") if err != nil { return nil, err } if m, ok := b[""].(map[string]interface{}); ok { if opts.TTL > 0 { m["ttl"] = opts.TTL } return m, nil } return nil, fmt.Errorf("Expected map but got %T", b[""]) }
go
func (opts ZoneCreateOpts) ToZoneCreateMap() (map[string]interface{}, error) { b, err := BuildRequest(opts, "") if err != nil { return nil, err } if m, ok := b[""].(map[string]interface{}); ok { if opts.TTL > 0 { m["ttl"] = opts.TTL } return m, nil } return nil, fmt.Errorf("Expected map but got %T", b[""]) }
[ "func", "(", "opts", "ZoneCreateOpts", ")", "ToZoneCreateMap", "(", ")", "(", "map", "[", "string", "]", "interface", "{", "}", ",", "error", ")", "{", "b", ",", "err", ":=", "BuildRequest", "(", "opts", ",", "\"", "\"", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "if", "m", ",", "ok", ":=", "b", "[", "\"", "\"", "]", ".", "(", "map", "[", "string", "]", "interface", "{", "}", ")", ";", "ok", "{", "if", "opts", ".", "TTL", ">", "0", "{", "m", "[", "\"", "\"", "]", "=", "opts", ".", "TTL", "\n", "}", "\n\n", "return", "m", ",", "nil", "\n", "}", "\n\n", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "b", "[", "\"", "\"", "]", ")", "\n", "}" ]
// ToZoneCreateMap casts a CreateOpts struct to a map. // It overrides zones.ToZoneCreateMap to add the ValueSpecs field.
[ "ToZoneCreateMap", "casts", "a", "CreateOpts", "struct", "to", "a", "map", ".", "It", "overrides", "zones", ".", "ToZoneCreateMap", "to", "add", "the", "ValueSpecs", "field", "." ]
a4c13eee81a7ca8682741b049cb067610bdf45b2
https://github.com/terraform-providers/terraform-provider-openstack/blob/a4c13eee81a7ca8682741b049cb067610bdf45b2/openstack/dns_zone_v2.go#L21-L36
train