text
stringlengths
2
1.1M
id
stringlengths
11
117
metadata
dict
__index_level_0__
int64
0
885
// Copyright 2022 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package gocommand import ( "strconv" "testing" ) func TestParseGoVersionOutput(t *testing.T) { tests := []struct { args string want string }{ {"go version go1.12 linux/amd64", "go1.12"}, {"go version go1.18.1 darwin/amd64", "go1.18.1"}, {"go version go1.19.rc1 windows/arm64", "go1.19.rc1"}, {"go version devel d5de62df152baf4de6e9fe81933319b86fd95ae4 linux/386", "devel d5de62df152baf4de6e9fe81933319b86fd95ae4"}, {"go version devel go1.20-1f068f0dc7 Tue Oct 18 20:58:37 2022 +0000 darwin/amd64", "devel go1.20-1f068f0dc7"}, {"v1.19.1 foo/bar", ""}, } for i, tt := range tests { t.Run(strconv.Itoa(i), func(t *testing.T) { if got := ParseGoVersionOutput(tt.args); got != tt.want { t.Errorf("parseGoVersionOutput() = %v, want %v", got, tt.want) } }) } }
tools/internal/gocommand/version_test.go/0
{ "file_path": "tools/internal/gocommand/version_test.go", "repo_id": "tools", "token_count": 418 }
749
// Copyright 2020 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package jsonrpc2 import ( "context" "net" "sync" "testing" "time" "golang.org/x/tools/internal/stack/stacktest" "golang.org/x/tools/internal/testenv" ) func TestIdleTimeout(t *testing.T) { testenv.NeedsLocalhostNet(t) stacktest.NoLeak(t) ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) defer cancel() ln, err := net.Listen("tcp", "localhost:0") if err != nil { t.Fatal(err) } defer ln.Close() connect := func() net.Conn { conn, err := net.DialTimeout("tcp", ln.Addr().String(), 5*time.Second) if err != nil { panic(err) } return conn } server := HandlerServer(MethodNotFound) // connTimer := &fakeTimer{c: make(chan time.Time, 1)} var ( runErr error wg sync.WaitGroup ) wg.Add(1) go func() { defer wg.Done() runErr = Serve(ctx, ln, server, 100*time.Millisecond) }() // Exercise some connection/disconnection patterns, and then assert that when // our timer fires, the server exits. conn1 := connect() conn2 := connect() conn1.Close() conn2.Close() conn3 := connect() conn3.Close() wg.Wait() if runErr != ErrIdleTimeout { t.Errorf("run() returned error %v, want %v", runErr, ErrIdleTimeout) } }
tools/internal/jsonrpc2/serve_test.go/0
{ "file_path": "tools/internal/jsonrpc2/serve_test.go", "repo_id": "tools", "token_count": 529 }
750
// Copyright 2018 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package jsonrpc2 import ( "encoding/json" ) // This file contains the go forms of the wire specification. // see http://www.jsonrpc.org/specification for details var ( // ErrParse is used when invalid JSON was received by the server. ErrParse = NewError(-32700, "JSON RPC parse error") // ErrInvalidRequest is used when the JSON sent is not a valid Request object. ErrInvalidRequest = NewError(-32600, "JSON RPC invalid request") // ErrMethodNotFound should be returned by the handler when the method does // not exist / is not available. ErrMethodNotFound = NewError(-32601, "JSON RPC method not found") // ErrInvalidParams should be returned by the handler when method // parameter(s) were invalid. ErrInvalidParams = NewError(-32602, "JSON RPC invalid params") // ErrInternal indicates a failure to process a call correctly ErrInternal = NewError(-32603, "JSON RPC internal error") // The following errors are not part of the json specification, but // compliant extensions specific to this implementation. // ErrServerOverloaded is returned when a message was refused due to a // server being temporarily unable to accept any new messages. ErrServerOverloaded = NewError(-32000, "JSON RPC overloaded") // ErrUnknown should be used for all non coded errors. ErrUnknown = NewError(-32001, "JSON RPC unknown error") // ErrServerClosing is returned for calls that arrive while the server is closing. ErrServerClosing = NewError(-32002, "JSON RPC server is closing") // ErrClientClosing is a dummy error returned for calls initiated while the client is closing. ErrClientClosing = NewError(-32003, "JSON RPC client is closing") ) const wireVersion = "2.0" // wireCombined has all the fields of both Request and Response. // We can decode this and then work out which it is. type wireCombined struct { VersionTag string `json:"jsonrpc"` ID interface{} `json:"id,omitempty"` Method string `json:"method,omitempty"` Params json.RawMessage `json:"params,omitempty"` Result json.RawMessage `json:"result,omitempty"` Error *WireError `json:"error,omitempty"` } // WireError represents a structured error in a Response. type WireError struct { // Code is an error code indicating the type of failure. Code int64 `json:"code"` // Message is a short description of the error. Message string `json:"message"` // Data is optional structured data containing additional information about the error. Data json.RawMessage `json:"data,omitempty"` } // NewError returns an error that will encode on the wire correctly. // The standard codes are made available from this package, this function should // only be used to build errors for application specific codes as allowed by the // specification. func NewError(code int64, message string) error { return &WireError{ Code: code, Message: message, } } func (err *WireError) Error() string { return err.Message } func (err *WireError) Is(other error) bool { w, ok := other.(*WireError) if !ok { return false } return err.Code == w.Code }
tools/internal/jsonrpc2_v2/wire.go/0
{ "file_path": "tools/internal/jsonrpc2_v2/wire.go", "repo_id": "tools", "token_count": 949 }
751
// Copyright 2023 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. //go:build ignore // +build ignore // The pprof command prints the total time in a pprof profile provided // through the standard input. package main import ( "compress/gzip" "fmt" "io" "log" "os" "golang.org/x/tools/internal/pprof" ) func main() { rd, err := gzip.NewReader(os.Stdin) if err != nil { log.Fatal(err) } payload, err := io.ReadAll(rd) if err != nil { log.Fatal(err) } total, err := pprof.TotalTime(payload) if err != nil { log.Fatal(err) } fmt.Println(total) }
tools/internal/pprof/main.go/0
{ "file_path": "tools/internal/pprof/main.go", "repo_id": "tools", "token_count": 259 }
752
// Copyright 2023 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. /* Package inline implements inlining of Go function calls. The client provides information about the caller and callee, including the source text, syntax tree, and type information, and the inliner returns the modified source file for the caller, or an error if the inlining operation is invalid (for example because the function body refers to names that are inaccessible to the caller). Although this interface demands more information from the client than might seem necessary, it enables smoother integration with existing batch and interactive tools that have their own ways of managing the processes of reading, parsing, and type-checking packages. In particular, this package does not assume that the caller and callee belong to the same token.FileSet or types.Importer realms. There are many aspects to a function call. It is the only construct that can simultaneously bind multiple variables of different explicit types, with implicit assignment conversions. (Neither var nor := declarations can do that.) It defines the scope of control labels, of return statements, and of defer statements. Arguments and results of function calls may be tuples even though tuples are not first-class values in Go, and a tuple-valued call expression may be "spread" across the argument list of a call or the operands of a return statement. All these unique features mean that in the general case, not everything that can be expressed by a function call can be expressed without one. So, in general, inlining consists of modifying a function or method call expression f(a1, ..., an) so that the name of the function f is replaced ("literalized") by a literal copy of the function declaration, with free identifiers suitably modified to use the locally appropriate identifiers or perhaps constant argument values. Inlining must not change the semantics of the call. Semantics preservation is crucial for clients such as codebase maintenance tools that automatically inline all calls to designated functions on a large scale. Such tools must not introduce subtle behavior changes. (Fully inlining a call is dynamically observable using reflection over the call stack, but this exception to the rule is explicitly allowed.) In many cases it is possible to entirely replace ("reduce") the call by a copy of the function's body in which parameters have been replaced by arguments. The inliner supports a number of reduction strategies, and we expect this set to grow. Nonetheless, sound reduction is surprisingly tricky. The inliner is in some ways like an optimizing compiler. A compiler is considered correct if it doesn't change the meaning of the program in translation from source language to target language. An optimizing compiler exploits the particulars of the input to generate better code, where "better" usually means more efficient. When a case is found in which it emits suboptimal code, the compiler is improved to recognize more cases, or more rules, and more exceptions to rules; this process has no end. Inlining is similar except that "better" code means tidier code. The baseline translation (literalization) is correct, but there are endless rules--and exceptions to rules--by which the output can be improved. The following section lists some of the challenges, and ways in which they can be addressed. - All effects of the call argument expressions must be preserved, both in their number (they must not be eliminated or repeated), and in their order (both with respect to other arguments, and any effects in the callee function). This must be the case even if the corresponding parameters are never referenced, are referenced multiple times, referenced in a different order from the arguments, or referenced within a nested function that may be executed an arbitrary number of times. Currently, parameter replacement is not applied to arguments with effects, but with further analysis of the sequence of strict effects within the callee we could relax this constraint. - When not all parameters can be substituted by their arguments (e.g. due to possible effects), if the call appears in a statement context, the inliner may introduce a var declaration that declares the parameter variables (with the correct types) and assigns them to their corresponding argument values. The rest of the function body may then follow. For example, the call f(1, 2) to the function func f(x, y int32) { stmts } may be reduced to { var x, y int32 = 1, 2; stmts }. There are many reasons why this is not always possible. For example, true parameters are statically resolved in the same scope, and are dynamically assigned their arguments in parallel; but each spec in a var declaration is statically resolved in sequence and dynamically executed in sequence, so earlier parameters may shadow references in later ones. - Even an argument expression as simple as ptr.x may not be referentially transparent, because another argument may have the effect of changing the value of ptr. This constraint could be relaxed by some kind of alias or escape analysis that proves that ptr cannot be mutated during the call. - Although constants are referentially transparent, as a matter of style we do not wish to duplicate literals that are referenced multiple times in the body because this undoes proper factoring. Also, string literals may be arbitrarily large. - If the function body consists of statements other than just "return expr", in some contexts it may be syntactically impossible to reduce the call. Consider: if x := f(); cond { ... } Go has no equivalent to Lisp's progn or Rust's blocks, nor ML's let expressions (let param = arg in body); its closest equivalent is func(param){body}(arg). Reduction strategies must therefore consider the syntactic context of the call. In such situations we could work harder to extract a statement context for the call, by transforming it to: { x := f(); if cond { ... } } - Similarly, without the equivalent of Rust-style blocks and first-class tuples, there is no general way to reduce a call to a function such as func(params)(args)(results) { stmts; return expr } to an expression such as { var params = args; stmts; expr } or even a statement such as results = { var params = args; stmts; expr } Consequently the declaration and scope of the result variables, and the assignment and control-flow implications of the return statement, must be dealt with by cases. - A standalone call statement that calls a function whose body is "return expr" cannot be simply replaced by the body expression if it is not itself a call or channel receive expression; it is necessary to explicitly discard the result using "_ = expr". Similarly, if the body is a call expression, only calls to some built-in functions with no result (such as copy or panic) are permitted as statements, whereas others (such as append) return a result that must be used, even if just by discarding. - If a parameter or result variable is updated by an assignment within the function body, it cannot always be safely replaced by a variable in the caller. For example, given func f(a int) int { a++; return a } The call y = f(x) cannot be replaced by { x++; y = x } because this would change the value of the caller's variable x. Only if the caller is finished with x is this safe. A similar argument applies to parameter or result variables that escape: by eliminating a variable, inlining would change the identity of the variable that escapes. - If the function body uses 'defer' and the inlined call is not a tail-call, inlining may delay the deferred effects. - Because the scope of a control label is the entire function, a call cannot be reduced if the caller and callee have intersecting sets of control labels. (It is possible to α-rename any conflicting ones, but our colleagues building C++ refactoring tools report that, when tools must choose new identifiers, they generally do a poor job.) - Given func f() uint8 { return 0 } var x any = f() reducing the call to var x any = 0 is unsound because it discards the implicit conversion to uint8. We may need to make each argument-to-parameter conversion explicit if the types differ. Assignments to variadic parameters may need to explicitly construct a slice. An analogous problem applies to the implicit assignments in return statements: func g() any { return f() } Replacing the call f() with 0 would silently lose a conversion to uint8 and change the behavior of the program. - When inlining a call f(1, x, g()) where those parameters are unreferenced, we should be able to avoid evaluating 1 and x since they are pure and thus have no effect. But x may be the last reference to a local variable in the caller, so removing it would cause a compilation error. Parameter substitution must avoid making the caller's local variables unreferenced (or must be prepared to eliminate the declaration too---this is where an iterative framework for simplification would really help). - An expression such as s[i] may be valid if s and i are variables but invalid if either or both of them are constants. For example, a negative constant index s[-1] is always out of bounds, and even a non-negative constant index may be out of bounds depending on the particular string constant (e.g. "abc"[4]). So, if a parameter participates in any expression that is subject to additional compile-time checks when its operands are constant, it may be unsafe to substitute that parameter by a constant argument value (#62664). More complex callee functions are inlinable with more elaborate and invasive changes to the statements surrounding the call expression. TODO(adonovan): future work: - Handle more of the above special cases by careful analysis, thoughtful factoring of the large design space, and thorough test coverage. - Compute precisely (not conservatively) when parameter substitution would remove the last reference to a caller local variable, and blank out the local instead of retreating from the substitution. - Afford the client more control such as a limit on the total increase in line count, or a refusal to inline using the general approach (replacing name by function literal). This could be achieved by returning metadata alongside the result and having the client conditionally discard the change. - Support inlining of generic functions, replacing type parameters by their instantiations. - Support inlining of calls to function literals ("closures"). But note that the existing algorithm makes widespread assumptions that the callee is a package-level function or method. - Eliminate explicit conversions of "untyped" literals inserted conservatively when they are redundant. For example, the conversion int32(1) is redundant when this value is used only as a slice index; but it may be crucial if it is used in x := int32(1) as it changes the type of x, which may have further implications. The conversions may also be important to the falcon analysis. - Allow non-'go' build systems such as Bazel/Blaze a chance to decide whether an import is accessible using logic other than "/internal/" path segments. This could be achieved by returning the list of added import paths instead of a text diff. - Inlining a function from another module may change the effective version of the Go language spec that governs it. We should probably make the client responsible for rejecting attempts to inline from newer callees to older callers, since there's no way for this package to access module versions. - Use an alternative implementation of the import-organizing operation that doesn't require operating on a complete file (and reformatting). Then return the results in a higher-level form as a set of import additions and deletions plus a single diff that encloses the call expression. This interface could perhaps be implemented atop imports.Process by post-processing its result to obtain the abstract import changes and discarding its formatted output. */ package inline
tools/internal/refactor/inline/doc.go/0
{ "file_path": "tools/internal/refactor/inline/doc.go", "repo_id": "tools", "token_count": 3174 }
753
Test of implicit field selections in method calls. The two level wrapping T -> unexported -> U is required to exercise the implicit selections exportedness check; with only a single level, the receiver declaration in "func (unexported) F()" would fail the earlier unexportedness check. -- go.mod -- module testdata go 1.12 -- a/a.go -- package a import "testdata/b" func _(x b.T) { x.F() //@ inline(re"F", re"in x.F, implicit reference to unexported field .unexported cannot be made explicit") } -- b/b.go -- package b type T struct { unexported } type unexported struct { U } type U struct{} func (U) F() {}
tools/internal/refactor/inline/testdata/embed.txtar/0
{ "file_path": "tools/internal/refactor/inline/testdata/embed.txtar", "repo_id": "tools", "token_count": 196 }
754
Test of parameter substitution. -- go.mod -- module testdata go 1.12 -- a/a0.go -- package a var _ = add(2, 1+1) //@ inline(re"add", add) func add(x, y int) int { return x + 2*y } -- add -- package a var _ = 2 + 2*(1+1) //@ inline(re"add", add) func add(x, y int) int { return x + 2*y }
tools/internal/refactor/inline/testdata/param-subst.txtar/0
{ "file_path": "tools/internal/refactor/inline/testdata/param-subst.txtar", "repo_id": "tools", "token_count": 127 }
755
// Copyright 2020 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package stack import ( "bufio" "errors" "io" "regexp" "strconv" ) var ( reBlank = regexp.MustCompile(`^\s*$`) reGoroutine = regexp.MustCompile(`^\s*goroutine (\d+) \[([^\]]*)\]:\s*$`) reCall = regexp.MustCompile(`^\s*` + `(created by )?` + //marker `(([\w/.]+/)?[\w]+)\.` + //package `(\(([^:.)]*)\)\.)?` + //optional type `([\w\.]+)` + //function `(\(.*\))?` + // args `\s*$`) rePos = regexp.MustCompile(`^\s*(.*):(\d+)( .*)?$`) errBreakParse = errors.New("break parse") ) // Scanner splits an input stream into lines in a way that is consumable by // the parser. type Scanner struct { lines *bufio.Scanner done bool } // NewScanner creates a scanner on top of a reader. func NewScanner(r io.Reader) *Scanner { s := &Scanner{ lines: bufio.NewScanner(r), } s.Skip() // prefill return s } // Peek returns the next line without consuming it. func (s *Scanner) Peek() string { if s.done { return "" } return s.lines.Text() } // Skip consumes the next line without looking at it. // Normally used after it has already been looked at using Peek. func (s *Scanner) Skip() { if !s.lines.Scan() { s.done = true } } // Next consumes and returns the next line. func (s *Scanner) Next() string { line := s.Peek() s.Skip() return line } // Done returns true if the scanner has reached the end of the underlying // stream. func (s *Scanner) Done() bool { return s.done } // Err returns true if the scanner has reached the end of the underlying // stream. func (s *Scanner) Err() error { return s.lines.Err() } // Match returns the submatchs of the regular expression against the next line. // If it matched the line is also consumed. func (s *Scanner) Match(re *regexp.Regexp) []string { if s.done { return nil } match := re.FindStringSubmatch(s.Peek()) if match != nil { s.Skip() } return match } // SkipBlank skips any number of pure whitespace lines. func (s *Scanner) SkipBlank() { for !s.done { line := s.Peek() if len(line) != 0 && !reBlank.MatchString(line) { return } s.Skip() } } // Parse the current contiguous block of goroutine stack traces until the // scanned content no longer matches. func Parse(scanner *Scanner) (Dump, error) { dump := Dump{} for { gr, ok := parseGoroutine(scanner) if !ok { return dump, nil } dump = append(dump, gr) } } func parseGoroutine(scanner *Scanner) (Goroutine, bool) { match := scanner.Match(reGoroutine) if match == nil { return Goroutine{}, false } id, _ := strconv.ParseInt(match[1], 0, 32) gr := Goroutine{ ID: int(id), State: match[2], } for { frame, ok := parseFrame(scanner) if !ok { scanner.SkipBlank() return gr, true } if frame.Position.Filename != "" { gr.Stack = append(gr.Stack, frame) } } } func parseFrame(scanner *Scanner) (Frame, bool) { fun, ok := parseFunction(scanner) if !ok { return Frame{}, false } frame := Frame{ Function: fun, } frame.Position, ok = parsePosition(scanner) // if ok is false, then this is a broken state. // we got the func but not the file that must follow // the consumed line can be recovered from the frame //TODO: push back the fun raw return frame, ok } func parseFunction(scanner *Scanner) (Function, bool) { match := scanner.Match(reCall) if match == nil { return Function{}, false } return Function{ Package: match[2], Type: match[5], Name: match[6], }, true } func parsePosition(scanner *Scanner) (Position, bool) { match := scanner.Match(rePos) if match == nil { return Position{}, false } line, _ := strconv.ParseInt(match[2], 0, 32) return Position{Filename: match[1], Line: int(line)}, true }
tools/internal/stack/parse.go/0
{ "file_path": "tools/internal/stack/parse.go", "repo_id": "tools", "token_count": 1481 }
756
//go:build go1.20 package versions // want "pre.go@go1.20"
tools/internal/testfiles/testdata/versions/pre.go/0
{ "file_path": "tools/internal/testfiles/testdata/versions/pre.go", "repo_id": "tools", "token_count": 25 }
757
// Copyright 2021 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package typeparams_test import ( "go/ast" "go/parser" "go/token" "go/types" "regexp" "strings" "testing" . "golang.org/x/tools/internal/typeparams" ) func TestStructuralTerms(t *testing.T) { // In the following tests, src must define a type T with (at least) one type // parameter. We will compute the structural terms of the first type // parameter. tests := []struct { src string want string wantError string }{ {"package emptyinterface0; type T[P interface{}] int", "all", ""}, {"package emptyinterface1; type T[P interface{ int | interface{} }] int", "all", ""}, {"package singleton; type T[P interface{ int }] int", "int", ""}, {"package under; type T[P interface{~int}] int", "~int", ""}, {"package superset; type T[P interface{ ~int | int }] int", "~int", ""}, {"package overlap; type T[P interface{ ~int; int }] int", "int", ""}, {"package emptyintersection; type T[P interface{ ~int; string }] int", "", "empty type set"}, {"package embedded0; type T[P interface{ I }] int; type I interface { int }", "int", ""}, {"package embedded1; type T[P interface{ I | string }] int; type I interface{ int | ~string }", "int ?\\| ?~string", ""}, {"package embedded2; type T[P interface{ I; string }] int; type I interface{ int | ~string }", "string", ""}, {"package named; type T[P C] int; type C interface{ ~int|int }", "~int", ""}, {`// package example is taken from the docstring for StructuralTerms package example type A interface{ ~string|~[]byte } type B interface{ int|string } type C interface { ~string|~int } type T[P interface{ A|B; C }] int `, "~string ?\\| ?int", ""}, } for _, test := range tests { fset := token.NewFileSet() f, err := parser.ParseFile(fset, "p.go", test.src, 0) if err != nil { t.Fatal(err) } t.Run(f.Name.Name, func(t *testing.T) { conf := types.Config{ Error: func(error) {}, // keep going on errors } pkg, err := conf.Check("", fset, []*ast.File{f}, nil) if err != nil { t.Logf("types.Config.Check: %v", err) // keep going on type checker errors: we want to assert on behavior of // invalid code as well. } obj := pkg.Scope().Lookup("T") if obj == nil { t.Fatal("type T not found") } T := obj.Type().(*types.Named).TypeParams().At(0) terms, err := StructuralTerms(T) if test.wantError != "" { if err == nil { t.Fatalf("StructuralTerms(%s): nil error, want %q", T, test.wantError) } if !strings.Contains(err.Error(), test.wantError) { t.Errorf("StructuralTerms(%s): err = %q, want %q", T, err, test.wantError) } return } if err != nil { t.Fatal(err) } var got string if len(terms) == 0 { got = "all" } else { qf := types.RelativeTo(pkg) got = types.TypeString(types.NewUnion(terms), qf) } want := regexp.MustCompile(test.want) if !want.MatchString(got) { t.Errorf("StructuralTerms(%s) = %q, want %q", T, got, test.want) } }) } }
tools/internal/typeparams/normalize_test.go/0
{ "file_path": "tools/internal/typeparams/normalize_test.go", "repo_id": "tools", "token_count": 1251 }
758
// Copyright 2023 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. //go:build !go1.22 // +build !go1.22 package versions import ( "go/ast" "go/types" ) // FileVersion returns a language version (<=1.21) derived from runtime.Version() // or an unknown future version. func FileVersion(info *types.Info, file *ast.File) string { // In x/tools built with Go <= 1.21, we do not have Info.FileVersions // available. We use a go version derived from the toolchain used to // compile the tool by default. // This will be <= go1.21. We take this as the maximum version that // this tool can support. // // There are no features currently in x/tools that need to tell fine grained // differences for versions <1.22. return toolchain } // InitFileVersions is a noop when compiled with this Go version. func InitFileVersions(*types.Info) {}
tools/internal/versions/types_go121.go/0
{ "file_path": "tools/internal/versions/types_go121.go", "repo_id": "tools", "token_count": 278 }
759
// Copyright 2012 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package present import ( "fmt" "strings" ) func init() { Register("image", parseImage) } type Image struct { Cmd string // original command from present source URL string Width int Height int } func (i Image) PresentCmd() string { return i.Cmd } func (i Image) TemplateName() string { return "image" } func parseImage(ctx *Context, fileName string, lineno int, text string) (Elem, error) { args := strings.Fields(text) if len(args) < 2 { return nil, fmt.Errorf("incorrect image invocation: %q", text) } img := Image{Cmd: text, URL: args[1]} a, err := parseArgs(fileName, lineno, args[2:]) if err != nil { return nil, err } switch len(a) { case 0: // no size parameters case 2: // If a parameter is empty (underscore) or invalid // leave the field set to zero. The "image" action // template will then omit that img tag attribute and // the browser will calculate the value to preserve // the aspect ratio. if v, ok := a[0].(int); ok { img.Height = v } if v, ok := a[1].(int); ok { img.Width = v } default: return nil, fmt.Errorf("incorrect image invocation: %q", text) } return img, nil }
tools/present/image.go/0
{ "file_path": "tools/present/image.go", "repo_id": "tools", "token_count": 461 }
760
# Media ## .image gopher.jpg _ 100 .caption A gopher. .iframe https://golang.org/ .link https://golang.org/ The Gopher's home. .html testdata/media.html --- <h1>Media</h1> <section> <img src="gopher.jpg" width="100" alt=""> <figcaption>A gopher.</figcaption> <iframe src="https://golang.org/"></iframe> <p class="link"><a href="https://golang.org/">The Gopher&#39;s home.</a></p> <!-- media.html --> </section>
tools/present/testdata/media.md/0
{ "file_path": "tools/present/testdata/media.md", "repo_id": "tools", "token_count": 172 }
761
package B1 import "time" var startup = time.Now() func example() time.Duration { before := time.Now() time.Sleep(1) return time.Now().Sub(before) } func msSinceStartup() int64 { return int64(time.Now().Sub(startup) / time.Millisecond) }
tools/refactor/eg/testdata/B1.go/0
{ "file_path": "tools/refactor/eg/testdata/B1.go", "repo_id": "tools", "token_count": 92 }
762
package G1 import "go/ast" func example() { _ = ast.BadExpr{123, 456} // match _ = ast.BadExpr{123, 456} // no match _ = ast.BadExpr{From: 123} // no match _ = ast.BadExpr{To: 456} // no match }
tools/refactor/eg/testdata/G1.golden/0
{ "file_path": "tools/refactor/eg/testdata/G1.golden", "repo_id": "tools", "token_count": 94 }
763
// Copyright 2015 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // Incomplete std lib sources on Android. //go:build !android // +build !android package importgraph_test import ( "fmt" "go/build" "os" "sort" "strings" "testing" "golang.org/x/tools/go/packages/packagestest" "golang.org/x/tools/refactor/importgraph" _ "crypto/hmac" // just for test, below ) const this = "golang.org/x/tools/refactor/importgraph" func TestBuild(t *testing.T) { exported := packagestest.Export(t, packagestest.GOPATH, []packagestest.Module{ {Name: "golang.org/x/tools/refactor/importgraph", Files: packagestest.MustCopyFileTree(".")}}) defer exported.Cleanup() var gopath string for _, env := range exported.Config.Env { eq := strings.Index(env, "=") if eq == 0 { // We sometimes see keys with a single leading "=" in the environment on Windows. // TODO(#49886): What is the correct way to parse them in general? eq = strings.Index(env[1:], "=") + 1 } if eq < 0 { t.Fatalf("invalid variable in exported.Config.Env: %q", env) } k := env[:eq] v := env[eq+1:] if k == "GOPATH" { gopath = v } if os.Getenv(k) == v { continue } defer func(prev string, prevOK bool) { if !prevOK { if err := os.Unsetenv(k); err != nil { t.Fatal(err) } } else { if err := os.Setenv(k, prev); err != nil { t.Fatal(err) } } }(os.LookupEnv(k)) if err := os.Setenv(k, v); err != nil { t.Fatal(err) } t.Logf("%s=%s", k, v) } if gopath == "" { t.Fatal("Failed to fish GOPATH out of env: ", exported.Config.Env) } var buildContext = build.Default buildContext.GOPATH = gopath buildContext.Dir = exported.Config.Dir forward, reverse, errs := importgraph.Build(&buildContext) for path, err := range errs { t.Errorf("%s: %s", path, err) } if t.Failed() { return } // Log the complete graph before the errors, so that the errors are near the // end of the log (where we expect them to be). nodePrinted := map[string]bool{} printNode := func(direction string, from string) { key := fmt.Sprintf("%s[%q]", direction, from) if nodePrinted[key] { return } nodePrinted[key] = true var g importgraph.Graph switch direction { case "forward": g = forward case "reverse": g = reverse default: t.Helper() t.Fatalf("bad direction: %q", direction) } t.Log(key) var pkgs []string for pkg := range g[from] { pkgs = append(pkgs, pkg) } sort.Strings(pkgs) for _, pkg := range pkgs { t.Logf("\t%s", pkg) } } if testing.Verbose() { printNode("forward", this) printNode("reverse", this) } // Test direct edges. // We throw in crypto/hmac to prove that external test files // (such as this one) are inspected. for _, p := range []string{"go/build", "testing", "crypto/hmac"} { if !forward[this][p] { printNode("forward", this) t.Errorf("forward[%q][%q] not found", this, p) } if !reverse[p][this] { printNode("reverse", p) t.Errorf("reverse[%q][%q] not found", p, this) } } // Test non-existent direct edges for _, p := range []string{"errors", "reflect"} { if forward[this][p] { printNode("forward", this) t.Errorf("unexpected: forward[%q][%q] found", this, p) } if reverse[p][this] { printNode("reverse", p) t.Errorf("unexpected: reverse[%q][%q] found", p, this) } } // Test Search is reflexive. if !forward.Search(this)[this] { printNode("forward", this) t.Errorf("irreflexive: forward.Search(importgraph)[importgraph] not found") } if !reverse.Search(this)[this] { printNode("reverse", this) t.Errorf("irrefexive: reverse.Search(importgraph)[importgraph] not found") } // Test Search is transitive. (There is no direct edge to these packages.) for _, p := range []string{"errors", "reflect", "unsafe"} { if !forward.Search(this)[p] { printNode("forward", this) t.Errorf("intransitive: forward.Search(importgraph)[%s] not found", p) } if !reverse.Search(p)[this] { printNode("reverse", p) t.Errorf("intransitive: reverse.Search(%s)[importgraph] not found", p) } } // Test strongly-connected components. Because A's external // test package can depend on B, and vice versa, most of the // standard libraries are mutually dependent when their external // tests are considered. // // For any nodes x, y in the same SCC, y appears in the results // of both forward and reverse searches starting from x if !forward.Search("fmt")["io"] || !forward.Search("io")["fmt"] || !reverse.Search("fmt")["io"] || !reverse.Search("io")["fmt"] { printNode("forward", "fmt") printNode("forward", "io") printNode("reverse", "fmt") printNode("reverse", "io") t.Errorf("fmt and io are not mutually reachable despite being in the same SCC") } }
tools/refactor/importgraph/graph_test.go/0
{ "file_path": "tools/refactor/importgraph/graph_test.go", "repo_id": "tools", "token_count": 1923 }
764
### Release process The golang.go-nightly extension is released daily during weekdays, based on the latest commit to the master branch. (Note: the release process is currently in GH workflow. We are in process of moving it to a GCB workflow.) * Dockerfile: defines the image containing tools and environments needed to build and test the extension. (e.g. Go, Node.js, jq, etc.) * build-ci-image.yaml: defines the workflow to build the container image used for extension testing and releasing. * release-nightly.yaml: defines the workflow that builds the nightly extension and runs tests. The built extension is pushed only after all tests pass.
vscode-go/build/README.md/0
{ "file_path": "vscode-go/build/README.md", "repo_id": "vscode-go", "token_count": 155 }
765
module.exports = { ...require('.prettierrc.json') }
vscode-go/extension/.prettierrc.js/0
{ "file_path": "vscode-go/extension/.prettierrc.js", "repo_id": "vscode-go", "token_count": 22 }
766
{ ".source.go": { "single import": { "prefix": "im", "body": "import \"${1:package}\"", "description": "Snippet for import statement" }, "multiple imports": { "prefix": "ims", "body": "import (\n\t\"${1:package}\"\n)", "description": "Snippet for a import block" }, "single constant": { "prefix": "co", "body": "const ${1:name} = ${2:value}", "description": "Snippet for a constant" }, "multiple constants": { "prefix": "cos", "body": "const (\n\t${1:name} = ${2:value}\n)", "description": "Snippet for a constant block" }, "type function declaration": { "prefix": "tyf", "body": "type ${1:name} func($3) $4", "description": "Snippet for a type function declaration" }, "type interface declaration": { "prefix": "tyi", "body": "type ${1:name} interface {\n\t$0\n}", "description": "Snippet for a type interface" }, "type struct declaration": { "prefix": "tys", "body": "type ${1:name} struct {\n\t$0\n}", "description": "Snippet for a struct declaration" }, "package main and main function": { "prefix": "pkgm", "body": "package main\n\nfunc main() {\n\t$0\n}", "description": "Snippet for main package & function" }, "function declaration": { "prefix": "func", "body": "func $1($2) $3 {\n\t$0\n}", "description": "Snippet for function declaration" }, "single variable": { "prefix": "var", "body": "var ${1:name} ${2:type}", "description": "Snippet for a variable" }, "multiple variables": { "prefix": "vars", "body": "var (\n\t${1:name} ${2:type}\n)", "description": "Snippet for variable block" }, "switch statement": { "prefix": "switch", "body": "switch ${1:expression} {\ncase ${2:condition}:\n\t$0\n}", "description": "Snippet for switch statement" }, "select statement": { "prefix": "sel", "body": "select {\ncase ${1:condition}:\n\t$0\n}", "description": "Snippet for select statement" }, "case clause": { "prefix": "cs", "body": "case ${1:condition}:$0", "description": "Snippet for case clause" }, "for statement": { "prefix": "for", "body": "for ${1:i} := ${2:0}; $1 < ${3:count}; $1${4:++} {\n\t$0\n}", "description": "Snippet for a for loop" }, "for range statement": { "prefix": "forr", "body": "for ${1:_, }${2:v} := range ${3:v} {\n\t$0\n}", "description": "Snippet for a for range loop" }, "channel declaration": { "prefix": "ch", "body": "chan ${1:type}", "description": "Snippet for a channel" }, "map declaration": { "prefix": "map", "body": "map[${1:type}]${2:type}", "description": "Snippet for a map" }, "empty interface": { "prefix": "in", "body": "interface{}", "description": "Snippet for empty interface" }, "if statement": { "prefix": "if", "body": "if ${1:condition} {\n\t$0\n}", "description": "Snippet for if statement" }, "else branch": { "prefix": "el", "body": "else {\n\t$0\n}", "description": "Snippet for else branch" }, "if else statement": { "prefix": "ie", "body": "if ${1:condition} {\n\t$2\n} else {\n\t$0\n}", "description": "Snippet for if else" }, "if err != nil": { "prefix": "iferr", "body": "if err != nil {\n\t${1:return ${2:nil, }${3:err}}\n}", "description": "Snippet for if err != nil" }, "fmt.Println": { "prefix": "fp", "body": "fmt.Println(\"$1\")", "description": "Snippet for fmt.Println()" }, "fmt.Printf": { "prefix": "ff", "body": "fmt.Printf(\"$1\", ${2:var})", "description": "Snippet for fmt.Printf()" }, "log.Println": { "prefix": "lp", "body": "log.Println(\"$1\")", "description": "Snippet for log.Println()" }, "log.Printf": { "prefix": "lf", "body": "log.Printf(\"$1\", ${2:var})", "description": "Snippet for log.Printf()" }, "log variable content": { "prefix": "lv", "body": "log.Printf(\"${1:var}: %#+v\\\\n\", ${1:var})", "description": "Snippet for log.Printf() with variable content" }, "t.Log": { "prefix": "tl", "body": "t.Log(\"$1\")", "description": "Snippet for t.Log()" }, "t.Logf": { "prefix": "tlf", "body": "t.Logf(\"$1\", ${2:var})", "description": "Snippet for t.Logf()" }, "t.Logf variable content": { "prefix": "tlv", "body": "t.Logf(\"${1:var}: %#+v\\\\n\", ${1:var})", "description": "Snippet for t.Logf() with variable content" }, "make(...)": { "prefix": "make", "body": "make(${1:type}, ${2:0})", "description": "Snippet for make statement" }, "new(...)": { "prefix": "new", "body": "new(${1:type})", "description": "Snippet for new statement" }, "panic(...)": { "prefix": "pn", "body": "panic(\"$0\")", "description": "Snippet for panic" }, "http ResponseWriter *Request": { "prefix": "wr", "body": "${1:w} http.ResponseWriter, ${2:r} *http.Request", "description": "Snippet for http Response" }, "http.HandleFunc": { "prefix": "hf", "body": "${1:http}.HandleFunc(\"${2:/}\", ${3:handler})", "description": "Snippet for http.HandleFunc()" }, "http handler declaration": { "prefix": "hand", "body": "func $1(${2:w} http.ResponseWriter, ${3:r} *http.Request) {\n\t$0\n}", "description": "Snippet for http handler declaration" }, "http.Redirect": { "prefix": "rd", "body": "http.Redirect(${1:w}, ${2:r}, \"${3:/}\", ${4:http.StatusFound})", "description": "Snippet for http.Redirect()" }, "http.Error": { "prefix": "herr", "body": "http.Error(${1:w}, ${2:err}.Error(), ${3:http.StatusInternalServerError})", "description": "Snippet for http.Error()" }, "http.ListenAndServe": { "prefix": "las", "body": "http.ListenAndServe(\"${1::8080}\", ${2:nil})", "description": "Snippet for http.ListenAndServe" }, "http.Serve": { "prefix": "sv", "body": "http.Serve(\"${1::8080}\", ${2:nil})", "description": "Snippet for http.Serve" }, "goroutine anonymous function": { "prefix": "go", "body": "go func($1) {\n\t$0\n}($2)", "description": "Snippet for anonymous goroutine declaration" }, "goroutine function": { "prefix": "gf", "body": "go ${1:func}($0)", "description": "Snippet for goroutine declaration" }, "defer statement": { "prefix": "df", "body": "defer ${1:func}($0)", "description": "Snippet for defer statement" }, "test function": { "prefix": "tf", "body": "func Test$1(t *testing.T) {\n\t$0\n}", "description": "Snippet for Test function" }, "test main": { "prefix": "tm", "body": "func TestMain(m *testing.M) {\n\t$1\n\n\tos.Exit(m.Run())\n}", "description": "Snippet for TestMain function" }, "benchmark function": { "prefix": "bf", "body": "func Benchmark$1(b *testing.B) {\n\tfor ${2:i} := 0; ${2:i} < b.N; ${2:i}++ {\n\t\t$0\n\t}\n}", "description": "Snippet for Benchmark function" }, "example function": { "prefix": "ef", "body": "func Example$1() {\n\t$2\n\t//Output:\n\t$3\n}", "description": "Snippet for Example function" }, "table driven test": { "prefix": "tdt", "body": "func Test$1(t *testing.T) {\n\ttestCases := []struct {\n\t\tdesc\tstring\n\t\t$2\n\t}{\n\t\t{\n\t\t\tdesc: \"$3\",\n\t\t\t$4\n\t\t},\n\t}\n\tfor _, tC := range testCases {\n\t\tt.Run(tC.desc, func(t *testing.T) {\n\t\t\t$0\n\t\t})\n\t}\n}", "description": "Snippet for table driven test" }, "init function": { "prefix": "finit", "body": "func init() {\n\t$1\n}", "description": "Snippet for init function" }, "main function": { "prefix": "fmain", "body": "func main() {\n\t$1\n}", "description": "Snippet for main function" }, "method declaration": { "prefix": "meth", "body": "func (${1:receiver} ${2:type}) ${3:method}($4) $5 {\n\t$0\n}", "description": "Snippet for method declaration" }, "hello world web app": { "prefix": "helloweb", "body": "package main\n\nimport (\n\t\"fmt\"\n\t\"net/http\"\n\t\"time\"\n)\n\nfunc greet(w http.ResponseWriter, r *http.Request) {\n\tfmt.Fprintf(w, \"Hello World! %s\", time.Now())\n}\n\nfunc main() {\n\thttp.HandleFunc(\"/\", greet)\n\thttp.ListenAndServe(\":8080\", nil)\n}", "description": "Snippet for sample hello world webapp" }, "sort implementation": { "prefix": "sort", "body": "type ${1:SortBy} []${2:Type}\n\nfunc (a $1) Len() int { return len(a) }\nfunc (a $1) Swap(i, j int) { a[i], a[j] = a[j], a[i] }\nfunc (a $1) Less(i, j int) bool { ${3:return a[i] < a[j]} }", "description": "Snippet for a custom sort.Sort interface implementation, for a given slice type." } } }
vscode-go/extension/snippets/go.json/0
{ "file_path": "vscode-go/extension/snippets/go.json", "repo_id": "vscode-go", "token_count": 3928 }
767
/* eslint-disable @typescript-eslint/no-unused-vars */ /* eslint-disable no-case-declarations */ /* eslint-disable eqeqeq */ /* eslint-disable no-useless-escape */ /* eslint-disable no-async-promise-executor */ /* eslint-disable @typescript-eslint/no-explicit-any */ /*--------------------------------------------------------- * Copyright (C) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See LICENSE in the project root for license information. *--------------------------------------------------------*/ import { ChildProcess, execFile, spawn, spawnSync } from 'child_process'; import { EventEmitter } from 'events'; import * as fs from 'fs'; import { existsSync, lstatSync } from 'fs'; import * as glob from 'glob'; import { Client, RPCConnection } from 'json-rpc2'; import * as os from 'os'; import * as path from 'path'; import * as util from 'util'; import { ContinuedEvent, DebugSession, ErrorDestination, Handles, InitializedEvent, logger, Logger, LoggingDebugSession, OutputEvent, Scope, Source, StackFrame, StoppedEvent, TerminatedEvent, Thread } from 'vscode-debugadapter'; import { DebugProtocol } from 'vscode-debugprotocol'; import { parseEnvFiles } from '../utils/envUtils'; import { correctBinname, getEnvPath, expandFilePathInOutput, fixDriveCasingInWindows, getBinPathWithPreferredGopathGoroot, getCurrentGoWorkspaceFromGOPATH, getInferredGopath } from '../utils/pathUtils'; import { killProcessTree } from '../utils/processUtils'; const fsAccess = util.promisify(fs.access); const fsUnlink = util.promisify(fs.unlink); // This enum should stay in sync with https://golang.org/pkg/reflect/#Kind enum GoReflectKind { Invalid = 0, Bool, Int, Int8, Int16, Int32, Int64, Uint, Uint8, Uint16, Uint32, Uint64, Uintptr, Float32, Float64, Complex64, Complex128, Array, Chan, Func, Interface, Map, Ptr, Slice, String, Struct, UnsafePointer } // These types should stay in sync with: // https://github.com/go-delve/delve/blob/master/service/api/types.go interface CommandOut { State: DebuggerState; } interface DebuggerState { exited: boolean; exitStatus: number; currentThread: DebugThread; currentGoroutine: DebugGoroutine; Running: boolean; Threads: DebugThread[]; NextInProgress: boolean; } export interface PackageBuildInfo { ImportPath: string; DirectoryPath: string; Files: string[]; } export interface ListPackagesBuildInfoOut { List: PackageBuildInfo[]; } export interface ListSourcesOut { Sources: string[]; } interface CreateBreakpointOut { Breakpoint: DebugBreakpoint; } interface GetVersionOut { DelveVersion: string; APIVersion: number; } interface DebugBreakpoint { addr: number; continue: boolean; file: string; functionName?: string; goroutine: boolean; id: number; name: string; line: number; stacktrace: number; variables?: DebugVariable[]; loadArgs?: LoadConfig; loadLocals?: LoadConfig; cond?: string; } interface LoadConfig { // FollowPointers requests pointers to be automatically dereferenced. followPointers: boolean; // MaxVariableRecurse is how far to recurse when evaluating nested types. maxVariableRecurse: number; // MaxStringLen is the maximum number of bytes read from a string maxStringLen: number; // MaxArrayValues is the maximum number of elements read from an array, a slice or a map. maxArrayValues: number; // MaxStructFields is the maximum number of fields read from a struct, -1 will read all fields. maxStructFields: number; } interface DebugThread { file: string; id: number; line: number; pc: number; goroutineID: number; breakPoint: DebugBreakpoint; breakPointInfo: {}; function?: DebugFunction; ReturnValues: DebugVariable[]; } interface StacktraceOut { Locations: DebugLocation[]; } interface DebugLocation { pc: number; file: string; line: number; function: DebugFunction; } interface DebugFunction { name: string; value: number; type: number; goType: number; args: DebugVariable[]; locals: DebugVariable[]; optimized: boolean; } interface ListVarsOut { Variables: DebugVariable[]; } interface ListFunctionArgsOut { Args: DebugVariable[]; } interface EvalOut { Variable: DebugVariable; } enum GoVariableFlags { VariableUnknown = 0, VariableEscaped = 1, VariableShadowed = 2, VariableConstant = 4, VariableArgument = 8, VariableReturnArgument = 16, VariableFakeAddress = 32 } interface DebugVariable { // DebugVariable corresponds to api.Variable in Delve API. // https://github.com/go-delve/delve/blob/328cf87808822693dc611591519689dcd42696a3/service/api/types.go#L239-L284 name: string; addr: number; type: string; realType: string; kind: GoReflectKind; flags: GoVariableFlags; onlyAddr: boolean; DeclLine: number; value: string; len: number; cap: number; children: DebugVariable[]; unreadable: string; fullyQualifiedName: string; base: number; } interface ListGoroutinesOut { Goroutines: DebugGoroutine[]; } interface DebugGoroutine { id: number; currentLoc: DebugLocation; userCurrentLoc: DebugLocation; goStatementLoc: DebugLocation; } interface DebuggerCommand { name: string; threadID?: number; goroutineID?: number; } interface ListBreakpointsOut { Breakpoints: DebugBreakpoint[]; } interface RestartOut { DiscardedBreakpoints: DiscardedBreakpoint[]; } interface DiscardedBreakpoint { breakpoint: DebugBreakpoint; reason: string; } // Unrecovered panic and fatal throw breakpoint IDs taken from delve: // https://github.com/go-delve/delve/blob/f90134eb4db1c423e24fddfbc6eff41b288e6297/pkg/proc/breakpoints.go#L11-L21 // UnrecoveredPanic is the name given to the unrecovered panic breakpoint. const unrecoveredPanicID = -1; // FatalThrow is the name given to the breakpoint triggered when the target // process dies because of a fatal runtime error. const fatalThrowID = -2; // This interface should always match the schema found in `package.json`. interface LaunchRequestArguments extends DebugProtocol.LaunchRequestArguments { request: 'launch'; [key: string]: any; program: string; stopOnEntry?: boolean; dlvFlags?: string[]; args?: string[]; showLog?: boolean; logOutput?: string; cwd?: string; env?: { [key: string]: string }; mode?: 'auto' | 'debug' | 'remote' | 'test' | 'exec'; remotePath?: string; port?: number; host?: string; buildFlags?: string; init?: string; // trace, info, warn are to match goLogging. // In practice, this adapter handles only verbose, log, and error // verbose === trace, // log === info === warn, // error trace?: 'verbose' | 'trace' | 'info' | 'log' | 'warn' | 'error'; backend?: string; output?: string; substitutePath?: { from: string; to: string }[]; /** Delve LoadConfig parameters */ dlvLoadConfig?: LoadConfig; dlvToolPath: string; /** Delve Version */ apiVersion: number; /** Delve maximum stack trace depth */ stackTraceDepth: number; showGlobalVariables?: boolean; packagePathToGoModPathMap: { [key: string]: string }; /** Optional path to .env file. */ // TODO: deprecate .env file processing from DA. // We expect the extension processes .env files // and send the information to DA using the 'env' property. envFile?: string | string[]; } interface AttachRequestArguments extends DebugProtocol.AttachRequestArguments { request: 'attach'; processId?: number; stopOnEntry?: boolean; dlvFlags?: string[]; showLog?: boolean; logOutput?: string; cwd?: string; mode?: 'local' | 'remote'; remotePath?: string; port?: number; host?: string; trace?: 'verbose' | 'trace' | 'info' | 'log' | 'warn' | 'error'; backend?: string; substitutePath?: { from: string; to: string }[]; /** Delve LoadConfig parameters */ dlvLoadConfig?: LoadConfig; dlvToolPath: string; /** Delve Version */ apiVersion: number; /** Delve maximum stack trace depth */ stackTraceDepth: number; showGlobalVariables?: boolean; } process.on('uncaughtException', (err: any) => { const errMessage = err && (err.stack || err.message); logger.error(`Unhandled error in debug adapter: ${errMessage}`); throw err; }); function logArgsToString(args: any[]): string { return args .map((arg) => { return typeof arg === 'string' ? arg : JSON.stringify(arg); }) .join(' '); } function log(...args: any[]) { logger.warn(logArgsToString(args)); } function logError(...args: any[]) { logger.error(logArgsToString(args)); } export function findPathSeparator(filePath: string | undefined) { return filePath && filePath.includes('\\') ? '\\' : '/'; } // Comparing two different file paths while ignoring any different path separators. function compareFilePathIgnoreSeparator(firstFilePath: string, secondFilePath: string): boolean { const firstSeparator = findPathSeparator(firstFilePath); const secondSeparator = findPathSeparator(secondFilePath); if (firstSeparator === secondSeparator) { return firstFilePath === secondFilePath; } return firstFilePath === secondFilePath.split(secondSeparator).join(firstSeparator); } export function escapeGoModPath(filePath: string) { return filePath.replace(/[A-Z]/g, (match: string) => `!${match.toLocaleLowerCase()}`); } function normalizePath(filePath: string) { if (process.platform === 'win32') { const pathSeparator = findPathSeparator(filePath); filePath = path.normalize(filePath); // Normalize will replace everything with backslash on Windows. filePath = filePath.replace(/\\/g, pathSeparator); return fixDriveCasingInWindows(filePath); } return filePath; } // normalizeSeparators will prepare the filepath for comparison in mapping from // local to debugger path and from debugger path to local path. All separators are // replaced with '/', and the drive name is capitalized for windows paths. // Exported for testing export function normalizeSeparators(filePath: string): string { // Although the current machine may not be running windows, // the remote machine may be and we need to fix the drive // casing. // This is a workaround for issue in https://github.com/Microsoft/vscode/issues/9448#issuecomment-244804026 if (filePath.indexOf(':') === 1) { filePath = filePath.substr(0, 1).toUpperCase() + filePath.substr(1); } return filePath.replace(/\/|\\/g, '/'); } function getBaseName(filePath: string) { return filePath.includes('/') ? path.basename(filePath) : path.win32.basename(filePath); } export class Delve { public program: string; public remotePath?: string; public loadConfig?: LoadConfig; public connection: Promise<RPCConnection | null>; // null if connection isn't necessary (e.g. noDebug mode) public onstdout?: (str: string) => void; public onstderr?: (str: string) => void; public onclose?: (code: number) => void; public noDebug?: boolean; public isApiV1: boolean; public dlvEnv: any; public stackTraceDepth: number; public isRemoteDebugging?: boolean; public goroot?: string; public delveConnectionClosed = false; private localDebugeePath: string | undefined; private debugProcess?: ChildProcess; private request: 'attach' | 'launch'; constructor(launchArgs: LaunchRequestArguments | AttachRequestArguments, program: string) { this.request = launchArgs.request; this.program = normalizePath(program); this.remotePath = launchArgs.remotePath; this.isApiV1 = false; if (typeof launchArgs.apiVersion === 'number') { this.isApiV1 = launchArgs.apiVersion === 1; } this.stackTraceDepth = typeof launchArgs.stackTraceDepth === 'number' ? launchArgs.stackTraceDepth : 50; this.connection = new Promise(async (resolve, reject) => { const mode = launchArgs.mode; let dlvCwd = path.dirname(program); let serverRunning = false; const dlvArgs = new Array<string>(); // Get default LoadConfig values according to delve API: // https://github.com/go-delve/delve/blob/c5c41f635244a22d93771def1c31cf1e0e9a2e63/service/rpc1/server.go#L13 // https://github.com/go-delve/delve/blob/c5c41f635244a22d93771def1c31cf1e0e9a2e63/service/rpc2/server.go#L423 this.loadConfig = launchArgs.dlvLoadConfig || { followPointers: true, maxVariableRecurse: 1, maxStringLen: 64, maxArrayValues: 64, maxStructFields: -1 }; if (mode === 'remote') { log(`Start remote debugging: connecting ${launchArgs.host}:${launchArgs.port}`); this.debugProcess = undefined; this.isRemoteDebugging = true; this.goroot = await queryGOROOT(dlvCwd, process.env); serverRunning = true; // assume server is running when in remote mode if (!launchArgs.port || !launchArgs.host) { return reject('Unable to connect, missing host or port from launchArgs.'); } connectClient(launchArgs.port, launchArgs.host, this.onclose); return; } this.isRemoteDebugging = false; let env: NodeJS.ProcessEnv | undefined; if (launchArgs.request === 'launch') { let isProgramDirectory = false; // Validations on the program if (!program) { return reject('The program attribute is missing in the debug configuration in launch.json'); } try { const pstats = lstatSync(program); if (pstats.isDirectory()) { if (mode === 'exec') { logError(`The program "${program}" must not be a directory in exec mode`); return reject('The program attribute must be an executable in exec mode'); } dlvCwd = program; isProgramDirectory = true; } else if (mode !== 'exec' && path.extname(program) !== '.go') { logError(`The program "${program}" must be a valid go file in debug mode`); return reject('The program attribute must be a directory or .go file in debug mode'); } } catch (e) { logError(`The program "${program}" does not exist: ${e}`); return reject('The program attribute must point to valid directory, .go file or executable.'); } // read env from disk and merge into env variables try { const fileEnvs = parseEnvFiles(launchArgs.envFile); const launchArgsEnv = launchArgs.env || {}; env = Object.assign({}, process.env, fileEnvs, launchArgsEnv); } catch (e) { return reject(`failed to process 'envFile' and 'env' settings: ${e}`); } const dirname = isProgramDirectory ? program : path.dirname(program); if (!env['GOPATH'] && (mode === 'debug' || mode === 'test')) { // If no GOPATH is set, then infer it from the file/package path // Not applicable to exec mode in which case `program` need not point to source code under GOPATH env['GOPATH'] = getInferredGopath(dirname) || env['GOPATH']; } this.dlvEnv = env; this.goroot = await queryGOROOT(dlvCwd, env); log(`Using GOPATH: ${env['GOPATH']}`); log(`Using GOROOT: ${this.goroot}`); log(`Using PATH: ${env['PATH']}`); if (launchArgs.noDebug) { if (mode === 'debug') { this.noDebug = true; const build = ['build']; const output = path.join(os.tmpdir(), correctBinname('out')); build.push(`-o=${output}`); const buildOptions: { [key: string]: any } = { cwd: dirname, env }; if (launchArgs.buildFlags) { build.push(launchArgs.buildFlags); } if (isProgramDirectory) { build.push('.'); } else { build.push(program); } const goExe = getBinPathWithPreferredGopathGoroot('go', []); log(`Current working directory: ${dirname}`); log(`Building: ${goExe} ${build.join(' ')}`); // Use spawnSync to ensure that the binary exists before running it. const buffer = spawnSync(goExe, build, buildOptions); if (buffer.stderr && buffer.stderr.length > 0) { const str = buffer.stderr.toString(); if (this.onstderr) { this.onstderr(str); } } if (buffer.stdout && buffer.stdout.length > 0) { const str = buffer.stdout.toString(); if (this.onstdout) { this.onstdout(str); } } if (buffer.status) { logError(`Build process exiting with code: ${buffer.status} signal: ${buffer.signal}`); if (this.onclose) { this.onclose(buffer.status); } } else { log(`Build process exiting normally ${buffer.signal}`); } if (buffer.error) { reject(buffer.error); } // Run the built binary let wd = dirname; if (launchArgs.cwd) { wd = launchArgs.cwd; } const runOptions: { [key: string]: any } = { cwd: wd, env }; const run = []; if (launchArgs.args) { run.push(...launchArgs.args); } log(`Current working directory: ${wd}`); log(`Running: ${output} ${run.join(' ')}`); this.debugProcess = spawn(output, run, runOptions); this.debugProcess.stderr?.on('data', (chunk) => { const str = chunk.toString(); if (this.onstderr) { this.onstderr(str); } }); this.debugProcess.stdout?.on('data', (chunk) => { const str = chunk.toString(); if (this.onstdout) { this.onstdout(str); } }); this.debugProcess.on('close', (code) => { if (code) { logError(`Process exiting with code: ${code} signal: ${this.debugProcess?.killed}`); } else { log(`Process exiting normally ${this.debugProcess?.killed}`); } if (this.onclose) { this.onclose(code); } }); this.debugProcess.on('error', (err) => { reject(err); }); resolve(null); return; } } this.noDebug = false; if (!existsSync(launchArgs.dlvToolPath)) { log( `Couldn't find dlv at the Go tools path, ${process.env['GOPATH']}${ env['GOPATH'] ? ', ' + env['GOPATH'] : '' } or ${getEnvPath()}` ); return reject( 'Cannot find Delve debugger. Install from https://github.com/go-delve/delve & ensure it is in your Go tools path, "GOPATH/bin" or "PATH".' ); } const currentGOWorkspace = getCurrentGoWorkspaceFromGOPATH(env['GOPATH'], dirname); if (!launchArgs.packagePathToGoModPathMap) { launchArgs.packagePathToGoModPathMap = {}; } dlvArgs.push(mode || 'debug'); if (mode === 'exec' || (mode === 'debug' && !isProgramDirectory)) { dlvArgs.push(program); } else if (currentGOWorkspace && !launchArgs.packagePathToGoModPathMap[dirname]) { dlvArgs.push(dirname.substr(currentGOWorkspace.length + 1)); } // add user-specified dlv flags first. When duplicate flags are specified, // dlv doesn't mind but accepts the last flag value. if (launchArgs.dlvFlags && launchArgs.dlvFlags.length > 0) { dlvArgs.push(...launchArgs.dlvFlags); } dlvArgs.push('--headless=true', `--listen=${launchArgs.host}:${launchArgs.port}`); if (!this.isApiV1) { dlvArgs.push('--api-version=2'); } if (launchArgs.showLog) { dlvArgs.push('--log=' + launchArgs.showLog.toString()); // Only add the log output flag if we have already added the log flag. // Otherwise, delve complains. if (launchArgs.logOutput) { dlvArgs.push('--log-output=' + launchArgs.logOutput); } } if (launchArgs.cwd) { dlvArgs.push('--wd=' + launchArgs.cwd); } if (launchArgs.buildFlags) { dlvArgs.push('--build-flags=' + launchArgs.buildFlags); } if (launchArgs.backend) { dlvArgs.push('--backend=' + launchArgs.backend); } if (launchArgs.output && (mode === 'debug' || mode === 'test')) { dlvArgs.push('--output=' + launchArgs.output); } if (launchArgs.args && launchArgs.args.length > 0) { dlvArgs.push('--', ...launchArgs.args); } this.localDebugeePath = this.getLocalDebugeePath(launchArgs.output); } else if (launchArgs.request === 'attach') { if (!launchArgs.processId) { return reject('Missing process ID'); } if (!existsSync(launchArgs.dlvToolPath)) { return reject( 'Cannot find Delve debugger. Install from https://github.com/go-delve/delve & ensure it is in your Go tools path, "GOPATH/bin" or "PATH".' ); } dlvArgs.push('attach', `${launchArgs.processId}`); // add user-specified dlv flags first. When duplicate flags are specified, // dlv doesn't mind but accepts the last flag value. if (launchArgs.dlvFlags && launchArgs.dlvFlags.length > 0) { dlvArgs.push(...launchArgs.dlvFlags); } dlvArgs.push('--headless=true', '--listen=' + launchArgs.host + ':' + launchArgs.port?.toString()); if (!this.isApiV1) { dlvArgs.push('--api-version=2'); } if (launchArgs.showLog) { dlvArgs.push('--log=' + launchArgs.showLog.toString()); } if (launchArgs.logOutput) { dlvArgs.push('--log-output=' + launchArgs.logOutput); } if (launchArgs.cwd) { dlvArgs.push('--wd=' + launchArgs.cwd); } if (launchArgs.backend) { dlvArgs.push('--backend=' + launchArgs.backend); } } log(`Current working directory: ${dlvCwd}`); log(`Running: ${launchArgs.dlvToolPath} ${dlvArgs.join(' ')}`); this.debugProcess = spawn(launchArgs.dlvToolPath, dlvArgs, { cwd: dlvCwd, env }); function connectClient(port: number, host: string, onClose?: Delve['onclose']) { // Add a slight delay to avoid issues on Linux with // Delve failing calls made shortly after connection. setTimeout(() => { const conn = Client.$create(port, host).connectSocket(); conn.on('connect', () => resolve(conn)) .on('error', reject) .on('close', (hadError) => { logError('Socket connection to remote was closed'); onClose?.(hadError ? 1 : 0); }); }, 200); } this.debugProcess.stderr?.on('data', (chunk) => { const str = chunk.toString(); if (this.onstderr) { this.onstderr(str); } }); this.debugProcess.stdout?.on('data', (chunk) => { const str = chunk.toString(); if (this.onstdout) { this.onstdout(str); } if (!serverRunning) { serverRunning = true; if (!launchArgs.port || !launchArgs.host) { return reject('Unable to connect, missing host or port from launchArgs.'); } connectClient(launchArgs.port, launchArgs.host, this.onclose); } }); this.debugProcess.on('close', (code) => { // TODO: Report `dlv` crash to user. logError('Process exiting with code: ' + code); if (this.onclose) { this.onclose(code); } }); this.debugProcess.on('error', (err) => { reject(err); }); }); } public call<T>(command: string, args: any[], callback: (err: Error, results?: T) => void) { this.connection.then( (conn) => { conn?.call('RPCServer.' + command, args, callback); }, (err) => { callback(err); } ); } public callPromise<T>(command: string, args: any[]): Thenable<T> { return new Promise<T>((resolve, reject) => { this.connection.then( (conn) => { conn?.call<T>(`RPCServer.${command}`, args, (err, res) => { return err ? reject(err) : resolve(res); }); }, (err) => { reject(err); } ); }); } /** * Returns the current state of the delve debugger. * This method does not block delve and should return immediately. */ public async getDebugState(): Promise<DebuggerState> { // If a program is launched with --continue, the program is running // before we can run attach. So we would need to check the state. // We use NonBlocking so the call would return immediately. const callResult = await this.callPromise<DebuggerState | CommandOut>('State', [{ NonBlocking: true }]); return this.isApiV1 ? <DebuggerState>callResult : (<CommandOut>callResult).State; } /** * Closing a debugging session follows different approaches for launch vs attach debugging. * * For launch without debugging, we kill the process since the extension started the `go run` process. * * For launch debugging, since the extension starts the delve process, the extension should close it as well. * To gracefully clean up the assets created by delve, we send the Detach request with kill option set to true. * * For attach debugging there are two scenarios; attaching to a local process by ID or connecting to a * remote delve server. For attach-local we start the delve process so will also terminate it however we * detach from the debugee without killing it. For attach-remote we only close the client connection, * but do not terminate the remote server. * * For local debugging, the only way to detach from delve when it is running a program is to send a Halt request first. * Since the Halt request might sometimes take too long to complete, we have a timer in place to forcefully kill * the debug process and clean up the assets in case of local debugging */ public async close(): Promise<void> { const forceCleanup = async () => { log(`killing debugee (pid: ${this.debugProcess?.pid})...`); if (this.debugProcess) { await killProcessTree(this.debugProcess, log); } if (this.localDebugeePath) { await removeFile(this.localDebugeePath); } }; if (this.noDebug) { // delve isn't running so no need to halt await forceCleanup(); return Promise.resolve(); } const isLocalDebugging: boolean = this.request === 'launch' && !!this.debugProcess; return new Promise(async (resolve) => { this.delveConnectionClosed = true; // For remote debugging, we want to leave the remote dlv server running, // so instead of killing it via halt+detach, we just close the network connection. // See https://www.github.com/go-delve/delve/issues/1587 if (this.isRemoteDebugging) { log('Remote Debugging: close dlv connection.'); const rpcConnection = await this.connection; // tslint:disable-next-line no-any (rpcConnection as any)['conn']['end'](); return resolve(); } const timeoutToken = isLocalDebugging && setTimeout(async () => { log('Killing debug process manually as we could not halt delve in time'); await forceCleanup(); resolve(); }, 1000); let haltErrMsg: string | undefined; try { log('HaltRequest'); await this.callPromise('Command', [{ name: 'halt' }]); } catch (err) { log('HaltResponse'); log(`Failed to halt - ${err}`); } if (timeoutToken) { clearTimeout(timeoutToken); } const targetHasExited = !!haltErrMsg && haltErrMsg.endsWith('has exited with status 0'); const shouldDetach = !haltErrMsg || targetHasExited; let shouldForceClean = !shouldDetach && isLocalDebugging; if (shouldDetach) { log('DetachRequest'); try { await this.callPromise('Detach', [this.isApiV1 ? true : { Kill: isLocalDebugging }]); } catch (err) { log('DetachResponse'); logError(`Failed to detach - ${err}`); shouldForceClean = isLocalDebugging; } } if (shouldForceClean) { await forceCleanup(); } return resolve(); }); } private getLocalDebugeePath(output: string | undefined): string { const configOutput = output || 'debug'; return path.isAbsolute(configOutput) ? configOutput : path.resolve(this.program, configOutput); } } export class GoDebugSession extends LoggingDebugSession { private variableHandles: Handles<DebugVariable>; private breakpoints: Map<string, DebugBreakpoint[]>; // Editing breakpoints requires halting delve, skip sending Stop Event to VS Code in such cases private skipStopEventOnce: boolean; private overrideStopReason: string; private debugState?: DebuggerState; private delve?: Delve; private localPathSeparator?: string; private remotePathSeparator?: string; private stackFrameHandles: Handles<[number, number]>; private packageInfo = new Map<string, string>(); private stopOnEntry: boolean; private logLevel: Logger.LogLevel = Logger.LogLevel.Error; private readonly initdone = 'initdone·'; private remoteSourcesAndPackages = new RemoteSourcesAndPackages(); private localToRemotePathMapping = new Map<string, string>(); private remoteToLocalPathMapping = new Map<string, string>(); // TODO(suzmue): Use delve's implementation of substitute-path. private substitutePath?: { from: string; to: string }[]; private showGlobalVariables = false; private continueEpoch = 0; private continueRequestRunning = false; private nextEpoch = 0; private nextRequestRunning = false; public constructor(debuggerLinesStartAt1: boolean, isServer = false, readonly fileSystem = fs) { super('', debuggerLinesStartAt1, isServer); this.variableHandles = new Handles<DebugVariable>(); this.skipStopEventOnce = false; this.overrideStopReason = ''; this.stopOnEntry = false; this.breakpoints = new Map<string, DebugBreakpoint[]>(); this.stackFrameHandles = new Handles<[number, number]>(); } protected initializeRequest( response: DebugProtocol.InitializeResponse, args: DebugProtocol.InitializeRequestArguments ): void { log('InitializeRequest'); // Set the capabilities that this debug adapter supports. response.body = response.body ?? {}; response.body.supportsConditionalBreakpoints = true; response.body.supportsConfigurationDoneRequest = true; response.body.supportsSetVariable = true; this.sendResponse(response); log('InitializeResponse'); } protected launchRequest(response: DebugProtocol.LaunchResponse, args: LaunchRequestArguments): void { log('LaunchRequest'); if (!args.program) { this.sendErrorResponse( response, 3000, 'Failed to continue: The program attribute is missing in the debug configuration in launch.json' ); return; } this.initLaunchAttachRequest(response, args); } protected attachRequest(response: DebugProtocol.AttachResponse, args: AttachRequestArguments): void { log('AttachRequest'); if (args.mode === 'local' && !args.processId) { this.sendErrorResponse( response, 3000, 'Failed to continue: the processId attribute is missing in the debug configuration in launch.json' ); } else if (args.mode === 'remote' && !args.port) { this.sendErrorResponse( response, 3000, 'Failed to continue: the port attribute is missing in the debug configuration in launch.json' ); } this.initLaunchAttachRequest(response, args); } protected async disconnectRequest( response: DebugProtocol.DisconnectResponse, args: DebugProtocol.DisconnectArguments ): Promise<void> { log('DisconnectRequest'); if (this.delve) { // Since users want to reset when they issue a disconnect request, // we should have a timeout in case disconnectRequestHelper hangs. await Promise.race([ this.disconnectRequestHelper(response, args), new Promise<void>((resolve) => setTimeout(() => { log('DisconnectRequestHelper timed out after 5s.'); resolve(); }, 5_000) ) ]); } this.shutdownProtocolServer(response, args); log('DisconnectResponse'); } protected async disconnectRequestHelper( response: DebugProtocol.DisconnectResponse, args: DebugProtocol.DisconnectArguments ): Promise<void> { // There is a chance that a second disconnectRequest can come through // if users click detach multiple times. In that case, we want to // guard against talking to the closed Delve connection. // Note: this does not completely guard against users attempting to // disconnect multiple times when a disconnect request is still running. // The order of the execution may results in strange states that don't allow // the delve connection to fully disconnect. if (this.delve?.delveConnectionClosed) { log("Skip disconnectRequestHelper as Delve's connection is already closed."); return; } // For remote process, we have to issue a continue request // before disconnecting. if (this.delve?.isRemoteDebugging) { if (!(await this.isDebuggeeRunning())) { log("Issuing a continue command before closing Delve's connection as the debuggee is not running."); this.continue(); } } log('Closing Delve.'); await this.delve?.close(); } protected async configurationDoneRequest( response: DebugProtocol.ConfigurationDoneResponse, args: DebugProtocol.ConfigurationDoneArguments ): Promise<void> { log('ConfigurationDoneRequest'); if (this.stopOnEntry) { this.sendEvent(new StoppedEvent('entry', 1)); log('StoppedEvent("entry")'); } else if (!(await this.isDebuggeeRunning())) { log('Changing DebugState from Halted to Running'); this.continue(); } this.sendResponse(response); log('ConfigurationDoneResponse', response); } /** * Given a potential list of paths in potentialPaths array, we will * find the path that has the longest suffix matching filePath. * For example, if filePath is /usr/local/foo/bar/main.go * and potentialPaths are abc/xyz/main.go, bar/main.go * then bar/main.go will be the result. * NOTE: This function assumes that potentialPaths array only contains * files with the same base names as filePath. */ protected findPathWithBestMatchingSuffix(filePath: string, potentialPaths: string[]): string | undefined { if (!potentialPaths?.length) { return; } if (potentialPaths.length === 1) { return potentialPaths[0]; } const filePathSegments = filePath.split(/\/|\\/).reverse(); let bestPathSoFar = potentialPaths[0]; let bestSegmentsCount = 0; for (const potentialPath of potentialPaths) { const potentialPathSegments = potentialPath.split(/\/|\\/).reverse(); let i = 0; for ( ; i < filePathSegments.length && i < potentialPathSegments.length && filePathSegments[i] === potentialPathSegments[i]; i++ ) { if (i > bestSegmentsCount) { bestSegmentsCount = i; bestPathSoFar = potentialPath; } } } return bestPathSoFar; } /** * Given a local path, try to find matching file in the remote machine * using remote sources and remote packages info that we get from Delve. * The result would be cached in localToRemotePathMapping. */ protected inferRemotePathFromLocalPath(localPath: string): string | undefined { if (this.localToRemotePathMapping.has(localPath)) { return this.localToRemotePathMapping.get(localPath); } const fileName = getBaseName(localPath); const potentialMatchingRemoteFiles = this.remoteSourcesAndPackages.remoteSourceFilesNameGrouping.get(fileName) ?? []; const bestMatchingRemoteFile = this.findPathWithBestMatchingSuffix(localPath, potentialMatchingRemoteFiles); if (!bestMatchingRemoteFile) { return; } this.localToRemotePathMapping.set(localPath, bestMatchingRemoteFile); return bestMatchingRemoteFile; } protected async toDebuggerPath(filePath: string): Promise<string> { if (this.substitutePath?.length === 0) { if (this.delve?.isRemoteDebugging) { // The user trusts us to infer the remote path mapping! await this.initializeRemotePackagesAndSources(); const matchedRemoteFile = this.inferRemotePathFromLocalPath(filePath); if (matchedRemoteFile) { return matchedRemoteFile; } } return this.convertClientPathToDebugger(filePath); } // The filePath may have a different path separator than the localPath // So, update it to use the same separator for ease in path replacement. filePath = normalizeSeparators(filePath); let substitutedPath = filePath; let substituteRule: { from: string; to: string }; this.substitutePath?.forEach((value) => { if (filePath.startsWith(value.from)) { if (substituteRule) { log( `Substitutition rule ${value.from}:${value.to} applies to local path ${filePath} but it was already mapped to debugger path using rule ${substituteRule.from}:${substituteRule.to}` ); return; } substitutedPath = filePath.replace(value.from, value.to); substituteRule = { from: value.from, to: value.to }; } }); filePath = substitutedPath; return (filePath = filePath.replace(/\/|\\/g, this.remotePathSeparator ?? '')); } /** * Given a remote path, try to infer the matching local path. * We attempt to find the path in local Go packages as well as workspaceFolder. * Cache the result in remoteToLocalPathMapping. */ protected inferLocalPathFromRemotePath(remotePath: string): string | undefined { // Don't try to infer a path for a file that does not exist if (remotePath === '') { return remotePath; } if (this.remoteToLocalPathMapping.has(remotePath)) { return this.remoteToLocalPathMapping.get(remotePath); } const convertedLocalPackageFile = this.inferLocalPathFromRemoteGoPackage(remotePath); if (convertedLocalPackageFile) { this.remoteToLocalPathMapping.set(remotePath, convertedLocalPackageFile); return convertedLocalPackageFile; } // If we cannot find the path in packages, most likely it will be in the current directory. const fileName = getBaseName(remotePath); const globSync = glob.sync(fileName, { matchBase: true, cwd: this.delve?.program }); const bestMatchingLocalPath = this.findPathWithBestMatchingSuffix(remotePath, globSync); if (bestMatchingLocalPath) { const fullLocalPath = path.join(this.delve?.program ?? '', bestMatchingLocalPath); this.remoteToLocalPathMapping.set(remotePath, fullLocalPath); return fullLocalPath; } } /** * Given a remote path, we attempt to infer the local path by first checking * if it is in any remote packages. If so, then we attempt to find the matching * local package and find the local path from there. */ protected inferLocalPathFromRemoteGoPackage(remotePath: string): string | undefined { const remotePackage = this.remoteSourcesAndPackages.remotePackagesBuildInfo.find((buildInfo) => remotePath.startsWith(buildInfo.DirectoryPath) ); // Since we know pathToConvert exists in a remote package, we can try to find // that same package in the local client. We can use import path to search for the package. if (!remotePackage) { return; } if (!this.remotePathSeparator) { this.remotePathSeparator = findPathSeparator(remotePackage.DirectoryPath); } // Escaping package path. // It seems like sometimes Delve don't escape the path properly // so we should do it. remotePath = escapeGoModPath(remotePath); const escapedImportPath = escapeGoModPath(remotePackage.ImportPath); // The remotePackage.DirectoryPath should be something like // <gopath|goroot|source>/<import-path>/xyz... // Directory Path can be like "/go/pkg/mod/github.com/google/go-cmp@v0.4.0/cmp" // and Import Path can be like "github.com/google/go-cmp/cmp" // and Remote Path "/go/pkg/mod/github.com/google/go-cmp@v0.4.0/cmp/blah.go" const importPathIndex = remotePath.replace(/@v\d+\.\d+\.\d+[^\/]*/, '').indexOf(escapedImportPath); if (importPathIndex < 0) { return; } const relativeRemotePath = remotePath .substr(importPathIndex) .split(this.remotePathSeparator) .join(this.localPathSeparator); const pathToConvertWithLocalSeparator = remotePath .split(this.remotePathSeparator) .join(this.localPathSeparator); // Scenario 1: The package is inside the current working directory. const localWorkspacePath = path.join(this.delve?.program ?? '', relativeRemotePath); if (this.fileSystem.existsSync(localWorkspacePath)) { return localWorkspacePath; } // Scenario 2: The package is inside GOPATH. const localGoPathImportPath = this.inferLocalPathInGoPathFromRemoteGoPackage( pathToConvertWithLocalSeparator, relativeRemotePath ); if (localGoPathImportPath) { return localGoPathImportPath; } // Scenario 3: The package is inside GOROOT. return this.inferLocalPathInGoRootFromRemoteGoPackage(pathToConvertWithLocalSeparator, relativeRemotePath); } /** * Given a remotePath, check whether the file path exists in $GOROOT/src. * Return the path if it exists. * We are assuming that remotePath is of the form <prefix>/src/<suffix>. */ protected inferLocalPathInGoRootFromRemoteGoPackage( remotePathWithLocalSeparator: string, relativeRemotePath: string ): string | undefined { const srcIndex = remotePathWithLocalSeparator.indexOf( `${this.localPathSeparator}src${this.localPathSeparator}` ); const goroot = this.getGOROOT(); const localGoRootImportPath = path.join( goroot, srcIndex >= 0 ? remotePathWithLocalSeparator.substr(srcIndex) : path.join('src', relativeRemotePath) ); if (this.fileSystem.existsSync(localGoRootImportPath)) { return localGoRootImportPath; } } /** * Given a remotePath, check whether the file path exists in $GOPATH. * This can be either in $GOPATH/pkg/mod or $GOPATH/src. If so, return that path. * remotePath can be something like /usr/local/gopath/src/hello-world/main.go * and relativeRemotePath should be hello-world/main.go. In other words, * relativeRemotePath is a relative version of remotePath starting * from the import path of the module. */ protected inferLocalPathInGoPathFromRemoteGoPackage( remotePathWithLocalSeparator: string, relativeRemotePath: string ): string | undefined { // Scenario 1: The package is inside $GOPATH/pkg/mod. const gopath = (process.env['GOPATH'] || '').split(path.delimiter)[0]; const indexGoModCache = remotePathWithLocalSeparator.indexOf( `${this.localPathSeparator}pkg${this.localPathSeparator}mod${this.localPathSeparator}` ); const localGoPathImportPath = path.join( gopath, indexGoModCache >= 0 ? remotePathWithLocalSeparator.substr(indexGoModCache) : path.join('pkg', 'mod', relativeRemotePath) ); if (this.fileSystem.existsSync(localGoPathImportPath)) { return localGoPathImportPath; } // Scenario 2: The file is in a package in $GOPATH/src. const localGoPathSrcPath = path.join( gopath, 'src', relativeRemotePath.split(this.remotePathSeparator ?? '').join(this.localPathSeparator) ); if (this.fileSystem.existsSync(localGoPathSrcPath)) { return localGoPathSrcPath; } } /** * This functions assumes that remote packages and paths information * have been initialized. */ protected toLocalPath(pathToConvert: string): string { if (this.substitutePath?.length === 0) { // User trusts use to infer the path if (this.delve?.isRemoteDebugging) { const inferredPath = this.inferLocalPathFromRemotePath(pathToConvert); if (inferredPath) { return inferredPath; } } return this.convertDebuggerPathToClient(pathToConvert); } // If there is a substitutePath mapping, then we replace the path. pathToConvert = normalizeSeparators(pathToConvert); let substitutedPath = pathToConvert; let substituteRule: { from: string; to: string } | undefined; this.substitutePath?.forEach((value) => { if (pathToConvert.startsWith(value.to)) { if (substituteRule) { log( `Substitutition rule ${value.from}:${value.to} applies to debugger path ${pathToConvert} but it was already mapped to local path using rule ${substituteRule.from}:${substituteRule.to}` ); return; } substitutedPath = pathToConvert.replace(value.to, value.from); substituteRule = { from: value.from, to: value.to }; } }); pathToConvert = substitutedPath; // When the pathToConvert is under GOROOT or Go module cache, replace path appropriately if (!substituteRule) { // Fix for https://github.com/Microsoft/vscode-go/issues/1178 const index = pathToConvert.indexOf(`${this.remotePathSeparator}src${this.remotePathSeparator}`); const goroot = this.getGOROOT(); if (goroot && index > 0) { return path.join(goroot, pathToConvert.substr(index)); } const indexGoModCache = pathToConvert.indexOf( `${this.remotePathSeparator}pkg${this.remotePathSeparator}mod${this.remotePathSeparator}` ); const gopath = (process.env['GOPATH'] || '').split(path.delimiter)[0]; if (gopath && indexGoModCache > 0) { return path.join( gopath, pathToConvert .substr(indexGoModCache) .split(this.remotePathSeparator ?? '') .join(this.localPathSeparator) ); } } return pathToConvert.split(this.remotePathSeparator ?? '').join(this.localPathSeparator); } protected async setBreakPointsRequest( response: DebugProtocol.SetBreakpointsResponse, args: DebugProtocol.SetBreakpointsArguments ): Promise<void> { log('SetBreakPointsRequest'); if (!(await this.isDebuggeeRunning())) { log('Debuggee is not running. Setting breakpoints without halting.'); await this.setBreakPoints(response, args); } else { // Skip stop event if a continue request is running. this.skipStopEventOnce = this.continueRequestRunning; const haltedDuringNext = this.nextRequestRunning; if (haltedDuringNext) { this.overrideStopReason = 'next cancelled'; } log(`Halting before setting breakpoints. SkipStopEventOnce is ${this.skipStopEventOnce}.`); this.delve?.callPromise('Command', [{ name: 'halt' }]).then( () => { return this.setBreakPoints(response, args).then(() => { // We do not want to continue if it was running a next request, since the // request was automatically cancelled. if (haltedDuringNext) { // Send an output event containing a warning that next was cancelled. const warning = "Setting breakpoints during 'next', 'step in' or 'step out' halted delve and cancelled the next request"; this.sendEvent(new OutputEvent(warning, 'stderr')); return; } return this.continue(true).then(undefined, (err) => { this.logDelveError(err, 'Failed to continue delve after halting it to set breakpoints'); }); }); }, (err) => { this.skipStopEventOnce = false; this.logDelveError(err, 'Failed to halt delve before attempting to set breakpoint'); return this.sendErrorResponse( response, 2008, 'Failed to halt delve before attempting to set breakpoint: "{e}"', { e: err.toString() } ); } ); } } protected async threadsRequest(response: DebugProtocol.ThreadsResponse): Promise<void> { if (await this.isDebuggeeRunning()) { // Thread request to delve is synchronous and will block if a previous async continue request didn't return response.body = { threads: [new Thread(1, 'Dummy')] }; return this.sendResponse(response); } else if (this.debugState && this.debugState.exited) { // If the program exits very quickly, the initial threadsRequest will complete after it has exited. // A TerminatedEvent has already been sent. d response.body = { threads: [] }; return this.sendResponse(response); } log('ThreadsRequest'); this.delve?.call<DebugGoroutine[] | ListGoroutinesOut>('ListGoroutines', [], (err, out) => { if (this.debugState && this.debugState.exited) { // If the program exits very quickly, the initial threadsRequest will complete after it has exited. // A TerminatedEvent has already been sent. Ignore the err returned in this case. response.body = { threads: [] }; return this.sendResponse(response); } if (err) { this.logDelveError(err, 'Failed to get threads'); return this.sendErrorResponse(response, 2003, 'Unable to display threads: "{e}"', { e: err.toString() }); } const goroutines = this.delve?.isApiV1 ? <DebugGoroutine[]>out : (<ListGoroutinesOut>out).Goroutines; log('goroutines', goroutines); const threads = goroutines.map( (goroutine) => new Thread( goroutine.id, goroutine.userCurrentLoc.function ? goroutine.userCurrentLoc.function.name : goroutine.userCurrentLoc.file + '@' + goroutine.userCurrentLoc.line ) ); if (threads.length === 0) { threads.push(new Thread(1, 'Dummy')); } response.body = { threads }; this.sendResponse(response); log('ThreadsResponse', threads); }); } protected async stackTraceRequest( response: DebugProtocol.StackTraceResponse, args: DebugProtocol.StackTraceArguments ): Promise<void> { log('StackTraceRequest'); // For normal VSCode, this request doesn't get invoked when we send a Dummy thread // in the scenario where the debuggee is running. // For Theia, however, this does get invoked and so we should just send an error // response that we cannot get the stack trace at this point since the debugggee is running. if (await this.isDebuggeeRunning()) { this.sendErrorResponse(response, 2004, 'Unable to produce stack trace as the debugger is running'); return; } // delve does not support frame paging, so we ask for a large depth const goroutineId = args.threadId; const stackTraceIn = { id: goroutineId, depth: this.delve?.stackTraceDepth }; if (!this.delve?.isApiV1) { Object.assign(stackTraceIn, { full: false, cfg: this.delve?.loadConfig }); } this.delve?.call<DebugLocation[] | StacktraceOut>( this.delve?.isApiV1 ? 'StacktraceGoroutine' : 'Stacktrace', [stackTraceIn], async (err, out) => { if (err) { this.logDelveError(err, 'Failed to produce stacktrace'); return this.sendErrorResponse( response, 2004, 'Unable to produce stack trace: "{e}"', { e: err.toString() }, // Disable showUser pop-up since errors already show up under the CALL STACK pane undefined ); } const locations = this.delve?.isApiV1 ? <DebugLocation[]>out : (<StacktraceOut>out).Locations; log('locations', locations); if (this.delve?.isRemoteDebugging) { await this.initializeRemotePackagesAndSources(); } let stackFrames = locations.map((location, frameId) => { const uniqueStackFrameId = this.stackFrameHandles.create([goroutineId, frameId]); return new StackFrame( uniqueStackFrameId, location.function ? location.function.name : '<unknown>', location.file === '<autogenerated>' ? undefined : new Source(path.basename(location.file), this.toLocalPath(location.file)), location.line, 0 ); }); const { startFrame = 0, levels = 0 } = args; if (startFrame > 0) { stackFrames = stackFrames.slice(startFrame); } if (levels > 0) { stackFrames = stackFrames.slice(0, levels); } response.body = { stackFrames, totalFrames: locations.length }; this.sendResponse(response); log('StackTraceResponse'); } ); } protected scopesRequest(response: DebugProtocol.ScopesResponse, args: DebugProtocol.ScopesArguments): void { log('ScopesRequest'); // TODO(polinasok): this.stackFrameHandles.get should succeed as long as DA // clients behaves well. Find the documentation around stack frame management // and in case of a failure caused by misbehavior, consider to indicate it // in the error response. const [goroutineId, frameId] = this.stackFrameHandles.get(args.frameId); const listLocalVarsIn = { goroutineID: goroutineId, frame: frameId }; this.delve?.call<DebugVariable[] | ListVarsOut>( 'ListLocalVars', this.delve?.isApiV1 ? [listLocalVarsIn] : [{ scope: listLocalVarsIn, cfg: this.delve?.loadConfig }], (err, out) => { if (err) { this.logDelveError(err, 'Failed to get list local variables'); return this.sendErrorResponse(response, 2005, 'Unable to list locals: "{e}"', { e: err.toString() }); } const locals = this.delve?.isApiV1 ? <DebugVariable[]>out : (<ListVarsOut>out).Variables; log('locals', locals); this.addFullyQualifiedName(locals); const listLocalFunctionArgsIn = { goroutineID: goroutineId, frame: frameId }; this.delve?.call<DebugVariable[] | ListFunctionArgsOut>( 'ListFunctionArgs', this.delve?.isApiV1 ? [listLocalFunctionArgsIn] : [{ scope: listLocalFunctionArgsIn, cfg: this.delve?.loadConfig }], (listFunctionErr, outArgs) => { if (listFunctionErr) { this.logDelveError(listFunctionErr, 'Failed to list function args'); return this.sendErrorResponse(response, 2006, 'Unable to list args: "{e}"', { e: listFunctionErr.toString() }); } const vars = this.delve?.isApiV1 ? <DebugVariable[]>outArgs : (<ListFunctionArgsOut>outArgs).Args; log('functionArgs', vars); this.addFullyQualifiedName(vars); vars.push(...locals); // annotate shadowed variables in parentheses const shadowedVars = new Map<string, Array<number>>(); for (let i = 0; i < vars.length; ++i) { if ((vars[i].flags & GoVariableFlags.VariableShadowed) === 0) { continue; } const varName = vars[i].name; if (!shadowedVars.has(varName)) { const indices = new Array<number>(); indices.push(i); shadowedVars.set(varName, indices); } else { shadowedVars.get(varName)?.push(i); } } for (const svIndices of shadowedVars.values()) { // sort by declared line number in descending order svIndices.sort((lhs: number, rhs: number) => { return vars[rhs].DeclLine - vars[lhs].DeclLine; }); // enclose in parentheses, one pair per scope for (let scope = 0; scope < svIndices.length; ++scope) { const svIndex = svIndices[scope]; // start at -1 so scope of 0 has one pair of parens for (let count = -1; count < scope; ++count) { vars[svIndex].name = `(${vars[svIndex].name})`; } } } const scopes = new Array<Scope>(); const localVariables: DebugVariable = { name: 'Local', addr: 0, type: '', realType: '', kind: 0, flags: 0, onlyAddr: false, DeclLine: 0, value: '', len: 0, cap: 0, children: vars, unreadable: '', fullyQualifiedName: '', base: 0 }; scopes.push(new Scope('Local', this.variableHandles.create(localVariables), false)); response.body = { scopes }; if (!this.showGlobalVariables) { this.sendResponse(response); log('ScopesResponse'); return; } this.getPackageInfo(this.debugState).then((packageName) => { if (!packageName) { this.sendResponse(response); log('ScopesResponse'); return; } const filter = `^${packageName}\\.`; this.delve?.call<DebugVariable[] | ListVarsOut>( 'ListPackageVars', this.delve?.isApiV1 ? [filter] : [{ filter, cfg: this.delve?.loadConfig }], (listPkgVarsErr, listPkgVarsOut) => { if (listPkgVarsErr) { this.logDelveError(listPkgVarsErr, 'Failed to list global vars'); return this.sendErrorResponse( response, 2007, 'Unable to list global vars: "{e}"', { e: listPkgVarsErr.toString() } ); } const globals = this.delve?.isApiV1 ? <DebugVariable[]>listPkgVarsOut : (<ListVarsOut>listPkgVarsOut).Variables; let initdoneIndex = -1; for (let i = 0; i < globals.length; i++) { globals[i].name = globals[i].name.substr(packageName.length + 1); if (initdoneIndex === -1 && globals[i].name === this.initdone) { initdoneIndex = i; } } if (initdoneIndex > -1) { globals.splice(initdoneIndex, 1); } log('global vars', globals); const globalVariables: DebugVariable = { name: 'Global', addr: 0, type: '', realType: '', kind: 0, flags: 0, onlyAddr: false, DeclLine: 0, value: '', len: 0, cap: 0, children: globals, unreadable: '', fullyQualifiedName: '', base: 0 }; scopes.push( new Scope('Global', this.variableHandles.create(globalVariables), false) ); this.sendResponse(response); log('ScopesResponse'); } ); }); } ); } ); } protected variablesRequest( response: DebugProtocol.VariablesResponse, args: DebugProtocol.VariablesArguments ): void { log('VariablesRequest'); const vari = this.variableHandles.get(args.variablesReference); let variablesPromise: Promise<DebugProtocol.Variable[]> | undefined; const loadChildren = async (exp: string, v: DebugVariable) => { // from https://github.com/go-delve/delve/blob/master/Documentation/api/ClientHowto.md#looking-into-variables if ( (v.kind === GoReflectKind.Struct && v.len > v.children.length) || (v.kind === GoReflectKind.Interface && v.children.length > 0 && v.children[0].onlyAddr === true) ) { await this.evaluateRequestImpl({ expression: exp }).then( (result) => { const variable = this.delve?.isApiV1 ? <DebugVariable>result : (<EvalOut>result).Variable; v.children = variable.children; }, (err) => this.logDelveError(err, 'Failed to evaluate expression') ); } }; // expressions passed to loadChildren defined per // https://github.com/go-delve/delve/blob/master/Documentation/api/ClientHowto.md#loading-more-of-a-variable if (vari.kind === GoReflectKind.Array || vari.kind === GoReflectKind.Slice) { variablesPromise = Promise.all( vari.children.map((v, i) => { return loadChildren(`*(*"${v.type}")(${v.addr})`, v).then( (): DebugProtocol.Variable => { const { result, variablesReference } = this.convertDebugVariableToProtocolVariable(v); return { name: '[' + i + ']', value: result, evaluateName: vari.fullyQualifiedName + '[' + i + ']', variablesReference }; } ); }) ); } else if (vari.kind === GoReflectKind.Map) { variablesPromise = Promise.all( vari.children .map((_, i) => { // even indices are map keys, odd indices are values if (i % 2 === 0 && i + 1 < vari.children.length) { const mapKey = this.convertDebugVariableToProtocolVariable(vari.children[i]); return loadChildren( `${vari.fullyQualifiedName}.${vari.name}[${mapKey.result}]`, vari.children[i + 1] ).then(() => { const mapValue = this.convertDebugVariableToProtocolVariable(vari.children[i + 1]); return { name: mapKey.result, value: mapValue.result, evaluateName: vari.fullyQualifiedName + '[' + mapKey.result + ']', variablesReference: mapValue.variablesReference } as DebugProtocol.Variable; }); } }) .filter((v): v is Promise<DebugProtocol.Variable> => !!v) // remove the null values created by combining keys and values ); } else { variablesPromise = Promise.all( vari.children.map((v) => { return loadChildren(`*(*"${v.type}")(${v.addr})`, v).then( (): DebugProtocol.Variable => { const { result, variablesReference } = this.convertDebugVariableToProtocolVariable(v); return { name: v.name, value: result, evaluateName: v.fullyQualifiedName, variablesReference }; } ); }) ); } variablesPromise.then((variables) => { response.body = { variables }; this.sendResponse(response); log('VariablesResponse', JSON.stringify(variables, null, ' ')); }); } protected continueRequest(response: DebugProtocol.ContinueResponse): void { log('ContinueRequest'); this.continue(); this.sendResponse(response); log('ContinueResponse'); } protected nextRequest(response: DebugProtocol.NextResponse): void { this.nextEpoch++; const closureEpoch = this.nextEpoch; this.nextRequestRunning = true; log('NextRequest'); this.delve?.call<DebuggerState | CommandOut>('Command', [{ name: 'next' }], (err, out) => { if (closureEpoch === this.continueEpoch) { this.nextRequestRunning = false; } if (err) { this.logDelveError(err, 'Failed to next'); } const state = this.delve?.isApiV1 ? <DebuggerState>out : (<CommandOut>out).State; log('next state', state); this.debugState = state; this.handleReenterDebug('step'); }); // All threads are resumed on a next request this.sendEvent(new ContinuedEvent(1, true)); this.sendResponse(response); log('NextResponse'); } protected stepInRequest(response: DebugProtocol.StepInResponse): void { this.nextEpoch++; const closureEpoch = this.nextEpoch; this.nextRequestRunning = true; log('StepInRequest'); this.delve?.call<DebuggerState | CommandOut>('Command', [{ name: 'step' }], (err, out) => { if (closureEpoch === this.continueEpoch) { this.nextRequestRunning = false; } if (err) { this.logDelveError(err, 'Failed to step in'); } const state = this.delve?.isApiV1 ? <DebuggerState>out : (<CommandOut>out).State; log('stop state', state); this.debugState = state; this.handleReenterDebug('step'); }); // All threads are resumed on a step in request this.sendEvent(new ContinuedEvent(1, true)); this.sendResponse(response); log('StepInResponse'); } protected stepOutRequest(response: DebugProtocol.StepOutResponse): void { this.nextEpoch++; const closureEpoch = this.nextEpoch; this.nextRequestRunning = true; log('StepOutRequest'); this.delve?.call<DebuggerState | CommandOut>('Command', [{ name: 'stepOut' }], (err, out) => { if (closureEpoch === this.continueEpoch) { this.nextRequestRunning = false; } if (err) { this.logDelveError(err, 'Failed to step out'); } const state = this.delve?.isApiV1 ? <DebuggerState>out : (<CommandOut>out).State; log('stepout state', state); this.debugState = state; this.handleReenterDebug('step'); }); // All threads are resumed on a step out request this.sendEvent(new ContinuedEvent(1, true)); this.sendResponse(response); log('StepOutResponse'); } protected pauseRequest(response: DebugProtocol.PauseResponse): void { log('PauseRequest'); this.delve?.call<DebuggerState | CommandOut>('Command', [{ name: 'halt' }], (err, out) => { if (err) { this.logDelveError(err, 'Failed to halt'); return this.sendErrorResponse(response, 2010, 'Unable to halt execution: "{e}"', { e: err.toString() }); } const state = this.delve?.isApiV1 ? <DebuggerState>out : (<CommandOut>out).State; log('pause state', state); this.debugState = state; this.handleReenterDebug('pause'); }); this.sendResponse(response); log('PauseResponse'); } // evaluateRequest is used both for the traditional expression evaluation // (https://github.com/go-delve/delve/blob/master/Documentation/cli/expr.md) and // for the 'call' command support. // If the args.expression starts with the 'call' keyword followed by an expression that looks // like a function call, the request is interpreted as a 'call' command request, // and otherwise, interpreted as `print` command equivalent with RPCServer.Eval. protected evaluateRequest(response: DebugProtocol.EvaluateResponse, args: DebugProtocol.EvaluateArguments): void { log('EvaluateRequest'); // Captures pattern that looks like the expression that starts with `call<space>` // command call. This is supported only with APIv2. const isCallCommand = args.expression.match(/^\s*call\s+\S+/); if (!this.delve?.isApiV1 && isCallCommand) { this.evaluateCallImpl(args).then( (out) => { const state = (<CommandOut>out).State; const returnValues = state?.currentThread?.ReturnValues ?? []; switch (returnValues.length) { case 0: response.body = { result: '', variablesReference: 0 }; break; case 1: response.body = this.convertDebugVariableToProtocolVariable(returnValues[0]); break; default: // Go function can return multiple return values while // DAP EvaluateResponse assumes a single result with possibly // multiple children. So, create a fake DebugVariable // that has all the results as children. const returnResults = this.wrapReturnVars(returnValues); response.body = this.convertDebugVariableToProtocolVariable(returnResults); break; } this.sendResponse(response); log('EvaluateCallResponse'); }, (err) => { this.sendErrorResponse( response, 2009, 'Unable to complete call: "{e}"', { e: err.toString() }, args.context === 'watch' ? undefined : ErrorDestination.User ); } ); return; } // Now handle it as a conventional evaluateRequest. this.evaluateRequestImpl(args).then( (out) => { const variable = this.delve?.isApiV1 ? <DebugVariable>out : (<EvalOut>out).Variable; // #2326: Set the fully qualified name for variable mapping variable.fullyQualifiedName = variable.name; response.body = this.convertDebugVariableToProtocolVariable(variable); this.sendResponse(response); log('EvaluateResponse'); }, (err) => { // No need to repeatedly show the error pop-up when expressions // are continuously reevaluated in the Watch panel, which // already displays errors. this.sendErrorResponse( response, 2009, 'Unable to eval expression: "{e}"', { e: err.toString() }, args.context === 'watch' ? undefined : ErrorDestination.User ); } ); } protected setVariableRequest( response: DebugProtocol.SetVariableResponse, args: DebugProtocol.SetVariableArguments ): void { log('SetVariableRequest'); const scope = { goroutineID: this.debugState?.currentGoroutine.id }; const setSymbolArgs = { Scope: scope, Symbol: args.name, Value: args.value }; this.delve?.call(this.delve?.isApiV1 ? 'SetSymbol' : 'Set', [setSymbolArgs], (err) => { if (err) { const errMessage = `Failed to set variable: ${err.toString()}`; this.logDelveError(err, 'Failed to set variable'); return this.sendErrorResponse(response, 2010, errMessage); } response.body = { value: args.value }; this.sendResponse(response); log('SetVariableResponse'); }); } private getGOROOT(): string { if (this.delve && this.delve?.goroot) { return this.delve?.goroot; } return process.env['GOROOT'] || ''; // this is a workaround to keep the tests in integration/goDebug.test.ts running. // The tests synthesize a bogus Delve instance. } // contains common code for launch and attach debugging initialization private initLaunchAttachRequest( response: DebugProtocol.LaunchResponse, args: LaunchRequestArguments | AttachRequestArguments ) { this.logLevel = args.trace === 'verbose' || args.trace === 'trace' ? Logger.LogLevel.Verbose : args.trace === 'log' || args.trace === 'info' || args.trace === 'warn' ? Logger.LogLevel.Log : Logger.LogLevel.Error; const logPath = this.logLevel !== Logger.LogLevel.Error ? path.join(os.tmpdir(), 'vscode-go-debug.txt') : undefined; logger.setup(this.logLevel, logPath); if (typeof args.showGlobalVariables === 'boolean') { this.showGlobalVariables = args.showGlobalVariables; } if (args.stopOnEntry) { this.stopOnEntry = args.stopOnEntry; } if (!args.port) { args.port = random(2000, 50000); } if (!args.host) { args.host = '127.0.0.1'; } let localPath = ''; if (args.request === 'attach') { localPath = args.cwd ?? ''; } else if (args.request === 'launch') { localPath = args.program; } if (!args.remotePath) { // too much code relies on remotePath never being null args.remotePath = ''; } this.localPathSeparator = findPathSeparator(localPath); this.substitutePath = []; if (args.remotePath.length > 0) { this.remotePathSeparator = findPathSeparator(args.remotePath); const llist = localPath?.split(/\/|\\/).reverse(); const rlist = args.remotePath.split(/\/|\\/).reverse(); let i = 0; for (; llist && i < llist.length; i++) { if (llist[i] !== rlist[i] || llist[i] === 'src') { break; } } if (i) { localPath = llist?.reverse().slice(0, -i).join(this.localPathSeparator) + this.localPathSeparator; args.remotePath = rlist.reverse().slice(0, -i).join(this.remotePathSeparator) + this.remotePathSeparator; } else if ( args.remotePath.length > 1 && (args.remotePath.endsWith('\\') || args.remotePath.endsWith('/')) ) { args.remotePath = args.remotePath.substring(0, args.remotePath.length - 1); } // Make the remotePath mapping the first one in substitutePath // so that it will take precedence over the other mappings. this.substitutePath.push({ from: normalizeSeparators(localPath), to: normalizeSeparators(args.remotePath) }); } if (args.substitutePath) { args.substitutePath.forEach((value) => { if (!this.remotePathSeparator) { this.remotePathSeparator = findPathSeparator(value.to); } this.substitutePath?.push({ from: normalizeSeparators(value.from), to: normalizeSeparators(value.to) }); }); } // Launch the Delve debugger on the program this.delve = new Delve(args, localPath); this.delve.onstdout = (str: string) => { this.sendEvent(new OutputEvent(str, 'stdout')); }; this.delve.onstderr = (str: string) => { if (localPath.length > 0) { str = expandFilePathInOutput(str, localPath); } this.sendEvent(new OutputEvent(str, 'stderr')); }; this.delve.onclose = (code) => { if (code !== 0) { this.sendErrorResponse(response, 3000, 'Failed to continue: Check the debug console for details.'); } log('Sending TerminatedEvent as delve is closed'); this.sendEvent(new TerminatedEvent()); }; this.delve?.connection.then( () => { if (!this.delve?.noDebug) { this.delve?.call<GetVersionOut>('GetVersion', [], (err, out) => { if (err) { logError(err); return this.sendErrorResponse( response, 2001, 'Failed to get remote server version: "{e}"', { e: err.toString() } ); } const clientVersion = this.delve?.isApiV1 ? 1 : 2; if (out?.APIVersion !== clientVersion) { const errorMessage = `The remote server is running on delve v${out?.APIVersion} API and the client is running v${clientVersion} API. Change the version used on the client by using the property "apiVersion" in your launch.json file.`; logError(errorMessage); return this.sendErrorResponse(response, 3000, errorMessage); } }); this.sendEvent(new InitializedEvent()); log('InitializeEvent'); } this.sendResponse(response); }, (err) => { this.sendErrorResponse(response, 3000, 'Failed to continue: "{e}"', { e: err.toString() }); log('ContinueResponse'); } ); } /** * Initializing remote packages and sources. * We use event model to prevent race conditions. */ private async initializeRemotePackagesAndSources(): Promise<void> { if (this.remoteSourcesAndPackages.initializedRemoteSourceFiles) { return; } if (!this.remoteSourcesAndPackages.initializingRemoteSourceFiles) { if (!this.delve) { return; } try { await this.remoteSourcesAndPackages.initializeRemotePackagesAndSources(this.delve); } catch (error) { log(`Failing to initialize remote sources: ${error}`); } return; } if (this.remoteSourcesAndPackages.initializingRemoteSourceFiles) { try { await new Promise<void>((resolve) => { this.remoteSourcesAndPackages.on(RemoteSourcesAndPackages.INITIALIZED, () => { resolve(); }); }); } catch (error) { log(`Failing to initialize remote sources: ${error}`); } } } private async setBreakPoints( response: DebugProtocol.SetBreakpointsResponse, args: DebugProtocol.SetBreakpointsArguments ): Promise<void> { const file = normalizePath(args.source.path ?? ''); if (!this.breakpoints.get(file)) { this.breakpoints.set(file, []); } const remoteFile = await this.toDebuggerPath(file); return Promise.all( this.breakpoints.get(file)?.map((existingBP) => { log('Clearing: ' + existingBP.id); return this.delve?.callPromise('ClearBreakpoint', [ this.delve?.isApiV1 ? existingBP.id : { Id: existingBP.id } ]); }) ?? [] ) .then(() => { log('All cleared'); let existingBreakpoints: DebugBreakpoint[] | undefined; return Promise.all( args.breakpoints?.map((breakpoint) => { if (this.delve?.remotePath?.length === 0) { log('Creating on: ' + file + ':' + breakpoint.line); } else { log('Creating on: ' + file + ' (' + remoteFile + ') :' + breakpoint.line); } const breakpointIn = <DebugBreakpoint>{}; breakpointIn.file = remoteFile; breakpointIn.line = breakpoint.line; breakpointIn.loadArgs = this.delve?.loadConfig; breakpointIn.loadLocals = this.delve?.loadConfig; breakpointIn.cond = breakpoint.condition; return this.delve ?.callPromise('CreateBreakpoint', [ this.delve?.isApiV1 ? breakpointIn : { Breakpoint: breakpointIn } ]) .then(undefined, async (err) => { // Delve does not seem to support error code at this time. // TODO(quoct): Follow up with delve team. if (err.toString().startsWith('Breakpoint exists at')) { log('Encounter existing breakpoint: ' + breakpointIn); // We need to call listbreakpoints to find the ID. // Otherwise, we would not be able to clear the breakpoints. if (!existingBreakpoints) { try { const listBreakpointsResponse = await this.delve?.callPromise< ListBreakpointsOut | DebugBreakpoint[] >('ListBreakpoints', this.delve?.isApiV1 ? [] : [{}]); existingBreakpoints = this.delve?.isApiV1 ? (listBreakpointsResponse as DebugBreakpoint[]) : (listBreakpointsResponse as ListBreakpointsOut).Breakpoints; } catch (error) { log('Error listing breakpoints: ' + error); return null; } } // Make sure that we compare the file names with the same separators. const matchedBreakpoint = existingBreakpoints.find( (existingBreakpoint) => existingBreakpoint.line === breakpointIn.line && compareFilePathIgnoreSeparator(existingBreakpoint.file, breakpointIn.file) ); if (!matchedBreakpoint) { log(`Cannot match breakpoint ${breakpointIn} with existing breakpoints.`); return null; } return this.delve?.isApiV1 ? matchedBreakpoint : { Breakpoint: matchedBreakpoint }; } log('Error on CreateBreakpoint: ' + err.toString()); return null; }); }) ?? [] ); }) .then((newBreakpoints) => { let convertedBreakpoints: (DebugBreakpoint | null)[]; if (!this.delve?.isApiV1) { // Unwrap breakpoints from v2 apicall convertedBreakpoints = newBreakpoints.map((bp, i) => { return bp ? (bp as CreateBreakpointOut).Breakpoint : null; }); } else { convertedBreakpoints = newBreakpoints as DebugBreakpoint[]; } log('All set:' + JSON.stringify(newBreakpoints)); const breakpoints = convertedBreakpoints.map((bp, i) => { if (bp) { return { verified: true, line: bp.line }; } else { return { verified: false, line: args.lines?.[i] }; } }); this.breakpoints.set( file, convertedBreakpoints.filter((x): x is DebugBreakpoint => !!x) ); return breakpoints; }) .then( (breakpoints) => { response.body = { breakpoints }; this.sendResponse(response); log('SetBreakPointsResponse'); }, (err) => { this.sendErrorResponse(response, 2002, 'Failed to set breakpoint: "{e}"', { e: err.toString() }); logError(err); } ); } private async getPackageInfo(debugState: DebuggerState | undefined): Promise<string | void> { if (!debugState || !debugState.currentThread || !debugState.currentThread.file) { return Promise.resolve(); } if (this.delve?.isRemoteDebugging) { await this.initializeRemotePackagesAndSources(); } const dir = path.dirname( this.delve?.remotePath?.length || this.delve?.isRemoteDebugging ? this.toLocalPath(debugState.currentThread.file) : debugState.currentThread.file ); if (this.packageInfo.has(dir)) { return Promise.resolve(this.packageInfo.get(dir)); } return new Promise((resolve) => { execFile( getBinPathWithPreferredGopathGoroot('go', []), ['list', '-f', '{{.Name}} {{.ImportPath}}'], { cwd: dir, env: this.delve?.dlvEnv }, (err, stdout, stderr) => { if (err || stderr || !stdout) { logError(`go list failed on ${dir}: ${stderr || err}`); return resolve(); } if (stdout.split('\n').length !== 2) { logError(`Cannot determine package for ${dir}`); return resolve(); } const spaceIndex = stdout.indexOf(' '); const result = stdout.substr(0, spaceIndex) === 'main' ? 'main' : stdout.substr(spaceIndex).trim(); this.packageInfo.set(dir, result); resolve(result); } ); }); } // Go might return more than one result while DAP and VS Code do not support // such scenario but assume one single result. So, wrap all return variables // in one made-up, nameless, invalid variable. This is similar to how scopes // are represented. This assumes the vars are the ordered list of return // values from a function call. private wrapReturnVars(vars: DebugVariable[]): DebugVariable { // VS Code uses the value property of the DebugVariable // when displaying it. So let's formulate it in a user friendly way // as if they look like a list of multiple values. // Note: we use only convertDebugVariableToProtocolVariable's result, // which means we will leak the variable references until the handle // map is cleared. Assuming the number of return parameters is handful, // this waste shouldn't be significant. const values = vars.map((v) => this.convertDebugVariableToProtocolVariable(v).result) || []; return { value: values.join(', '), kind: GoReflectKind.Invalid, flags: GoVariableFlags.VariableFakeAddress | GoVariableFlags.VariableReturnArgument, children: vars, // DebugVariable requires the following fields. name: '', addr: 0, type: '', realType: '', onlyAddr: false, DeclLine: 0, len: 0, cap: 0, unreadable: '', base: 0, fullyQualifiedName: '' }; } private convertDebugVariableToProtocolVariable(v: DebugVariable): { result: string; variablesReference: number } { if (v.kind === GoReflectKind.UnsafePointer) { return { result: `unsafe.Pointer(0x${v.children[0].addr.toString(16)})`, variablesReference: 0 }; } else if (v.kind === GoReflectKind.Ptr) { if (!v.children[0]) { return { result: 'unknown <' + v.type + '>', variablesReference: 0 }; } else if (v.children[0].addr === 0) { return { result: 'nil <' + v.type + '>', variablesReference: 0 }; } else if (v.children[0].type === 'void') { return { result: 'void', variablesReference: 0 }; } else { if (v.children[0].children.length > 0) { // Generate correct fullyQualified names for variable expressions v.children[0].fullyQualifiedName = v.fullyQualifiedName; v.children[0].children.forEach((child) => { child.fullyQualifiedName = v.fullyQualifiedName + '.' + child.name; }); } return { result: `<${v.type}>(0x${v.children[0].addr.toString(16)})`, variablesReference: v.children.length > 0 ? this.variableHandles.create(v) : 0 }; } } else if (v.kind === GoReflectKind.Slice) { if (v.base === 0) { return { result: 'nil <' + v.type + '>', variablesReference: 0 }; } return { result: '<' + v.type + '> (length: ' + v.len + ', cap: ' + v.cap + ')', variablesReference: this.variableHandles.create(v) }; } else if (v.kind === GoReflectKind.Map) { if (v.base === 0) { return { result: 'nil <' + v.type + '>', variablesReference: 0 }; } return { result: '<' + v.type + '> (length: ' + v.len + ')', variablesReference: this.variableHandles.create(v) }; } else if (v.kind === GoReflectKind.Array) { return { result: '<' + v.type + '>', variablesReference: this.variableHandles.create(v) }; } else if (v.kind === GoReflectKind.String) { let val = v.value; const byteLength = Buffer.byteLength(val || ''); if (v.value && byteLength < v.len) { val += `...+${v.len - byteLength} more`; } return { result: v.unreadable ? '<' + v.unreadable + '>' : '"' + val + '"', variablesReference: 0 }; } else if (v.kind === GoReflectKind.Interface) { if (v.addr === 0) { // an escaped interface variable that points to nil, this shouldn't // happen in normal code but can happen if the variable is out of scope. return { result: 'nil', variablesReference: 0 }; } if (v.children.length === 0) { // Shouldn't happen, but to be safe. return { result: 'nil', variablesReference: 0 }; } const child = v.children[0]; if (child.kind === GoReflectKind.Invalid && child.addr === 0) { return { result: `nil <${v.type}>`, variablesReference: 0 }; } return { // TODO(hyangah): v.value will be useless. consider displaying more info from the child. // https://github.com/go-delve/delve/blob/930fa3b/service/api/prettyprint.go#L106-L124 result: v.value || `<${v.type}(${child.type})>)`, variablesReference: v.children?.length > 0 ? this.variableHandles.create(v) : 0 }; } else { // Default case - structs if (v.children.length > 0) { // Generate correct fullyQualified names for variable expressions v.children.forEach((child) => { child.fullyQualifiedName = v.fullyQualifiedName + '.' + child.name; }); } return { result: v.value || '<' + v.type + '>', variablesReference: v.children.length > 0 ? this.variableHandles.create(v) : 0 }; } } private cleanupHandles(): void { this.variableHandles.reset(); this.stackFrameHandles.reset(); } private handleReenterDebug(reason: string): void { log(`handleReenterDebug(${reason}).`); this.cleanupHandles(); if (this.debugState?.exited) { this.sendEvent(new TerminatedEvent()); log('TerminatedEvent'); } else { // Delve blocks on continue and does not support events, so there is no way to // refresh the list of goroutines while the program is running. And when the program is // stopped, the development tool will issue a threads request and update the list of // threads in the UI even without the optional thread events. Therefore, instead of // analyzing all goroutines here, only retrieve the current one. // TODO(polina): validate the assumption in this code that the first goroutine // is the current one. So far it appears to me that this is always the main goroutine // with id 1. this.delve?.call<DebugGoroutine[] | ListGoroutinesOut>('ListGoroutines', [{ count: 1 }], (err, out) => { if (err) { this.logDelveError(err, 'Failed to get threads'); } const goroutines = this.delve?.isApiV1 ? <DebugGoroutine[]>out : (<ListGoroutinesOut>out).Goroutines; if (this.debugState && !this.debugState?.currentGoroutine && goroutines.length > 0) { this.debugState.currentGoroutine = goroutines[0]; } if (this.skipStopEventOnce) { log( `Skipping stop event for ${reason}. The current Go routines is ${this.debugState?.currentGoroutine}.` ); this.skipStopEventOnce = false; return; } if (this.overrideStopReason?.length > 0) { reason = this.overrideStopReason; this.overrideStopReason = ''; } const stoppedEvent = new StoppedEvent(reason, this.debugState?.currentGoroutine.id); (<any>stoppedEvent.body).allThreadsStopped = true; this.sendEvent(stoppedEvent); log('StoppedEvent("' + reason + '")'); }); } } // Returns true if the debuggee is running. // The call getDebugState is non-blocking so it should return // almost instantaneously. However, if we run into some errors, // we will fall back to the internal tracking of the debug state. // TODO: If Delve is not in multi-client state, we can simply // track the running state with continueRequestRunning internally // instead of issuing a getDebugState call to Delve. Perhaps we want to // do that to improve performance in the future. private async isDebuggeeRunning(): Promise<boolean> { if (this.debugState && this.debugState.exited) { return false; } try { this.debugState = await this.delve?.getDebugState(); return !!this.debugState?.Running; } catch (error) { this.logDelveError(error, 'Failed to get state'); // Fall back to the internal tracking. return this.continueRequestRunning || this.nextRequestRunning; } } private shutdownProtocolServer( response: DebugProtocol.DisconnectResponse, args: DebugProtocol.DisconnectArguments ): void { log('DisconnectRequest to parent to shut down protocol server.'); super.disconnectRequest(response, args); } private continue(calledWhenSettingBreakpoint?: boolean): Thenable<void> { this.continueEpoch++; const closureEpoch = this.continueEpoch; this.continueRequestRunning = true; const callback = (out: any) => { if (closureEpoch === this.continueEpoch) { this.continueRequestRunning = false; } const state = this.delve?.isApiV1 ? <DebuggerState>out : (<CommandOut>out).State; log('continue state', state); this.debugState = state; let reason = 'breakpoint'; // Check if the current thread was stopped on 'panic' or 'fatal error'. if (!!state.currentThread && !!state.currentThread.breakPoint) { const bp = state.currentThread.breakPoint; if (bp.id === unrecoveredPanicID) { // If the breakpoint is actually caused by a panic, // we want to return on "panic". reason = 'panic'; } else if (bp.id === fatalThrowID) { // If the breakpoint is actually caused by a fatal throw, // we want to return on "fatal error". reason = 'fatal error'; } } this.handleReenterDebug(reason); }; // If called when setting breakpoint internally, we want the error to bubble up. let errorCallback = (_: unknown): any => void 0; if (!calledWhenSettingBreakpoint) { errorCallback = (err: any) => { if (err) { this.logDelveError(err, 'Failed to continue'); } this.handleReenterDebug('breakpoint'); throw err; }; } if (this.delve) { return this.delve.callPromise('Command', [{ name: 'continue' }]).then(callback, errorCallback); } return Promise.resolve(); } // evaluateCallImpl expects args.expression starts with the 'call ' command. private evaluateCallImpl(args: DebugProtocol.EvaluateArguments): Thenable<DebuggerState | CommandOut | void> { const callExpr = args.expression.trimLeft().slice('call '.length); // if args.frameID is 'not specified', expression is evaluated in the global scope, according to DAP. // default to the topmost stack frame of the current goroutine let goroutineId = -1; let frameId = 0; if (args.frameId) { [goroutineId, frameId] = this.stackFrameHandles.get(args.frameId, [goroutineId, frameId]); } // See https://github.com/go-delve/delve/blob/328cf87808822693dc611591519689dcd42696a3/service/api/types.go#L321-L350 // for the command args for function call. const returnValue = this.delve ?.callPromise<DebuggerState | CommandOut>('Command', [ { name: 'call', goroutineID: goroutineId, returnInfoLoadConfig: this.delve?.loadConfig, expr: callExpr, unsafe: false } ]) .then( (val) => val, (err) => { logError( 'Failed to call function: ', JSON.stringify(callExpr, null, ' '), '\n\rCall error:', err.toString() ); return Promise.reject(err); } ); return returnValue ?? Promise.resolve(); } private evaluateRequestImpl(args: DebugProtocol.EvaluateArguments): Thenable<EvalOut | DebugVariable | void> { // default to the topmost stack frame of the current goroutine let goroutineId = -1; let frameId = 0; // args.frameId won't be specified when evaluating global vars if (args.frameId) { [goroutineId, frameId] = this.stackFrameHandles.get(args.frameId, [goroutineId, frameId]); } const scope = { goroutineID: goroutineId, frame: frameId }; const apiV1Args = { symbol: args.expression, scope }; const apiV2Args = { Expr: args.expression, Scope: scope, Cfg: this.delve?.loadConfig }; const evalSymbolArgs = this.delve?.isApiV1 ? apiV1Args : apiV2Args; const returnValue = this.delve ?.callPromise<EvalOut | DebugVariable>(this.delve?.isApiV1 ? 'EvalSymbol' : 'Eval', [evalSymbolArgs]) .then( (val) => val, (err) => { log( 'Failed to eval expression: ', JSON.stringify(evalSymbolArgs, null, ' '), '\n\rEval error:', err.toString() ); return Promise.reject(err); } ); return returnValue ?? Promise.resolve(); } private addFullyQualifiedName(variables: DebugVariable[]) { variables.forEach((local) => { local.fullyQualifiedName = local.name; local.children.forEach((child) => { child.fullyQualifiedName = local.name; }); }); } private logDelveError(err: any, message: string) { if (err === undefined) { return; } let errorMessage = err.toString(); // Use a more user friendly message for an unpropagated SIGSEGV (EXC_BAD_ACCESS) // signal that delve is unable to send back to the target process to be // handled as a panic. // https://github.com/microsoft/vscode-go/issues/1903#issuecomment-460126884 // https://github.com/go-delve/delve/issues/852 // This affects macOS only although we're agnostic of the OS at this stage. if (errorMessage === 'bad access') { // Reuse the panic message from the Go runtime. errorMessage = 'runtime error: invalid memory address or nil pointer dereference [signal SIGSEGV: segmentation violation]\nUnable to propagate EXC_BAD_ACCESS signal to target process and panic (see https://github.com/go-delve/delve/issues/852)'; } logError(message + ' - ' + errorMessage); this.dumpStacktrace(); } private async dumpStacktrace() { // Get current goroutine // Debugger may be stopped at this point but we still can (and need) to obtain state and stacktrace let goroutineId = 0; try { this.debugState = await this.delve?.getDebugState(); // In some fault scenarios there may not be a currentGoroutine available from the debugger state // Use the current thread if (!this.debugState?.currentGoroutine) { goroutineId = this.debugState?.currentThread.goroutineID ?? 0; } else { goroutineId = this.debugState?.currentGoroutine.id ?? 0; } } catch (error) { logError('dumpStacktrace - Failed to get debugger state ' + error); } // Get goroutine stacktrace const stackTraceIn = { id: goroutineId, depth: this.delve?.stackTraceDepth }; if (!this.delve?.isApiV1) { Object.assign(stackTraceIn, { full: false, cfg: this.delve?.loadConfig }); } this.delve?.call<DebugLocation[] | StacktraceOut>( this.delve?.isApiV1 ? 'StacktraceGoroutine' : 'Stacktrace', [stackTraceIn], (err, out) => { if (err) { logError('dumpStacktrace: Failed to produce stack trace' + err); return; } const locations = this.delve?.isApiV1 ? <DebugLocation[]>out : (<StacktraceOut>out).Locations; log('locations', locations); const stackFrames = locations.map((location, frameId) => { const uniqueStackFrameId = this.stackFrameHandles.create([goroutineId, frameId]); return new StackFrame( uniqueStackFrameId, location.function ? location.function.name : '<unknown>', location.file === '<autogenerated>' ? undefined : new Source(path.basename(location.file), this.toLocalPath(location.file)), location.line, 0 ); }); // Dump stacktrace into error logger logError(`Last known immediate stacktrace (goroutine id ${goroutineId}):`); let output = ''; stackFrames.forEach((stackFrame) => { output = output.concat(`\t${stackFrame.source.path}:${stackFrame.line}\n`); if (stackFrame.name) { output = output.concat(`\t\t${stackFrame.name}\n`); } }); logError(output); } ); } } // Class for fetching remote sources and packages // in the remote program using Delve. // tslint:disable-next-line:max-classes-per-file export class RemoteSourcesAndPackages extends EventEmitter { public static readonly INITIALIZED = 'INITIALIZED'; public initializingRemoteSourceFiles = false; public initializedRemoteSourceFiles = false; public remotePackagesBuildInfo: PackageBuildInfo[] = []; public remoteSourceFiles: string[] = []; public remoteSourceFilesNameGrouping = new Map<string, string[]>(); /** * Initialize and fill out remote packages build info and remote source files. * Emits the INITIALIZED event once initialization is complete. */ public async initializeRemotePackagesAndSources(delve: Delve): Promise<void> { this.initializingRemoteSourceFiles = true; try { // ListPackagesBuildInfo is not available on V1. if (!delve.isApiV1 && this.remotePackagesBuildInfo.length === 0) { const packagesBuildInfoResponse: ListPackagesBuildInfoOut = await delve.callPromise( 'ListPackagesBuildInfo', [{ IncludeFiles: true }] ); if (packagesBuildInfoResponse && packagesBuildInfoResponse.List) { this.remotePackagesBuildInfo = packagesBuildInfoResponse.List; } } // List sources will return all the source files used by Delve. if (delve.isApiV1) { this.remoteSourceFiles = await delve.callPromise('ListSources', []); } else { const listSourcesResponse: ListSourcesOut = await delve.callPromise('ListSources', [{}]); if (listSourcesResponse && listSourcesResponse.Sources) { this.remoteSourceFiles = listSourcesResponse.Sources; } } // Group the source files by name for easy searching later. this.remoteSourceFiles = this.remoteSourceFiles.filter((sourceFile) => !sourceFile.startsWith('<')); this.remoteSourceFiles.forEach((sourceFile) => { const fileName = getBaseName(sourceFile); if (!this.remoteSourceFilesNameGrouping.has(fileName)) { this.remoteSourceFilesNameGrouping.set(fileName, []); } this.remoteSourceFilesNameGrouping.get(fileName)?.push(sourceFile); }); } catch (error) { logError(`Failed to initialize remote sources and packages: ${(error as Error).message}`); } finally { this.emit(RemoteSourcesAndPackages.INITIALIZED); this.initializedRemoteSourceFiles = true; } } } function random(low: number, high: number): number { return Math.floor(Math.random() * (high - low) + low); } async function removeFile(filePath: string): Promise<void> { try { const fileExists = await fsAccess(filePath) .then(() => true) .catch(() => false); if (filePath && fileExists) { await fsUnlink(filePath); } } catch (e) { logError(`Potentially failed remove file: ${filePath} - ${e}`); } } // queryGOROOT returns `go env GOROOT`. function queryGOROOT(cwd: any, env: any): Promise<string> { return new Promise<string>((resolve) => { execFile( getBinPathWithPreferredGopathGoroot('go', []), ['env', 'GOROOT'], { cwd, env }, (err, stdout, stderr) => { if (err) { return resolve(''); } return resolve(stdout.trim()); } ); }); } DebugSession.run(GoDebugSession);
vscode-go/extension/src/debugAdapter/goDebug.ts/0
{ "file_path": "vscode-go/extension/src/debugAdapter/goDebug.ts", "repo_id": "vscode-go", "token_count": 36296 }
768
/* eslint-disable @typescript-eslint/no-unused-vars */ /* eslint-disable eqeqeq */ /* eslint-disable @typescript-eslint/no-explicit-any */ /*--------------------------------------------------------- * Copyright (C) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See LICENSE in the project root for license information. *--------------------------------------------------------*/ 'use strict'; import cp = require('child_process'); import path = require('path'); import vscode = require('vscode'); import { getGoConfig } from './config'; import { toolExecutionEnvironment } from './goEnv'; import { promptForMissingTool } from './goInstallTools'; import { GoDocumentSymbolProvider } from './goDocumentSymbols'; import { outputChannel } from './goStatus'; import { getBinPath, resolvePath } from './util'; import { CommandFactory } from './commands'; import { GoExtensionContext } from './context'; const generatedWord = 'Generated '; /** * If current active editor has a Go file, returns the editor. */ function checkActiveEditor(): vscode.TextEditor | undefined { const editor = vscode.window.activeTextEditor; if (!editor) { vscode.window.showInformationMessage('Cannot generate unit tests. No editor selected.'); return; } if (!editor.document.fileName.endsWith('.go')) { vscode.window.showInformationMessage('Cannot generate unit tests. File in the editor is not a Go file.'); return; } if (editor.document.isDirty) { vscode.window.showInformationMessage('File has unsaved changes. Save and try again.'); return; } return editor; } /** * Toggles between file in current active editor and the corresponding test file. */ export const toggleTestFile: CommandFactory = () => () => { const editor = vscode.window.activeTextEditor; if (!editor) { vscode.window.showInformationMessage('Cannot toggle test file. No editor selected.'); return; } const currentFilePath = editor.document.fileName; if (!currentFilePath.endsWith('.go')) { vscode.window.showInformationMessage('Cannot toggle test file. File in the editor is not a Go file.'); return; } let targetFilePath = ''; if (currentFilePath.endsWith('_test.go')) { targetFilePath = currentFilePath.substr(0, currentFilePath.lastIndexOf('_test.go')) + '.go'; } else { targetFilePath = currentFilePath.substr(0, currentFilePath.lastIndexOf('.go')) + '_test.go'; } for (const doc of vscode.window.visibleTextEditors) { if (doc.document.fileName === targetFilePath) { vscode.commands.executeCommand('vscode.open', vscode.Uri.file(targetFilePath), doc.viewColumn); return; } } vscode.commands.executeCommand('vscode.open', vscode.Uri.file(targetFilePath)); }; export const generateTestCurrentPackage: CommandFactory = (ctx, goCtx) => () => { const editor = checkActiveEditor(); if (!editor) { return false; } return generateTests( ctx, goCtx, { dir: path.dirname(editor.document.uri.fsPath), isTestFile: editor.document.fileName.endsWith('_test.go') }, getGoConfig(editor.document.uri) ); }; export const generateTestCurrentFile: CommandFactory = (ctx, goCtx) => () => { const editor = checkActiveEditor(); if (!editor) { return false; } return generateTests( ctx, goCtx, { dir: editor.document.uri.fsPath, isTestFile: editor.document.fileName.endsWith('_test.go') }, getGoConfig(editor.document.uri) ); }; export const generateTestCurrentFunction: CommandFactory = (ctx, goCtx) => async () => { const editor = checkActiveEditor(); if (!editor) { return false; } const functions = await getFunctions(goCtx, editor.document); const selection = editor.selection; const currentFunction = functions.find((func) => selection && func.range.contains(selection.start)); if (!currentFunction) { vscode.window.showInformationMessage('No function found at cursor.'); return Promise.resolve(false); } let funcName = currentFunction.name; const funcNameParts = funcName.match(/^\(\*?(.*)\)\.(.*)$/); if (funcNameParts != null && funcNameParts.length === 3) { // receiver type specified const rType = funcNameParts[1].replace(/^\w/, (c) => c.toUpperCase()); const fName = funcNameParts[2].replace(/^\w/, (c) => c.toUpperCase()); funcName = rType + fName; } return generateTests( ctx, goCtx, { dir: editor.document.uri.fsPath, func: funcName, isTestFile: editor.document.fileName.endsWith('_test.go') }, getGoConfig(editor.document.uri) ); }; /** * Input to goTests. */ interface Config { /** * The working directory for `gotests`. */ dir: string; /** * Specific function names to generate tests skeleton. */ func?: string; /** * Whether or not the file to generate test functions for is a test file. */ isTestFile?: boolean; } function generateTests( ctx: vscode.ExtensionContext, goCtx: GoExtensionContext, conf: Config, goConfig: vscode.WorkspaceConfiguration ): Promise<boolean> { return new Promise<boolean>((resolve, reject) => { const cmd = getBinPath('gotests'); let args = ['-w']; const goGenerateTestsFlags: string[] = goConfig['generateTestsFlags'] || []; for (let i = 0; i < goGenerateTestsFlags.length; i++) { const flag = goGenerateTestsFlags[i]; if (flag === '-w' || flag === 'all') { continue; } if (flag === '-only') { i++; continue; } if (i + 1 < goGenerateTestsFlags.length && (flag === '-template_dir' || flag === '-template_params_file')) { const configFilePath = resolvePath(goGenerateTestsFlags[i + 1]); args.push(flag, configFilePath); i++; continue; } args.push(flag); } if (conf.func) { args = args.concat(['-only', `^${conf.func}$`, conf.dir]); } else { args = args.concat(['-all', conf.dir]); } cp.execFile(cmd, args, { env: toolExecutionEnvironment() }, (err, stdout, stderr) => { outputChannel.appendLine('Generating Tests: ' + cmd + ' ' + args.join(' ')); try { if (err && (<any>err).code === 'ENOENT') { promptForMissingTool('gotests'); return resolve(false); } if (err) { outputChannel.error(err.message); return reject('Cannot generate test due to errors'); } let message = stdout; let testsGenerated = false; // Expected stdout is of the format "Generated TestMain\nGenerated Testhello\n" if (stdout.startsWith(generatedWord)) { const lines = stdout .split('\n') .filter((element) => { return element.startsWith(generatedWord); }) .map((element) => { return element.substr(generatedWord.length); }); message = `Generated ${lines.join(', ')}`; testsGenerated = true; } vscode.window.showInformationMessage(message); outputChannel.append(message); if (testsGenerated && !conf.isTestFile) { toggleTestFile(ctx, goCtx)(); } return resolve(true); } catch (e) { vscode.window.showInformationMessage((e as any).msg); outputChannel.append((e as any).msg); reject(e); } }); }); } async function getFunctions(goCtx: GoExtensionContext, doc: vscode.TextDocument): Promise<vscode.DocumentSymbol[]> { const documentSymbolProvider = GoDocumentSymbolProvider(goCtx); const symbols = await documentSymbolProvider.provideDocumentSymbols(doc); if (!symbols || symbols.length == 0) { return []; } return symbols[0].children.filter((sym) => [vscode.SymbolKind.Function, vscode.SymbolKind.Method].includes(sym.kind) ); }
vscode-go/extension/src/goGenerateTests.ts/0
{ "file_path": "vscode-go/extension/src/goGenerateTests.ts", "repo_id": "vscode-go", "token_count": 2670 }
769
/*--------------------------------------------------------- * Copyright 2023 The Go Authors. All rights reserved. * Licensed under the MIT License. See LICENSE in the project root for license information. *--------------------------------------------------------*/ import * as vscode from 'vscode'; import { getGoConfig } from './config'; import { toolExecutionEnvironment } from './goEnv'; import { getBinPath } from './util'; const TASK_TYPE = 'go'; type GoCommand = 'build' | 'test'; // TODO(hyangah): run, install? interface GoTaskDefinition extends vscode.TaskDefinition { label?: string; command: GoCommand; args?: string[]; options?: vscode.ProcessExecutionOptions; // TODO(hyangah): plumb go.testFlags and go.buildFlags } type Workspace = Pick<typeof vscode.workspace, 'workspaceFolders' | 'getWorkspaceFolder'>; // GoTaskProvider provides default tasks // - build/test the current package // - build/test all packages in the current workspace // This default task provider can be disabled by `go.tasks.provideDefault`. // // Note that these tasks run from the workspace root folder. If the workspace root // folder and the package to test are not in the same module nor in the same workspace // defined by a go.work file, the build/test task will fail because the tested package // is not visible from the workspace root folder. export class GoTaskProvider implements vscode.TaskProvider { private constructor(private workspace: Workspace) {} static setup(ctx: vscode.ExtensionContext, workspace: Workspace): GoTaskProvider | undefined { if (workspace.workspaceFolders && workspace.workspaceFolders.length > 0) { const provider = new GoTaskProvider(workspace); ctx.subscriptions.push(vscode.tasks.registerTaskProvider('go', provider)); return provider; } return undefined; } // provides the default tasks. // eslint-disable-next-line @typescript-eslint/no-unused-vars provideTasks(_: vscode.CancellationToken): vscode.ProviderResult<vscode.Task[]> { const folders = this.workspace.workspaceFolders; if (!folders || !folders.length) { // zero workspace folder setup. // In zero-workspace folder setup, vscode.TaskScope.Workspace doesn't seem to work. // The task API does not implement vscode.TaskScope.Global yet. // Once Global scope is supported, we can consider to add tasks like `go build ${fileDirname}`. return undefined; } const opened = vscode.window.activeTextEditor?.document?.uri; const goCfg = getGoConfig(opened); if (!goCfg.get('tasks.provideDefault')) { return undefined; } // Explicitly specify the workspace folder directory based on the current open file. // Behavior of tasks constructed with vscode.TaskScope.Workspace as scope // is not well-defined when handling multiple folder workspace. const folder = (opened && this.workspace.getWorkspaceFolder(opened)) || folders[0]; return [ // all tasks run from the chosen workspace root folder. buildGoTask(folder, { type: TASK_TYPE, label: 'build package', command: 'build', args: ['${fileDirname}'] }), buildGoTask(folder, { type: TASK_TYPE, label: 'test package', command: 'test', args: ['${fileDirname}'] }), buildGoTask(folder, { type: TASK_TYPE, label: 'build workspace', command: 'build', args: ['./...'] }), buildGoTask(folder, { type: TASK_TYPE, label: 'test workspace', command: 'test', args: ['./...'] }) ]; } // fill an incomplete task definition ('tasks.json') whose type is "go". // eslint-disable-next-line @typescript-eslint/no-unused-vars resolveTask(_task: vscode.Task, _: vscode.CancellationToken): vscode.ProviderResult<vscode.Task> { // vscode calls resolveTask for every 'go' type task in tasks.json. const def = _task.definition; if (def && def.type === TASK_TYPE) { if (!def.command) { def.command = 'build'; } return buildGoTask(_task.scope ?? vscode.TaskScope.Workspace, def as GoTaskDefinition); } return undefined; } } function buildGoTask(scope: vscode.WorkspaceFolder | vscode.TaskScope, definition: GoTaskDefinition): vscode.Task { const cwd = definition.options?.cwd ?? (isWorkspaceFolder(scope) ? scope.uri.fsPath : undefined); const task = new vscode.Task( definition, scope, definition.label ?? defaultTaskName(definition), TASK_TYPE, new vscode.ProcessExecution(getBinPath('go'), [definition.command, ...(definition.args ?? [])], { cwd, env: mergedToolExecutionEnv(scope, definition.options?.env) }), ['$go'] ); task.group = taskGroup(definition.command); task.detail = defaultTaskDetail(definition, cwd); task.runOptions = { reevaluateOnRerun: true }; task.isBackground = false; task.presentationOptions.clear = true; task.presentationOptions.echo = true; task.presentationOptions.showReuseMessage = true; task.presentationOptions.panel = vscode.TaskPanelKind.Dedicated; return task; } function defaultTaskName({ command, args }: GoTaskDefinition): string { return `go ${command} ${(args ?? []).join(' ')}`; } function defaultTaskDetail(def: GoTaskDefinition, cwd: string | undefined): string { const cd = cwd ? `cd ${cwd}; ` : ''; return `${cd}${defaultTaskName(def)}`; } function taskGroup(command: GoCommand): vscode.TaskGroup | undefined { switch (command) { case 'build': return vscode.TaskGroup.Build; case 'test': return vscode.TaskGroup.Test; default: return undefined; } } function isWorkspaceFolder(scope: vscode.WorkspaceFolder | vscode.TaskScope): scope is vscode.WorkspaceFolder { return typeof scope !== 'number' && 'uri' in scope; } function mergedToolExecutionEnv( scope: vscode.WorkspaceFolder | vscode.TaskScope, toAdd: { [key: string]: string } = {} ): { [key: string]: string } { const env = toolExecutionEnvironment(isWorkspaceFolder(scope) ? scope.uri : undefined, /* addProcessEnv: */ false); Object.keys(env).forEach((key) => { if (env[key] === undefined) { env[key] = ''; } }); // unset return Object.assign(env, toAdd); }
vscode-go/extension/src/goTaskProvider.ts/0
{ "file_path": "vscode-go/extension/src/goTaskProvider.ts", "repo_id": "vscode-go", "token_count": 1967 }
770
/* eslint-disable @typescript-eslint/no-explicit-any */ /*--------------------------------------------------------- * Copyright (C) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See LICENSE in the project root for license information. *--------------------------------------------------------*/ 'use strict'; import cp = require('child_process'); import path = require('path'); import vscode = require('vscode'); import { getGoConfig } from '../../config'; import { toolExecutionEnvironment } from '../../goEnv'; import { promptForMissingTool, promptForUpdatingTool } from '../../goInstallTools'; import { getBinPath, resolvePath } from '../../util'; import { killProcessTree } from '../../utils/processUtils'; export class GoDocumentFormattingEditProvider implements vscode.DocumentFormattingEditProvider { public provideDocumentFormattingEdits( document: vscode.TextDocument, options: vscode.FormattingOptions, token: vscode.CancellationToken ): vscode.ProviderResult<vscode.TextEdit[]> { if (vscode.window.visibleTextEditors.every((e) => e.document.fileName !== document.fileName)) { return []; } const filename = document.fileName; const goConfig = getGoConfig(document.uri); const formatFlags = goConfig['formatFlags'].slice() || []; // Ignore -w because we don't want to write directly to disk. if (formatFlags.indexOf('-w') > -1) { formatFlags.splice(formatFlags.indexOf('-w'), 1); } const formatTool = getFormatTool(goConfig); // Handle issues: // https://github.com/Microsoft/vscode-go/issues/613 // https://github.com/Microsoft/vscode-go/issues/630 if (formatTool === 'goimports' || formatTool === 'goreturns') { formatFlags.push('-srcdir', filename); } // Since goformat supports the style flag, set tabsize if the user hasn't. if (formatTool === 'goformat' && formatFlags.length === 0 && options.insertSpaces) { formatFlags.push('-style=indent=' + options.tabSize); } return this.runFormatter(formatTool, formatFlags, document, token).then( (edits) => edits, (err) => { if (typeof err === 'string' && err.startsWith('flag provided but not defined: -srcdir')) { promptForUpdatingTool(formatTool); return Promise.resolve([]); } if (err) { // TODO(hyangah): investigate why this console.log is not visible at all in dev console. // Ideally, this error message should be accessible through one of the output channels. console.log(err); return Promise.reject( `Check the console in dev tools to find errors when formatting with ${formatTool}` ); } } ); } private runFormatter( formatTool: string, formatFlags: string[], document: vscode.TextDocument, token: vscode.CancellationToken ): Thenable<vscode.TextEdit[]> { const formatCommandBinPath = getBinPath(formatTool); if (!path.isAbsolute(formatCommandBinPath)) { // executable not found. promptForMissingTool(formatTool); return Promise.reject('failed to find tool ' + formatTool); } return new Promise<vscode.TextEdit[]>((resolve, reject) => { const env = toolExecutionEnvironment(); const cwd = path.dirname(document.fileName); let stdout = ''; let stderr = ''; // Use spawn instead of exec to avoid maxBufferExceeded error const p = cp.spawn(formatCommandBinPath, formatFlags, { env, cwd }); token.onCancellationRequested(() => !p.killed && killProcessTree(p)); p.stdout.setEncoding('utf8'); p.stdout.on('data', (data) => (stdout += data)); p.stderr.on('data', (data) => (stderr += data)); p.on('error', (err) => { if (err && (<any>err).code === 'ENOENT') { promptForMissingTool(formatTool); return reject(`failed to find format tool: ${formatTool}`); } }); p.on('close', (code) => { if (code !== 0) { return reject(stderr); } // Return the complete file content in the edit. // VS Code will calculate minimal edits to be applied const fileStart = new vscode.Position(0, 0); const fileEnd = document.lineAt(document.lineCount - 1).range.end; const textEdits: vscode.TextEdit[] = [ new vscode.TextEdit(new vscode.Range(fileStart, fileEnd), stdout) ]; return resolve(textEdits); }); if (p.pid) { p.stdin.end(document.getText()); } }); } } export function usingCustomFormatTool(goConfig: { [key: string]: any }): boolean { const formatTool = getFormatTool(goConfig); switch (formatTool) { case 'goreturns': return false; case 'goimports': return false; case 'gofmt': return false; case 'gofumpt': // TODO(rstambler): Prompt to configure setting in gopls. return false; case 'gofumports': // TODO(rstambler): Prompt to configure setting in gopls. return false; default: return true; } } export function getFormatTool(goConfig: { [key: string]: any }): string { const formatTool = goConfig['formatTool']; if (formatTool === 'default') { return 'goimports'; } if (formatTool === 'custom') { return resolvePath(goConfig['alternateTools']['customFormatter'] || 'goimports'); } return formatTool; }
vscode-go/extension/src/language/legacy/goFormat.ts/0
{ "file_path": "vscode-go/extension/src/language/legacy/goFormat.ts", "repo_id": "vscode-go", "token_count": 1822 }
771
/*--------------------------------------------------------- * Copyright (C) Microsoft Corporation. All rights reserved. * Modification copyright 2021 The Go Authors. All rights reserved. * Licensed under the MIT License. See LICENSE in the project root for license information. *--------------------------------------------------------*/ // Modified from: // https://github.com/microsoft/vscode-python/blob/main/src/client/debugger/extension/attachQuickPick/wmicProcessParser.ts. // - Added arguments to get the ExecutablePath from wmic. 'use strict'; import { AttachItem, ProcessListCommand } from '../pickProcess'; const wmicNameTitle = 'Name'; const wmicCommandLineTitle = 'CommandLine'; const wmicPidTitle = 'ProcessId'; const wmicExecutableTitle = 'ExecutablePath'; const defaultEmptyEntry: AttachItem = { label: '', description: '', detail: '', id: '', processName: '', commandLine: '' }; // Perf numbers on Win10: // | # of processes | Time (ms) | // |----------------+-----------| // | 309 | 413 | // | 407 | 463 | // | 887 | 746 | // | 1308 | 1132 | export const wmicCommand: ProcessListCommand = { command: 'wmic', args: ['process', 'get', 'Name,ProcessId,CommandLine,ExecutablePath', '/FORMAT:list'] }; export function parseWmicProcesses(processes: string): AttachItem[] { const lines: string[] = processes.split('\r\n'); const processEntries: AttachItem[] = []; let entry = { ...defaultEmptyEntry }; for (const line of lines) { if (!line.length) { continue; } parseLineFromWmic(line, entry); // Each entry of processes has ProcessId as the last line if (line.lastIndexOf(wmicPidTitle, 0) === 0) { processEntries.push(entry); entry = { ...defaultEmptyEntry }; } } return processEntries; } function parseLineFromWmic(line: string, item: AttachItem): AttachItem { const splitter = line.indexOf('='); const currentItem = item; if (splitter > 0) { const key = line.slice(0, splitter).trim(); let value = line.slice(splitter + 1).trim(); if (key === wmicNameTitle) { currentItem.label = value; currentItem.processName = value; } else if (key === wmicPidTitle) { currentItem.description = value; currentItem.id = value; } else if (key === wmicCommandLineTitle) { const dosDevicePrefix = '\\??\\'; // DOS device prefix, see https://reverseengineering.stackexchange.com/a/15178 if (value.lastIndexOf(dosDevicePrefix, 0) === 0) { value = value.slice(dosDevicePrefix.length); } currentItem.detail = value; currentItem.commandLine = value; } else if (key === wmicExecutableTitle) { currentItem.executable = value; } } return currentItem; }
vscode-go/extension/src/utils/wmicProcessParser.ts/0
{ "file_path": "vscode-go/extension/src/utils/wmicProcessParser.ts", "repo_id": "vscode-go", "token_count": 887 }
772
/* eslint-disable @typescript-eslint/no-explicit-any */ /*--------------------------------------------------------- * Copyright 2020 The Go Authors. All rights reserved. * Licensed under the MIT License. See LICENSE in the project root for license information. *--------------------------------------------------------*/ 'use strict'; import assert from 'assert'; import { getGoConfig } from '../../src/config'; import { computeTestCommand, getTestFlags, goTest } from '../../src/testUtils'; import { rmdirRecursive } from '../../src/util'; import fs = require('fs-extra'); import os = require('os'); import path = require('path'); import sinon = require('sinon'); import vscode = require('vscode'); suite('Test Go Test Args', () => { function runTest(param: { expectedArgs: string; expectedOutArgs: string; flags?: string[]; functions?: string[]; isBenchmark?: boolean; }) { const { args, outArgs } = computeTestCommand( { dir: '', goConfig: getGoConfig(), flags: param.flags || [], functions: param.functions || [], isBenchmark: param.isBenchmark || false, applyCodeCoverage: false }, ['./...'] ); assert.strictEqual(args.join(' '), param.expectedArgs, 'actual command'); assert.strictEqual(outArgs.join(' '), param.expectedOutArgs, 'displayed command'); } test('default config', () => { runTest({ expectedArgs: 'test -timeout 30s ./...', expectedOutArgs: 'test -timeout 30s ./...' }); }); test('user flag [-v] enables -json flag', () => { runTest({ expectedArgs: 'test -timeout 30s -json ./... -v', expectedOutArgs: 'test -timeout 30s ./... -v', flags: ['-v'] }); }); test('user flag [-json -v] prevents -json flag addition', () => { runTest({ expectedArgs: 'test -timeout 30s ./... -json -v', expectedOutArgs: 'test -timeout 30s ./... -json -v', flags: ['-json', '-v'] }); }); test('user flag [-args] does not crash', () => { runTest({ expectedArgs: 'test -timeout 30s ./... -args', expectedOutArgs: 'test -timeout 30s ./... -args', flags: ['-args'] }); }); test('user flag [-args -v] does not enable -json flag', () => { runTest({ expectedArgs: 'test -timeout 30s ./... -args -v', expectedOutArgs: 'test -timeout 30s ./... -args -v', flags: ['-args', '-v'] }); }); test('specifying functions adds -run flags', () => { runTest({ expectedArgs: 'test -timeout 30s -run ^(TestA|TestB)$ ./...', expectedOutArgs: 'test -timeout 30s -run ^(TestA|TestB)$ ./...', functions: ['TestA', 'TestB'] }); }); test('functions & benchmark adds -bench flags and skips timeout', () => { runTest({ expectedArgs: 'test -benchmem -run=^$ -bench ^(TestA|TestB)$ ./...', expectedOutArgs: 'test -benchmem -run=^$ -bench ^(TestA|TestB)$ ./...', functions: ['TestA', 'TestB'], isBenchmark: true }); }); test('user -run flag is ignored when functions are provided', () => { runTest({ expectedArgs: 'test -timeout 30s -run ^(TestA|TestB)$ ./...', expectedOutArgs: 'test -timeout 30s -run ^(TestA|TestB)$ ./...', functions: ['TestA', 'TestB'], flags: ['-run', 'TestC'] }); }); test('use -testify.m for methods', () => { runTest({ expectedArgs: 'test -timeout 30s -run ^TestExampleTestSuite$ -testify.m ^(TestExample|TestAnotherExample)$ ./...', expectedOutArgs: 'test -timeout 30s -run ^TestExampleTestSuite$ -testify.m ^(TestExample|TestAnotherExample)$ ./...', functions: [ '(*ExampleTestSuite).TestExample', '(*ExampleTestSuite).TestAnotherExample', 'TestExampleTestSuite' ] }); }); }); suite('Test Go Test', function () { this.timeout(50000); const sourcePath = path.join(__dirname, '..', '..', '..', 'test', 'testdata', 'goTestTest'); let tmpGopath: string; let repoPath: string; let previousEnv: any; setup(() => { previousEnv = Object.assign({}, process.env); }); teardown(async () => { process.env = previousEnv; rmdirRecursive(tmpGopath); }); function setupRepo(isModuleMode: boolean) { tmpGopath = fs.mkdtempSync(path.join(os.tmpdir(), 'go-test-test')); fs.mkdirSync(path.join(tmpGopath, 'src')); repoPath = path.join(tmpGopath, 'src', 'goTestTest'); fs.copySync(sourcePath, repoPath, { recursive: true, filter: (src: string): boolean => { if (isModuleMode) { return true; } return path.basename(src) !== 'go.mod'; // skip go.mod file. } }); process.env.GOPATH = tmpGopath; process.env.GO111MODULE = isModuleMode ? 'on' : 'off'; } async function runTest( input: { isMod: boolean; includeSubDirectories: boolean; testFlags?: string[]; applyCodeCoverage?: boolean }, wantFiles: string[] ) { const config = Object.create(getGoConfig()); const outputChannel = new FakeOutputChannel(); const testConfig = { goConfig: config, outputChannel, dir: repoPath, flags: input.testFlags ? input.testFlags : getTestFlags(config), isMod: input.isMod, includeSubDirectories: input.includeSubDirectories, applyCodeCoverage: input.applyCodeCoverage }; try { // TODO: instead of calling goTest, consider to test // testCurrentPackage, testCurrentWorkspace, testCurrentFile // which are closer to the features exposed to users. const result = await goTest(testConfig); assert.equal(result, false); // we expect tests to fail. } catch (e) { console.log('exception: ${e}'); } const testOutput = outputChannel.toString(); for (const want of wantFiles) { assert.ok(testOutput.includes(want), `\nFully resolved file path "${want}" not found in \n${testOutput}`); } } test('resolves file names in logs (modules)', async () => { setupRepo(true); await runTest({ isMod: true, includeSubDirectories: true }, [ path.join(repoPath, 'a_test.go'), path.join(repoPath, 'b', 'b_test.go') ]); await runTest({ isMod: true, includeSubDirectories: false }, [path.join(repoPath, 'a_test.go')]); await runTest({ isMod: true, includeSubDirectories: true, testFlags: ['-v'] }, [ path.join(repoPath, 'a_test.go'), path.join(repoPath, 'b', 'b_test.go') ]); await runTest({ isMod: true, includeSubDirectories: true, testFlags: ['-race'], applyCodeCoverage: true }, [ path.join(repoPath, 'a_test.go'), path.join(repoPath, 'b', 'b_test.go') ]); await runTest({ isMod: true, includeSubDirectories: false, testFlags: ['-v'] }, [ path.join(repoPath, 'a_test.go') ]); }); test('resolves file names in logs (GOPATH)', async () => { setupRepo(false); await runTest({ isMod: false, includeSubDirectories: true }, [ path.join(repoPath, 'a_test.go'), path.join(repoPath, 'b', 'b_test.go') ]); await runTest({ isMod: false, includeSubDirectories: false }, [path.join(repoPath, 'a_test.go')]); await runTest({ isMod: false, includeSubDirectories: true, testFlags: ['-v'] }, [ path.join(repoPath, 'a_test.go'), path.join(repoPath, 'b', 'b_test.go') ]); await runTest({ isMod: false, includeSubDirectories: true, testFlags: ['-race'], applyCodeCoverage: true }, [ path.join(repoPath, 'a_test.go'), path.join(repoPath, 'b', 'b_test.go') ]); await runTest({ isMod: false, includeSubDirectories: false, testFlags: ['-v'] }, [ path.join(repoPath, 'a_test.go') ]); }); }); // FakeOutputChannel is a fake output channel used to buffer // the output of the tested language client in an in-memory // string array until cleared. class FakeOutputChannel implements vscode.OutputChannel { public name = 'FakeOutputChannel'; public show = sinon.fake(); // no-empty public hide = sinon.fake(); // no-empty public dispose = sinon.fake(); // no-empty public replace = sinon.fake(); // no-empty private buf = [] as string[]; public append = (v: string) => this.enqueue(v); public appendLine = (v: string) => this.enqueue(v); public clear = () => { this.buf = []; }; public toString = () => { return this.buf.join('\n'); }; private enqueue = (v: string) => { if (this.buf.length > 1024) { this.buf.shift(); } this.buf.push(v.trim()); }; }
vscode-go/extension/test/integration/test.test.ts/0
{ "file_path": "vscode-go/extension/test/integration/test.test.ts", "repo_id": "vscode-go", "token_count": 3012 }
773
//go:build go1.18 // +build go1.18 package main import ( "testing" ) func FuzzFunc(f *testing.F) { } func Fuzz(f *testing.F) { } func TestGo118(t *testing.T) { }
vscode-go/extension/test/testdata/codelens/codelens_go118_test.go/0
{ "file_path": "vscode-go/extension/test/testdata/codelens/codelens_go118_test.go", "repo_id": "vscode-go", "token_count": 80 }
774
module example/cwdTest go 1.15
vscode-go/extension/test/testdata/cwdTest/cwdTest/go.mod/0
{ "file_path": "vscode-go/extension/test/testdata/cwdTest/cwdTest/go.mod", "repo_id": "vscode-go", "token_count": 13 }
775
module github.com/microsoft/vscode-go/gofixtures/gogetdoctestdata go 1.14
vscode-go/extension/test/testdata/gogetdocTestData/go.mod/0
{ "file_path": "vscode-go/extension/test/testdata/gogetdocTestData/go.mod", "repo_id": "vscode-go", "token_count": 31 }
776
module github.com/microsoft/vscode-go/gofixtures/outlinetest go 1.14
vscode-go/extension/test/testdata/outlineTest/go.mod/0
{ "file_path": "vscode-go/extension/test/testdata/outlineTest/go.mod", "repo_id": "vscode-go", "token_count": 28 }
777
package main import ( "fmt" "example/vendorpls" ) func main() { fmt.Prinln(vendorpls.F()) }
vscode-go/extension/test/testdata/vendoring/main.go/0
{ "file_path": "vscode-go/extension/test/testdata/vendoring/main.go", "repo_id": "vscode-go", "token_count": 48 }
778
Tree Kill ========= Kill all processes in the process tree, including the root process. Examples ======= Kill all the descendent processes of the process with pid `1`, including the process with pid `1` itself: ```js var kill = require('tree-kill'); kill(1); ``` Send a signal other than SIGTERM.: ```js var kill = require('tree-kill'); kill(1, 'SIGKILL'); ``` Run a callback when done killing the processes. Passes an error argument if there was an error. ```js var kill = require('tree-kill'); kill(1, 'SIGKILL', function(err) { // Do things }); ``` You can also install tree-kill globally and use it as a command: ```sh tree-kill 1 # sends SIGTERM to process 1 and its descendents tree-kill 1 SIGTERM # same tree-kill 1 SIGKILL # sends KILL instead of TERMINATE ``` Methods ======= ## require('tree-kill')(pid, [signal], [callback]); Sends signal `signal` to all children processes of the process with pid `pid`, including `pid`. Signal defaults to `SIGTERM`. For Linux, this uses `ps -o pid --no-headers --ppid PID` to find the parent pids of `PID`. For Darwin/OSX, this uses `pgrep -P PID` to find the parent pids of `PID`. For Windows, this uses `'taskkill /pid PID /T /F'` to kill the process tree. Note that on Windows, sending the different kinds of POSIX signals is not possible. Install ======= With [npm](https://npmjs.org) do: ``` npm install tree-kill ``` License ======= MIT Changelog ========= ## [1.2.2] - 2019-12-11 ### Changed - security fix: sanitize `pid` parameter to fix arbitrary code execution vulnerability ## [1.2.1] - 2018-11-05 ### Changed - added missing LICENSE file - updated TypeScript definitions ## [1.2.0] - 2017-09-19 ### Added - TypeScript definitions ### Changed - `kill(pid, callback)` works. Before you had to use `kill(pid, signal, callback)` ## [1.1.0] - 2016-05-13 ### Added - A `tree-kill` CLI ## [1.0.0] - 2015-09-17 ### Added - optional callback - Darwin support
vscode-go/extension/third_party/tree-kill/README.md/0
{ "file_path": "vscode-go/extension/third_party/tree-kill/README.md", "repo_id": "vscode-go", "token_count": 650 }
779
jq -r .version package.json cp ../README.md README.md npx vsce package -o go-0.0.0.vsix --baseContentUrl https://github.com/golang/vscode-go/raw/v0.0.0 --baseImagesUrl https://github.com/golang/vscode-go/raw/v0.0.0 --no-update-package-json --no-git-tag-version 0.0.0
vscode-go/extension/tools/release/testdata/package-v0.0.0.golden/0
{ "file_path": "vscode-go/extension/tools/release/testdata/package-v0.0.0.golden", "repo_id": "vscode-go", "token_count": 117 }
780