repo
stringlengths
5
54
path
stringlengths
4
155
func_name
stringlengths
1
118
original_string
stringlengths
52
85.5k
language
stringclasses
1 value
code
stringlengths
52
85.5k
code_tokens
sequence
docstring
stringlengths
6
2.61k
docstring_tokens
sequence
sha
stringlengths
40
40
url
stringlengths
85
252
partition
stringclasses
1 value
vmware/govmomi
simulator/simulator.go
RegisterSDK
func (s *Service) RegisterSDK(r *Registry) { if s.ServeMux == nil { s.ServeMux = http.NewServeMux() } s.sdk[r.Path] = r s.ServeMux.HandleFunc(r.Path, s.ServeSDK) }
go
func (s *Service) RegisterSDK(r *Registry) { if s.ServeMux == nil { s.ServeMux = http.NewServeMux() } s.sdk[r.Path] = r s.ServeMux.HandleFunc(r.Path, s.ServeSDK) }
[ "func", "(", "s", "*", "Service", ")", "RegisterSDK", "(", "r", "*", "Registry", ")", "{", "if", "s", ".", "ServeMux", "==", "nil", "{", "s", ".", "ServeMux", "=", "http", ".", "NewServeMux", "(", ")", "\n", "}", "\n\n", "s", ".", "sdk", "[", "r", ".", "Path", "]", "=", "r", "\n", "s", ".", "ServeMux", ".", "HandleFunc", "(", "r", ".", "Path", ",", "s", ".", "ServeSDK", ")", "\n", "}" ]
// RegisterSDK adds an HTTP handler for the Registry's Path and Namespace.
[ "RegisterSDK", "adds", "an", "HTTP", "handler", "for", "the", "Registry", "s", "Path", "and", "Namespace", "." ]
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/simulator/simulator.go#L376-L383
train
vmware/govmomi
simulator/simulator.go
ServeSDK
func (s *Service) ServeSDK(w http.ResponseWriter, r *http.Request) { if r.Method != http.MethodPost { w.WriteHeader(http.StatusMethodNotAllowed) return } body, err := s.readAll(r.Body) _ = r.Body.Close() if err != nil { log.Printf("error reading body: %s", err) w.WriteHeader(http.StatusBadRequest) return } if Trace { fmt.Fprintf(os.Stderr, "Request: %s\n", string(body)) } ctx := &Context{ req: r, res: w, svc: s, Map: s.sdk[r.URL.Path], Context: context.Background(), } ctx.Map.WithLock(s.sm, ctx.mapSession) var res soap.HasFault var soapBody interface{} method, err := UnmarshalBody(ctx.Map.typeFunc, body) if err != nil { res = serverFault(err.Error()) } else { ctx.Header = method.Header if method.Name == "Fetch" { // Redirect any Fetch method calls to the PropertyCollector singleton method.This = ctx.Map.content().PropertyCollector } res = s.call(ctx, method) } if f := res.Fault(); f != nil { w.WriteHeader(http.StatusInternalServerError) // the generated method/*Body structs use the '*soap.Fault' type, // so we need our own Body type to use the modified '*soapFault' type. soapBody = struct { Fault *soapFault }{ &soapFault{ Code: f.Code, String: f.String, Detail: struct { Fault *faultDetail }{&faultDetail{f.Detail.Fault}}, }, } } else { w.WriteHeader(http.StatusOK) soapBody = &response{ctx.Map.Namespace, res} } var out bytes.Buffer fmt.Fprint(&out, xml.Header) e := xml.NewEncoder(&out) err = e.Encode(&soapEnvelope{ Enc: "http://schemas.xmlsoap.org/soap/encoding/", Env: "http://schemas.xmlsoap.org/soap/envelope/", XSD: "http://www.w3.org/2001/XMLSchema", XSI: "http://www.w3.org/2001/XMLSchema-instance", Body: soapBody, }) if err == nil { err = e.Flush() } if err != nil { log.Printf("error encoding %s response: %s", method.Name, err) return } if Trace { fmt.Fprintf(os.Stderr, "Response: %s\n", out.String()) } _, _ = w.Write(out.Bytes()) }
go
func (s *Service) ServeSDK(w http.ResponseWriter, r *http.Request) { if r.Method != http.MethodPost { w.WriteHeader(http.StatusMethodNotAllowed) return } body, err := s.readAll(r.Body) _ = r.Body.Close() if err != nil { log.Printf("error reading body: %s", err) w.WriteHeader(http.StatusBadRequest) return } if Trace { fmt.Fprintf(os.Stderr, "Request: %s\n", string(body)) } ctx := &Context{ req: r, res: w, svc: s, Map: s.sdk[r.URL.Path], Context: context.Background(), } ctx.Map.WithLock(s.sm, ctx.mapSession) var res soap.HasFault var soapBody interface{} method, err := UnmarshalBody(ctx.Map.typeFunc, body) if err != nil { res = serverFault(err.Error()) } else { ctx.Header = method.Header if method.Name == "Fetch" { // Redirect any Fetch method calls to the PropertyCollector singleton method.This = ctx.Map.content().PropertyCollector } res = s.call(ctx, method) } if f := res.Fault(); f != nil { w.WriteHeader(http.StatusInternalServerError) // the generated method/*Body structs use the '*soap.Fault' type, // so we need our own Body type to use the modified '*soapFault' type. soapBody = struct { Fault *soapFault }{ &soapFault{ Code: f.Code, String: f.String, Detail: struct { Fault *faultDetail }{&faultDetail{f.Detail.Fault}}, }, } } else { w.WriteHeader(http.StatusOK) soapBody = &response{ctx.Map.Namespace, res} } var out bytes.Buffer fmt.Fprint(&out, xml.Header) e := xml.NewEncoder(&out) err = e.Encode(&soapEnvelope{ Enc: "http://schemas.xmlsoap.org/soap/encoding/", Env: "http://schemas.xmlsoap.org/soap/envelope/", XSD: "http://www.w3.org/2001/XMLSchema", XSI: "http://www.w3.org/2001/XMLSchema-instance", Body: soapBody, }) if err == nil { err = e.Flush() } if err != nil { log.Printf("error encoding %s response: %s", method.Name, err) return } if Trace { fmt.Fprintf(os.Stderr, "Response: %s\n", out.String()) } _, _ = w.Write(out.Bytes()) }
[ "func", "(", "s", "*", "Service", ")", "ServeSDK", "(", "w", "http", ".", "ResponseWriter", ",", "r", "*", "http", ".", "Request", ")", "{", "if", "r", ".", "Method", "!=", "http", ".", "MethodPost", "{", "w", ".", "WriteHeader", "(", "http", ".", "StatusMethodNotAllowed", ")", "\n", "return", "\n", "}", "\n\n", "body", ",", "err", ":=", "s", ".", "readAll", "(", "r", ".", "Body", ")", "\n", "_", "=", "r", ".", "Body", ".", "Close", "(", ")", "\n", "if", "err", "!=", "nil", "{", "log", ".", "Printf", "(", "\"", "\"", ",", "err", ")", "\n", "w", ".", "WriteHeader", "(", "http", ".", "StatusBadRequest", ")", "\n", "return", "\n", "}", "\n\n", "if", "Trace", "{", "fmt", ".", "Fprintf", "(", "os", ".", "Stderr", ",", "\"", "\\n", "\"", ",", "string", "(", "body", ")", ")", "\n", "}", "\n\n", "ctx", ":=", "&", "Context", "{", "req", ":", "r", ",", "res", ":", "w", ",", "svc", ":", "s", ",", "Map", ":", "s", ".", "sdk", "[", "r", ".", "URL", ".", "Path", "]", ",", "Context", ":", "context", ".", "Background", "(", ")", ",", "}", "\n", "ctx", ".", "Map", ".", "WithLock", "(", "s", ".", "sm", ",", "ctx", ".", "mapSession", ")", "\n\n", "var", "res", "soap", ".", "HasFault", "\n", "var", "soapBody", "interface", "{", "}", "\n\n", "method", ",", "err", ":=", "UnmarshalBody", "(", "ctx", ".", "Map", ".", "typeFunc", ",", "body", ")", "\n", "if", "err", "!=", "nil", "{", "res", "=", "serverFault", "(", "err", ".", "Error", "(", ")", ")", "\n", "}", "else", "{", "ctx", ".", "Header", "=", "method", ".", "Header", "\n", "if", "method", ".", "Name", "==", "\"", "\"", "{", "// Redirect any Fetch method calls to the PropertyCollector singleton", "method", ".", "This", "=", "ctx", ".", "Map", ".", "content", "(", ")", ".", "PropertyCollector", "\n", "}", "\n", "res", "=", "s", ".", "call", "(", "ctx", ",", "method", ")", "\n", "}", "\n\n", "if", "f", ":=", "res", ".", "Fault", "(", ")", ";", "f", "!=", "nil", "{", "w", ".", "WriteHeader", "(", "http", ".", "StatusInternalServerError", ")", "\n\n", "// the generated method/*Body structs use the '*soap.Fault' type,", "// so we need our own Body type to use the modified '*soapFault' type.", "soapBody", "=", "struct", "{", "Fault", "*", "soapFault", "\n", "}", "{", "&", "soapFault", "{", "Code", ":", "f", ".", "Code", ",", "String", ":", "f", ".", "String", ",", "Detail", ":", "struct", "{", "Fault", "*", "faultDetail", "\n", "}", "{", "&", "faultDetail", "{", "f", ".", "Detail", ".", "Fault", "}", "}", ",", "}", ",", "}", "\n", "}", "else", "{", "w", ".", "WriteHeader", "(", "http", ".", "StatusOK", ")", "\n\n", "soapBody", "=", "&", "response", "{", "ctx", ".", "Map", ".", "Namespace", ",", "res", "}", "\n", "}", "\n\n", "var", "out", "bytes", ".", "Buffer", "\n\n", "fmt", ".", "Fprint", "(", "&", "out", ",", "xml", ".", "Header", ")", "\n", "e", ":=", "xml", ".", "NewEncoder", "(", "&", "out", ")", "\n", "err", "=", "e", ".", "Encode", "(", "&", "soapEnvelope", "{", "Enc", ":", "\"", "\"", ",", "Env", ":", "\"", "\"", ",", "XSD", ":", "\"", "\"", ",", "XSI", ":", "\"", "\"", ",", "Body", ":", "soapBody", ",", "}", ")", "\n", "if", "err", "==", "nil", "{", "err", "=", "e", ".", "Flush", "(", ")", "\n", "}", "\n\n", "if", "err", "!=", "nil", "{", "log", ".", "Printf", "(", "\"", "\"", ",", "method", ".", "Name", ",", "err", ")", "\n", "return", "\n", "}", "\n\n", "if", "Trace", "{", "fmt", ".", "Fprintf", "(", "os", ".", "Stderr", ",", "\"", "\\n", "\"", ",", "out", ".", "String", "(", ")", ")", "\n", "}", "\n\n", "_", ",", "_", "=", "w", ".", "Write", "(", "out", ".", "Bytes", "(", ")", ")", "\n", "}" ]
// ServeSDK implements the http.Handler interface
[ "ServeSDK", "implements", "the", "http", ".", "Handler", "interface" ]
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/simulator/simulator.go#L386-L476
train
vmware/govmomi
simulator/simulator.go
defaultIP
func defaultIP(addr *net.TCPAddr) string { if !addr.IP.IsUnspecified() { return addr.IP.String() } nics, err := net.Interfaces() if err != nil { return addr.IP.String() } for _, nic := range nics { if nic.Name == "docker0" || strings.HasPrefix(nic.Name, "vmnet") { continue } addrs, aerr := nic.Addrs() if aerr != nil { continue } for _, addr := range addrs { if ip, ok := addr.(*net.IPNet); ok && !ip.IP.IsLoopback() { if ip.IP.To4() != nil { return ip.IP.String() } } } } return addr.IP.String() }
go
func defaultIP(addr *net.TCPAddr) string { if !addr.IP.IsUnspecified() { return addr.IP.String() } nics, err := net.Interfaces() if err != nil { return addr.IP.String() } for _, nic := range nics { if nic.Name == "docker0" || strings.HasPrefix(nic.Name, "vmnet") { continue } addrs, aerr := nic.Addrs() if aerr != nil { continue } for _, addr := range addrs { if ip, ok := addr.(*net.IPNet); ok && !ip.IP.IsLoopback() { if ip.IP.To4() != nil { return ip.IP.String() } } } } return addr.IP.String() }
[ "func", "defaultIP", "(", "addr", "*", "net", ".", "TCPAddr", ")", "string", "{", "if", "!", "addr", ".", "IP", ".", "IsUnspecified", "(", ")", "{", "return", "addr", ".", "IP", ".", "String", "(", ")", "\n", "}", "\n\n", "nics", ",", "err", ":=", "net", ".", "Interfaces", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "addr", ".", "IP", ".", "String", "(", ")", "\n", "}", "\n\n", "for", "_", ",", "nic", ":=", "range", "nics", "{", "if", "nic", ".", "Name", "==", "\"", "\"", "||", "strings", ".", "HasPrefix", "(", "nic", ".", "Name", ",", "\"", "\"", ")", "{", "continue", "\n", "}", "\n", "addrs", ",", "aerr", ":=", "nic", ".", "Addrs", "(", ")", "\n", "if", "aerr", "!=", "nil", "{", "continue", "\n", "}", "\n", "for", "_", ",", "addr", ":=", "range", "addrs", "{", "if", "ip", ",", "ok", ":=", "addr", ".", "(", "*", "net", ".", "IPNet", ")", ";", "ok", "&&", "!", "ip", ".", "IP", ".", "IsLoopback", "(", ")", "{", "if", "ip", ".", "IP", ".", "To4", "(", ")", "!=", "nil", "{", "return", "ip", ".", "IP", ".", "String", "(", ")", "\n", "}", "\n", "}", "\n", "}", "\n", "}", "\n\n", "return", "addr", ".", "IP", ".", "String", "(", ")", "\n", "}" ]
// defaultIP returns addr.IP if specified, otherwise attempts to find a non-loopback ipv4 IP
[ "defaultIP", "returns", "addr", ".", "IP", "if", "specified", "otherwise", "attempts", "to", "find", "a", "non", "-", "loopback", "ipv4", "IP" ]
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/simulator/simulator.go#L561-L589
train
vmware/govmomi
simulator/simulator.go
NewServer
func (s *Service) NewServer() *Server { s.RegisterSDK(Map) mux := s.ServeMux vim := Map.Path + "/vimService" s.sdk[vim] = s.sdk[vim25.Path] mux.HandleFunc(vim, s.ServeSDK) mux.HandleFunc(Map.Path+"/vimServiceVersions.xml", s.ServiceVersions) mux.HandleFunc(folderPrefix, s.ServeDatastore) mux.HandleFunc(nfcPrefix, ServeNFC) mux.HandleFunc("/about", s.About) ts := internal.NewUnstartedServer(mux, s.Listen) addr := ts.Listener.Addr().(*net.TCPAddr) port := strconv.Itoa(addr.Port) u := &url.URL{ Scheme: "http", Host: net.JoinHostPort(defaultIP(addr), port), Path: Map.Path, } if s.TLS != nil { u.Scheme += "s" } // Redirect clients to this http server, rather than HostSystem.Name Map.SessionManager().ServiceHostName = u.Host // Add vcsim config to OptionManager for use by SDK handlers (see lookup/simulator for example) m := Map.OptionManager() m.Setting = append(m.Setting, &types.OptionValue{ Key: "vcsim.server.url", Value: u.String(), }, ) u.User = url.UserPassword("user", "pass") if s.TLS != nil { ts.TLS = s.TLS ts.TLS.ClientAuth = tls.RequestClientCert // Used by SessionManager.LoginExtensionByCertificate Map.SessionManager().TLSCert = func() string { return base64.StdEncoding.EncodeToString(ts.TLS.Certificates[0].Certificate[0]) } ts.StartTLS() } else { ts.Start() } return &Server{ Server: ts, URL: u, } }
go
func (s *Service) NewServer() *Server { s.RegisterSDK(Map) mux := s.ServeMux vim := Map.Path + "/vimService" s.sdk[vim] = s.sdk[vim25.Path] mux.HandleFunc(vim, s.ServeSDK) mux.HandleFunc(Map.Path+"/vimServiceVersions.xml", s.ServiceVersions) mux.HandleFunc(folderPrefix, s.ServeDatastore) mux.HandleFunc(nfcPrefix, ServeNFC) mux.HandleFunc("/about", s.About) ts := internal.NewUnstartedServer(mux, s.Listen) addr := ts.Listener.Addr().(*net.TCPAddr) port := strconv.Itoa(addr.Port) u := &url.URL{ Scheme: "http", Host: net.JoinHostPort(defaultIP(addr), port), Path: Map.Path, } if s.TLS != nil { u.Scheme += "s" } // Redirect clients to this http server, rather than HostSystem.Name Map.SessionManager().ServiceHostName = u.Host // Add vcsim config to OptionManager for use by SDK handlers (see lookup/simulator for example) m := Map.OptionManager() m.Setting = append(m.Setting, &types.OptionValue{ Key: "vcsim.server.url", Value: u.String(), }, ) u.User = url.UserPassword("user", "pass") if s.TLS != nil { ts.TLS = s.TLS ts.TLS.ClientAuth = tls.RequestClientCert // Used by SessionManager.LoginExtensionByCertificate Map.SessionManager().TLSCert = func() string { return base64.StdEncoding.EncodeToString(ts.TLS.Certificates[0].Certificate[0]) } ts.StartTLS() } else { ts.Start() } return &Server{ Server: ts, URL: u, } }
[ "func", "(", "s", "*", "Service", ")", "NewServer", "(", ")", "*", "Server", "{", "s", ".", "RegisterSDK", "(", "Map", ")", "\n\n", "mux", ":=", "s", ".", "ServeMux", "\n", "vim", ":=", "Map", ".", "Path", "+", "\"", "\"", "\n", "s", ".", "sdk", "[", "vim", "]", "=", "s", ".", "sdk", "[", "vim25", ".", "Path", "]", "\n", "mux", ".", "HandleFunc", "(", "vim", ",", "s", ".", "ServeSDK", ")", "\n", "mux", ".", "HandleFunc", "(", "Map", ".", "Path", "+", "\"", "\"", ",", "s", ".", "ServiceVersions", ")", "\n", "mux", ".", "HandleFunc", "(", "folderPrefix", ",", "s", ".", "ServeDatastore", ")", "\n", "mux", ".", "HandleFunc", "(", "nfcPrefix", ",", "ServeNFC", ")", "\n", "mux", ".", "HandleFunc", "(", "\"", "\"", ",", "s", ".", "About", ")", "\n\n", "ts", ":=", "internal", ".", "NewUnstartedServer", "(", "mux", ",", "s", ".", "Listen", ")", "\n", "addr", ":=", "ts", ".", "Listener", ".", "Addr", "(", ")", ".", "(", "*", "net", ".", "TCPAddr", ")", "\n", "port", ":=", "strconv", ".", "Itoa", "(", "addr", ".", "Port", ")", "\n", "u", ":=", "&", "url", ".", "URL", "{", "Scheme", ":", "\"", "\"", ",", "Host", ":", "net", ".", "JoinHostPort", "(", "defaultIP", "(", "addr", ")", ",", "port", ")", ",", "Path", ":", "Map", ".", "Path", ",", "}", "\n", "if", "s", ".", "TLS", "!=", "nil", "{", "u", ".", "Scheme", "+=", "\"", "\"", "\n", "}", "\n\n", "// Redirect clients to this http server, rather than HostSystem.Name", "Map", ".", "SessionManager", "(", ")", ".", "ServiceHostName", "=", "u", ".", "Host", "\n\n", "// Add vcsim config to OptionManager for use by SDK handlers (see lookup/simulator for example)", "m", ":=", "Map", ".", "OptionManager", "(", ")", "\n", "m", ".", "Setting", "=", "append", "(", "m", ".", "Setting", ",", "&", "types", ".", "OptionValue", "{", "Key", ":", "\"", "\"", ",", "Value", ":", "u", ".", "String", "(", ")", ",", "}", ",", ")", "\n\n", "u", ".", "User", "=", "url", ".", "UserPassword", "(", "\"", "\"", ",", "\"", "\"", ")", "\n\n", "if", "s", ".", "TLS", "!=", "nil", "{", "ts", ".", "TLS", "=", "s", ".", "TLS", "\n", "ts", ".", "TLS", ".", "ClientAuth", "=", "tls", ".", "RequestClientCert", "// Used by SessionManager.LoginExtensionByCertificate", "\n", "Map", ".", "SessionManager", "(", ")", ".", "TLSCert", "=", "func", "(", ")", "string", "{", "return", "base64", ".", "StdEncoding", ".", "EncodeToString", "(", "ts", ".", "TLS", ".", "Certificates", "[", "0", "]", ".", "Certificate", "[", "0", "]", ")", "\n", "}", "\n", "ts", ".", "StartTLS", "(", ")", "\n", "}", "else", "{", "ts", ".", "Start", "(", ")", "\n", "}", "\n\n", "return", "&", "Server", "{", "Server", ":", "ts", ",", "URL", ":", "u", ",", "}", "\n", "}" ]
// NewServer returns an http Server instance for the given service
[ "NewServer", "returns", "an", "http", "Server", "instance", "for", "the", "given", "service" ]
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/simulator/simulator.go#L592-L645
train
vmware/govmomi
simulator/simulator.go
Certificate
func (s *Server) Certificate() *x509.Certificate { // By default httptest.StartTLS uses http/internal.LocalhostCert, which we can access here: cert, _ := x509.ParseCertificate(s.TLS.Certificates[0].Certificate[0]) return cert }
go
func (s *Server) Certificate() *x509.Certificate { // By default httptest.StartTLS uses http/internal.LocalhostCert, which we can access here: cert, _ := x509.ParseCertificate(s.TLS.Certificates[0].Certificate[0]) return cert }
[ "func", "(", "s", "*", "Server", ")", "Certificate", "(", ")", "*", "x509", ".", "Certificate", "{", "// By default httptest.StartTLS uses http/internal.LocalhostCert, which we can access here:", "cert", ",", "_", ":=", "x509", ".", "ParseCertificate", "(", "s", ".", "TLS", ".", "Certificates", "[", "0", "]", ".", "Certificate", "[", "0", "]", ")", "\n", "return", "cert", "\n", "}" ]
// Certificate returns the TLS certificate for the Server if started with TLS enabled. // This method will panic if TLS is not enabled for the server.
[ "Certificate", "returns", "the", "TLS", "certificate", "for", "the", "Server", "if", "started", "with", "TLS", "enabled", ".", "This", "method", "will", "panic", "if", "TLS", "is", "not", "enabled", "for", "the", "server", "." ]
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/simulator/simulator.go#L649-L653
train
vmware/govmomi
simulator/simulator.go
proxy
func (s *Server) proxy(w http.ResponseWriter, r *http.Request) { if r.Method != http.MethodConnect { http.Error(w, "", http.StatusMethodNotAllowed) return } dst, err := net.Dial("tcp", s.URL.Host) if err != nil { http.Error(w, err.Error(), http.StatusBadGateway) return } w.WriteHeader(http.StatusOK) src, _, err := w.(http.Hijacker).Hijack() if err != nil { http.Error(w, err.Error(), http.StatusBadRequest) return } go io.Copy(src, dst) go func() { _, _ = io.Copy(dst, src) _ = dst.Close() _ = src.Close() }() }
go
func (s *Server) proxy(w http.ResponseWriter, r *http.Request) { if r.Method != http.MethodConnect { http.Error(w, "", http.StatusMethodNotAllowed) return } dst, err := net.Dial("tcp", s.URL.Host) if err != nil { http.Error(w, err.Error(), http.StatusBadGateway) return } w.WriteHeader(http.StatusOK) src, _, err := w.(http.Hijacker).Hijack() if err != nil { http.Error(w, err.Error(), http.StatusBadRequest) return } go io.Copy(src, dst) go func() { _, _ = io.Copy(dst, src) _ = dst.Close() _ = src.Close() }() }
[ "func", "(", "s", "*", "Server", ")", "proxy", "(", "w", "http", ".", "ResponseWriter", ",", "r", "*", "http", ".", "Request", ")", "{", "if", "r", ".", "Method", "!=", "http", ".", "MethodConnect", "{", "http", ".", "Error", "(", "w", ",", "\"", "\"", ",", "http", ".", "StatusMethodNotAllowed", ")", "\n", "return", "\n", "}", "\n\n", "dst", ",", "err", ":=", "net", ".", "Dial", "(", "\"", "\"", ",", "s", ".", "URL", ".", "Host", ")", "\n", "if", "err", "!=", "nil", "{", "http", ".", "Error", "(", "w", ",", "err", ".", "Error", "(", ")", ",", "http", ".", "StatusBadGateway", ")", "\n", "return", "\n", "}", "\n", "w", ".", "WriteHeader", "(", "http", ".", "StatusOK", ")", "\n\n", "src", ",", "_", ",", "err", ":=", "w", ".", "(", "http", ".", "Hijacker", ")", ".", "Hijack", "(", ")", "\n", "if", "err", "!=", "nil", "{", "http", ".", "Error", "(", "w", ",", "err", ".", "Error", "(", ")", ",", "http", ".", "StatusBadRequest", ")", "\n", "return", "\n", "}", "\n\n", "go", "io", ".", "Copy", "(", "src", ",", "dst", ")", "\n", "go", "func", "(", ")", "{", "_", ",", "_", "=", "io", ".", "Copy", "(", "dst", ",", "src", ")", "\n", "_", "=", "dst", ".", "Close", "(", ")", "\n", "_", "=", "src", ".", "Close", "(", ")", "\n", "}", "(", ")", "\n", "}" ]
// proxy tunnels SDK requests
[ "proxy", "tunnels", "SDK", "requests" ]
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/simulator/simulator.go#L681-L706
train
vmware/govmomi
simulator/simulator.go
StartTunnel
func (s *Server) StartTunnel() error { tunnel := &http.Server{ Addr: fmt.Sprintf("%s:%d", s.URL.Hostname(), s.Tunnel), Handler: http.HandlerFunc(s.proxy), } l, err := net.Listen("tcp", tunnel.Addr) if err != nil { return err } if s.Tunnel == 0 { s.Tunnel = l.Addr().(*net.TCPAddr).Port } // Set client proxy port (defaults to vCenter host port 80 in real life) q := s.URL.Query() q.Set("GOVMOMI_TUNNEL_PROXY_PORT", strconv.Itoa(s.Tunnel)) s.URL.RawQuery = q.Encode() go tunnel.Serve(l) return nil }
go
func (s *Server) StartTunnel() error { tunnel := &http.Server{ Addr: fmt.Sprintf("%s:%d", s.URL.Hostname(), s.Tunnel), Handler: http.HandlerFunc(s.proxy), } l, err := net.Listen("tcp", tunnel.Addr) if err != nil { return err } if s.Tunnel == 0 { s.Tunnel = l.Addr().(*net.TCPAddr).Port } // Set client proxy port (defaults to vCenter host port 80 in real life) q := s.URL.Query() q.Set("GOVMOMI_TUNNEL_PROXY_PORT", strconv.Itoa(s.Tunnel)) s.URL.RawQuery = q.Encode() go tunnel.Serve(l) return nil }
[ "func", "(", "s", "*", "Server", ")", "StartTunnel", "(", ")", "error", "{", "tunnel", ":=", "&", "http", ".", "Server", "{", "Addr", ":", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "s", ".", "URL", ".", "Hostname", "(", ")", ",", "s", ".", "Tunnel", ")", ",", "Handler", ":", "http", ".", "HandlerFunc", "(", "s", ".", "proxy", ")", ",", "}", "\n\n", "l", ",", "err", ":=", "net", ".", "Listen", "(", "\"", "\"", ",", "tunnel", ".", "Addr", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "if", "s", ".", "Tunnel", "==", "0", "{", "s", ".", "Tunnel", "=", "l", ".", "Addr", "(", ")", ".", "(", "*", "net", ".", "TCPAddr", ")", ".", "Port", "\n", "}", "\n\n", "// Set client proxy port (defaults to vCenter host port 80 in real life)", "q", ":=", "s", ".", "URL", ".", "Query", "(", ")", "\n", "q", ".", "Set", "(", "\"", "\"", ",", "strconv", ".", "Itoa", "(", "s", ".", "Tunnel", ")", ")", "\n", "s", ".", "URL", ".", "RawQuery", "=", "q", ".", "Encode", "(", ")", "\n\n", "go", "tunnel", ".", "Serve", "(", "l", ")", "\n\n", "return", "nil", "\n", "}" ]
// StartTunnel runs an HTTP proxy for tunneling SDK requests that require TLS client certificate authentication.
[ "StartTunnel", "runs", "an", "HTTP", "proxy", "for", "tunneling", "SDK", "requests", "that", "require", "TLS", "client", "certificate", "authentication", "." ]
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/simulator/simulator.go#L709-L732
train
vmware/govmomi
simulator/simulator.go
UnmarshalBody
func UnmarshalBody(typeFunc func(string) (reflect.Type, bool), data []byte) (*Method, error) { body := &Element{typeFunc: typeFunc} req := soap.Envelope{ Header: &soap.Header{ Security: new(Element), }, Body: body, } err := xml.Unmarshal(data, &req) if err != nil { return nil, fmt.Errorf("xml.Unmarshal: %s", err) } var start xml.StartElement var ok bool decoder := body.decoder() for { tok, derr := decoder.Token() if derr != nil { return nil, fmt.Errorf("decoding: %s", derr) } if start, ok = tok.(xml.StartElement); ok { break } } if !ok { return nil, fmt.Errorf("decoding: method token not found") } kind := start.Name.Local rtype, ok := typeFunc(kind) if !ok { return nil, fmt.Errorf("no vmomi type defined for '%s'", kind) } val := reflect.New(rtype).Interface() err = decoder.DecodeElement(val, &start) if err != nil { return nil, fmt.Errorf("decoding %s: %s", kind, err) } method := &Method{Name: kind, Header: *req.Header, Body: val} field := reflect.ValueOf(val).Elem().FieldByName("This") method.This = field.Interface().(types.ManagedObjectReference) return method, nil }
go
func UnmarshalBody(typeFunc func(string) (reflect.Type, bool), data []byte) (*Method, error) { body := &Element{typeFunc: typeFunc} req := soap.Envelope{ Header: &soap.Header{ Security: new(Element), }, Body: body, } err := xml.Unmarshal(data, &req) if err != nil { return nil, fmt.Errorf("xml.Unmarshal: %s", err) } var start xml.StartElement var ok bool decoder := body.decoder() for { tok, derr := decoder.Token() if derr != nil { return nil, fmt.Errorf("decoding: %s", derr) } if start, ok = tok.(xml.StartElement); ok { break } } if !ok { return nil, fmt.Errorf("decoding: method token not found") } kind := start.Name.Local rtype, ok := typeFunc(kind) if !ok { return nil, fmt.Errorf("no vmomi type defined for '%s'", kind) } val := reflect.New(rtype).Interface() err = decoder.DecodeElement(val, &start) if err != nil { return nil, fmt.Errorf("decoding %s: %s", kind, err) } method := &Method{Name: kind, Header: *req.Header, Body: val} field := reflect.ValueOf(val).Elem().FieldByName("This") method.This = field.Interface().(types.ManagedObjectReference) return method, nil }
[ "func", "UnmarshalBody", "(", "typeFunc", "func", "(", "string", ")", "(", "reflect", ".", "Type", ",", "bool", ")", ",", "data", "[", "]", "byte", ")", "(", "*", "Method", ",", "error", ")", "{", "body", ":=", "&", "Element", "{", "typeFunc", ":", "typeFunc", "}", "\n", "req", ":=", "soap", ".", "Envelope", "{", "Header", ":", "&", "soap", ".", "Header", "{", "Security", ":", "new", "(", "Element", ")", ",", "}", ",", "Body", ":", "body", ",", "}", "\n\n", "err", ":=", "xml", ".", "Unmarshal", "(", "data", ",", "&", "req", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n\n", "var", "start", "xml", ".", "StartElement", "\n", "var", "ok", "bool", "\n", "decoder", ":=", "body", ".", "decoder", "(", ")", "\n\n", "for", "{", "tok", ",", "derr", ":=", "decoder", ".", "Token", "(", ")", "\n", "if", "derr", "!=", "nil", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "derr", ")", "\n", "}", "\n", "if", "start", ",", "ok", "=", "tok", ".", "(", "xml", ".", "StartElement", ")", ";", "ok", "{", "break", "\n", "}", "\n", "}", "\n\n", "if", "!", "ok", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n\n", "kind", ":=", "start", ".", "Name", ".", "Local", "\n", "rtype", ",", "ok", ":=", "typeFunc", "(", "kind", ")", "\n", "if", "!", "ok", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "kind", ")", "\n", "}", "\n\n", "val", ":=", "reflect", ".", "New", "(", "rtype", ")", ".", "Interface", "(", ")", "\n\n", "err", "=", "decoder", ".", "DecodeElement", "(", "val", ",", "&", "start", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "kind", ",", "err", ")", "\n", "}", "\n\n", "method", ":=", "&", "Method", "{", "Name", ":", "kind", ",", "Header", ":", "*", "req", ".", "Header", ",", "Body", ":", "val", "}", "\n\n", "field", ":=", "reflect", ".", "ValueOf", "(", "val", ")", ".", "Elem", "(", ")", ".", "FieldByName", "(", "\"", "\"", ")", "\n\n", "method", ".", "This", "=", "field", ".", "Interface", "(", ")", ".", "(", "types", ".", "ManagedObjectReference", ")", "\n\n", "return", "method", ",", "nil", "\n", "}" ]
// UnmarshalBody extracts the Body from a soap.Envelope and unmarshals to the corresponding govmomi type
[ "UnmarshalBody", "extracts", "the", "Body", "from", "a", "soap", ".", "Envelope", "and", "unmarshals", "to", "the", "corresponding", "govmomi", "type" ]
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/simulator/simulator.go#L786-L838
train
vmware/govmomi
govc/host/autostart/info.go
vmPaths
func (r *infoResult) vmPaths() (map[string]string, error) { ctx := context.TODO() paths := make(map[string]string) for _, info := range r.mhas.Config.PowerInfo { mes, err := mo.Ancestors(ctx, r.client, r.client.ServiceContent.PropertyCollector, info.Key) if err != nil { return nil, err } path := "" for _, me := range mes { // Skip root entity in building inventory path. if me.Parent == nil { continue } path += "/" + me.Name } paths[info.Key.Value] = path } return paths, nil }
go
func (r *infoResult) vmPaths() (map[string]string, error) { ctx := context.TODO() paths := make(map[string]string) for _, info := range r.mhas.Config.PowerInfo { mes, err := mo.Ancestors(ctx, r.client, r.client.ServiceContent.PropertyCollector, info.Key) if err != nil { return nil, err } path := "" for _, me := range mes { // Skip root entity in building inventory path. if me.Parent == nil { continue } path += "/" + me.Name } paths[info.Key.Value] = path } return paths, nil }
[ "func", "(", "r", "*", "infoResult", ")", "vmPaths", "(", ")", "(", "map", "[", "string", "]", "string", ",", "error", ")", "{", "ctx", ":=", "context", ".", "TODO", "(", ")", "\n", "paths", ":=", "make", "(", "map", "[", "string", "]", "string", ")", "\n", "for", "_", ",", "info", ":=", "range", "r", ".", "mhas", ".", "Config", ".", "PowerInfo", "{", "mes", ",", "err", ":=", "mo", ".", "Ancestors", "(", "ctx", ",", "r", ".", "client", ",", "r", ".", "client", ".", "ServiceContent", ".", "PropertyCollector", ",", "info", ".", "Key", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "path", ":=", "\"", "\"", "\n", "for", "_", ",", "me", ":=", "range", "mes", "{", "// Skip root entity in building inventory path.", "if", "me", ".", "Parent", "==", "nil", "{", "continue", "\n", "}", "\n", "path", "+=", "\"", "\"", "+", "me", ".", "Name", "\n", "}", "\n\n", "paths", "[", "info", ".", "Key", ".", "Value", "]", "=", "path", "\n", "}", "\n\n", "return", "paths", ",", "nil", "\n", "}" ]
// vmPaths resolves the paths for the VMs in the result.
[ "vmPaths", "resolves", "the", "paths", "for", "the", "VMs", "in", "the", "result", "." ]
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/govc/host/autostart/info.go#L86-L108
train
vmware/govmomi
simulator/custom_fields_manager.go
entitiesFieldRemove
func entitiesFieldRemove(field types.CustomFieldDef) { entities := Map.All(field.ManagedObjectType) for _, e := range entities { entity := e.Entity() Map.WithLock(entity, func() { aFields := entity.AvailableField for i, aField := range aFields { if aField.Key == field.Key { entity.AvailableField = append(aFields[:i], aFields[i+1:]...) break } } values := e.Entity().Value for i, value := range values { if value.(*types.CustomFieldStringValue).Key == field.Key { entity.Value = append(values[:i], values[i+1:]...) break } } cValues := e.Entity().CustomValue for i, cValue := range cValues { if cValue.(*types.CustomFieldStringValue).Key == field.Key { entity.CustomValue = append(cValues[:i], cValues[i+1:]...) break } } }) } }
go
func entitiesFieldRemove(field types.CustomFieldDef) { entities := Map.All(field.ManagedObjectType) for _, e := range entities { entity := e.Entity() Map.WithLock(entity, func() { aFields := entity.AvailableField for i, aField := range aFields { if aField.Key == field.Key { entity.AvailableField = append(aFields[:i], aFields[i+1:]...) break } } values := e.Entity().Value for i, value := range values { if value.(*types.CustomFieldStringValue).Key == field.Key { entity.Value = append(values[:i], values[i+1:]...) break } } cValues := e.Entity().CustomValue for i, cValue := range cValues { if cValue.(*types.CustomFieldStringValue).Key == field.Key { entity.CustomValue = append(cValues[:i], cValues[i+1:]...) break } } }) } }
[ "func", "entitiesFieldRemove", "(", "field", "types", ".", "CustomFieldDef", ")", "{", "entities", ":=", "Map", ".", "All", "(", "field", ".", "ManagedObjectType", ")", "\n", "for", "_", ",", "e", ":=", "range", "entities", "{", "entity", ":=", "e", ".", "Entity", "(", ")", "\n", "Map", ".", "WithLock", "(", "entity", ",", "func", "(", ")", "{", "aFields", ":=", "entity", ".", "AvailableField", "\n", "for", "i", ",", "aField", ":=", "range", "aFields", "{", "if", "aField", ".", "Key", "==", "field", ".", "Key", "{", "entity", ".", "AvailableField", "=", "append", "(", "aFields", "[", ":", "i", "]", ",", "aFields", "[", "i", "+", "1", ":", "]", "...", ")", "\n", "break", "\n", "}", "\n", "}", "\n\n", "values", ":=", "e", ".", "Entity", "(", ")", ".", "Value", "\n", "for", "i", ",", "value", ":=", "range", "values", "{", "if", "value", ".", "(", "*", "types", ".", "CustomFieldStringValue", ")", ".", "Key", "==", "field", ".", "Key", "{", "entity", ".", "Value", "=", "append", "(", "values", "[", ":", "i", "]", ",", "values", "[", "i", "+", "1", ":", "]", "...", ")", "\n", "break", "\n", "}", "\n", "}", "\n\n", "cValues", ":=", "e", ".", "Entity", "(", ")", ".", "CustomValue", "\n", "for", "i", ",", "cValue", ":=", "range", "cValues", "{", "if", "cValue", ".", "(", "*", "types", ".", "CustomFieldStringValue", ")", ".", "Key", "==", "field", ".", "Key", "{", "entity", ".", "CustomValue", "=", "append", "(", "cValues", "[", ":", "i", "]", ",", "cValues", "[", "i", "+", "1", ":", "]", "...", ")", "\n", "break", "\n", "}", "\n", "}", "\n", "}", ")", "\n", "}", "\n", "}" ]
// Iterates through all entities of passed field type; // Removes found field from their custom field properties.
[ "Iterates", "through", "all", "entities", "of", "passed", "field", "type", ";", "Removes", "found", "field", "from", "their", "custom", "field", "properties", "." ]
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/simulator/custom_fields_manager.go#L41-L71
train
vmware/govmomi
simulator/custom_fields_manager.go
entitiesFieldRename
func entitiesFieldRename(field types.CustomFieldDef) { entities := Map.All(field.ManagedObjectType) for _, e := range entities { entity := e.Entity() Map.WithLock(entity, func() { aFields := entity.AvailableField for i, aField := range aFields { if aField.Key == field.Key { aFields[i].Name = field.Name break } } }) } }
go
func entitiesFieldRename(field types.CustomFieldDef) { entities := Map.All(field.ManagedObjectType) for _, e := range entities { entity := e.Entity() Map.WithLock(entity, func() { aFields := entity.AvailableField for i, aField := range aFields { if aField.Key == field.Key { aFields[i].Name = field.Name break } } }) } }
[ "func", "entitiesFieldRename", "(", "field", "types", ".", "CustomFieldDef", ")", "{", "entities", ":=", "Map", ".", "All", "(", "field", ".", "ManagedObjectType", ")", "\n", "for", "_", ",", "e", ":=", "range", "entities", "{", "entity", ":=", "e", ".", "Entity", "(", ")", "\n", "Map", ".", "WithLock", "(", "entity", ",", "func", "(", ")", "{", "aFields", ":=", "entity", ".", "AvailableField", "\n", "for", "i", ",", "aField", ":=", "range", "aFields", "{", "if", "aField", ".", "Key", "==", "field", ".", "Key", "{", "aFields", "[", "i", "]", ".", "Name", "=", "field", ".", "Name", "\n", "break", "\n", "}", "\n", "}", "\n", "}", ")", "\n", "}", "\n", "}" ]
// Iterates through all entities of passed field type; // Renames found field in entity's AvailableField property.
[ "Iterates", "through", "all", "entities", "of", "passed", "field", "type", ";", "Renames", "found", "field", "in", "entity", "s", "AvailableField", "property", "." ]
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/simulator/custom_fields_manager.go#L75-L89
train
vmware/govmomi
toolbox/hgfs/archive.go
Stat
func (*ArchiveHandler) Stat(u *url.URL) (os.FileInfo, error) { switch u.Query().Get("format") { case "", "tar", "tgz": // ok default: log.Printf("unknown archive format: %q", u) return nil, vix.Error(vix.InvalidArg) } return &archive{ name: u.Path, size: math.MaxInt64, }, nil }
go
func (*ArchiveHandler) Stat(u *url.URL) (os.FileInfo, error) { switch u.Query().Get("format") { case "", "tar", "tgz": // ok default: log.Printf("unknown archive format: %q", u) return nil, vix.Error(vix.InvalidArg) } return &archive{ name: u.Path, size: math.MaxInt64, }, nil }
[ "func", "(", "*", "ArchiveHandler", ")", "Stat", "(", "u", "*", "url", ".", "URL", ")", "(", "os", ".", "FileInfo", ",", "error", ")", "{", "switch", "u", ".", "Query", "(", ")", ".", "Get", "(", "\"", "\"", ")", "{", "case", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ":", "// ok", "default", ":", "log", ".", "Printf", "(", "\"", "\"", ",", "u", ")", "\n", "return", "nil", ",", "vix", ".", "Error", "(", "vix", ".", "InvalidArg", ")", "\n", "}", "\n\n", "return", "&", "archive", "{", "name", ":", "u", ".", "Path", ",", "size", ":", "math", ".", "MaxInt64", ",", "}", ",", "nil", "\n", "}" ]
// Stat implements FileHandler.Stat
[ "Stat", "implements", "FileHandler", ".", "Stat" ]
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/toolbox/hgfs/archive.go#L56-L69
train
vmware/govmomi
toolbox/hgfs/archive.go
Open
func (h *ArchiveHandler) Open(u *url.URL, mode int32) (File, error) { switch mode { case OpenModeReadOnly: return h.newArchiveFromGuest(u) case OpenModeWriteOnly: return h.newArchiveToGuest(u) default: return nil, os.ErrNotExist } }
go
func (h *ArchiveHandler) Open(u *url.URL, mode int32) (File, error) { switch mode { case OpenModeReadOnly: return h.newArchiveFromGuest(u) case OpenModeWriteOnly: return h.newArchiveToGuest(u) default: return nil, os.ErrNotExist } }
[ "func", "(", "h", "*", "ArchiveHandler", ")", "Open", "(", "u", "*", "url", ".", "URL", ",", "mode", "int32", ")", "(", "File", ",", "error", ")", "{", "switch", "mode", "{", "case", "OpenModeReadOnly", ":", "return", "h", ".", "newArchiveFromGuest", "(", "u", ")", "\n", "case", "OpenModeWriteOnly", ":", "return", "h", ".", "newArchiveToGuest", "(", "u", ")", "\n", "default", ":", "return", "nil", ",", "os", ".", "ErrNotExist", "\n", "}", "\n", "}" ]
// Open implements FileHandler.Open
[ "Open", "implements", "FileHandler", ".", "Open" ]
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/toolbox/hgfs/archive.go#L72-L81
train
vmware/govmomi
toolbox/hgfs/archive.go
newArchiveFromGuest
func (h *ArchiveHandler) newArchiveFromGuest(u *url.URL) (File, error) { r, w := io.Pipe() a := &archive{ name: u.Path, done: r.Close, Reader: r, Writer: w, } var z io.Writer = w var c io.Closer = ioutil.NopCloser(nil) switch u.Query().Get("format") { case "tgz": gz := gzip.NewWriter(w) z = gz c = gz } tw := tar.NewWriter(z) go func() { err := h.Write(u, tw) _ = tw.Close() _ = c.Close() if gzipTrailer { _, _ = w.Write(gzipHeader) } _ = w.CloseWithError(err) }() return a, nil }
go
func (h *ArchiveHandler) newArchiveFromGuest(u *url.URL) (File, error) { r, w := io.Pipe() a := &archive{ name: u.Path, done: r.Close, Reader: r, Writer: w, } var z io.Writer = w var c io.Closer = ioutil.NopCloser(nil) switch u.Query().Get("format") { case "tgz": gz := gzip.NewWriter(w) z = gz c = gz } tw := tar.NewWriter(z) go func() { err := h.Write(u, tw) _ = tw.Close() _ = c.Close() if gzipTrailer { _, _ = w.Write(gzipHeader) } _ = w.CloseWithError(err) }() return a, nil }
[ "func", "(", "h", "*", "ArchiveHandler", ")", "newArchiveFromGuest", "(", "u", "*", "url", ".", "URL", ")", "(", "File", ",", "error", ")", "{", "r", ",", "w", ":=", "io", ".", "Pipe", "(", ")", "\n\n", "a", ":=", "&", "archive", "{", "name", ":", "u", ".", "Path", ",", "done", ":", "r", ".", "Close", ",", "Reader", ":", "r", ",", "Writer", ":", "w", ",", "}", "\n\n", "var", "z", "io", ".", "Writer", "=", "w", "\n", "var", "c", "io", ".", "Closer", "=", "ioutil", ".", "NopCloser", "(", "nil", ")", "\n\n", "switch", "u", ".", "Query", "(", ")", ".", "Get", "(", "\"", "\"", ")", "{", "case", "\"", "\"", ":", "gz", ":=", "gzip", ".", "NewWriter", "(", "w", ")", "\n", "z", "=", "gz", "\n", "c", "=", "gz", "\n", "}", "\n\n", "tw", ":=", "tar", ".", "NewWriter", "(", "z", ")", "\n\n", "go", "func", "(", ")", "{", "err", ":=", "h", ".", "Write", "(", "u", ",", "tw", ")", "\n\n", "_", "=", "tw", ".", "Close", "(", ")", "\n", "_", "=", "c", ".", "Close", "(", ")", "\n", "if", "gzipTrailer", "{", "_", ",", "_", "=", "w", ".", "Write", "(", "gzipHeader", ")", "\n", "}", "\n", "_", "=", "w", ".", "CloseWithError", "(", "err", ")", "\n", "}", "(", ")", "\n\n", "return", "a", ",", "nil", "\n", "}" ]
// newArchiveFromGuest returns an hgfs.File implementation to read a directory as a gzip'd tar.
[ "newArchiveFromGuest", "returns", "an", "hgfs", ".", "File", "implementation", "to", "read", "a", "directory", "as", "a", "gzip", "d", "tar", "." ]
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/toolbox/hgfs/archive.go#L131-L165
train
vmware/govmomi
toolbox/hgfs/archive.go
newArchiveToGuest
func (h *ArchiveHandler) newArchiveToGuest(u *url.URL) (File, error) { r, w := io.Pipe() buf := bufio.NewReader(r) a := &archive{ name: u.Path, Reader: buf, Writer: w, } var cerr error var wg sync.WaitGroup a.done = func() error { _ = w.Close() // We need to wait for unpack to finish to complete its work // and to propagate the error if any to Close. wg.Wait() return cerr } wg.Add(1) go func() { defer wg.Done() c := func() error { // Drain the pipe of tar trailer data (two null blocks) if cerr == nil { _, _ = io.Copy(ioutil.Discard, a.Reader) } return nil } header, _ := buf.Peek(len(gzipHeader)) if bytes.Equal(header, gzipHeader) { gz, err := gzip.NewReader(a.Reader) if err != nil { _ = r.CloseWithError(err) cerr = err return } c = gz.Close a.Reader = gz } tr := tar.NewReader(a.Reader) cerr = h.Read(u, tr) _ = c() _ = r.CloseWithError(cerr) }() return a, nil }
go
func (h *ArchiveHandler) newArchiveToGuest(u *url.URL) (File, error) { r, w := io.Pipe() buf := bufio.NewReader(r) a := &archive{ name: u.Path, Reader: buf, Writer: w, } var cerr error var wg sync.WaitGroup a.done = func() error { _ = w.Close() // We need to wait for unpack to finish to complete its work // and to propagate the error if any to Close. wg.Wait() return cerr } wg.Add(1) go func() { defer wg.Done() c := func() error { // Drain the pipe of tar trailer data (two null blocks) if cerr == nil { _, _ = io.Copy(ioutil.Discard, a.Reader) } return nil } header, _ := buf.Peek(len(gzipHeader)) if bytes.Equal(header, gzipHeader) { gz, err := gzip.NewReader(a.Reader) if err != nil { _ = r.CloseWithError(err) cerr = err return } c = gz.Close a.Reader = gz } tr := tar.NewReader(a.Reader) cerr = h.Read(u, tr) _ = c() _ = r.CloseWithError(cerr) }() return a, nil }
[ "func", "(", "h", "*", "ArchiveHandler", ")", "newArchiveToGuest", "(", "u", "*", "url", ".", "URL", ")", "(", "File", ",", "error", ")", "{", "r", ",", "w", ":=", "io", ".", "Pipe", "(", ")", "\n\n", "buf", ":=", "bufio", ".", "NewReader", "(", "r", ")", "\n\n", "a", ":=", "&", "archive", "{", "name", ":", "u", ".", "Path", ",", "Reader", ":", "buf", ",", "Writer", ":", "w", ",", "}", "\n\n", "var", "cerr", "error", "\n", "var", "wg", "sync", ".", "WaitGroup", "\n\n", "a", ".", "done", "=", "func", "(", ")", "error", "{", "_", "=", "w", ".", "Close", "(", ")", "\n", "// We need to wait for unpack to finish to complete its work", "// and to propagate the error if any to Close.", "wg", ".", "Wait", "(", ")", "\n", "return", "cerr", "\n", "}", "\n\n", "wg", ".", "Add", "(", "1", ")", "\n", "go", "func", "(", ")", "{", "defer", "wg", ".", "Done", "(", ")", "\n\n", "c", ":=", "func", "(", ")", "error", "{", "// Drain the pipe of tar trailer data (two null blocks)", "if", "cerr", "==", "nil", "{", "_", ",", "_", "=", "io", ".", "Copy", "(", "ioutil", ".", "Discard", ",", "a", ".", "Reader", ")", "\n", "}", "\n", "return", "nil", "\n", "}", "\n\n", "header", ",", "_", ":=", "buf", ".", "Peek", "(", "len", "(", "gzipHeader", ")", ")", "\n\n", "if", "bytes", ".", "Equal", "(", "header", ",", "gzipHeader", ")", "{", "gz", ",", "err", ":=", "gzip", ".", "NewReader", "(", "a", ".", "Reader", ")", "\n", "if", "err", "!=", "nil", "{", "_", "=", "r", ".", "CloseWithError", "(", "err", ")", "\n", "cerr", "=", "err", "\n", "return", "\n", "}", "\n\n", "c", "=", "gz", ".", "Close", "\n", "a", ".", "Reader", "=", "gz", "\n", "}", "\n\n", "tr", ":=", "tar", ".", "NewReader", "(", "a", ".", "Reader", ")", "\n\n", "cerr", "=", "h", ".", "Read", "(", "u", ",", "tr", ")", "\n\n", "_", "=", "c", "(", ")", "\n", "_", "=", "r", ".", "CloseWithError", "(", "cerr", ")", "\n", "}", "(", ")", "\n\n", "return", "a", ",", "nil", "\n", "}" ]
// newArchiveToGuest returns an hgfs.File implementation to expand a gzip'd tar into a directory.
[ "newArchiveToGuest", "returns", "an", "hgfs", ".", "File", "implementation", "to", "expand", "a", "gzip", "d", "tar", "into", "a", "directory", "." ]
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/toolbox/hgfs/archive.go#L168-L225
train
vmware/govmomi
toolbox/hgfs/archive.go
archiveRead
func archiveRead(u *url.URL, tr *tar.Reader) error { for { header, err := tr.Next() if err != nil { if err == io.EOF { return nil } return err } name := filepath.Join(u.Path, header.Name) mode := os.FileMode(header.Mode) switch header.Typeflag { case tar.TypeDir: err = os.MkdirAll(name, mode) case tar.TypeReg: _ = os.MkdirAll(filepath.Dir(name), 0750) var f *os.File f, err = os.OpenFile(name, os.O_CREATE|os.O_RDWR|os.O_TRUNC, mode) if err == nil { _, cerr := io.Copy(f, tr) err = f.Close() if cerr != nil { err = cerr } } case tar.TypeSymlink: err = os.Symlink(header.Linkname, name) } // TODO: Uid/Gid may not be meaningful here without some mapping. // The other option to consider would be making use of the guest auth user ID. // os.Lchown(name, header.Uid, header.Gid) if err != nil { return err } } }
go
func archiveRead(u *url.URL, tr *tar.Reader) error { for { header, err := tr.Next() if err != nil { if err == io.EOF { return nil } return err } name := filepath.Join(u.Path, header.Name) mode := os.FileMode(header.Mode) switch header.Typeflag { case tar.TypeDir: err = os.MkdirAll(name, mode) case tar.TypeReg: _ = os.MkdirAll(filepath.Dir(name), 0750) var f *os.File f, err = os.OpenFile(name, os.O_CREATE|os.O_RDWR|os.O_TRUNC, mode) if err == nil { _, cerr := io.Copy(f, tr) err = f.Close() if cerr != nil { err = cerr } } case tar.TypeSymlink: err = os.Symlink(header.Linkname, name) } // TODO: Uid/Gid may not be meaningful here without some mapping. // The other option to consider would be making use of the guest auth user ID. // os.Lchown(name, header.Uid, header.Gid) if err != nil { return err } } }
[ "func", "archiveRead", "(", "u", "*", "url", ".", "URL", ",", "tr", "*", "tar", ".", "Reader", ")", "error", "{", "for", "{", "header", ",", "err", ":=", "tr", ".", "Next", "(", ")", "\n", "if", "err", "!=", "nil", "{", "if", "err", "==", "io", ".", "EOF", "{", "return", "nil", "\n", "}", "\n", "return", "err", "\n", "}", "\n\n", "name", ":=", "filepath", ".", "Join", "(", "u", ".", "Path", ",", "header", ".", "Name", ")", "\n", "mode", ":=", "os", ".", "FileMode", "(", "header", ".", "Mode", ")", "\n\n", "switch", "header", ".", "Typeflag", "{", "case", "tar", ".", "TypeDir", ":", "err", "=", "os", ".", "MkdirAll", "(", "name", ",", "mode", ")", "\n", "case", "tar", ".", "TypeReg", ":", "_", "=", "os", ".", "MkdirAll", "(", "filepath", ".", "Dir", "(", "name", ")", ",", "0750", ")", "\n\n", "var", "f", "*", "os", ".", "File", "\n\n", "f", ",", "err", "=", "os", ".", "OpenFile", "(", "name", ",", "os", ".", "O_CREATE", "|", "os", ".", "O_RDWR", "|", "os", ".", "O_TRUNC", ",", "mode", ")", "\n", "if", "err", "==", "nil", "{", "_", ",", "cerr", ":=", "io", ".", "Copy", "(", "f", ",", "tr", ")", "\n", "err", "=", "f", ".", "Close", "(", ")", "\n", "if", "cerr", "!=", "nil", "{", "err", "=", "cerr", "\n", "}", "\n", "}", "\n", "case", "tar", ".", "TypeSymlink", ":", "err", "=", "os", ".", "Symlink", "(", "header", ".", "Linkname", ",", "name", ")", "\n", "}", "\n\n", "// TODO: Uid/Gid may not be meaningful here without some mapping.", "// The other option to consider would be making use of the guest auth user ID.", "// os.Lchown(name, header.Uid, header.Gid)", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "}", "\n", "}" ]
// archiveRead writes the contents of the given tar.Reader to the given directory.
[ "archiveRead", "writes", "the", "contents", "of", "the", "given", "tar", ".", "Reader", "to", "the", "given", "directory", "." ]
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/toolbox/hgfs/archive.go#L232-L273
train
vmware/govmomi
toolbox/hgfs/archive.go
archiveWrite
func archiveWrite(u *url.URL, tw *tar.Writer) error { info, err := os.Stat(u.Path) if err != nil { return err } // Note that the VMX will trim any trailing slash. For example: // "/foo/bar/?prefix=bar/" will end up here as "/foo/bar/?prefix=bar" // Escape to avoid this: "/for/bar/?prefix=bar%2F" prefix := u.Query().Get("prefix") dir := u.Path f := func(file string, fi os.FileInfo, err error) error { if err != nil { return filepath.SkipDir } name := strings.TrimPrefix(file, dir) name = strings.TrimPrefix(name, "/") if name == "" { return nil // this is u.Path itself (which may or may not have a trailing "/") } if prefix != "" { name = prefix + name } header, _ := tar.FileInfoHeader(fi, name) header.Name = name if header.Typeflag == tar.TypeDir { header.Name += "/" } var f *os.File if header.Typeflag == tar.TypeReg && fi.Size() != 0 { f, err = os.Open(filepath.Clean(file)) if err != nil { if os.IsPermission(err) { return nil } return err } } _ = tw.WriteHeader(header) if f != nil { _, err = io.Copy(tw, f) _ = f.Close() } return err } if info.IsDir() { return filepath.Walk(u.Path, f) } dir = filepath.Dir(dir) return f(u.Path, info, nil) }
go
func archiveWrite(u *url.URL, tw *tar.Writer) error { info, err := os.Stat(u.Path) if err != nil { return err } // Note that the VMX will trim any trailing slash. For example: // "/foo/bar/?prefix=bar/" will end up here as "/foo/bar/?prefix=bar" // Escape to avoid this: "/for/bar/?prefix=bar%2F" prefix := u.Query().Get("prefix") dir := u.Path f := func(file string, fi os.FileInfo, err error) error { if err != nil { return filepath.SkipDir } name := strings.TrimPrefix(file, dir) name = strings.TrimPrefix(name, "/") if name == "" { return nil // this is u.Path itself (which may or may not have a trailing "/") } if prefix != "" { name = prefix + name } header, _ := tar.FileInfoHeader(fi, name) header.Name = name if header.Typeflag == tar.TypeDir { header.Name += "/" } var f *os.File if header.Typeflag == tar.TypeReg && fi.Size() != 0 { f, err = os.Open(filepath.Clean(file)) if err != nil { if os.IsPermission(err) { return nil } return err } } _ = tw.WriteHeader(header) if f != nil { _, err = io.Copy(tw, f) _ = f.Close() } return err } if info.IsDir() { return filepath.Walk(u.Path, f) } dir = filepath.Dir(dir) return f(u.Path, info, nil) }
[ "func", "archiveWrite", "(", "u", "*", "url", ".", "URL", ",", "tw", "*", "tar", ".", "Writer", ")", "error", "{", "info", ",", "err", ":=", "os", ".", "Stat", "(", "u", ".", "Path", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "// Note that the VMX will trim any trailing slash. For example:", "// \"/foo/bar/?prefix=bar/\" will end up here as \"/foo/bar/?prefix=bar\"", "// Escape to avoid this: \"/for/bar/?prefix=bar%2F\"", "prefix", ":=", "u", ".", "Query", "(", ")", ".", "Get", "(", "\"", "\"", ")", "\n\n", "dir", ":=", "u", ".", "Path", "\n\n", "f", ":=", "func", "(", "file", "string", ",", "fi", "os", ".", "FileInfo", ",", "err", "error", ")", "error", "{", "if", "err", "!=", "nil", "{", "return", "filepath", ".", "SkipDir", "\n", "}", "\n\n", "name", ":=", "strings", ".", "TrimPrefix", "(", "file", ",", "dir", ")", "\n", "name", "=", "strings", ".", "TrimPrefix", "(", "name", ",", "\"", "\"", ")", "\n\n", "if", "name", "==", "\"", "\"", "{", "return", "nil", "// this is u.Path itself (which may or may not have a trailing \"/\")", "\n", "}", "\n\n", "if", "prefix", "!=", "\"", "\"", "{", "name", "=", "prefix", "+", "name", "\n", "}", "\n\n", "header", ",", "_", ":=", "tar", ".", "FileInfoHeader", "(", "fi", ",", "name", ")", "\n\n", "header", ".", "Name", "=", "name", "\n\n", "if", "header", ".", "Typeflag", "==", "tar", ".", "TypeDir", "{", "header", ".", "Name", "+=", "\"", "\"", "\n", "}", "\n\n", "var", "f", "*", "os", ".", "File", "\n\n", "if", "header", ".", "Typeflag", "==", "tar", ".", "TypeReg", "&&", "fi", ".", "Size", "(", ")", "!=", "0", "{", "f", ",", "err", "=", "os", ".", "Open", "(", "filepath", ".", "Clean", "(", "file", ")", ")", "\n", "if", "err", "!=", "nil", "{", "if", "os", ".", "IsPermission", "(", "err", ")", "{", "return", "nil", "\n", "}", "\n", "return", "err", "\n", "}", "\n", "}", "\n\n", "_", "=", "tw", ".", "WriteHeader", "(", "header", ")", "\n\n", "if", "f", "!=", "nil", "{", "_", ",", "err", "=", "io", ".", "Copy", "(", "tw", ",", "f", ")", "\n", "_", "=", "f", ".", "Close", "(", ")", "\n", "}", "\n\n", "return", "err", "\n", "}", "\n\n", "if", "info", ".", "IsDir", "(", ")", "{", "return", "filepath", ".", "Walk", "(", "u", ".", "Path", ",", "f", ")", "\n", "}", "\n\n", "dir", "=", "filepath", ".", "Dir", "(", "dir", ")", "\n\n", "return", "f", "(", "u", ".", "Path", ",", "info", ",", "nil", ")", "\n", "}" ]
// archiveWrite writes the contents of the given source directory to the given tar.Writer.
[ "archiveWrite", "writes", "the", "contents", "of", "the", "given", "source", "directory", "to", "the", "given", "tar", ".", "Writer", "." ]
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/toolbox/hgfs/archive.go#L276-L342
train
vmware/govmomi
property/filter.go
MatchProperty
func (f Filter) MatchProperty(prop types.DynamicProperty) bool { match, ok := f[prop.Name] if !ok { return false } if match == prop.Val { return true } ptype := reflect.TypeOf(prop.Val) if strings.HasPrefix(ptype.Name(), "ArrayOf") { pval := reflect.ValueOf(prop.Val).Field(0) for i := 0; i < pval.Len(); i++ { prop.Val = pval.Index(i).Interface() if f.MatchProperty(prop) { return true } } return false } if reflect.TypeOf(match) != ptype { s, ok := match.(string) if !ok { return false } // convert if we can switch prop.Val.(type) { case bool: match, _ = strconv.ParseBool(s) case int16: x, _ := strconv.ParseInt(s, 10, 16) match = int16(x) case int32: x, _ := strconv.ParseInt(s, 10, 32) match = int32(x) case int64: match, _ = strconv.ParseInt(s, 10, 64) case float32: x, _ := strconv.ParseFloat(s, 32) match = float32(x) case float64: match, _ = strconv.ParseFloat(s, 64) case fmt.Stringer: prop.Val = prop.Val.(fmt.Stringer).String() default: if ptype.Kind() != reflect.String { return false } // An enum type we can convert to a string type prop.Val = reflect.ValueOf(prop.Val).String() } } switch pval := prop.Val.(type) { case string: s := match.(string) if s == "*" { return true // TODO: path.Match fails if s contains a '/' } m, _ := path.Match(s, pval) return m default: return reflect.DeepEqual(match, pval) } }
go
func (f Filter) MatchProperty(prop types.DynamicProperty) bool { match, ok := f[prop.Name] if !ok { return false } if match == prop.Val { return true } ptype := reflect.TypeOf(prop.Val) if strings.HasPrefix(ptype.Name(), "ArrayOf") { pval := reflect.ValueOf(prop.Val).Field(0) for i := 0; i < pval.Len(); i++ { prop.Val = pval.Index(i).Interface() if f.MatchProperty(prop) { return true } } return false } if reflect.TypeOf(match) != ptype { s, ok := match.(string) if !ok { return false } // convert if we can switch prop.Val.(type) { case bool: match, _ = strconv.ParseBool(s) case int16: x, _ := strconv.ParseInt(s, 10, 16) match = int16(x) case int32: x, _ := strconv.ParseInt(s, 10, 32) match = int32(x) case int64: match, _ = strconv.ParseInt(s, 10, 64) case float32: x, _ := strconv.ParseFloat(s, 32) match = float32(x) case float64: match, _ = strconv.ParseFloat(s, 64) case fmt.Stringer: prop.Val = prop.Val.(fmt.Stringer).String() default: if ptype.Kind() != reflect.String { return false } // An enum type we can convert to a string type prop.Val = reflect.ValueOf(prop.Val).String() } } switch pval := prop.Val.(type) { case string: s := match.(string) if s == "*" { return true // TODO: path.Match fails if s contains a '/' } m, _ := path.Match(s, pval) return m default: return reflect.DeepEqual(match, pval) } }
[ "func", "(", "f", "Filter", ")", "MatchProperty", "(", "prop", "types", ".", "DynamicProperty", ")", "bool", "{", "match", ",", "ok", ":=", "f", "[", "prop", ".", "Name", "]", "\n", "if", "!", "ok", "{", "return", "false", "\n", "}", "\n\n", "if", "match", "==", "prop", ".", "Val", "{", "return", "true", "\n", "}", "\n\n", "ptype", ":=", "reflect", ".", "TypeOf", "(", "prop", ".", "Val", ")", "\n\n", "if", "strings", ".", "HasPrefix", "(", "ptype", ".", "Name", "(", ")", ",", "\"", "\"", ")", "{", "pval", ":=", "reflect", ".", "ValueOf", "(", "prop", ".", "Val", ")", ".", "Field", "(", "0", ")", "\n\n", "for", "i", ":=", "0", ";", "i", "<", "pval", ".", "Len", "(", ")", ";", "i", "++", "{", "prop", ".", "Val", "=", "pval", ".", "Index", "(", "i", ")", ".", "Interface", "(", ")", "\n\n", "if", "f", ".", "MatchProperty", "(", "prop", ")", "{", "return", "true", "\n", "}", "\n", "}", "\n\n", "return", "false", "\n", "}", "\n\n", "if", "reflect", ".", "TypeOf", "(", "match", ")", "!=", "ptype", "{", "s", ",", "ok", ":=", "match", ".", "(", "string", ")", "\n", "if", "!", "ok", "{", "return", "false", "\n", "}", "\n\n", "// convert if we can", "switch", "prop", ".", "Val", ".", "(", "type", ")", "{", "case", "bool", ":", "match", ",", "_", "=", "strconv", ".", "ParseBool", "(", "s", ")", "\n", "case", "int16", ":", "x", ",", "_", ":=", "strconv", ".", "ParseInt", "(", "s", ",", "10", ",", "16", ")", "\n", "match", "=", "int16", "(", "x", ")", "\n", "case", "int32", ":", "x", ",", "_", ":=", "strconv", ".", "ParseInt", "(", "s", ",", "10", ",", "32", ")", "\n", "match", "=", "int32", "(", "x", ")", "\n", "case", "int64", ":", "match", ",", "_", "=", "strconv", ".", "ParseInt", "(", "s", ",", "10", ",", "64", ")", "\n", "case", "float32", ":", "x", ",", "_", ":=", "strconv", ".", "ParseFloat", "(", "s", ",", "32", ")", "\n", "match", "=", "float32", "(", "x", ")", "\n", "case", "float64", ":", "match", ",", "_", "=", "strconv", ".", "ParseFloat", "(", "s", ",", "64", ")", "\n", "case", "fmt", ".", "Stringer", ":", "prop", ".", "Val", "=", "prop", ".", "Val", ".", "(", "fmt", ".", "Stringer", ")", ".", "String", "(", ")", "\n", "default", ":", "if", "ptype", ".", "Kind", "(", ")", "!=", "reflect", ".", "String", "{", "return", "false", "\n", "}", "\n", "// An enum type we can convert to a string type", "prop", ".", "Val", "=", "reflect", ".", "ValueOf", "(", "prop", ".", "Val", ")", ".", "String", "(", ")", "\n", "}", "\n", "}", "\n\n", "switch", "pval", ":=", "prop", ".", "Val", ".", "(", "type", ")", "{", "case", "string", ":", "s", ":=", "match", ".", "(", "string", ")", "\n", "if", "s", "==", "\"", "\"", "{", "return", "true", "// TODO: path.Match fails if s contains a '/'", "\n", "}", "\n", "m", ",", "_", ":=", "path", ".", "Match", "(", "s", ",", "pval", ")", "\n", "return", "m", "\n", "default", ":", "return", "reflect", ".", "DeepEqual", "(", "match", ",", "pval", ")", "\n", "}", "\n", "}" ]
// MatchProperty returns true if a Filter entry matches the given prop.
[ "MatchProperty", "returns", "true", "if", "a", "Filter", "entry", "matches", "the", "given", "prop", "." ]
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/property/filter.go#L44-L115
train
vmware/govmomi
property/filter.go
MatchPropertyList
func (f Filter) MatchPropertyList(props []types.DynamicProperty) bool { for _, p := range props { if !f.MatchProperty(p) { return false } } return len(f) == len(props) // false if a property such as VM "guest" is unset }
go
func (f Filter) MatchPropertyList(props []types.DynamicProperty) bool { for _, p := range props { if !f.MatchProperty(p) { return false } } return len(f) == len(props) // false if a property such as VM "guest" is unset }
[ "func", "(", "f", "Filter", ")", "MatchPropertyList", "(", "props", "[", "]", "types", ".", "DynamicProperty", ")", "bool", "{", "for", "_", ",", "p", ":=", "range", "props", "{", "if", "!", "f", ".", "MatchProperty", "(", "p", ")", "{", "return", "false", "\n", "}", "\n", "}", "\n\n", "return", "len", "(", "f", ")", "==", "len", "(", "props", ")", "// false if a property such as VM \"guest\" is unset", "\n", "}" ]
// MatchPropertyList returns true if all given props match the Filter.
[ "MatchPropertyList", "returns", "true", "if", "all", "given", "props", "match", "the", "Filter", "." ]
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/property/filter.go#L118-L126
train
vmware/govmomi
property/filter.go
MatchObjectContent
func (f Filter) MatchObjectContent(objects []types.ObjectContent) []types.ManagedObjectReference { var refs []types.ManagedObjectReference for _, o := range objects { if f.MatchPropertyList(o.PropSet) { refs = append(refs, o.Obj) } } return refs }
go
func (f Filter) MatchObjectContent(objects []types.ObjectContent) []types.ManagedObjectReference { var refs []types.ManagedObjectReference for _, o := range objects { if f.MatchPropertyList(o.PropSet) { refs = append(refs, o.Obj) } } return refs }
[ "func", "(", "f", "Filter", ")", "MatchObjectContent", "(", "objects", "[", "]", "types", ".", "ObjectContent", ")", "[", "]", "types", ".", "ManagedObjectReference", "{", "var", "refs", "[", "]", "types", ".", "ManagedObjectReference", "\n\n", "for", "_", ",", "o", ":=", "range", "objects", "{", "if", "f", ".", "MatchPropertyList", "(", "o", ".", "PropSet", ")", "{", "refs", "=", "append", "(", "refs", ",", "o", ".", "Obj", ")", "\n", "}", "\n", "}", "\n\n", "return", "refs", "\n", "}" ]
// MatchObjectContent returns a list of ObjectContent.Obj where the ObjectContent.PropSet matches the Filter.
[ "MatchObjectContent", "returns", "a", "list", "of", "ObjectContent", ".", "Obj", "where", "the", "ObjectContent", ".", "PropSet", "matches", "the", "Filter", "." ]
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/property/filter.go#L129-L139
train
golang/lint
lint.go
Lint
func (l *Linter) Lint(filename string, src []byte) ([]Problem, error) { return l.LintFiles(map[string][]byte{filename: src}) }
go
func (l *Linter) Lint(filename string, src []byte) ([]Problem, error) { return l.LintFiles(map[string][]byte{filename: src}) }
[ "func", "(", "l", "*", "Linter", ")", "Lint", "(", "filename", "string", ",", "src", "[", "]", "byte", ")", "(", "[", "]", "Problem", ",", "error", ")", "{", "return", "l", ".", "LintFiles", "(", "map", "[", "string", "]", "[", "]", "byte", "{", "filename", ":", "src", "}", ")", "\n", "}" ]
// Lint lints src.
[ "Lint", "lints", "src", "." ]
959b441ac422379a43da2230f62be024250818b0
https://github.com/golang/lint/blob/959b441ac422379a43da2230f62be024250818b0/lint.go#L79-L81
train
golang/lint
lint.go
LintFiles
func (l *Linter) LintFiles(files map[string][]byte) ([]Problem, error) { pkg := &pkg{ fset: token.NewFileSet(), files: make(map[string]*file), } var pkgName string for filename, src := range files { if isGenerated(src) { continue // See issue #239 } f, err := parser.ParseFile(pkg.fset, filename, src, parser.ParseComments) if err != nil { return nil, err } if pkgName == "" { pkgName = f.Name.Name } else if f.Name.Name != pkgName { return nil, fmt.Errorf("%s is in package %s, not %s", filename, f.Name.Name, pkgName) } pkg.files[filename] = &file{ pkg: pkg, f: f, fset: pkg.fset, src: src, filename: filename, } } if len(pkg.files) == 0 { return nil, nil } return pkg.lint(), nil }
go
func (l *Linter) LintFiles(files map[string][]byte) ([]Problem, error) { pkg := &pkg{ fset: token.NewFileSet(), files: make(map[string]*file), } var pkgName string for filename, src := range files { if isGenerated(src) { continue // See issue #239 } f, err := parser.ParseFile(pkg.fset, filename, src, parser.ParseComments) if err != nil { return nil, err } if pkgName == "" { pkgName = f.Name.Name } else if f.Name.Name != pkgName { return nil, fmt.Errorf("%s is in package %s, not %s", filename, f.Name.Name, pkgName) } pkg.files[filename] = &file{ pkg: pkg, f: f, fset: pkg.fset, src: src, filename: filename, } } if len(pkg.files) == 0 { return nil, nil } return pkg.lint(), nil }
[ "func", "(", "l", "*", "Linter", ")", "LintFiles", "(", "files", "map", "[", "string", "]", "[", "]", "byte", ")", "(", "[", "]", "Problem", ",", "error", ")", "{", "pkg", ":=", "&", "pkg", "{", "fset", ":", "token", ".", "NewFileSet", "(", ")", ",", "files", ":", "make", "(", "map", "[", "string", "]", "*", "file", ")", ",", "}", "\n", "var", "pkgName", "string", "\n", "for", "filename", ",", "src", ":=", "range", "files", "{", "if", "isGenerated", "(", "src", ")", "{", "continue", "// See issue #239", "\n", "}", "\n", "f", ",", "err", ":=", "parser", ".", "ParseFile", "(", "pkg", ".", "fset", ",", "filename", ",", "src", ",", "parser", ".", "ParseComments", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "if", "pkgName", "==", "\"", "\"", "{", "pkgName", "=", "f", ".", "Name", ".", "Name", "\n", "}", "else", "if", "f", ".", "Name", ".", "Name", "!=", "pkgName", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "filename", ",", "f", ".", "Name", ".", "Name", ",", "pkgName", ")", "\n", "}", "\n", "pkg", ".", "files", "[", "filename", "]", "=", "&", "file", "{", "pkg", ":", "pkg", ",", "f", ":", "f", ",", "fset", ":", "pkg", ".", "fset", ",", "src", ":", "src", ",", "filename", ":", "filename", ",", "}", "\n", "}", "\n", "if", "len", "(", "pkg", ".", "files", ")", "==", "0", "{", "return", "nil", ",", "nil", "\n", "}", "\n", "return", "pkg", ".", "lint", "(", ")", ",", "nil", "\n", "}" ]
// LintFiles lints a set of files of a single package. // The argument is a map of filename to source.
[ "LintFiles", "lints", "a", "set", "of", "files", "of", "a", "single", "package", ".", "The", "argument", "is", "a", "map", "of", "filename", "to", "source", "." ]
959b441ac422379a43da2230f62be024250818b0
https://github.com/golang/lint/blob/959b441ac422379a43da2230f62be024250818b0/lint.go#L85-L116
train
golang/lint
lint.go
errorf
func (f *file) errorf(n ast.Node, confidence float64, args ...interface{}) *Problem { pos := f.fset.Position(n.Pos()) if pos.Filename == "" { pos.Filename = f.filename } return f.pkg.errorfAt(pos, confidence, args...) }
go
func (f *file) errorf(n ast.Node, confidence float64, args ...interface{}) *Problem { pos := f.fset.Position(n.Pos()) if pos.Filename == "" { pos.Filename = f.filename } return f.pkg.errorfAt(pos, confidence, args...) }
[ "func", "(", "f", "*", "file", ")", "errorf", "(", "n", "ast", ".", "Node", ",", "confidence", "float64", ",", "args", "...", "interface", "{", "}", ")", "*", "Problem", "{", "pos", ":=", "f", ".", "fset", ".", "Position", "(", "n", ".", "Pos", "(", ")", ")", "\n", "if", "pos", ".", "Filename", "==", "\"", "\"", "{", "pos", ".", "Filename", "=", "f", ".", "filename", "\n", "}", "\n", "return", "f", ".", "pkg", ".", "errorfAt", "(", "pos", ",", "confidence", ",", "args", "...", ")", "\n", "}" ]
// The variadic arguments may start with link and category types, // and must end with a format string and any arguments. // It returns the new Problem.
[ "The", "variadic", "arguments", "may", "start", "with", "link", "and", "category", "types", "and", "must", "end", "with", "a", "format", "string", "and", "any", "arguments", ".", "It", "returns", "the", "new", "Problem", "." ]
959b441ac422379a43da2230f62be024250818b0
https://github.com/golang/lint/blob/959b441ac422379a43da2230f62be024250818b0/lint.go#L222-L228
train
golang/lint
lint.go
scopeOf
func (p *pkg) scopeOf(id *ast.Ident) *types.Scope { var scope *types.Scope if obj := p.typesInfo.ObjectOf(id); obj != nil { scope = obj.Parent() } if scope == p.typesPkg.Scope() { // We were given a top-level identifier. // Use the file-level scope instead of the package-level scope. pos := id.Pos() for _, f := range p.files { if f.f.Pos() <= pos && pos < f.f.End() { scope = p.typesInfo.Scopes[f.f] break } } } return scope }
go
func (p *pkg) scopeOf(id *ast.Ident) *types.Scope { var scope *types.Scope if obj := p.typesInfo.ObjectOf(id); obj != nil { scope = obj.Parent() } if scope == p.typesPkg.Scope() { // We were given a top-level identifier. // Use the file-level scope instead of the package-level scope. pos := id.Pos() for _, f := range p.files { if f.f.Pos() <= pos && pos < f.f.End() { scope = p.typesInfo.Scopes[f.f] break } } } return scope }
[ "func", "(", "p", "*", "pkg", ")", "scopeOf", "(", "id", "*", "ast", ".", "Ident", ")", "*", "types", ".", "Scope", "{", "var", "scope", "*", "types", ".", "Scope", "\n", "if", "obj", ":=", "p", ".", "typesInfo", ".", "ObjectOf", "(", "id", ")", ";", "obj", "!=", "nil", "{", "scope", "=", "obj", ".", "Parent", "(", ")", "\n", "}", "\n", "if", "scope", "==", "p", ".", "typesPkg", ".", "Scope", "(", ")", "{", "// We were given a top-level identifier.", "// Use the file-level scope instead of the package-level scope.", "pos", ":=", "id", ".", "Pos", "(", ")", "\n", "for", "_", ",", "f", ":=", "range", "p", ".", "files", "{", "if", "f", ".", "f", ".", "Pos", "(", ")", "<=", "pos", "&&", "pos", "<", "f", ".", "f", ".", "End", "(", ")", "{", "scope", "=", "p", ".", "typesInfo", ".", "Scopes", "[", "f", ".", "f", "]", "\n", "break", "\n", "}", "\n", "}", "\n", "}", "\n", "return", "scope", "\n", "}" ]
// scopeOf returns the tightest scope encompassing id.
[ "scopeOf", "returns", "the", "tightest", "scope", "encompassing", "id", "." ]
959b441ac422379a43da2230f62be024250818b0
https://github.com/golang/lint/blob/959b441ac422379a43da2230f62be024250818b0/lint.go#L308-L325
train
golang/lint
lint.go
lintPackageComment
func (f *file) lintPackageComment() { if f.isTest() { return } const ref = styleGuideBase + "#package-comments" prefix := "Package " + f.f.Name.Name + " " // Look for a detached package comment. // First, scan for the last comment that occurs before the "package" keyword. var lastCG *ast.CommentGroup for _, cg := range f.f.Comments { if cg.Pos() > f.f.Package { // Gone past "package" keyword. break } lastCG = cg } if lastCG != nil && strings.HasPrefix(lastCG.Text(), prefix) { endPos := f.fset.Position(lastCG.End()) pkgPos := f.fset.Position(f.f.Package) if endPos.Line+1 < pkgPos.Line { // There isn't a great place to anchor this error; // the start of the blank lines between the doc and the package statement // is at least pointing at the location of the problem. pos := token.Position{ Filename: endPos.Filename, // Offset not set; it is non-trivial, and doesn't appear to be needed. Line: endPos.Line + 1, Column: 1, } f.pkg.errorfAt(pos, 0.9, link(ref), category("comments"), "package comment is detached; there should be no blank lines between it and the package statement") return } } if f.f.Doc == nil { f.errorf(f.f, 0.2, link(ref), category("comments"), "should have a package comment, unless it's in another file for this package") return } s := f.f.Doc.Text() if ts := strings.TrimLeft(s, " \t"); ts != s { f.errorf(f.f.Doc, 1, link(ref), category("comments"), "package comment should not have leading space") s = ts } // Only non-main packages need to keep to this form. if !f.pkg.main && !strings.HasPrefix(s, prefix) { f.errorf(f.f.Doc, 1, link(ref), category("comments"), `package comment should be of the form "%s..."`, prefix) } }
go
func (f *file) lintPackageComment() { if f.isTest() { return } const ref = styleGuideBase + "#package-comments" prefix := "Package " + f.f.Name.Name + " " // Look for a detached package comment. // First, scan for the last comment that occurs before the "package" keyword. var lastCG *ast.CommentGroup for _, cg := range f.f.Comments { if cg.Pos() > f.f.Package { // Gone past "package" keyword. break } lastCG = cg } if lastCG != nil && strings.HasPrefix(lastCG.Text(), prefix) { endPos := f.fset.Position(lastCG.End()) pkgPos := f.fset.Position(f.f.Package) if endPos.Line+1 < pkgPos.Line { // There isn't a great place to anchor this error; // the start of the blank lines between the doc and the package statement // is at least pointing at the location of the problem. pos := token.Position{ Filename: endPos.Filename, // Offset not set; it is non-trivial, and doesn't appear to be needed. Line: endPos.Line + 1, Column: 1, } f.pkg.errorfAt(pos, 0.9, link(ref), category("comments"), "package comment is detached; there should be no blank lines between it and the package statement") return } } if f.f.Doc == nil { f.errorf(f.f, 0.2, link(ref), category("comments"), "should have a package comment, unless it's in another file for this package") return } s := f.f.Doc.Text() if ts := strings.TrimLeft(s, " \t"); ts != s { f.errorf(f.f.Doc, 1, link(ref), category("comments"), "package comment should not have leading space") s = ts } // Only non-main packages need to keep to this form. if !f.pkg.main && !strings.HasPrefix(s, prefix) { f.errorf(f.f.Doc, 1, link(ref), category("comments"), `package comment should be of the form "%s..."`, prefix) } }
[ "func", "(", "f", "*", "file", ")", "lintPackageComment", "(", ")", "{", "if", "f", ".", "isTest", "(", ")", "{", "return", "\n", "}", "\n\n", "const", "ref", "=", "styleGuideBase", "+", "\"", "\"", "\n", "prefix", ":=", "\"", "\"", "+", "f", ".", "f", ".", "Name", ".", "Name", "+", "\"", "\"", "\n\n", "// Look for a detached package comment.", "// First, scan for the last comment that occurs before the \"package\" keyword.", "var", "lastCG", "*", "ast", ".", "CommentGroup", "\n", "for", "_", ",", "cg", ":=", "range", "f", ".", "f", ".", "Comments", "{", "if", "cg", ".", "Pos", "(", ")", ">", "f", ".", "f", ".", "Package", "{", "// Gone past \"package\" keyword.", "break", "\n", "}", "\n", "lastCG", "=", "cg", "\n", "}", "\n", "if", "lastCG", "!=", "nil", "&&", "strings", ".", "HasPrefix", "(", "lastCG", ".", "Text", "(", ")", ",", "prefix", ")", "{", "endPos", ":=", "f", ".", "fset", ".", "Position", "(", "lastCG", ".", "End", "(", ")", ")", "\n", "pkgPos", ":=", "f", ".", "fset", ".", "Position", "(", "f", ".", "f", ".", "Package", ")", "\n", "if", "endPos", ".", "Line", "+", "1", "<", "pkgPos", ".", "Line", "{", "// There isn't a great place to anchor this error;", "// the start of the blank lines between the doc and the package statement", "// is at least pointing at the location of the problem.", "pos", ":=", "token", ".", "Position", "{", "Filename", ":", "endPos", ".", "Filename", ",", "// Offset not set; it is non-trivial, and doesn't appear to be needed.", "Line", ":", "endPos", ".", "Line", "+", "1", ",", "Column", ":", "1", ",", "}", "\n", "f", ".", "pkg", ".", "errorfAt", "(", "pos", ",", "0.9", ",", "link", "(", "ref", ")", ",", "category", "(", "\"", "\"", ")", ",", "\"", "\"", ")", "\n", "return", "\n", "}", "\n", "}", "\n\n", "if", "f", ".", "f", ".", "Doc", "==", "nil", "{", "f", ".", "errorf", "(", "f", ".", "f", ",", "0.2", ",", "link", "(", "ref", ")", ",", "category", "(", "\"", "\"", ")", ",", "\"", "\"", ")", "\n", "return", "\n", "}", "\n", "s", ":=", "f", ".", "f", ".", "Doc", ".", "Text", "(", ")", "\n", "if", "ts", ":=", "strings", ".", "TrimLeft", "(", "s", ",", "\"", "\\t", "\"", ")", ";", "ts", "!=", "s", "{", "f", ".", "errorf", "(", "f", ".", "f", ".", "Doc", ",", "1", ",", "link", "(", "ref", ")", ",", "category", "(", "\"", "\"", ")", ",", "\"", "\"", ")", "\n", "s", "=", "ts", "\n", "}", "\n", "// Only non-main packages need to keep to this form.", "if", "!", "f", ".", "pkg", ".", "main", "&&", "!", "strings", ".", "HasPrefix", "(", "s", ",", "prefix", ")", "{", "f", ".", "errorf", "(", "f", ".", "f", ".", "Doc", ",", "1", ",", "link", "(", "ref", ")", ",", "category", "(", "\"", "\"", ")", ",", "`package comment should be of the form \"%s...\"`", ",", "prefix", ")", "\n", "}", "\n", "}" ]
// lintPackageComment checks package comments. It complains if // there is no package comment, or if it is not of the right form. // This has a notable false positive in that a package comment // could rightfully appear in a different file of the same package, // but that's not easy to fix since this linter is file-oriented.
[ "lintPackageComment", "checks", "package", "comments", ".", "It", "complains", "if", "there", "is", "no", "package", "comment", "or", "if", "it", "is", "not", "of", "the", "right", "form", ".", "This", "has", "a", "notable", "false", "positive", "in", "that", "a", "package", "comment", "could", "rightfully", "appear", "in", "a", "different", "file", "of", "the", "same", "package", "but", "that", "s", "not", "easy", "to", "fix", "since", "this", "linter", "is", "file", "-", "oriented", "." ]
959b441ac422379a43da2230f62be024250818b0
https://github.com/golang/lint/blob/959b441ac422379a43da2230f62be024250818b0/lint.go#L380-L429
train
golang/lint
lint.go
lintBlankImports
func (f *file) lintBlankImports() { // In package main and in tests, we don't complain about blank imports. if f.pkg.main || f.isTest() { return } // The first element of each contiguous group of blank imports should have // an explanatory comment of some kind. for i, imp := range f.f.Imports { pos := f.fset.Position(imp.Pos()) if !isBlank(imp.Name) { continue // Ignore non-blank imports. } if i > 0 { prev := f.f.Imports[i-1] prevPos := f.fset.Position(prev.Pos()) if isBlank(prev.Name) && prevPos.Line+1 == pos.Line { continue // A subsequent blank in a group. } } // This is the first blank import of a group. if imp.Doc == nil && imp.Comment == nil { ref := "" f.errorf(imp, 1, link(ref), category("imports"), "a blank import should be only in a main or test package, or have a comment justifying it") } } }
go
func (f *file) lintBlankImports() { // In package main and in tests, we don't complain about blank imports. if f.pkg.main || f.isTest() { return } // The first element of each contiguous group of blank imports should have // an explanatory comment of some kind. for i, imp := range f.f.Imports { pos := f.fset.Position(imp.Pos()) if !isBlank(imp.Name) { continue // Ignore non-blank imports. } if i > 0 { prev := f.f.Imports[i-1] prevPos := f.fset.Position(prev.Pos()) if isBlank(prev.Name) && prevPos.Line+1 == pos.Line { continue // A subsequent blank in a group. } } // This is the first blank import of a group. if imp.Doc == nil && imp.Comment == nil { ref := "" f.errorf(imp, 1, link(ref), category("imports"), "a blank import should be only in a main or test package, or have a comment justifying it") } } }
[ "func", "(", "f", "*", "file", ")", "lintBlankImports", "(", ")", "{", "// In package main and in tests, we don't complain about blank imports.", "if", "f", ".", "pkg", ".", "main", "||", "f", ".", "isTest", "(", ")", "{", "return", "\n", "}", "\n\n", "// The first element of each contiguous group of blank imports should have", "// an explanatory comment of some kind.", "for", "i", ",", "imp", ":=", "range", "f", ".", "f", ".", "Imports", "{", "pos", ":=", "f", ".", "fset", ".", "Position", "(", "imp", ".", "Pos", "(", ")", ")", "\n\n", "if", "!", "isBlank", "(", "imp", ".", "Name", ")", "{", "continue", "// Ignore non-blank imports.", "\n", "}", "\n", "if", "i", ">", "0", "{", "prev", ":=", "f", ".", "f", ".", "Imports", "[", "i", "-", "1", "]", "\n", "prevPos", ":=", "f", ".", "fset", ".", "Position", "(", "prev", ".", "Pos", "(", ")", ")", "\n", "if", "isBlank", "(", "prev", ".", "Name", ")", "&&", "prevPos", ".", "Line", "+", "1", "==", "pos", ".", "Line", "{", "continue", "// A subsequent blank in a group.", "\n", "}", "\n", "}", "\n\n", "// This is the first blank import of a group.", "if", "imp", ".", "Doc", "==", "nil", "&&", "imp", ".", "Comment", "==", "nil", "{", "ref", ":=", "\"", "\"", "\n", "f", ".", "errorf", "(", "imp", ",", "1", ",", "link", "(", "ref", ")", ",", "category", "(", "\"", "\"", ")", ",", "\"", "\"", ")", "\n", "}", "\n", "}", "\n", "}" ]
// lintBlankImports complains if a non-main package has blank imports that are // not documented.
[ "lintBlankImports", "complains", "if", "a", "non", "-", "main", "package", "has", "blank", "imports", "that", "are", "not", "documented", "." ]
959b441ac422379a43da2230f62be024250818b0
https://github.com/golang/lint/blob/959b441ac422379a43da2230f62be024250818b0/lint.go#L433-L461
train
golang/lint
lint.go
lintImports
func (f *file) lintImports() { for i, is := range f.f.Imports { _ = i if is.Name != nil && is.Name.Name == "." && !f.isTest() { f.errorf(is, 1, link(styleGuideBase+"#import-dot"), category("imports"), "should not use dot imports") } } }
go
func (f *file) lintImports() { for i, is := range f.f.Imports { _ = i if is.Name != nil && is.Name.Name == "." && !f.isTest() { f.errorf(is, 1, link(styleGuideBase+"#import-dot"), category("imports"), "should not use dot imports") } } }
[ "func", "(", "f", "*", "file", ")", "lintImports", "(", ")", "{", "for", "i", ",", "is", ":=", "range", "f", ".", "f", ".", "Imports", "{", "_", "=", "i", "\n", "if", "is", ".", "Name", "!=", "nil", "&&", "is", ".", "Name", ".", "Name", "==", "\"", "\"", "&&", "!", "f", ".", "isTest", "(", ")", "{", "f", ".", "errorf", "(", "is", ",", "1", ",", "link", "(", "styleGuideBase", "+", "\"", "\"", ")", ",", "category", "(", "\"", "\"", ")", ",", "\"", "\"", ")", "\n", "}", "\n\n", "}", "\n", "}" ]
// lintImports examines import blocks.
[ "lintImports", "examines", "import", "blocks", "." ]
959b441ac422379a43da2230f62be024250818b0
https://github.com/golang/lint/blob/959b441ac422379a43da2230f62be024250818b0/lint.go#L464-L472
train
golang/lint
lint.go
lintExported
func (f *file) lintExported() { if f.isTest() { return } var lastGen *ast.GenDecl // last GenDecl entered. // Set of GenDecls that have already had missing comments flagged. genDeclMissingComments := make(map[*ast.GenDecl]bool) f.walk(func(node ast.Node) bool { switch v := node.(type) { case *ast.GenDecl: if v.Tok == token.IMPORT { return false } // token.CONST, token.TYPE or token.VAR lastGen = v return true case *ast.FuncDecl: f.lintFuncDoc(v) if v.Recv == nil { // Only check for stutter on functions, not methods. // Method names are not used package-qualified. f.checkStutter(v.Name, "func") } // Don't proceed inside funcs. return false case *ast.TypeSpec: // inside a GenDecl, which usually has the doc doc := v.Doc if doc == nil { doc = lastGen.Doc } f.lintTypeDoc(v, doc) f.checkStutter(v.Name, "type") // Don't proceed inside types. return false case *ast.ValueSpec: f.lintValueSpecDoc(v, lastGen, genDeclMissingComments) return false } return true }) }
go
func (f *file) lintExported() { if f.isTest() { return } var lastGen *ast.GenDecl // last GenDecl entered. // Set of GenDecls that have already had missing comments flagged. genDeclMissingComments := make(map[*ast.GenDecl]bool) f.walk(func(node ast.Node) bool { switch v := node.(type) { case *ast.GenDecl: if v.Tok == token.IMPORT { return false } // token.CONST, token.TYPE or token.VAR lastGen = v return true case *ast.FuncDecl: f.lintFuncDoc(v) if v.Recv == nil { // Only check for stutter on functions, not methods. // Method names are not used package-qualified. f.checkStutter(v.Name, "func") } // Don't proceed inside funcs. return false case *ast.TypeSpec: // inside a GenDecl, which usually has the doc doc := v.Doc if doc == nil { doc = lastGen.Doc } f.lintTypeDoc(v, doc) f.checkStutter(v.Name, "type") // Don't proceed inside types. return false case *ast.ValueSpec: f.lintValueSpecDoc(v, lastGen, genDeclMissingComments) return false } return true }) }
[ "func", "(", "f", "*", "file", ")", "lintExported", "(", ")", "{", "if", "f", ".", "isTest", "(", ")", "{", "return", "\n", "}", "\n\n", "var", "lastGen", "*", "ast", ".", "GenDecl", "// last GenDecl entered.", "\n\n", "// Set of GenDecls that have already had missing comments flagged.", "genDeclMissingComments", ":=", "make", "(", "map", "[", "*", "ast", ".", "GenDecl", "]", "bool", ")", "\n\n", "f", ".", "walk", "(", "func", "(", "node", "ast", ".", "Node", ")", "bool", "{", "switch", "v", ":=", "node", ".", "(", "type", ")", "{", "case", "*", "ast", ".", "GenDecl", ":", "if", "v", ".", "Tok", "==", "token", ".", "IMPORT", "{", "return", "false", "\n", "}", "\n", "// token.CONST, token.TYPE or token.VAR", "lastGen", "=", "v", "\n", "return", "true", "\n", "case", "*", "ast", ".", "FuncDecl", ":", "f", ".", "lintFuncDoc", "(", "v", ")", "\n", "if", "v", ".", "Recv", "==", "nil", "{", "// Only check for stutter on functions, not methods.", "// Method names are not used package-qualified.", "f", ".", "checkStutter", "(", "v", ".", "Name", ",", "\"", "\"", ")", "\n", "}", "\n", "// Don't proceed inside funcs.", "return", "false", "\n", "case", "*", "ast", ".", "TypeSpec", ":", "// inside a GenDecl, which usually has the doc", "doc", ":=", "v", ".", "Doc", "\n", "if", "doc", "==", "nil", "{", "doc", "=", "lastGen", ".", "Doc", "\n", "}", "\n", "f", ".", "lintTypeDoc", "(", "v", ",", "doc", ")", "\n", "f", ".", "checkStutter", "(", "v", ".", "Name", ",", "\"", "\"", ")", "\n", "// Don't proceed inside types.", "return", "false", "\n", "case", "*", "ast", ".", "ValueSpec", ":", "f", ".", "lintValueSpecDoc", "(", "v", ",", "lastGen", ",", "genDeclMissingComments", ")", "\n", "return", "false", "\n", "}", "\n", "return", "true", "\n", "}", ")", "\n", "}" ]
// lintExported examines the exported names. // It complains if any required doc comments are missing, // or if they are not of the right form. The exact rules are in // lintFuncDoc, lintTypeDoc and lintValueSpecDoc; this function // also tracks the GenDecl structure being traversed to permit // doc comments for constants to be on top of the const block. // It also complains if the names stutter when combined with // the package name.
[ "lintExported", "examines", "the", "exported", "names", ".", "It", "complains", "if", "any", "required", "doc", "comments", "are", "missing", "or", "if", "they", "are", "not", "of", "the", "right", "form", ".", "The", "exact", "rules", "are", "in", "lintFuncDoc", "lintTypeDoc", "and", "lintValueSpecDoc", ";", "this", "function", "also", "tracks", "the", "GenDecl", "structure", "being", "traversed", "to", "permit", "doc", "comments", "for", "constants", "to", "be", "on", "top", "of", "the", "const", "block", ".", "It", "also", "complains", "if", "the", "names", "stutter", "when", "combined", "with", "the", "package", "name", "." ]
959b441ac422379a43da2230f62be024250818b0
https://github.com/golang/lint/blob/959b441ac422379a43da2230f62be024250818b0/lint.go#L484-L528
train
golang/lint
lint.go
lintTypeDoc
func (f *file) lintTypeDoc(t *ast.TypeSpec, doc *ast.CommentGroup) { if !ast.IsExported(t.Name.Name) { return } if doc == nil { f.errorf(t, 1, link(docCommentsLink), category("comments"), "exported type %v should have comment or be unexported", t.Name) return } s := doc.Text() articles := [...]string{"A", "An", "The"} for _, a := range articles { if strings.HasPrefix(s, a+" ") { s = s[len(a)+1:] break } } if !strings.HasPrefix(s, t.Name.Name+" ") { f.errorf(doc, 1, link(docCommentsLink), category("comments"), `comment on exported type %v should be of the form "%v ..." (with optional leading article)`, t.Name, t.Name) } }
go
func (f *file) lintTypeDoc(t *ast.TypeSpec, doc *ast.CommentGroup) { if !ast.IsExported(t.Name.Name) { return } if doc == nil { f.errorf(t, 1, link(docCommentsLink), category("comments"), "exported type %v should have comment or be unexported", t.Name) return } s := doc.Text() articles := [...]string{"A", "An", "The"} for _, a := range articles { if strings.HasPrefix(s, a+" ") { s = s[len(a)+1:] break } } if !strings.HasPrefix(s, t.Name.Name+" ") { f.errorf(doc, 1, link(docCommentsLink), category("comments"), `comment on exported type %v should be of the form "%v ..." (with optional leading article)`, t.Name, t.Name) } }
[ "func", "(", "f", "*", "file", ")", "lintTypeDoc", "(", "t", "*", "ast", ".", "TypeSpec", ",", "doc", "*", "ast", ".", "CommentGroup", ")", "{", "if", "!", "ast", ".", "IsExported", "(", "t", ".", "Name", ".", "Name", ")", "{", "return", "\n", "}", "\n", "if", "doc", "==", "nil", "{", "f", ".", "errorf", "(", "t", ",", "1", ",", "link", "(", "docCommentsLink", ")", ",", "category", "(", "\"", "\"", ")", ",", "\"", "\"", ",", "t", ".", "Name", ")", "\n", "return", "\n", "}", "\n\n", "s", ":=", "doc", ".", "Text", "(", ")", "\n", "articles", ":=", "[", "...", "]", "string", "{", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", "}", "\n", "for", "_", ",", "a", ":=", "range", "articles", "{", "if", "strings", ".", "HasPrefix", "(", "s", ",", "a", "+", "\"", "\"", ")", "{", "s", "=", "s", "[", "len", "(", "a", ")", "+", "1", ":", "]", "\n", "break", "\n", "}", "\n", "}", "\n", "if", "!", "strings", ".", "HasPrefix", "(", "s", ",", "t", ".", "Name", ".", "Name", "+", "\"", "\"", ")", "{", "f", ".", "errorf", "(", "doc", ",", "1", ",", "link", "(", "docCommentsLink", ")", ",", "category", "(", "\"", "\"", ")", ",", "`comment on exported type %v should be of the form \"%v ...\" (with optional leading article)`", ",", "t", ".", "Name", ",", "t", ".", "Name", ")", "\n", "}", "\n", "}" ]
// lintTypeDoc examines the doc comment on a type. // It complains if they are missing from an exported type, // or if they are not of the standard form.
[ "lintTypeDoc", "examines", "the", "doc", "comment", "on", "a", "type", ".", "It", "complains", "if", "they", "are", "missing", "from", "an", "exported", "type", "or", "if", "they", "are", "not", "of", "the", "standard", "form", "." ]
959b441ac422379a43da2230f62be024250818b0
https://github.com/golang/lint/blob/959b441ac422379a43da2230f62be024250818b0/lint.go#L815-L835
train
golang/lint
lint.go
lintVarDecls
func (f *file) lintVarDecls() { var lastGen *ast.GenDecl // last GenDecl entered. f.walk(func(node ast.Node) bool { switch v := node.(type) { case *ast.GenDecl: if v.Tok != token.CONST && v.Tok != token.VAR { return false } lastGen = v return true case *ast.ValueSpec: if lastGen.Tok == token.CONST { return false } if len(v.Names) > 1 || v.Type == nil || len(v.Values) == 0 { return false } rhs := v.Values[0] // An underscore var appears in a common idiom for compile-time interface satisfaction, // as in "var _ Interface = (*Concrete)(nil)". if isIdent(v.Names[0], "_") { return false } // If the RHS is a zero value, suggest dropping it. zero := false if lit, ok := rhs.(*ast.BasicLit); ok { zero = zeroLiteral[lit.Value] } else if isIdent(rhs, "nil") { zero = true } if zero { f.errorf(rhs, 0.9, category("zero-value"), "should drop = %s from declaration of var %s; it is the zero value", f.render(rhs), v.Names[0]) return false } lhsTyp := f.pkg.typeOf(v.Type) rhsTyp := f.pkg.typeOf(rhs) if !validType(lhsTyp) || !validType(rhsTyp) { // Type checking failed (often due to missing imports). return false } if !types.Identical(lhsTyp, rhsTyp) { // Assignment to a different type is not redundant. return false } // The next three conditions are for suppressing the warning in situations // where we were unable to typecheck. // If the LHS type is an interface, don't warn, since it is probably a // concrete type on the RHS. Note that our feeble lexical check here // will only pick up interface{} and other literal interface types; // that covers most of the cases we care to exclude right now. if _, ok := v.Type.(*ast.InterfaceType); ok { return false } // If the RHS is an untyped const, only warn if the LHS type is its default type. if defType, ok := f.isUntypedConst(rhs); ok && !isIdent(v.Type, defType) { return false } f.errorf(v.Type, 0.8, category("type-inference"), "should omit type %s from declaration of var %s; it will be inferred from the right-hand side", f.render(v.Type), v.Names[0]) return false } return true }) }
go
func (f *file) lintVarDecls() { var lastGen *ast.GenDecl // last GenDecl entered. f.walk(func(node ast.Node) bool { switch v := node.(type) { case *ast.GenDecl: if v.Tok != token.CONST && v.Tok != token.VAR { return false } lastGen = v return true case *ast.ValueSpec: if lastGen.Tok == token.CONST { return false } if len(v.Names) > 1 || v.Type == nil || len(v.Values) == 0 { return false } rhs := v.Values[0] // An underscore var appears in a common idiom for compile-time interface satisfaction, // as in "var _ Interface = (*Concrete)(nil)". if isIdent(v.Names[0], "_") { return false } // If the RHS is a zero value, suggest dropping it. zero := false if lit, ok := rhs.(*ast.BasicLit); ok { zero = zeroLiteral[lit.Value] } else if isIdent(rhs, "nil") { zero = true } if zero { f.errorf(rhs, 0.9, category("zero-value"), "should drop = %s from declaration of var %s; it is the zero value", f.render(rhs), v.Names[0]) return false } lhsTyp := f.pkg.typeOf(v.Type) rhsTyp := f.pkg.typeOf(rhs) if !validType(lhsTyp) || !validType(rhsTyp) { // Type checking failed (often due to missing imports). return false } if !types.Identical(lhsTyp, rhsTyp) { // Assignment to a different type is not redundant. return false } // The next three conditions are for suppressing the warning in situations // where we were unable to typecheck. // If the LHS type is an interface, don't warn, since it is probably a // concrete type on the RHS. Note that our feeble lexical check here // will only pick up interface{} and other literal interface types; // that covers most of the cases we care to exclude right now. if _, ok := v.Type.(*ast.InterfaceType); ok { return false } // If the RHS is an untyped const, only warn if the LHS type is its default type. if defType, ok := f.isUntypedConst(rhs); ok && !isIdent(v.Type, defType) { return false } f.errorf(v.Type, 0.8, category("type-inference"), "should omit type %s from declaration of var %s; it will be inferred from the right-hand side", f.render(v.Type), v.Names[0]) return false } return true }) }
[ "func", "(", "f", "*", "file", ")", "lintVarDecls", "(", ")", "{", "var", "lastGen", "*", "ast", ".", "GenDecl", "// last GenDecl entered.", "\n\n", "f", ".", "walk", "(", "func", "(", "node", "ast", ".", "Node", ")", "bool", "{", "switch", "v", ":=", "node", ".", "(", "type", ")", "{", "case", "*", "ast", ".", "GenDecl", ":", "if", "v", ".", "Tok", "!=", "token", ".", "CONST", "&&", "v", ".", "Tok", "!=", "token", ".", "VAR", "{", "return", "false", "\n", "}", "\n", "lastGen", "=", "v", "\n", "return", "true", "\n", "case", "*", "ast", ".", "ValueSpec", ":", "if", "lastGen", ".", "Tok", "==", "token", ".", "CONST", "{", "return", "false", "\n", "}", "\n", "if", "len", "(", "v", ".", "Names", ")", ">", "1", "||", "v", ".", "Type", "==", "nil", "||", "len", "(", "v", ".", "Values", ")", "==", "0", "{", "return", "false", "\n", "}", "\n", "rhs", ":=", "v", ".", "Values", "[", "0", "]", "\n", "// An underscore var appears in a common idiom for compile-time interface satisfaction,", "// as in \"var _ Interface = (*Concrete)(nil)\".", "if", "isIdent", "(", "v", ".", "Names", "[", "0", "]", ",", "\"", "\"", ")", "{", "return", "false", "\n", "}", "\n", "// If the RHS is a zero value, suggest dropping it.", "zero", ":=", "false", "\n", "if", "lit", ",", "ok", ":=", "rhs", ".", "(", "*", "ast", ".", "BasicLit", ")", ";", "ok", "{", "zero", "=", "zeroLiteral", "[", "lit", ".", "Value", "]", "\n", "}", "else", "if", "isIdent", "(", "rhs", ",", "\"", "\"", ")", "{", "zero", "=", "true", "\n", "}", "\n", "if", "zero", "{", "f", ".", "errorf", "(", "rhs", ",", "0.9", ",", "category", "(", "\"", "\"", ")", ",", "\"", "\"", ",", "f", ".", "render", "(", "rhs", ")", ",", "v", ".", "Names", "[", "0", "]", ")", "\n", "return", "false", "\n", "}", "\n", "lhsTyp", ":=", "f", ".", "pkg", ".", "typeOf", "(", "v", ".", "Type", ")", "\n", "rhsTyp", ":=", "f", ".", "pkg", ".", "typeOf", "(", "rhs", ")", "\n\n", "if", "!", "validType", "(", "lhsTyp", ")", "||", "!", "validType", "(", "rhsTyp", ")", "{", "// Type checking failed (often due to missing imports).", "return", "false", "\n", "}", "\n\n", "if", "!", "types", ".", "Identical", "(", "lhsTyp", ",", "rhsTyp", ")", "{", "// Assignment to a different type is not redundant.", "return", "false", "\n", "}", "\n\n", "// The next three conditions are for suppressing the warning in situations", "// where we were unable to typecheck.", "// If the LHS type is an interface, don't warn, since it is probably a", "// concrete type on the RHS. Note that our feeble lexical check here", "// will only pick up interface{} and other literal interface types;", "// that covers most of the cases we care to exclude right now.", "if", "_", ",", "ok", ":=", "v", ".", "Type", ".", "(", "*", "ast", ".", "InterfaceType", ")", ";", "ok", "{", "return", "false", "\n", "}", "\n", "// If the RHS is an untyped const, only warn if the LHS type is its default type.", "if", "defType", ",", "ok", ":=", "f", ".", "isUntypedConst", "(", "rhs", ")", ";", "ok", "&&", "!", "isIdent", "(", "v", ".", "Type", ",", "defType", ")", "{", "return", "false", "\n", "}", "\n\n", "f", ".", "errorf", "(", "v", ".", "Type", ",", "0.8", ",", "category", "(", "\"", "\"", ")", ",", "\"", "\"", ",", "f", ".", "render", "(", "v", ".", "Type", ")", ",", "v", ".", "Names", "[", "0", "]", ")", "\n", "return", "false", "\n", "}", "\n", "return", "true", "\n", "}", ")", "\n", "}" ]
// lintVarDecls examines variable declarations. It complains about declarations with // redundant LHS types that can be inferred from the RHS.
[ "lintVarDecls", "examines", "variable", "declarations", ".", "It", "complains", "about", "declarations", "with", "redundant", "LHS", "types", "that", "can", "be", "inferred", "from", "the", "RHS", "." ]
959b441ac422379a43da2230f62be024250818b0
https://github.com/golang/lint/blob/959b441ac422379a43da2230f62be024250818b0/lint.go#L982-L1050
train
golang/lint
lint.go
lintElses
func (f *file) lintElses() { // We don't want to flag if { } else if { } else { } constructions. // They will appear as an IfStmt whose Else field is also an IfStmt. // Record such a node so we ignore it when we visit it. ignore := make(map[*ast.IfStmt]bool) f.walk(func(node ast.Node) bool { ifStmt, ok := node.(*ast.IfStmt) if !ok || ifStmt.Else == nil { return true } if elseif, ok := ifStmt.Else.(*ast.IfStmt); ok { ignore[elseif] = true return true } if ignore[ifStmt] { return true } if _, ok := ifStmt.Else.(*ast.BlockStmt); !ok { // only care about elses without conditions return true } if len(ifStmt.Body.List) == 0 { return true } shortDecl := false // does the if statement have a ":=" initialization statement? if ifStmt.Init != nil { if as, ok := ifStmt.Init.(*ast.AssignStmt); ok && as.Tok == token.DEFINE { shortDecl = true } } lastStmt := ifStmt.Body.List[len(ifStmt.Body.List)-1] if _, ok := lastStmt.(*ast.ReturnStmt); ok { extra := "" if shortDecl { extra = " (move short variable declaration to its own line if necessary)" } f.errorf(ifStmt.Else, 1, link(styleGuideBase+"#indent-error-flow"), category("indent"), "if block ends with a return statement, so drop this else and outdent its block"+extra) } return true }) }
go
func (f *file) lintElses() { // We don't want to flag if { } else if { } else { } constructions. // They will appear as an IfStmt whose Else field is also an IfStmt. // Record such a node so we ignore it when we visit it. ignore := make(map[*ast.IfStmt]bool) f.walk(func(node ast.Node) bool { ifStmt, ok := node.(*ast.IfStmt) if !ok || ifStmt.Else == nil { return true } if elseif, ok := ifStmt.Else.(*ast.IfStmt); ok { ignore[elseif] = true return true } if ignore[ifStmt] { return true } if _, ok := ifStmt.Else.(*ast.BlockStmt); !ok { // only care about elses without conditions return true } if len(ifStmt.Body.List) == 0 { return true } shortDecl := false // does the if statement have a ":=" initialization statement? if ifStmt.Init != nil { if as, ok := ifStmt.Init.(*ast.AssignStmt); ok && as.Tok == token.DEFINE { shortDecl = true } } lastStmt := ifStmt.Body.List[len(ifStmt.Body.List)-1] if _, ok := lastStmt.(*ast.ReturnStmt); ok { extra := "" if shortDecl { extra = " (move short variable declaration to its own line if necessary)" } f.errorf(ifStmt.Else, 1, link(styleGuideBase+"#indent-error-flow"), category("indent"), "if block ends with a return statement, so drop this else and outdent its block"+extra) } return true }) }
[ "func", "(", "f", "*", "file", ")", "lintElses", "(", ")", "{", "// We don't want to flag if { } else if { } else { } constructions.", "// They will appear as an IfStmt whose Else field is also an IfStmt.", "// Record such a node so we ignore it when we visit it.", "ignore", ":=", "make", "(", "map", "[", "*", "ast", ".", "IfStmt", "]", "bool", ")", "\n\n", "f", ".", "walk", "(", "func", "(", "node", "ast", ".", "Node", ")", "bool", "{", "ifStmt", ",", "ok", ":=", "node", ".", "(", "*", "ast", ".", "IfStmt", ")", "\n", "if", "!", "ok", "||", "ifStmt", ".", "Else", "==", "nil", "{", "return", "true", "\n", "}", "\n", "if", "elseif", ",", "ok", ":=", "ifStmt", ".", "Else", ".", "(", "*", "ast", ".", "IfStmt", ")", ";", "ok", "{", "ignore", "[", "elseif", "]", "=", "true", "\n", "return", "true", "\n", "}", "\n", "if", "ignore", "[", "ifStmt", "]", "{", "return", "true", "\n", "}", "\n", "if", "_", ",", "ok", ":=", "ifStmt", ".", "Else", ".", "(", "*", "ast", ".", "BlockStmt", ")", ";", "!", "ok", "{", "// only care about elses without conditions", "return", "true", "\n", "}", "\n", "if", "len", "(", "ifStmt", ".", "Body", ".", "List", ")", "==", "0", "{", "return", "true", "\n", "}", "\n", "shortDecl", ":=", "false", "// does the if statement have a \":=\" initialization statement?", "\n", "if", "ifStmt", ".", "Init", "!=", "nil", "{", "if", "as", ",", "ok", ":=", "ifStmt", ".", "Init", ".", "(", "*", "ast", ".", "AssignStmt", ")", ";", "ok", "&&", "as", ".", "Tok", "==", "token", ".", "DEFINE", "{", "shortDecl", "=", "true", "\n", "}", "\n", "}", "\n", "lastStmt", ":=", "ifStmt", ".", "Body", ".", "List", "[", "len", "(", "ifStmt", ".", "Body", ".", "List", ")", "-", "1", "]", "\n", "if", "_", ",", "ok", ":=", "lastStmt", ".", "(", "*", "ast", ".", "ReturnStmt", ")", ";", "ok", "{", "extra", ":=", "\"", "\"", "\n", "if", "shortDecl", "{", "extra", "=", "\"", "\"", "\n", "}", "\n", "f", ".", "errorf", "(", "ifStmt", ".", "Else", ",", "1", ",", "link", "(", "styleGuideBase", "+", "\"", "\"", ")", ",", "category", "(", "\"", "\"", ")", ",", "\"", "\"", "+", "extra", ")", "\n", "}", "\n", "return", "true", "\n", "}", ")", "\n", "}" ]
// lintElses examines else blocks. It complains about any else block whose if block ends in a return.
[ "lintElses", "examines", "else", "blocks", ".", "It", "complains", "about", "any", "else", "block", "whose", "if", "block", "ends", "in", "a", "return", "." ]
959b441ac422379a43da2230f62be024250818b0
https://github.com/golang/lint/blob/959b441ac422379a43da2230f62be024250818b0/lint.go#L1059-L1100
train
golang/lint
lint.go
lintRanges
func (f *file) lintRanges() { f.walk(func(node ast.Node) bool { rs, ok := node.(*ast.RangeStmt) if !ok { return true } if isIdent(rs.Key, "_") && (rs.Value == nil || isIdent(rs.Value, "_")) { p := f.errorf(rs.Key, 1, category("range-loop"), "should omit values from range; this loop is equivalent to `for range ...`") newRS := *rs // shallow copy newRS.Value = nil newRS.Key = nil p.ReplacementLine = f.firstLineOf(&newRS, rs) return true } if isIdent(rs.Value, "_") { p := f.errorf(rs.Value, 1, category("range-loop"), "should omit 2nd value from range; this loop is equivalent to `for %s %s range ...`", f.render(rs.Key), rs.Tok) newRS := *rs // shallow copy newRS.Value = nil p.ReplacementLine = f.firstLineOf(&newRS, rs) } return true }) }
go
func (f *file) lintRanges() { f.walk(func(node ast.Node) bool { rs, ok := node.(*ast.RangeStmt) if !ok { return true } if isIdent(rs.Key, "_") && (rs.Value == nil || isIdent(rs.Value, "_")) { p := f.errorf(rs.Key, 1, category("range-loop"), "should omit values from range; this loop is equivalent to `for range ...`") newRS := *rs // shallow copy newRS.Value = nil newRS.Key = nil p.ReplacementLine = f.firstLineOf(&newRS, rs) return true } if isIdent(rs.Value, "_") { p := f.errorf(rs.Value, 1, category("range-loop"), "should omit 2nd value from range; this loop is equivalent to `for %s %s range ...`", f.render(rs.Key), rs.Tok) newRS := *rs // shallow copy newRS.Value = nil p.ReplacementLine = f.firstLineOf(&newRS, rs) } return true }) }
[ "func", "(", "f", "*", "file", ")", "lintRanges", "(", ")", "{", "f", ".", "walk", "(", "func", "(", "node", "ast", ".", "Node", ")", "bool", "{", "rs", ",", "ok", ":=", "node", ".", "(", "*", "ast", ".", "RangeStmt", ")", "\n", "if", "!", "ok", "{", "return", "true", "\n", "}", "\n\n", "if", "isIdent", "(", "rs", ".", "Key", ",", "\"", "\"", ")", "&&", "(", "rs", ".", "Value", "==", "nil", "||", "isIdent", "(", "rs", ".", "Value", ",", "\"", "\"", ")", ")", "{", "p", ":=", "f", ".", "errorf", "(", "rs", ".", "Key", ",", "1", ",", "category", "(", "\"", "\"", ")", ",", "\"", "\"", ")", "\n\n", "newRS", ":=", "*", "rs", "// shallow copy", "\n", "newRS", ".", "Value", "=", "nil", "\n", "newRS", ".", "Key", "=", "nil", "\n", "p", ".", "ReplacementLine", "=", "f", ".", "firstLineOf", "(", "&", "newRS", ",", "rs", ")", "\n\n", "return", "true", "\n", "}", "\n\n", "if", "isIdent", "(", "rs", ".", "Value", ",", "\"", "\"", ")", "{", "p", ":=", "f", ".", "errorf", "(", "rs", ".", "Value", ",", "1", ",", "category", "(", "\"", "\"", ")", ",", "\"", "\"", ",", "f", ".", "render", "(", "rs", ".", "Key", ")", ",", "rs", ".", "Tok", ")", "\n\n", "newRS", ":=", "*", "rs", "// shallow copy", "\n", "newRS", ".", "Value", "=", "nil", "\n", "p", ".", "ReplacementLine", "=", "f", ".", "firstLineOf", "(", "&", "newRS", ",", "rs", ")", "\n", "}", "\n\n", "return", "true", "\n", "}", ")", "\n", "}" ]
// lintRanges examines range clauses. It complains about redundant constructions.
[ "lintRanges", "examines", "range", "clauses", ".", "It", "complains", "about", "redundant", "constructions", "." ]
959b441ac422379a43da2230f62be024250818b0
https://github.com/golang/lint/blob/959b441ac422379a43da2230f62be024250818b0/lint.go#L1103-L1131
train
golang/lint
lint.go
lintErrorf
func (f *file) lintErrorf() { f.walk(func(node ast.Node) bool { ce, ok := node.(*ast.CallExpr) if !ok || len(ce.Args) != 1 { return true } isErrorsNew := isPkgDot(ce.Fun, "errors", "New") var isTestingError bool se, ok := ce.Fun.(*ast.SelectorExpr) if ok && se.Sel.Name == "Error" { if typ := f.pkg.typeOf(se.X); typ != nil { isTestingError = typ.String() == "*testing.T" } } if !isErrorsNew && !isTestingError { return true } if !f.imports("errors") { return true } arg := ce.Args[0] ce, ok = arg.(*ast.CallExpr) if !ok || !isPkgDot(ce.Fun, "fmt", "Sprintf") { return true } errorfPrefix := "fmt" if isTestingError { errorfPrefix = f.render(se.X) } p := f.errorf(node, 1, category("errors"), "should replace %s(fmt.Sprintf(...)) with %s.Errorf(...)", f.render(se), errorfPrefix) m := f.srcLineWithMatch(ce, `^(.*)`+f.render(se)+`\(fmt\.Sprintf\((.*)\)\)(.*)$`) if m != nil { p.ReplacementLine = m[1] + errorfPrefix + ".Errorf(" + m[2] + ")" + m[3] } return true }) }
go
func (f *file) lintErrorf() { f.walk(func(node ast.Node) bool { ce, ok := node.(*ast.CallExpr) if !ok || len(ce.Args) != 1 { return true } isErrorsNew := isPkgDot(ce.Fun, "errors", "New") var isTestingError bool se, ok := ce.Fun.(*ast.SelectorExpr) if ok && se.Sel.Name == "Error" { if typ := f.pkg.typeOf(se.X); typ != nil { isTestingError = typ.String() == "*testing.T" } } if !isErrorsNew && !isTestingError { return true } if !f.imports("errors") { return true } arg := ce.Args[0] ce, ok = arg.(*ast.CallExpr) if !ok || !isPkgDot(ce.Fun, "fmt", "Sprintf") { return true } errorfPrefix := "fmt" if isTestingError { errorfPrefix = f.render(se.X) } p := f.errorf(node, 1, category("errors"), "should replace %s(fmt.Sprintf(...)) with %s.Errorf(...)", f.render(se), errorfPrefix) m := f.srcLineWithMatch(ce, `^(.*)`+f.render(se)+`\(fmt\.Sprintf\((.*)\)\)(.*)$`) if m != nil { p.ReplacementLine = m[1] + errorfPrefix + ".Errorf(" + m[2] + ")" + m[3] } return true }) }
[ "func", "(", "f", "*", "file", ")", "lintErrorf", "(", ")", "{", "f", ".", "walk", "(", "func", "(", "node", "ast", ".", "Node", ")", "bool", "{", "ce", ",", "ok", ":=", "node", ".", "(", "*", "ast", ".", "CallExpr", ")", "\n", "if", "!", "ok", "||", "len", "(", "ce", ".", "Args", ")", "!=", "1", "{", "return", "true", "\n", "}", "\n", "isErrorsNew", ":=", "isPkgDot", "(", "ce", ".", "Fun", ",", "\"", "\"", ",", "\"", "\"", ")", "\n", "var", "isTestingError", "bool", "\n", "se", ",", "ok", ":=", "ce", ".", "Fun", ".", "(", "*", "ast", ".", "SelectorExpr", ")", "\n", "if", "ok", "&&", "se", ".", "Sel", ".", "Name", "==", "\"", "\"", "{", "if", "typ", ":=", "f", ".", "pkg", ".", "typeOf", "(", "se", ".", "X", ")", ";", "typ", "!=", "nil", "{", "isTestingError", "=", "typ", ".", "String", "(", ")", "==", "\"", "\"", "\n", "}", "\n", "}", "\n", "if", "!", "isErrorsNew", "&&", "!", "isTestingError", "{", "return", "true", "\n", "}", "\n", "if", "!", "f", ".", "imports", "(", "\"", "\"", ")", "{", "return", "true", "\n", "}", "\n", "arg", ":=", "ce", ".", "Args", "[", "0", "]", "\n", "ce", ",", "ok", "=", "arg", ".", "(", "*", "ast", ".", "CallExpr", ")", "\n", "if", "!", "ok", "||", "!", "isPkgDot", "(", "ce", ".", "Fun", ",", "\"", "\"", ",", "\"", "\"", ")", "{", "return", "true", "\n", "}", "\n", "errorfPrefix", ":=", "\"", "\"", "\n", "if", "isTestingError", "{", "errorfPrefix", "=", "f", ".", "render", "(", "se", ".", "X", ")", "\n", "}", "\n", "p", ":=", "f", ".", "errorf", "(", "node", ",", "1", ",", "category", "(", "\"", "\"", ")", ",", "\"", "\"", ",", "f", ".", "render", "(", "se", ")", ",", "errorfPrefix", ")", "\n\n", "m", ":=", "f", ".", "srcLineWithMatch", "(", "ce", ",", "`^(.*)`", "+", "f", ".", "render", "(", "se", ")", "+", "`\\(fmt\\.Sprintf\\((.*)\\)\\)(.*)$`", ")", "\n", "if", "m", "!=", "nil", "{", "p", ".", "ReplacementLine", "=", "m", "[", "1", "]", "+", "errorfPrefix", "+", "\"", "\"", "+", "m", "[", "2", "]", "+", "\"", "\"", "+", "m", "[", "3", "]", "\n", "}", "\n\n", "return", "true", "\n", "}", ")", "\n", "}" ]
// lintErrorf examines errors.New and testing.Error calls. It complains if its only argument is an fmt.Sprintf invocation.
[ "lintErrorf", "examines", "errors", ".", "New", "and", "testing", ".", "Error", "calls", ".", "It", "complains", "if", "its", "only", "argument", "is", "an", "fmt", ".", "Sprintf", "invocation", "." ]
959b441ac422379a43da2230f62be024250818b0
https://github.com/golang/lint/blob/959b441ac422379a43da2230f62be024250818b0/lint.go#L1134-L1172
train
golang/lint
lint.go
lintErrors
func (f *file) lintErrors() { for _, decl := range f.f.Decls { gd, ok := decl.(*ast.GenDecl) if !ok || gd.Tok != token.VAR { continue } for _, spec := range gd.Specs { spec := spec.(*ast.ValueSpec) if len(spec.Names) != 1 || len(spec.Values) != 1 { continue } ce, ok := spec.Values[0].(*ast.CallExpr) if !ok { continue } if !isPkgDot(ce.Fun, "errors", "New") && !isPkgDot(ce.Fun, "fmt", "Errorf") { continue } id := spec.Names[0] prefix := "err" if id.IsExported() { prefix = "Err" } if !strings.HasPrefix(id.Name, prefix) { f.errorf(id, 0.9, category("naming"), "error var %s should have name of the form %sFoo", id.Name, prefix) } } } }
go
func (f *file) lintErrors() { for _, decl := range f.f.Decls { gd, ok := decl.(*ast.GenDecl) if !ok || gd.Tok != token.VAR { continue } for _, spec := range gd.Specs { spec := spec.(*ast.ValueSpec) if len(spec.Names) != 1 || len(spec.Values) != 1 { continue } ce, ok := spec.Values[0].(*ast.CallExpr) if !ok { continue } if !isPkgDot(ce.Fun, "errors", "New") && !isPkgDot(ce.Fun, "fmt", "Errorf") { continue } id := spec.Names[0] prefix := "err" if id.IsExported() { prefix = "Err" } if !strings.HasPrefix(id.Name, prefix) { f.errorf(id, 0.9, category("naming"), "error var %s should have name of the form %sFoo", id.Name, prefix) } } } }
[ "func", "(", "f", "*", "file", ")", "lintErrors", "(", ")", "{", "for", "_", ",", "decl", ":=", "range", "f", ".", "f", ".", "Decls", "{", "gd", ",", "ok", ":=", "decl", ".", "(", "*", "ast", ".", "GenDecl", ")", "\n", "if", "!", "ok", "||", "gd", ".", "Tok", "!=", "token", ".", "VAR", "{", "continue", "\n", "}", "\n", "for", "_", ",", "spec", ":=", "range", "gd", ".", "Specs", "{", "spec", ":=", "spec", ".", "(", "*", "ast", ".", "ValueSpec", ")", "\n", "if", "len", "(", "spec", ".", "Names", ")", "!=", "1", "||", "len", "(", "spec", ".", "Values", ")", "!=", "1", "{", "continue", "\n", "}", "\n", "ce", ",", "ok", ":=", "spec", ".", "Values", "[", "0", "]", ".", "(", "*", "ast", ".", "CallExpr", ")", "\n", "if", "!", "ok", "{", "continue", "\n", "}", "\n", "if", "!", "isPkgDot", "(", "ce", ".", "Fun", ",", "\"", "\"", ",", "\"", "\"", ")", "&&", "!", "isPkgDot", "(", "ce", ".", "Fun", ",", "\"", "\"", ",", "\"", "\"", ")", "{", "continue", "\n", "}", "\n\n", "id", ":=", "spec", ".", "Names", "[", "0", "]", "\n", "prefix", ":=", "\"", "\"", "\n", "if", "id", ".", "IsExported", "(", ")", "{", "prefix", "=", "\"", "\"", "\n", "}", "\n", "if", "!", "strings", ".", "HasPrefix", "(", "id", ".", "Name", ",", "prefix", ")", "{", "f", ".", "errorf", "(", "id", ",", "0.9", ",", "category", "(", "\"", "\"", ")", ",", "\"", "\"", ",", "id", ".", "Name", ",", "prefix", ")", "\n", "}", "\n", "}", "\n", "}", "\n", "}" ]
// lintErrors examines global error vars. It complains if they aren't named in the standard way.
[ "lintErrors", "examines", "global", "error", "vars", ".", "It", "complains", "if", "they", "aren", "t", "named", "in", "the", "standard", "way", "." ]
959b441ac422379a43da2230f62be024250818b0
https://github.com/golang/lint/blob/959b441ac422379a43da2230f62be024250818b0/lint.go#L1175-L1204
train
golang/lint
lint.go
lintErrorStrings
func (f *file) lintErrorStrings() { f.walk(func(node ast.Node) bool { ce, ok := node.(*ast.CallExpr) if !ok { return true } if !isPkgDot(ce.Fun, "errors", "New") && !isPkgDot(ce.Fun, "fmt", "Errorf") { return true } if len(ce.Args) < 1 { return true } str, ok := ce.Args[0].(*ast.BasicLit) if !ok || str.Kind != token.STRING { return true } s, _ := strconv.Unquote(str.Value) // can assume well-formed Go if s == "" { return true } clean, conf := lintErrorString(s) if clean { return true } f.errorf(str, conf, link(styleGuideBase+"#error-strings"), category("errors"), "error strings should not be capitalized or end with punctuation or a newline") return true }) }
go
func (f *file) lintErrorStrings() { f.walk(func(node ast.Node) bool { ce, ok := node.(*ast.CallExpr) if !ok { return true } if !isPkgDot(ce.Fun, "errors", "New") && !isPkgDot(ce.Fun, "fmt", "Errorf") { return true } if len(ce.Args) < 1 { return true } str, ok := ce.Args[0].(*ast.BasicLit) if !ok || str.Kind != token.STRING { return true } s, _ := strconv.Unquote(str.Value) // can assume well-formed Go if s == "" { return true } clean, conf := lintErrorString(s) if clean { return true } f.errorf(str, conf, link(styleGuideBase+"#error-strings"), category("errors"), "error strings should not be capitalized or end with punctuation or a newline") return true }) }
[ "func", "(", "f", "*", "file", ")", "lintErrorStrings", "(", ")", "{", "f", ".", "walk", "(", "func", "(", "node", "ast", ".", "Node", ")", "bool", "{", "ce", ",", "ok", ":=", "node", ".", "(", "*", "ast", ".", "CallExpr", ")", "\n", "if", "!", "ok", "{", "return", "true", "\n", "}", "\n", "if", "!", "isPkgDot", "(", "ce", ".", "Fun", ",", "\"", "\"", ",", "\"", "\"", ")", "&&", "!", "isPkgDot", "(", "ce", ".", "Fun", ",", "\"", "\"", ",", "\"", "\"", ")", "{", "return", "true", "\n", "}", "\n", "if", "len", "(", "ce", ".", "Args", ")", "<", "1", "{", "return", "true", "\n", "}", "\n", "str", ",", "ok", ":=", "ce", ".", "Args", "[", "0", "]", ".", "(", "*", "ast", ".", "BasicLit", ")", "\n", "if", "!", "ok", "||", "str", ".", "Kind", "!=", "token", ".", "STRING", "{", "return", "true", "\n", "}", "\n", "s", ",", "_", ":=", "strconv", ".", "Unquote", "(", "str", ".", "Value", ")", "// can assume well-formed Go", "\n", "if", "s", "==", "\"", "\"", "{", "return", "true", "\n", "}", "\n", "clean", ",", "conf", ":=", "lintErrorString", "(", "s", ")", "\n", "if", "clean", "{", "return", "true", "\n", "}", "\n\n", "f", ".", "errorf", "(", "str", ",", "conf", ",", "link", "(", "styleGuideBase", "+", "\"", "\"", ")", ",", "category", "(", "\"", "\"", ")", ",", "\"", "\"", ")", "\n", "return", "true", "\n", "}", ")", "\n", "}" ]
// lintErrorStrings examines error strings. // It complains if they are capitalized or end in punctuation or a newline.
[ "lintErrorStrings", "examines", "error", "strings", ".", "It", "complains", "if", "they", "are", "capitalized", "or", "end", "in", "punctuation", "or", "a", "newline", "." ]
959b441ac422379a43da2230f62be024250818b0
https://github.com/golang/lint/blob/959b441ac422379a43da2230f62be024250818b0/lint.go#L1230-L1259
train
golang/lint
lint.go
lintReceiverNames
func (f *file) lintReceiverNames() { typeReceiver := map[string]string{} f.walk(func(n ast.Node) bool { fn, ok := n.(*ast.FuncDecl) if !ok || fn.Recv == nil || len(fn.Recv.List) == 0 { return true } names := fn.Recv.List[0].Names if len(names) < 1 { return true } name := names[0].Name const ref = styleGuideBase + "#receiver-names" if name == "_" { f.errorf(n, 1, link(ref), category("naming"), `receiver name should not be an underscore, omit the name if it is unused`) return true } if name == "this" || name == "self" { f.errorf(n, 1, link(ref), category("naming"), `receiver name should be a reflection of its identity; don't use generic names such as "this" or "self"`) return true } recv := receiverType(fn) if prev, ok := typeReceiver[recv]; ok && prev != name { f.errorf(n, 1, link(ref), category("naming"), "receiver name %s should be consistent with previous receiver name %s for %s", name, prev, recv) return true } typeReceiver[recv] = name return true }) }
go
func (f *file) lintReceiverNames() { typeReceiver := map[string]string{} f.walk(func(n ast.Node) bool { fn, ok := n.(*ast.FuncDecl) if !ok || fn.Recv == nil || len(fn.Recv.List) == 0 { return true } names := fn.Recv.List[0].Names if len(names) < 1 { return true } name := names[0].Name const ref = styleGuideBase + "#receiver-names" if name == "_" { f.errorf(n, 1, link(ref), category("naming"), `receiver name should not be an underscore, omit the name if it is unused`) return true } if name == "this" || name == "self" { f.errorf(n, 1, link(ref), category("naming"), `receiver name should be a reflection of its identity; don't use generic names such as "this" or "self"`) return true } recv := receiverType(fn) if prev, ok := typeReceiver[recv]; ok && prev != name { f.errorf(n, 1, link(ref), category("naming"), "receiver name %s should be consistent with previous receiver name %s for %s", name, prev, recv) return true } typeReceiver[recv] = name return true }) }
[ "func", "(", "f", "*", "file", ")", "lintReceiverNames", "(", ")", "{", "typeReceiver", ":=", "map", "[", "string", "]", "string", "{", "}", "\n", "f", ".", "walk", "(", "func", "(", "n", "ast", ".", "Node", ")", "bool", "{", "fn", ",", "ok", ":=", "n", ".", "(", "*", "ast", ".", "FuncDecl", ")", "\n", "if", "!", "ok", "||", "fn", ".", "Recv", "==", "nil", "||", "len", "(", "fn", ".", "Recv", ".", "List", ")", "==", "0", "{", "return", "true", "\n", "}", "\n", "names", ":=", "fn", ".", "Recv", ".", "List", "[", "0", "]", ".", "Names", "\n", "if", "len", "(", "names", ")", "<", "1", "{", "return", "true", "\n", "}", "\n", "name", ":=", "names", "[", "0", "]", ".", "Name", "\n", "const", "ref", "=", "styleGuideBase", "+", "\"", "\"", "\n", "if", "name", "==", "\"", "\"", "{", "f", ".", "errorf", "(", "n", ",", "1", ",", "link", "(", "ref", ")", ",", "category", "(", "\"", "\"", ")", ",", "`receiver name should not be an underscore, omit the name if it is unused`", ")", "\n", "return", "true", "\n", "}", "\n", "if", "name", "==", "\"", "\"", "||", "name", "==", "\"", "\"", "{", "f", ".", "errorf", "(", "n", ",", "1", ",", "link", "(", "ref", ")", ",", "category", "(", "\"", "\"", ")", ",", "`receiver name should be a reflection of its identity; don't use generic names such as \"this\" or \"self\"`", ")", "\n", "return", "true", "\n", "}", "\n", "recv", ":=", "receiverType", "(", "fn", ")", "\n", "if", "prev", ",", "ok", ":=", "typeReceiver", "[", "recv", "]", ";", "ok", "&&", "prev", "!=", "name", "{", "f", ".", "errorf", "(", "n", ",", "1", ",", "link", "(", "ref", ")", ",", "category", "(", "\"", "\"", ")", ",", "\"", "\"", ",", "name", ",", "prev", ",", "recv", ")", "\n", "return", "true", "\n", "}", "\n", "typeReceiver", "[", "recv", "]", "=", "name", "\n", "return", "true", "\n", "}", ")", "\n", "}" ]
// lintReceiverNames examines receiver names. It complains about inconsistent // names used for the same type and names such as "this".
[ "lintReceiverNames", "examines", "receiver", "names", ".", "It", "complains", "about", "inconsistent", "names", "used", "for", "the", "same", "type", "and", "names", "such", "as", "this", "." ]
959b441ac422379a43da2230f62be024250818b0
https://github.com/golang/lint/blob/959b441ac422379a43da2230f62be024250818b0/lint.go#L1263-L1292
train
golang/lint
lint.go
lintErrorReturn
func (f *file) lintErrorReturn() { f.walk(func(n ast.Node) bool { fn, ok := n.(*ast.FuncDecl) if !ok || fn.Type.Results == nil { return true } ret := fn.Type.Results.List if len(ret) <= 1 { return true } if isIdent(ret[len(ret)-1].Type, "error") { return true } // An error return parameter should be the last parameter. // Flag any error parameters found before the last. for _, r := range ret[:len(ret)-1] { if isIdent(r.Type, "error") { f.errorf(fn, 0.9, category("arg-order"), "error should be the last type when returning multiple items") break // only flag one } } return true }) }
go
func (f *file) lintErrorReturn() { f.walk(func(n ast.Node) bool { fn, ok := n.(*ast.FuncDecl) if !ok || fn.Type.Results == nil { return true } ret := fn.Type.Results.List if len(ret) <= 1 { return true } if isIdent(ret[len(ret)-1].Type, "error") { return true } // An error return parameter should be the last parameter. // Flag any error parameters found before the last. for _, r := range ret[:len(ret)-1] { if isIdent(r.Type, "error") { f.errorf(fn, 0.9, category("arg-order"), "error should be the last type when returning multiple items") break // only flag one } } return true }) }
[ "func", "(", "f", "*", "file", ")", "lintErrorReturn", "(", ")", "{", "f", ".", "walk", "(", "func", "(", "n", "ast", ".", "Node", ")", "bool", "{", "fn", ",", "ok", ":=", "n", ".", "(", "*", "ast", ".", "FuncDecl", ")", "\n", "if", "!", "ok", "||", "fn", ".", "Type", ".", "Results", "==", "nil", "{", "return", "true", "\n", "}", "\n", "ret", ":=", "fn", ".", "Type", ".", "Results", ".", "List", "\n", "if", "len", "(", "ret", ")", "<=", "1", "{", "return", "true", "\n", "}", "\n", "if", "isIdent", "(", "ret", "[", "len", "(", "ret", ")", "-", "1", "]", ".", "Type", ",", "\"", "\"", ")", "{", "return", "true", "\n", "}", "\n", "// An error return parameter should be the last parameter.", "// Flag any error parameters found before the last.", "for", "_", ",", "r", ":=", "range", "ret", "[", ":", "len", "(", "ret", ")", "-", "1", "]", "{", "if", "isIdent", "(", "r", ".", "Type", ",", "\"", "\"", ")", "{", "f", ".", "errorf", "(", "fn", ",", "0.9", ",", "category", "(", "\"", "\"", ")", ",", "\"", "\"", ")", "\n", "break", "// only flag one", "\n", "}", "\n", "}", "\n", "return", "true", "\n", "}", ")", "\n", "}" ]
// lintErrorReturn examines function declarations that return an error. // It complains if the error isn't the last parameter.
[ "lintErrorReturn", "examines", "function", "declarations", "that", "return", "an", "error", ".", "It", "complains", "if", "the", "error", "isn", "t", "the", "last", "parameter", "." ]
959b441ac422379a43da2230f62be024250818b0
https://github.com/golang/lint/blob/959b441ac422379a43da2230f62be024250818b0/lint.go#L1324-L1347
train
golang/lint
lint.go
lintUnexportedReturn
func (f *file) lintUnexportedReturn() { f.walk(func(n ast.Node) bool { fn, ok := n.(*ast.FuncDecl) if !ok { return true } if fn.Type.Results == nil { return false } if !fn.Name.IsExported() { return false } thing := "func" if fn.Recv != nil && len(fn.Recv.List) > 0 { thing = "method" if !ast.IsExported(receiverType(fn)) { // Don't report exported methods of unexported types, // such as private implementations of sort.Interface. return false } } for _, ret := range fn.Type.Results.List { typ := f.pkg.typeOf(ret.Type) if exportedType(typ) { continue } f.errorf(ret.Type, 0.8, category("unexported-type-in-api"), "exported %s %s returns unexported type %s, which can be annoying to use", thing, fn.Name.Name, typ) break // only flag one } return false }) }
go
func (f *file) lintUnexportedReturn() { f.walk(func(n ast.Node) bool { fn, ok := n.(*ast.FuncDecl) if !ok { return true } if fn.Type.Results == nil { return false } if !fn.Name.IsExported() { return false } thing := "func" if fn.Recv != nil && len(fn.Recv.List) > 0 { thing = "method" if !ast.IsExported(receiverType(fn)) { // Don't report exported methods of unexported types, // such as private implementations of sort.Interface. return false } } for _, ret := range fn.Type.Results.List { typ := f.pkg.typeOf(ret.Type) if exportedType(typ) { continue } f.errorf(ret.Type, 0.8, category("unexported-type-in-api"), "exported %s %s returns unexported type %s, which can be annoying to use", thing, fn.Name.Name, typ) break // only flag one } return false }) }
[ "func", "(", "f", "*", "file", ")", "lintUnexportedReturn", "(", ")", "{", "f", ".", "walk", "(", "func", "(", "n", "ast", ".", "Node", ")", "bool", "{", "fn", ",", "ok", ":=", "n", ".", "(", "*", "ast", ".", "FuncDecl", ")", "\n", "if", "!", "ok", "{", "return", "true", "\n", "}", "\n", "if", "fn", ".", "Type", ".", "Results", "==", "nil", "{", "return", "false", "\n", "}", "\n", "if", "!", "fn", ".", "Name", ".", "IsExported", "(", ")", "{", "return", "false", "\n", "}", "\n", "thing", ":=", "\"", "\"", "\n", "if", "fn", ".", "Recv", "!=", "nil", "&&", "len", "(", "fn", ".", "Recv", ".", "List", ")", ">", "0", "{", "thing", "=", "\"", "\"", "\n", "if", "!", "ast", ".", "IsExported", "(", "receiverType", "(", "fn", ")", ")", "{", "// Don't report exported methods of unexported types,", "// such as private implementations of sort.Interface.", "return", "false", "\n", "}", "\n", "}", "\n", "for", "_", ",", "ret", ":=", "range", "fn", ".", "Type", ".", "Results", ".", "List", "{", "typ", ":=", "f", ".", "pkg", ".", "typeOf", "(", "ret", ".", "Type", ")", "\n", "if", "exportedType", "(", "typ", ")", "{", "continue", "\n", "}", "\n", "f", ".", "errorf", "(", "ret", ".", "Type", ",", "0.8", ",", "category", "(", "\"", "\"", ")", ",", "\"", "\"", ",", "thing", ",", "fn", ".", "Name", ".", "Name", ",", "typ", ")", "\n", "break", "// only flag one", "\n", "}", "\n", "return", "false", "\n", "}", ")", "\n", "}" ]
// lintUnexportedReturn examines exported function declarations. // It complains if any return an unexported type.
[ "lintUnexportedReturn", "examines", "exported", "function", "declarations", ".", "It", "complains", "if", "any", "return", "an", "unexported", "type", "." ]
959b441ac422379a43da2230f62be024250818b0
https://github.com/golang/lint/blob/959b441ac422379a43da2230f62be024250818b0/lint.go#L1351-L1384
train
golang/lint
lint.go
exportedType
func exportedType(typ types.Type) bool { switch T := typ.(type) { case *types.Named: // Builtin types have no package. return T.Obj().Pkg() == nil || T.Obj().Exported() case *types.Map: return exportedType(T.Key()) && exportedType(T.Elem()) case interface { Elem() types.Type }: // array, slice, pointer, chan return exportedType(T.Elem()) } // Be conservative about other types, such as struct, interface, etc. return true }
go
func exportedType(typ types.Type) bool { switch T := typ.(type) { case *types.Named: // Builtin types have no package. return T.Obj().Pkg() == nil || T.Obj().Exported() case *types.Map: return exportedType(T.Key()) && exportedType(T.Elem()) case interface { Elem() types.Type }: // array, slice, pointer, chan return exportedType(T.Elem()) } // Be conservative about other types, such as struct, interface, etc. return true }
[ "func", "exportedType", "(", "typ", "types", ".", "Type", ")", "bool", "{", "switch", "T", ":=", "typ", ".", "(", "type", ")", "{", "case", "*", "types", ".", "Named", ":", "// Builtin types have no package.", "return", "T", ".", "Obj", "(", ")", ".", "Pkg", "(", ")", "==", "nil", "||", "T", ".", "Obj", "(", ")", ".", "Exported", "(", ")", "\n", "case", "*", "types", ".", "Map", ":", "return", "exportedType", "(", "T", ".", "Key", "(", ")", ")", "&&", "exportedType", "(", "T", ".", "Elem", "(", ")", ")", "\n", "case", "interface", "{", "Elem", "(", ")", "types", ".", "Type", "\n", "}", ":", "// array, slice, pointer, chan", "return", "exportedType", "(", "T", ".", "Elem", "(", ")", ")", "\n", "}", "\n", "// Be conservative about other types, such as struct, interface, etc.", "return", "true", "\n", "}" ]
// exportedType reports whether typ is an exported type. // It is imprecise, and will err on the side of returning true, // such as for composite types.
[ "exportedType", "reports", "whether", "typ", "is", "an", "exported", "type", ".", "It", "is", "imprecise", "and", "will", "err", "on", "the", "side", "of", "returning", "true", "such", "as", "for", "composite", "types", "." ]
959b441ac422379a43da2230f62be024250818b0
https://github.com/golang/lint/blob/959b441ac422379a43da2230f62be024250818b0/lint.go#L1389-L1403
train
golang/lint
lint.go
checkContextKeyType
func (f *file) checkContextKeyType(x *ast.CallExpr) { sel, ok := x.Fun.(*ast.SelectorExpr) if !ok { return } pkg, ok := sel.X.(*ast.Ident) if !ok || pkg.Name != "context" { return } if sel.Sel.Name != "WithValue" { return } // key is second argument to context.WithValue if len(x.Args) != 3 { return } key := f.pkg.typesInfo.Types[x.Args[1]] if ktyp, ok := key.Type.(*types.Basic); ok && ktyp.Kind() != types.Invalid { f.errorf(x, 1.0, category("context"), fmt.Sprintf("should not use basic type %s as key in context.WithValue", key.Type)) } }
go
func (f *file) checkContextKeyType(x *ast.CallExpr) { sel, ok := x.Fun.(*ast.SelectorExpr) if !ok { return } pkg, ok := sel.X.(*ast.Ident) if !ok || pkg.Name != "context" { return } if sel.Sel.Name != "WithValue" { return } // key is second argument to context.WithValue if len(x.Args) != 3 { return } key := f.pkg.typesInfo.Types[x.Args[1]] if ktyp, ok := key.Type.(*types.Basic); ok && ktyp.Kind() != types.Invalid { f.errorf(x, 1.0, category("context"), fmt.Sprintf("should not use basic type %s as key in context.WithValue", key.Type)) } }
[ "func", "(", "f", "*", "file", ")", "checkContextKeyType", "(", "x", "*", "ast", ".", "CallExpr", ")", "{", "sel", ",", "ok", ":=", "x", ".", "Fun", ".", "(", "*", "ast", ".", "SelectorExpr", ")", "\n", "if", "!", "ok", "{", "return", "\n", "}", "\n", "pkg", ",", "ok", ":=", "sel", ".", "X", ".", "(", "*", "ast", ".", "Ident", ")", "\n", "if", "!", "ok", "||", "pkg", ".", "Name", "!=", "\"", "\"", "{", "return", "\n", "}", "\n", "if", "sel", ".", "Sel", ".", "Name", "!=", "\"", "\"", "{", "return", "\n", "}", "\n\n", "// key is second argument to context.WithValue", "if", "len", "(", "x", ".", "Args", ")", "!=", "3", "{", "return", "\n", "}", "\n", "key", ":=", "f", ".", "pkg", ".", "typesInfo", ".", "Types", "[", "x", ".", "Args", "[", "1", "]", "]", "\n\n", "if", "ktyp", ",", "ok", ":=", "key", ".", "Type", ".", "(", "*", "types", ".", "Basic", ")", ";", "ok", "&&", "ktyp", ".", "Kind", "(", ")", "!=", "types", ".", "Invalid", "{", "f", ".", "errorf", "(", "x", ",", "1.0", ",", "category", "(", "\"", "\"", ")", ",", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "key", ".", "Type", ")", ")", "\n", "}", "\n", "}" ]
// checkContextKeyType reports an error if the call expression calls // context.WithValue with a key argument of basic type.
[ "checkContextKeyType", "reports", "an", "error", "if", "the", "call", "expression", "calls", "context", ".", "WithValue", "with", "a", "key", "argument", "of", "basic", "type", "." ]
959b441ac422379a43da2230f62be024250818b0
https://github.com/golang/lint/blob/959b441ac422379a43da2230f62be024250818b0/lint.go#L1464-L1486
train
golang/lint
lint.go
lintContextArgs
func (f *file) lintContextArgs() { f.walk(func(n ast.Node) bool { fn, ok := n.(*ast.FuncDecl) if !ok || len(fn.Type.Params.List) <= 1 { return true } // A context.Context should be the first parameter of a function. // Flag any that show up after the first. for _, arg := range fn.Type.Params.List[1:] { if isPkgDot(arg.Type, "context", "Context") { f.errorf(fn, 0.9, link("https://golang.org/pkg/context/"), category("arg-order"), "context.Context should be the first parameter of a function") break // only flag one } } return true }) }
go
func (f *file) lintContextArgs() { f.walk(func(n ast.Node) bool { fn, ok := n.(*ast.FuncDecl) if !ok || len(fn.Type.Params.List) <= 1 { return true } // A context.Context should be the first parameter of a function. // Flag any that show up after the first. for _, arg := range fn.Type.Params.List[1:] { if isPkgDot(arg.Type, "context", "Context") { f.errorf(fn, 0.9, link("https://golang.org/pkg/context/"), category("arg-order"), "context.Context should be the first parameter of a function") break // only flag one } } return true }) }
[ "func", "(", "f", "*", "file", ")", "lintContextArgs", "(", ")", "{", "f", ".", "walk", "(", "func", "(", "n", "ast", ".", "Node", ")", "bool", "{", "fn", ",", "ok", ":=", "n", ".", "(", "*", "ast", ".", "FuncDecl", ")", "\n", "if", "!", "ok", "||", "len", "(", "fn", ".", "Type", ".", "Params", ".", "List", ")", "<=", "1", "{", "return", "true", "\n", "}", "\n", "// A context.Context should be the first parameter of a function.", "// Flag any that show up after the first.", "for", "_", ",", "arg", ":=", "range", "fn", ".", "Type", ".", "Params", ".", "List", "[", "1", ":", "]", "{", "if", "isPkgDot", "(", "arg", ".", "Type", ",", "\"", "\"", ",", "\"", "\"", ")", "{", "f", ".", "errorf", "(", "fn", ",", "0.9", ",", "link", "(", "\"", "\"", ")", ",", "category", "(", "\"", "\"", ")", ",", "\"", "\"", ")", "\n", "break", "// only flag one", "\n", "}", "\n", "}", "\n", "return", "true", "\n", "}", ")", "\n", "}" ]
// lintContextArgs examines function declarations that contain an // argument with a type of context.Context // It complains if that argument isn't the first parameter.
[ "lintContextArgs", "examines", "function", "declarations", "that", "contain", "an", "argument", "with", "a", "type", "of", "context", ".", "Context", "It", "complains", "if", "that", "argument", "isn", "t", "the", "first", "parameter", "." ]
959b441ac422379a43da2230f62be024250818b0
https://github.com/golang/lint/blob/959b441ac422379a43da2230f62be024250818b0/lint.go#L1491-L1507
train
golang/lint
lint.go
isUntypedConst
func (f *file) isUntypedConst(expr ast.Expr) (defType string, ok bool) { // Re-evaluate expr outside of its context to see if it's untyped. // (An expr evaluated within, for example, an assignment context will get the type of the LHS.) exprStr := f.render(expr) tv, err := types.Eval(f.fset, f.pkg.typesPkg, expr.Pos(), exprStr) if err != nil { return "", false } if b, ok := tv.Type.(*types.Basic); ok { if dt, ok := basicTypeKinds[b.Kind()]; ok { return dt, true } } return "", false }
go
func (f *file) isUntypedConst(expr ast.Expr) (defType string, ok bool) { // Re-evaluate expr outside of its context to see if it's untyped. // (An expr evaluated within, for example, an assignment context will get the type of the LHS.) exprStr := f.render(expr) tv, err := types.Eval(f.fset, f.pkg.typesPkg, expr.Pos(), exprStr) if err != nil { return "", false } if b, ok := tv.Type.(*types.Basic); ok { if dt, ok := basicTypeKinds[b.Kind()]; ok { return dt, true } } return "", false }
[ "func", "(", "f", "*", "file", ")", "isUntypedConst", "(", "expr", "ast", ".", "Expr", ")", "(", "defType", "string", ",", "ok", "bool", ")", "{", "// Re-evaluate expr outside of its context to see if it's untyped.", "// (An expr evaluated within, for example, an assignment context will get the type of the LHS.)", "exprStr", ":=", "f", ".", "render", "(", "expr", ")", "\n", "tv", ",", "err", ":=", "types", ".", "Eval", "(", "f", ".", "fset", ",", "f", ".", "pkg", ".", "typesPkg", ",", "expr", ".", "Pos", "(", ")", ",", "exprStr", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "false", "\n", "}", "\n", "if", "b", ",", "ok", ":=", "tv", ".", "Type", ".", "(", "*", "types", ".", "Basic", ")", ";", "ok", "{", "if", "dt", ",", "ok", ":=", "basicTypeKinds", "[", "b", ".", "Kind", "(", ")", "]", ";", "ok", "{", "return", "dt", ",", "true", "\n", "}", "\n", "}", "\n\n", "return", "\"", "\"", ",", "false", "\n", "}" ]
// isUntypedConst reports whether expr is an untyped constant, // and indicates what its default type is. // scope may be nil.
[ "isUntypedConst", "reports", "whether", "expr", "is", "an", "untyped", "constant", "and", "indicates", "what", "its", "default", "type", "is", ".", "scope", "may", "be", "nil", "." ]
959b441ac422379a43da2230f62be024250818b0
https://github.com/golang/lint/blob/959b441ac422379a43da2230f62be024250818b0/lint.go#L1622-L1637
train
golang/lint
lint.go
firstLineOf
func (f *file) firstLineOf(node, match ast.Node) string { line := f.render(node) if i := strings.Index(line, "\n"); i >= 0 { line = line[:i] } return f.indentOf(match) + line }
go
func (f *file) firstLineOf(node, match ast.Node) string { line := f.render(node) if i := strings.Index(line, "\n"); i >= 0 { line = line[:i] } return f.indentOf(match) + line }
[ "func", "(", "f", "*", "file", ")", "firstLineOf", "(", "node", ",", "match", "ast", ".", "Node", ")", "string", "{", "line", ":=", "f", ".", "render", "(", "node", ")", "\n", "if", "i", ":=", "strings", ".", "Index", "(", "line", ",", "\"", "\\n", "\"", ")", ";", "i", ">=", "0", "{", "line", "=", "line", "[", ":", "i", "]", "\n", "}", "\n", "return", "f", ".", "indentOf", "(", "match", ")", "+", "line", "\n", "}" ]
// firstLineOf renders the given node and returns its first line. // It will also match the indentation of another node.
[ "firstLineOf", "renders", "the", "given", "node", "and", "returns", "its", "first", "line", ".", "It", "will", "also", "match", "the", "indentation", "of", "another", "node", "." ]
959b441ac422379a43da2230f62be024250818b0
https://github.com/golang/lint/blob/959b441ac422379a43da2230f62be024250818b0/lint.go#L1641-L1647
train
golang/lint
lint.go
imports
func (f *file) imports(importPath string) bool { all := astutil.Imports(f.fset, f.f) for _, p := range all { for _, i := range p { uq, err := strconv.Unquote(i.Path.Value) if err == nil && importPath == uq { return true } } } return false }
go
func (f *file) imports(importPath string) bool { all := astutil.Imports(f.fset, f.f) for _, p := range all { for _, i := range p { uq, err := strconv.Unquote(i.Path.Value) if err == nil && importPath == uq { return true } } } return false }
[ "func", "(", "f", "*", "file", ")", "imports", "(", "importPath", "string", ")", "bool", "{", "all", ":=", "astutil", ".", "Imports", "(", "f", ".", "fset", ",", "f", ".", "f", ")", "\n", "for", "_", ",", "p", ":=", "range", "all", "{", "for", "_", ",", "i", ":=", "range", "p", "{", "uq", ",", "err", ":=", "strconv", ".", "Unquote", "(", "i", ".", "Path", ".", "Value", ")", "\n", "if", "err", "==", "nil", "&&", "importPath", "==", "uq", "{", "return", "true", "\n", "}", "\n", "}", "\n", "}", "\n", "return", "false", "\n", "}" ]
// imports returns true if the current file imports the specified package path.
[ "imports", "returns", "true", "if", "the", "current", "file", "imports", "the", "specified", "package", "path", "." ]
959b441ac422379a43da2230f62be024250818b0
https://github.com/golang/lint/blob/959b441ac422379a43da2230f62be024250818b0/lint.go#L1669-L1680
train
golang/lint
lint.go
srcLine
func srcLine(src []byte, p token.Position) string { // Run to end of line in both directions if not at line start/end. lo, hi := p.Offset, p.Offset+1 for lo > 0 && src[lo-1] != '\n' { lo-- } for hi < len(src) && src[hi-1] != '\n' { hi++ } return string(src[lo:hi]) }
go
func srcLine(src []byte, p token.Position) string { // Run to end of line in both directions if not at line start/end. lo, hi := p.Offset, p.Offset+1 for lo > 0 && src[lo-1] != '\n' { lo-- } for hi < len(src) && src[hi-1] != '\n' { hi++ } return string(src[lo:hi]) }
[ "func", "srcLine", "(", "src", "[", "]", "byte", ",", "p", "token", ".", "Position", ")", "string", "{", "// Run to end of line in both directions if not at line start/end.", "lo", ",", "hi", ":=", "p", ".", "Offset", ",", "p", ".", "Offset", "+", "1", "\n", "for", "lo", ">", "0", "&&", "src", "[", "lo", "-", "1", "]", "!=", "'\\n'", "{", "lo", "--", "\n", "}", "\n", "for", "hi", "<", "len", "(", "src", ")", "&&", "src", "[", "hi", "-", "1", "]", "!=", "'\\n'", "{", "hi", "++", "\n", "}", "\n", "return", "string", "(", "src", "[", "lo", ":", "hi", "]", ")", "\n", "}" ]
// srcLine returns the complete line at p, including the terminating newline.
[ "srcLine", "returns", "the", "complete", "line", "at", "p", "including", "the", "terminating", "newline", "." ]
959b441ac422379a43da2230f62be024250818b0
https://github.com/golang/lint/blob/959b441ac422379a43da2230f62be024250818b0/lint.go#L1683-L1693
train
golang/lint
golint/import.go
importPaths
func importPaths(args []string) []string { args = importPathsNoDotExpansion(args) var out []string for _, a := range args { if strings.Contains(a, "...") { if build.IsLocalImport(a) { out = append(out, allPackagesInFS(a)...) } else { out = append(out, allPackages(a)...) } continue } out = append(out, a) } return out }
go
func importPaths(args []string) []string { args = importPathsNoDotExpansion(args) var out []string for _, a := range args { if strings.Contains(a, "...") { if build.IsLocalImport(a) { out = append(out, allPackagesInFS(a)...) } else { out = append(out, allPackages(a)...) } continue } out = append(out, a) } return out }
[ "func", "importPaths", "(", "args", "[", "]", "string", ")", "[", "]", "string", "{", "args", "=", "importPathsNoDotExpansion", "(", "args", ")", "\n", "var", "out", "[", "]", "string", "\n", "for", "_", ",", "a", ":=", "range", "args", "{", "if", "strings", ".", "Contains", "(", "a", ",", "\"", "\"", ")", "{", "if", "build", ".", "IsLocalImport", "(", "a", ")", "{", "out", "=", "append", "(", "out", ",", "allPackagesInFS", "(", "a", ")", "...", ")", "\n", "}", "else", "{", "out", "=", "append", "(", "out", ",", "allPackages", "(", "a", ")", "...", ")", "\n", "}", "\n", "continue", "\n", "}", "\n", "out", "=", "append", "(", "out", ",", "a", ")", "\n", "}", "\n", "return", "out", "\n", "}" ]
// importPaths returns the import paths to use for the given command line.
[ "importPaths", "returns", "the", "import", "paths", "to", "use", "for", "the", "given", "command", "line", "." ]
959b441ac422379a43da2230f62be024250818b0
https://github.com/golang/lint/blob/959b441ac422379a43da2230f62be024250818b0/golint/import.go#L65-L80
train
golang/lint
golint/import.go
hasPathPrefix
func hasPathPrefix(s, prefix string) bool { switch { default: return false case len(s) == len(prefix): return s == prefix case len(s) > len(prefix): if prefix != "" && prefix[len(prefix)-1] == '/' { return strings.HasPrefix(s, prefix) } return s[len(prefix)] == '/' && s[:len(prefix)] == prefix } }
go
func hasPathPrefix(s, prefix string) bool { switch { default: return false case len(s) == len(prefix): return s == prefix case len(s) > len(prefix): if prefix != "" && prefix[len(prefix)-1] == '/' { return strings.HasPrefix(s, prefix) } return s[len(prefix)] == '/' && s[:len(prefix)] == prefix } }
[ "func", "hasPathPrefix", "(", "s", ",", "prefix", "string", ")", "bool", "{", "switch", "{", "default", ":", "return", "false", "\n", "case", "len", "(", "s", ")", "==", "len", "(", "prefix", ")", ":", "return", "s", "==", "prefix", "\n", "case", "len", "(", "s", ")", ">", "len", "(", "prefix", ")", ":", "if", "prefix", "!=", "\"", "\"", "&&", "prefix", "[", "len", "(", "prefix", ")", "-", "1", "]", "==", "'/'", "{", "return", "strings", ".", "HasPrefix", "(", "s", ",", "prefix", ")", "\n", "}", "\n", "return", "s", "[", "len", "(", "prefix", ")", "]", "==", "'/'", "&&", "s", "[", ":", "len", "(", "prefix", ")", "]", "==", "prefix", "\n", "}", "\n", "}" ]
// hasPathPrefix reports whether the path s begins with the // elements in prefix.
[ "hasPathPrefix", "reports", "whether", "the", "path", "s", "begins", "with", "the", "elements", "in", "prefix", "." ]
959b441ac422379a43da2230f62be024250818b0
https://github.com/golang/lint/blob/959b441ac422379a43da2230f62be024250818b0/golint/import.go#L101-L113
train
hashicorp/go-plugin
grpc_client.go
newGRPCClient
func newGRPCClient(doneCtx context.Context, c *Client) (*GRPCClient, error) { conn, err := dialGRPCConn(c.config.TLSConfig, c.dialer) if err != nil { return nil, err } // Start the broker. brokerGRPCClient := newGRPCBrokerClient(conn) broker := newGRPCBroker(brokerGRPCClient, c.config.TLSConfig) go broker.Run() go brokerGRPCClient.StartStream() cl := &GRPCClient{ Conn: conn, Plugins: c.config.Plugins, doneCtx: doneCtx, broker: broker, controller: plugin.NewGRPCControllerClient(conn), } return cl, nil }
go
func newGRPCClient(doneCtx context.Context, c *Client) (*GRPCClient, error) { conn, err := dialGRPCConn(c.config.TLSConfig, c.dialer) if err != nil { return nil, err } // Start the broker. brokerGRPCClient := newGRPCBrokerClient(conn) broker := newGRPCBroker(brokerGRPCClient, c.config.TLSConfig) go broker.Run() go brokerGRPCClient.StartStream() cl := &GRPCClient{ Conn: conn, Plugins: c.config.Plugins, doneCtx: doneCtx, broker: broker, controller: plugin.NewGRPCControllerClient(conn), } return cl, nil }
[ "func", "newGRPCClient", "(", "doneCtx", "context", ".", "Context", ",", "c", "*", "Client", ")", "(", "*", "GRPCClient", ",", "error", ")", "{", "conn", ",", "err", ":=", "dialGRPCConn", "(", "c", ".", "config", ".", "TLSConfig", ",", "c", ".", "dialer", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "// Start the broker.", "brokerGRPCClient", ":=", "newGRPCBrokerClient", "(", "conn", ")", "\n", "broker", ":=", "newGRPCBroker", "(", "brokerGRPCClient", ",", "c", ".", "config", ".", "TLSConfig", ")", "\n", "go", "broker", ".", "Run", "(", ")", "\n", "go", "brokerGRPCClient", ".", "StartStream", "(", ")", "\n\n", "cl", ":=", "&", "GRPCClient", "{", "Conn", ":", "conn", ",", "Plugins", ":", "c", ".", "config", ".", "Plugins", ",", "doneCtx", ":", "doneCtx", ",", "broker", ":", "broker", ",", "controller", ":", "plugin", ".", "NewGRPCControllerClient", "(", "conn", ")", ",", "}", "\n\n", "return", "cl", ",", "nil", "\n", "}" ]
// newGRPCClient creates a new GRPCClient. The Client argument is expected // to be successfully started already with a lock held.
[ "newGRPCClient", "creates", "a", "new", "GRPCClient", ".", "The", "Client", "argument", "is", "expected", "to", "be", "successfully", "started", "already", "with", "a", "lock", "held", "." ]
5692942914bbdbc03558fde936b1f0bc2af365be
https://github.com/hashicorp/go-plugin/blob/5692942914bbdbc03558fde936b1f0bc2af365be/grpc_client.go#L47-L68
train
hashicorp/go-plugin
server_mux.go
ServeMux
func ServeMux(m ServeMuxMap) { if len(os.Args) != 2 { fmt.Fprintf(os.Stderr, "Invoked improperly. This is an internal command that shouldn't\n"+ "be manually invoked.\n") os.Exit(1) } opts, ok := m[os.Args[1]] if !ok { fmt.Fprintf(os.Stderr, "Unknown plugin: %s\n", os.Args[1]) os.Exit(1) } Serve(opts) }
go
func ServeMux(m ServeMuxMap) { if len(os.Args) != 2 { fmt.Fprintf(os.Stderr, "Invoked improperly. This is an internal command that shouldn't\n"+ "be manually invoked.\n") os.Exit(1) } opts, ok := m[os.Args[1]] if !ok { fmt.Fprintf(os.Stderr, "Unknown plugin: %s\n", os.Args[1]) os.Exit(1) } Serve(opts) }
[ "func", "ServeMux", "(", "m", "ServeMuxMap", ")", "{", "if", "len", "(", "os", ".", "Args", ")", "!=", "2", "{", "fmt", ".", "Fprintf", "(", "os", ".", "Stderr", ",", "\"", "\\n", "\"", "+", "\"", "\\n", "\"", ")", "\n", "os", ".", "Exit", "(", "1", ")", "\n", "}", "\n\n", "opts", ",", "ok", ":=", "m", "[", "os", ".", "Args", "[", "1", "]", "]", "\n", "if", "!", "ok", "{", "fmt", ".", "Fprintf", "(", "os", ".", "Stderr", ",", "\"", "\\n", "\"", ",", "os", ".", "Args", "[", "1", "]", ")", "\n", "os", ".", "Exit", "(", "1", ")", "\n", "}", "\n\n", "Serve", "(", "opts", ")", "\n", "}" ]
// ServeMux is like Serve, but serves multiple types of plugins determined // by the argument given on the command-line. // // This command doesn't return until the plugin is done being executed. Any // errors are logged or output to stderr.
[ "ServeMux", "is", "like", "Serve", "but", "serves", "multiple", "types", "of", "plugins", "determined", "by", "the", "argument", "given", "on", "the", "command", "-", "line", ".", "This", "command", "doesn", "t", "return", "until", "the", "plugin", "is", "done", "being", "executed", ".", "Any", "errors", "are", "logged", "or", "output", "to", "stderr", "." ]
5692942914bbdbc03558fde936b1f0bc2af365be
https://github.com/hashicorp/go-plugin/blob/5692942914bbdbc03558fde936b1f0bc2af365be/server_mux.go#L16-L31
train
hashicorp/go-plugin
grpc_broker.go
Recv
func (s *gRPCBrokerServer) Recv() (*plugin.ConnInfo, error) { select { case <-s.quit: return nil, errors.New("broker closed") case i := <-s.recv: return i, nil } }
go
func (s *gRPCBrokerServer) Recv() (*plugin.ConnInfo, error) { select { case <-s.quit: return nil, errors.New("broker closed") case i := <-s.recv: return i, nil } }
[ "func", "(", "s", "*", "gRPCBrokerServer", ")", "Recv", "(", ")", "(", "*", "plugin", ".", "ConnInfo", ",", "error", ")", "{", "select", "{", "case", "<-", "s", ".", "quit", ":", "return", "nil", ",", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "case", "i", ":=", "<-", "s", ".", "recv", ":", "return", "i", ",", "nil", "\n", "}", "\n", "}" ]
// Recv is used by the GRPCBroker to pass connection information that has been // sent from the client from the stream to the broker.
[ "Recv", "is", "used", "by", "the", "GRPCBroker", "to", "pass", "connection", "information", "that", "has", "been", "sent", "from", "the", "client", "from", "the", "stream", "to", "the", "broker", "." ]
5692942914bbdbc03558fde936b1f0bc2af365be
https://github.com/hashicorp/go-plugin/blob/5692942914bbdbc03558fde936b1f0bc2af365be/grpc_broker.go#L120-L127
train
hashicorp/go-plugin
grpc_broker.go
Send
func (s *gRPCBrokerClientImpl) Send(i *plugin.ConnInfo) error { ch := make(chan error) defer close(ch) select { case <-s.quit: return errors.New("broker closed") case s.send <- &sendErr{ i: i, ch: ch, }: } return <-ch }
go
func (s *gRPCBrokerClientImpl) Send(i *plugin.ConnInfo) error { ch := make(chan error) defer close(ch) select { case <-s.quit: return errors.New("broker closed") case s.send <- &sendErr{ i: i, ch: ch, }: } return <-ch }
[ "func", "(", "s", "*", "gRPCBrokerClientImpl", ")", "Send", "(", "i", "*", "plugin", ".", "ConnInfo", ")", "error", "{", "ch", ":=", "make", "(", "chan", "error", ")", "\n", "defer", "close", "(", "ch", ")", "\n\n", "select", "{", "case", "<-", "s", ".", "quit", ":", "return", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "case", "s", ".", "send", "<-", "&", "sendErr", "{", "i", ":", "i", ",", "ch", ":", "ch", ",", "}", ":", "}", "\n\n", "return", "<-", "ch", "\n", "}" ]
// Send is used by the GRPCBroker to pass connection information into the stream // to the plugin.
[ "Send", "is", "used", "by", "the", "GRPCBroker", "to", "pass", "connection", "information", "into", "the", "stream", "to", "the", "plugin", "." ]
5692942914bbdbc03558fde936b1f0bc2af365be
https://github.com/hashicorp/go-plugin/blob/5692942914bbdbc03558fde936b1f0bc2af365be/grpc_broker.go#L212-L226
train
hashicorp/go-plugin
grpc_broker.go
AcceptAndServe
func (b *GRPCBroker) AcceptAndServe(id uint32, s func([]grpc.ServerOption) *grpc.Server) { listener, err := b.Accept(id) if err != nil { log.Printf("[ERR] plugin: plugin acceptAndServe error: %s", err) return } defer listener.Close() var opts []grpc.ServerOption if b.tls != nil { opts = []grpc.ServerOption{grpc.Creds(credentials.NewTLS(b.tls))} } server := s(opts) // Here we use a run group to close this goroutine if the server is shutdown // or the broker is shutdown. var g run.Group { // Serve on the listener, if shutting down call GracefulStop. g.Add(func() error { return server.Serve(listener) }, func(err error) { server.GracefulStop() }) } { // block on the closeCh or the doneCh. If we are shutting down close the // closeCh. closeCh := make(chan struct{}) g.Add(func() error { select { case <-b.doneCh: case <-closeCh: } return nil }, func(err error) { close(closeCh) }) } // Block until we are done g.Run() }
go
func (b *GRPCBroker) AcceptAndServe(id uint32, s func([]grpc.ServerOption) *grpc.Server) { listener, err := b.Accept(id) if err != nil { log.Printf("[ERR] plugin: plugin acceptAndServe error: %s", err) return } defer listener.Close() var opts []grpc.ServerOption if b.tls != nil { opts = []grpc.ServerOption{grpc.Creds(credentials.NewTLS(b.tls))} } server := s(opts) // Here we use a run group to close this goroutine if the server is shutdown // or the broker is shutdown. var g run.Group { // Serve on the listener, if shutting down call GracefulStop. g.Add(func() error { return server.Serve(listener) }, func(err error) { server.GracefulStop() }) } { // block on the closeCh or the doneCh. If we are shutting down close the // closeCh. closeCh := make(chan struct{}) g.Add(func() error { select { case <-b.doneCh: case <-closeCh: } return nil }, func(err error) { close(closeCh) }) } // Block until we are done g.Run() }
[ "func", "(", "b", "*", "GRPCBroker", ")", "AcceptAndServe", "(", "id", "uint32", ",", "s", "func", "(", "[", "]", "grpc", ".", "ServerOption", ")", "*", "grpc", ".", "Server", ")", "{", "listener", ",", "err", ":=", "b", ".", "Accept", "(", "id", ")", "\n", "if", "err", "!=", "nil", "{", "log", ".", "Printf", "(", "\"", "\"", ",", "err", ")", "\n", "return", "\n", "}", "\n", "defer", "listener", ".", "Close", "(", ")", "\n\n", "var", "opts", "[", "]", "grpc", ".", "ServerOption", "\n", "if", "b", ".", "tls", "!=", "nil", "{", "opts", "=", "[", "]", "grpc", ".", "ServerOption", "{", "grpc", ".", "Creds", "(", "credentials", ".", "NewTLS", "(", "b", ".", "tls", ")", ")", "}", "\n", "}", "\n\n", "server", ":=", "s", "(", "opts", ")", "\n\n", "// Here we use a run group to close this goroutine if the server is shutdown", "// or the broker is shutdown.", "var", "g", "run", ".", "Group", "\n", "{", "// Serve on the listener, if shutting down call GracefulStop.", "g", ".", "Add", "(", "func", "(", ")", "error", "{", "return", "server", ".", "Serve", "(", "listener", ")", "\n", "}", ",", "func", "(", "err", "error", ")", "{", "server", ".", "GracefulStop", "(", ")", "\n", "}", ")", "\n", "}", "\n", "{", "// block on the closeCh or the doneCh. If we are shutting down close the", "// closeCh.", "closeCh", ":=", "make", "(", "chan", "struct", "{", "}", ")", "\n", "g", ".", "Add", "(", "func", "(", ")", "error", "{", "select", "{", "case", "<-", "b", ".", "doneCh", ":", "case", "<-", "closeCh", ":", "}", "\n", "return", "nil", "\n", "}", ",", "func", "(", "err", "error", ")", "{", "close", "(", "closeCh", ")", "\n", "}", ")", "\n", "}", "\n\n", "// Block until we are done", "g", ".", "Run", "(", ")", "\n", "}" ]
// AcceptAndServe is used to accept a specific stream ID and immediately // serve a gRPC server on that stream ID. This is used to easily serve // complex arguments. Each AcceptAndServe call opens a new listener socket and // sends the connection info down the stream to the dialer. Since a new // connection is opened every call, these calls should be used sparingly. // Multiple gRPC server implementations can be registered to a single // AcceptAndServe call.
[ "AcceptAndServe", "is", "used", "to", "accept", "a", "specific", "stream", "ID", "and", "immediately", "serve", "a", "gRPC", "server", "on", "that", "stream", "ID", ".", "This", "is", "used", "to", "easily", "serve", "complex", "arguments", ".", "Each", "AcceptAndServe", "call", "opens", "a", "new", "listener", "socket", "and", "sends", "the", "connection", "info", "down", "the", "stream", "to", "the", "dialer", ".", "Since", "a", "new", "connection", "is", "opened", "every", "call", "these", "calls", "should", "be", "used", "sparingly", ".", "Multiple", "gRPC", "server", "implementations", "can", "be", "registered", "to", "a", "single", "AcceptAndServe", "call", "." ]
5692942914bbdbc03558fde936b1f0bc2af365be
https://github.com/hashicorp/go-plugin/blob/5692942914bbdbc03558fde936b1f0bc2af365be/grpc_broker.go#L312-L355
train
hashicorp/go-plugin
grpc_broker.go
Close
func (b *GRPCBroker) Close() error { b.streamer.Close() b.o.Do(func() { close(b.doneCh) }) return nil }
go
func (b *GRPCBroker) Close() error { b.streamer.Close() b.o.Do(func() { close(b.doneCh) }) return nil }
[ "func", "(", "b", "*", "GRPCBroker", ")", "Close", "(", ")", "error", "{", "b", ".", "streamer", ".", "Close", "(", ")", "\n", "b", ".", "o", ".", "Do", "(", "func", "(", ")", "{", "close", "(", "b", ".", "doneCh", ")", "\n", "}", ")", "\n", "return", "nil", "\n", "}" ]
// Close closes the stream and all servers.
[ "Close", "closes", "the", "stream", "and", "all", "servers", "." ]
5692942914bbdbc03558fde936b1f0bc2af365be
https://github.com/hashicorp/go-plugin/blob/5692942914bbdbc03558fde936b1f0bc2af365be/grpc_broker.go#L358-L364
train
hashicorp/go-plugin
log_entry.go
parseJSON
func parseJSON(input []byte) (*logEntry, error) { var raw map[string]interface{} entry := &logEntry{} err := json.Unmarshal(input, &raw) if err != nil { return nil, err } // Parse hclog-specific objects if v, ok := raw["@message"]; ok { entry.Message = v.(string) delete(raw, "@message") } if v, ok := raw["@level"]; ok { entry.Level = v.(string) delete(raw, "@level") } if v, ok := raw["@timestamp"]; ok { t, err := time.Parse("2006-01-02T15:04:05.000000Z07:00", v.(string)) if err != nil { return nil, err } entry.Timestamp = t delete(raw, "@timestamp") } // Parse dynamic KV args from the hclog payload. for k, v := range raw { entry.KVPairs = append(entry.KVPairs, &logEntryKV{ Key: k, Value: v, }) } return entry, nil }
go
func parseJSON(input []byte) (*logEntry, error) { var raw map[string]interface{} entry := &logEntry{} err := json.Unmarshal(input, &raw) if err != nil { return nil, err } // Parse hclog-specific objects if v, ok := raw["@message"]; ok { entry.Message = v.(string) delete(raw, "@message") } if v, ok := raw["@level"]; ok { entry.Level = v.(string) delete(raw, "@level") } if v, ok := raw["@timestamp"]; ok { t, err := time.Parse("2006-01-02T15:04:05.000000Z07:00", v.(string)) if err != nil { return nil, err } entry.Timestamp = t delete(raw, "@timestamp") } // Parse dynamic KV args from the hclog payload. for k, v := range raw { entry.KVPairs = append(entry.KVPairs, &logEntryKV{ Key: k, Value: v, }) } return entry, nil }
[ "func", "parseJSON", "(", "input", "[", "]", "byte", ")", "(", "*", "logEntry", ",", "error", ")", "{", "var", "raw", "map", "[", "string", "]", "interface", "{", "}", "\n", "entry", ":=", "&", "logEntry", "{", "}", "\n\n", "err", ":=", "json", ".", "Unmarshal", "(", "input", ",", "&", "raw", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "// Parse hclog-specific objects", "if", "v", ",", "ok", ":=", "raw", "[", "\"", "\"", "]", ";", "ok", "{", "entry", ".", "Message", "=", "v", ".", "(", "string", ")", "\n", "delete", "(", "raw", ",", "\"", "\"", ")", "\n", "}", "\n\n", "if", "v", ",", "ok", ":=", "raw", "[", "\"", "\"", "]", ";", "ok", "{", "entry", ".", "Level", "=", "v", ".", "(", "string", ")", "\n", "delete", "(", "raw", ",", "\"", "\"", ")", "\n", "}", "\n\n", "if", "v", ",", "ok", ":=", "raw", "[", "\"", "\"", "]", ";", "ok", "{", "t", ",", "err", ":=", "time", ".", "Parse", "(", "\"", "\"", ",", "v", ".", "(", "string", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "entry", ".", "Timestamp", "=", "t", "\n", "delete", "(", "raw", ",", "\"", "\"", ")", "\n", "}", "\n\n", "// Parse dynamic KV args from the hclog payload.", "for", "k", ",", "v", ":=", "range", "raw", "{", "entry", ".", "KVPairs", "=", "append", "(", "entry", ".", "KVPairs", ",", "&", "logEntryKV", "{", "Key", ":", "k", ",", "Value", ":", "v", ",", "}", ")", "\n", "}", "\n\n", "return", "entry", ",", "nil", "\n", "}" ]
// parseJSON handles parsing JSON output
[ "parseJSON", "handles", "parsing", "JSON", "output" ]
5692942914bbdbc03558fde936b1f0bc2af365be
https://github.com/hashicorp/go-plugin/blob/5692942914bbdbc03558fde936b1f0bc2af365be/log_entry.go#L35-L73
train
hashicorp/go-plugin
client.go
Check
func (s *SecureConfig) Check(filePath string) (bool, error) { if len(s.Checksum) == 0 { return false, ErrSecureConfigNoChecksum } if s.Hash == nil { return false, ErrSecureConfigNoHash } file, err := os.Open(filePath) if err != nil { return false, err } defer file.Close() _, err = io.Copy(s.Hash, file) if err != nil { return false, err } sum := s.Hash.Sum(nil) return subtle.ConstantTimeCompare(sum, s.Checksum) == 1, nil }
go
func (s *SecureConfig) Check(filePath string) (bool, error) { if len(s.Checksum) == 0 { return false, ErrSecureConfigNoChecksum } if s.Hash == nil { return false, ErrSecureConfigNoHash } file, err := os.Open(filePath) if err != nil { return false, err } defer file.Close() _, err = io.Copy(s.Hash, file) if err != nil { return false, err } sum := s.Hash.Sum(nil) return subtle.ConstantTimeCompare(sum, s.Checksum) == 1, nil }
[ "func", "(", "s", "*", "SecureConfig", ")", "Check", "(", "filePath", "string", ")", "(", "bool", ",", "error", ")", "{", "if", "len", "(", "s", ".", "Checksum", ")", "==", "0", "{", "return", "false", ",", "ErrSecureConfigNoChecksum", "\n", "}", "\n\n", "if", "s", ".", "Hash", "==", "nil", "{", "return", "false", ",", "ErrSecureConfigNoHash", "\n", "}", "\n\n", "file", ",", "err", ":=", "os", ".", "Open", "(", "filePath", ")", "\n", "if", "err", "!=", "nil", "{", "return", "false", ",", "err", "\n", "}", "\n", "defer", "file", ".", "Close", "(", ")", "\n\n", "_", ",", "err", "=", "io", ".", "Copy", "(", "s", ".", "Hash", ",", "file", ")", "\n", "if", "err", "!=", "nil", "{", "return", "false", ",", "err", "\n", "}", "\n\n", "sum", ":=", "s", ".", "Hash", ".", "Sum", "(", "nil", ")", "\n\n", "return", "subtle", ".", "ConstantTimeCompare", "(", "sum", ",", "s", ".", "Checksum", ")", "==", "1", ",", "nil", "\n", "}" ]
// Check takes the filepath to an executable and returns true if the checksum of // the file matches the checksum provided in the SecureConfig.
[ "Check", "takes", "the", "filepath", "to", "an", "executable", "and", "returns", "true", "if", "the", "checksum", "of", "the", "file", "matches", "the", "checksum", "provided", "in", "the", "SecureConfig", "." ]
5692942914bbdbc03558fde936b1f0bc2af365be
https://github.com/hashicorp/go-plugin/blob/5692942914bbdbc03558fde936b1f0bc2af365be/client.go#L233-L256
train
hashicorp/go-plugin
client.go
Client
func (c *Client) Client() (ClientProtocol, error) { _, err := c.Start() if err != nil { return nil, err } c.l.Lock() defer c.l.Unlock() if c.client != nil { return c.client, nil } switch c.protocol { case ProtocolNetRPC: c.client, err = newRPCClient(c) case ProtocolGRPC: c.client, err = newGRPCClient(c.doneCtx, c) default: return nil, fmt.Errorf("unknown server protocol: %s", c.protocol) } if err != nil { c.client = nil return nil, err } return c.client, nil }
go
func (c *Client) Client() (ClientProtocol, error) { _, err := c.Start() if err != nil { return nil, err } c.l.Lock() defer c.l.Unlock() if c.client != nil { return c.client, nil } switch c.protocol { case ProtocolNetRPC: c.client, err = newRPCClient(c) case ProtocolGRPC: c.client, err = newGRPCClient(c.doneCtx, c) default: return nil, fmt.Errorf("unknown server protocol: %s", c.protocol) } if err != nil { c.client = nil return nil, err } return c.client, nil }
[ "func", "(", "c", "*", "Client", ")", "Client", "(", ")", "(", "ClientProtocol", ",", "error", ")", "{", "_", ",", "err", ":=", "c", ".", "Start", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "c", ".", "l", ".", "Lock", "(", ")", "\n", "defer", "c", ".", "l", ".", "Unlock", "(", ")", "\n\n", "if", "c", ".", "client", "!=", "nil", "{", "return", "c", ".", "client", ",", "nil", "\n", "}", "\n\n", "switch", "c", ".", "protocol", "{", "case", "ProtocolNetRPC", ":", "c", ".", "client", ",", "err", "=", "newRPCClient", "(", "c", ")", "\n\n", "case", "ProtocolGRPC", ":", "c", ".", "client", ",", "err", "=", "newGRPCClient", "(", "c", ".", "doneCtx", ",", "c", ")", "\n\n", "default", ":", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "c", ".", "protocol", ")", "\n", "}", "\n\n", "if", "err", "!=", "nil", "{", "c", ".", "client", "=", "nil", "\n", "return", "nil", ",", "err", "\n", "}", "\n\n", "return", "c", ".", "client", ",", "nil", "\n", "}" ]
// Client returns the protocol client for this connection. // // Subsequent calls to this will return the same client.
[ "Client", "returns", "the", "protocol", "client", "for", "this", "connection", ".", "Subsequent", "calls", "to", "this", "will", "return", "the", "same", "client", "." ]
5692942914bbdbc03558fde936b1f0bc2af365be
https://github.com/hashicorp/go-plugin/blob/5692942914bbdbc03558fde936b1f0bc2af365be/client.go#L340-L370
train
hashicorp/go-plugin
client.go
killed
func (c *Client) killed() bool { c.l.Lock() defer c.l.Unlock() return c.processKilled }
go
func (c *Client) killed() bool { c.l.Lock() defer c.l.Unlock() return c.processKilled }
[ "func", "(", "c", "*", "Client", ")", "killed", "(", ")", "bool", "{", "c", ".", "l", ".", "Lock", "(", ")", "\n", "defer", "c", ".", "l", ".", "Unlock", "(", ")", "\n", "return", "c", ".", "processKilled", "\n", "}" ]
// killed is used in tests to check if a process failed to exit gracefully, and // needed to be killed.
[ "killed", "is", "used", "in", "tests", "to", "check", "if", "a", "process", "failed", "to", "exit", "gracefully", "and", "needed", "to", "be", "killed", "." ]
5692942914bbdbc03558fde936b1f0bc2af365be
https://github.com/hashicorp/go-plugin/blob/5692942914bbdbc03558fde936b1f0bc2af365be/client.go#L381-L385
train
hashicorp/go-plugin
client.go
loadServerCert
func (c *Client) loadServerCert(cert string) error { certPool := x509.NewCertPool() asn1, err := base64.RawStdEncoding.DecodeString(cert) if err != nil { return err } x509Cert, err := x509.ParseCertificate([]byte(asn1)) if err != nil { return err } certPool.AddCert(x509Cert) c.config.TLSConfig.RootCAs = certPool return nil }
go
func (c *Client) loadServerCert(cert string) error { certPool := x509.NewCertPool() asn1, err := base64.RawStdEncoding.DecodeString(cert) if err != nil { return err } x509Cert, err := x509.ParseCertificate([]byte(asn1)) if err != nil { return err } certPool.AddCert(x509Cert) c.config.TLSConfig.RootCAs = certPool return nil }
[ "func", "(", "c", "*", "Client", ")", "loadServerCert", "(", "cert", "string", ")", "error", "{", "certPool", ":=", "x509", ".", "NewCertPool", "(", ")", "\n\n", "asn1", ",", "err", ":=", "base64", ".", "RawStdEncoding", ".", "DecodeString", "(", "cert", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "x509Cert", ",", "err", ":=", "x509", ".", "ParseCertificate", "(", "[", "]", "byte", "(", "asn1", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "certPool", ".", "AddCert", "(", "x509Cert", ")", "\n\n", "c", ".", "config", ".", "TLSConfig", ".", "RootCAs", "=", "certPool", "\n", "return", "nil", "\n", "}" ]
// loadServerCert is used by AutoMTLS to read an x.509 cert returned by the // server, and load it as the RootCA for the client TLSConfig.
[ "loadServerCert", "is", "used", "by", "AutoMTLS", "to", "read", "an", "x", ".", "509", "cert", "returned", "by", "the", "server", "and", "load", "it", "as", "the", "RootCA", "for", "the", "client", "TLSConfig", "." ]
5692942914bbdbc03558fde936b1f0bc2af365be
https://github.com/hashicorp/go-plugin/blob/5692942914bbdbc03558fde936b1f0bc2af365be/client.go#L759-L776
train
hashicorp/go-plugin
client.go
checkProtoVersion
func (c *Client) checkProtoVersion(protoVersion string) (int, PluginSet, error) { serverVersion, err := strconv.Atoi(protoVersion) if err != nil { return 0, nil, fmt.Errorf("Error parsing protocol version %q: %s", protoVersion, err) } // record these for the error message var clientVersions []int // all versions, including the legacy ProtocolVersion have been added to // the versions set for version, plugins := range c.config.VersionedPlugins { clientVersions = append(clientVersions, version) if serverVersion != version { continue } return version, plugins, nil } return 0, nil, fmt.Errorf("Incompatible API version with plugin. "+ "Plugin version: %d, Client versions: %d", serverVersion, clientVersions) }
go
func (c *Client) checkProtoVersion(protoVersion string) (int, PluginSet, error) { serverVersion, err := strconv.Atoi(protoVersion) if err != nil { return 0, nil, fmt.Errorf("Error parsing protocol version %q: %s", protoVersion, err) } // record these for the error message var clientVersions []int // all versions, including the legacy ProtocolVersion have been added to // the versions set for version, plugins := range c.config.VersionedPlugins { clientVersions = append(clientVersions, version) if serverVersion != version { continue } return version, plugins, nil } return 0, nil, fmt.Errorf("Incompatible API version with plugin. "+ "Plugin version: %d, Client versions: %d", serverVersion, clientVersions) }
[ "func", "(", "c", "*", "Client", ")", "checkProtoVersion", "(", "protoVersion", "string", ")", "(", "int", ",", "PluginSet", ",", "error", ")", "{", "serverVersion", ",", "err", ":=", "strconv", ".", "Atoi", "(", "protoVersion", ")", "\n", "if", "err", "!=", "nil", "{", "return", "0", ",", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "protoVersion", ",", "err", ")", "\n", "}", "\n\n", "// record these for the error message", "var", "clientVersions", "[", "]", "int", "\n\n", "// all versions, including the legacy ProtocolVersion have been added to", "// the versions set", "for", "version", ",", "plugins", ":=", "range", "c", ".", "config", ".", "VersionedPlugins", "{", "clientVersions", "=", "append", "(", "clientVersions", ",", "version", ")", "\n\n", "if", "serverVersion", "!=", "version", "{", "continue", "\n", "}", "\n", "return", "version", ",", "plugins", ",", "nil", "\n", "}", "\n\n", "return", "0", ",", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", "+", "\"", "\"", ",", "serverVersion", ",", "clientVersions", ")", "\n", "}" ]
// checkProtoVersion returns the negotiated version and PluginSet. // This returns an error if the server returned an incompatible protocol // version, or an invalid handshake response.
[ "checkProtoVersion", "returns", "the", "negotiated", "version", "and", "PluginSet", ".", "This", "returns", "an", "error", "if", "the", "server", "returned", "an", "incompatible", "protocol", "version", "or", "an", "invalid", "handshake", "response", "." ]
5692942914bbdbc03558fde936b1f0bc2af365be
https://github.com/hashicorp/go-plugin/blob/5692942914bbdbc03558fde936b1f0bc2af365be/client.go#L834-L856
train
hashicorp/go-plugin
client.go
ReattachConfig
func (c *Client) ReattachConfig() *ReattachConfig { c.l.Lock() defer c.l.Unlock() if c.address == nil { return nil } if c.config.Cmd != nil && c.config.Cmd.Process == nil { return nil } // If we connected via reattach, just return the information as-is if c.config.Reattach != nil { return c.config.Reattach } return &ReattachConfig{ Protocol: c.protocol, Addr: c.address, Pid: c.config.Cmd.Process.Pid, } }
go
func (c *Client) ReattachConfig() *ReattachConfig { c.l.Lock() defer c.l.Unlock() if c.address == nil { return nil } if c.config.Cmd != nil && c.config.Cmd.Process == nil { return nil } // If we connected via reattach, just return the information as-is if c.config.Reattach != nil { return c.config.Reattach } return &ReattachConfig{ Protocol: c.protocol, Addr: c.address, Pid: c.config.Cmd.Process.Pid, } }
[ "func", "(", "c", "*", "Client", ")", "ReattachConfig", "(", ")", "*", "ReattachConfig", "{", "c", ".", "l", ".", "Lock", "(", ")", "\n", "defer", "c", ".", "l", ".", "Unlock", "(", ")", "\n\n", "if", "c", ".", "address", "==", "nil", "{", "return", "nil", "\n", "}", "\n\n", "if", "c", ".", "config", ".", "Cmd", "!=", "nil", "&&", "c", ".", "config", ".", "Cmd", ".", "Process", "==", "nil", "{", "return", "nil", "\n", "}", "\n\n", "// If we connected via reattach, just return the information as-is", "if", "c", ".", "config", ".", "Reattach", "!=", "nil", "{", "return", "c", ".", "config", ".", "Reattach", "\n", "}", "\n\n", "return", "&", "ReattachConfig", "{", "Protocol", ":", "c", ".", "protocol", ",", "Addr", ":", "c", ".", "address", ",", "Pid", ":", "c", ".", "config", ".", "Cmd", ".", "Process", ".", "Pid", ",", "}", "\n", "}" ]
// ReattachConfig returns the information that must be provided to NewClient // to reattach to the plugin process that this client started. This is // useful for plugins that detach from their parent process. // // If this returns nil then the process hasn't been started yet. Please // call Start or Client before calling this.
[ "ReattachConfig", "returns", "the", "information", "that", "must", "be", "provided", "to", "NewClient", "to", "reattach", "to", "the", "plugin", "process", "that", "this", "client", "started", ".", "This", "is", "useful", "for", "plugins", "that", "detach", "from", "their", "parent", "process", ".", "If", "this", "returns", "nil", "then", "the", "process", "hasn", "t", "been", "started", "yet", ".", "Please", "call", "Start", "or", "Client", "before", "calling", "this", "." ]
5692942914bbdbc03558fde936b1f0bc2af365be
https://github.com/hashicorp/go-plugin/blob/5692942914bbdbc03558fde936b1f0bc2af365be/client.go#L864-L886
train
hashicorp/go-plugin
client.go
Protocol
func (c *Client) Protocol() Protocol { _, err := c.Start() if err != nil { return ProtocolInvalid } return c.protocol }
go
func (c *Client) Protocol() Protocol { _, err := c.Start() if err != nil { return ProtocolInvalid } return c.protocol }
[ "func", "(", "c", "*", "Client", ")", "Protocol", "(", ")", "Protocol", "{", "_", ",", "err", ":=", "c", ".", "Start", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "ProtocolInvalid", "\n", "}", "\n\n", "return", "c", ".", "protocol", "\n", "}" ]
// Protocol returns the protocol of server on the remote end. This will // start the plugin process if it isn't already started. Errors from // starting the plugin are surpressed and ProtocolInvalid is returned. It // is recommended you call Start explicitly before calling Protocol to ensure // no errors occur.
[ "Protocol", "returns", "the", "protocol", "of", "server", "on", "the", "remote", "end", ".", "This", "will", "start", "the", "plugin", "process", "if", "it", "isn", "t", "already", "started", ".", "Errors", "from", "starting", "the", "plugin", "are", "surpressed", "and", "ProtocolInvalid", "is", "returned", ".", "It", "is", "recommended", "you", "call", "Start", "explicitly", "before", "calling", "Protocol", "to", "ensure", "no", "errors", "occur", "." ]
5692942914bbdbc03558fde936b1f0bc2af365be
https://github.com/hashicorp/go-plugin/blob/5692942914bbdbc03558fde936b1f0bc2af365be/client.go#L893-L900
train
hashicorp/go-plugin
client.go
dialer
func (c *Client) dialer(_ string, timeout time.Duration) (net.Conn, error) { conn, err := netAddrDialer(c.address)("", timeout) if err != nil { return nil, err } // If we have a TLS config we wrap our connection. We only do this // for net/rpc since gRPC uses its own mechanism for TLS. if c.protocol == ProtocolNetRPC && c.config.TLSConfig != nil { conn = tls.Client(conn, c.config.TLSConfig) } return conn, nil }
go
func (c *Client) dialer(_ string, timeout time.Duration) (net.Conn, error) { conn, err := netAddrDialer(c.address)("", timeout) if err != nil { return nil, err } // If we have a TLS config we wrap our connection. We only do this // for net/rpc since gRPC uses its own mechanism for TLS. if c.protocol == ProtocolNetRPC && c.config.TLSConfig != nil { conn = tls.Client(conn, c.config.TLSConfig) } return conn, nil }
[ "func", "(", "c", "*", "Client", ")", "dialer", "(", "_", "string", ",", "timeout", "time", ".", "Duration", ")", "(", "net", ".", "Conn", ",", "error", ")", "{", "conn", ",", "err", ":=", "netAddrDialer", "(", "c", ".", "address", ")", "(", "\"", "\"", ",", "timeout", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "// If we have a TLS config we wrap our connection. We only do this", "// for net/rpc since gRPC uses its own mechanism for TLS.", "if", "c", ".", "protocol", "==", "ProtocolNetRPC", "&&", "c", ".", "config", ".", "TLSConfig", "!=", "nil", "{", "conn", "=", "tls", ".", "Client", "(", "conn", ",", "c", ".", "config", ".", "TLSConfig", ")", "\n", "}", "\n\n", "return", "conn", ",", "nil", "\n", "}" ]
// dialer is compatible with grpc.WithDialer and creates the connection // to the plugin.
[ "dialer", "is", "compatible", "with", "grpc", ".", "WithDialer", "and", "creates", "the", "connection", "to", "the", "plugin", "." ]
5692942914bbdbc03558fde936b1f0bc2af365be
https://github.com/hashicorp/go-plugin/blob/5692942914bbdbc03558fde936b1f0bc2af365be/client.go#L920-L933
train
hashicorp/go-plugin
mtls.go
generateCert
func generateCert() (cert []byte, privateKey []byte, err error) { key, err := ecdsa.GenerateKey(elliptic.P521(), rand.Reader) if err != nil { return nil, nil, err } serialNumberLimit := new(big.Int).Lsh(big.NewInt(1), 128) sn, err := rand.Int(rand.Reader, serialNumberLimit) if err != nil { return nil, nil, err } host := "localhost" template := &x509.Certificate{ Subject: pkix.Name{ CommonName: host, Organization: []string{"HashiCorp"}, }, DNSNames: []string{host}, ExtKeyUsage: []x509.ExtKeyUsage{ x509.ExtKeyUsageClientAuth, x509.ExtKeyUsageServerAuth, }, KeyUsage: x509.KeyUsageDigitalSignature | x509.KeyUsageKeyEncipherment | x509.KeyUsageKeyAgreement | x509.KeyUsageCertSign, BasicConstraintsValid: true, SerialNumber: sn, NotBefore: time.Now().Add(-30 * time.Second), NotAfter: time.Now().Add(262980 * time.Hour), IsCA: true, } der, err := x509.CreateCertificate(rand.Reader, template, template, key.Public(), key) if err != nil { return nil, nil, err } var certOut bytes.Buffer if err := pem.Encode(&certOut, &pem.Block{Type: "CERTIFICATE", Bytes: der}); err != nil { return nil, nil, err } keyBytes, err := x509.MarshalECPrivateKey(key) if err != nil { return nil, nil, err } var keyOut bytes.Buffer if err := pem.Encode(&keyOut, &pem.Block{Type: "EC PRIVATE KEY", Bytes: keyBytes}); err != nil { return nil, nil, err } cert = certOut.Bytes() privateKey = keyOut.Bytes() return cert, privateKey, nil }
go
func generateCert() (cert []byte, privateKey []byte, err error) { key, err := ecdsa.GenerateKey(elliptic.P521(), rand.Reader) if err != nil { return nil, nil, err } serialNumberLimit := new(big.Int).Lsh(big.NewInt(1), 128) sn, err := rand.Int(rand.Reader, serialNumberLimit) if err != nil { return nil, nil, err } host := "localhost" template := &x509.Certificate{ Subject: pkix.Name{ CommonName: host, Organization: []string{"HashiCorp"}, }, DNSNames: []string{host}, ExtKeyUsage: []x509.ExtKeyUsage{ x509.ExtKeyUsageClientAuth, x509.ExtKeyUsageServerAuth, }, KeyUsage: x509.KeyUsageDigitalSignature | x509.KeyUsageKeyEncipherment | x509.KeyUsageKeyAgreement | x509.KeyUsageCertSign, BasicConstraintsValid: true, SerialNumber: sn, NotBefore: time.Now().Add(-30 * time.Second), NotAfter: time.Now().Add(262980 * time.Hour), IsCA: true, } der, err := x509.CreateCertificate(rand.Reader, template, template, key.Public(), key) if err != nil { return nil, nil, err } var certOut bytes.Buffer if err := pem.Encode(&certOut, &pem.Block{Type: "CERTIFICATE", Bytes: der}); err != nil { return nil, nil, err } keyBytes, err := x509.MarshalECPrivateKey(key) if err != nil { return nil, nil, err } var keyOut bytes.Buffer if err := pem.Encode(&keyOut, &pem.Block{Type: "EC PRIVATE KEY", Bytes: keyBytes}); err != nil { return nil, nil, err } cert = certOut.Bytes() privateKey = keyOut.Bytes() return cert, privateKey, nil }
[ "func", "generateCert", "(", ")", "(", "cert", "[", "]", "byte", ",", "privateKey", "[", "]", "byte", ",", "err", "error", ")", "{", "key", ",", "err", ":=", "ecdsa", ".", "GenerateKey", "(", "elliptic", ".", "P521", "(", ")", ",", "rand", ".", "Reader", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "nil", ",", "err", "\n", "}", "\n\n", "serialNumberLimit", ":=", "new", "(", "big", ".", "Int", ")", ".", "Lsh", "(", "big", ".", "NewInt", "(", "1", ")", ",", "128", ")", "\n", "sn", ",", "err", ":=", "rand", ".", "Int", "(", "rand", ".", "Reader", ",", "serialNumberLimit", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "nil", ",", "err", "\n", "}", "\n\n", "host", ":=", "\"", "\"", "\n\n", "template", ":=", "&", "x509", ".", "Certificate", "{", "Subject", ":", "pkix", ".", "Name", "{", "CommonName", ":", "host", ",", "Organization", ":", "[", "]", "string", "{", "\"", "\"", "}", ",", "}", ",", "DNSNames", ":", "[", "]", "string", "{", "host", "}", ",", "ExtKeyUsage", ":", "[", "]", "x509", ".", "ExtKeyUsage", "{", "x509", ".", "ExtKeyUsageClientAuth", ",", "x509", ".", "ExtKeyUsageServerAuth", ",", "}", ",", "KeyUsage", ":", "x509", ".", "KeyUsageDigitalSignature", "|", "x509", ".", "KeyUsageKeyEncipherment", "|", "x509", ".", "KeyUsageKeyAgreement", "|", "x509", ".", "KeyUsageCertSign", ",", "BasicConstraintsValid", ":", "true", ",", "SerialNumber", ":", "sn", ",", "NotBefore", ":", "time", ".", "Now", "(", ")", ".", "Add", "(", "-", "30", "*", "time", ".", "Second", ")", ",", "NotAfter", ":", "time", ".", "Now", "(", ")", ".", "Add", "(", "262980", "*", "time", ".", "Hour", ")", ",", "IsCA", ":", "true", ",", "}", "\n\n", "der", ",", "err", ":=", "x509", ".", "CreateCertificate", "(", "rand", ".", "Reader", ",", "template", ",", "template", ",", "key", ".", "Public", "(", ")", ",", "key", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "nil", ",", "err", "\n", "}", "\n\n", "var", "certOut", "bytes", ".", "Buffer", "\n", "if", "err", ":=", "pem", ".", "Encode", "(", "&", "certOut", ",", "&", "pem", ".", "Block", "{", "Type", ":", "\"", "\"", ",", "Bytes", ":", "der", "}", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "nil", ",", "err", "\n", "}", "\n\n", "keyBytes", ",", "err", ":=", "x509", ".", "MarshalECPrivateKey", "(", "key", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "nil", ",", "err", "\n", "}", "\n\n", "var", "keyOut", "bytes", ".", "Buffer", "\n", "if", "err", ":=", "pem", ".", "Encode", "(", "&", "keyOut", ",", "&", "pem", ".", "Block", "{", "Type", ":", "\"", "\"", ",", "Bytes", ":", "keyBytes", "}", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "nil", ",", "err", "\n", "}", "\n\n", "cert", "=", "certOut", ".", "Bytes", "(", ")", "\n", "privateKey", "=", "keyOut", ".", "Bytes", "(", ")", "\n\n", "return", "cert", ",", "privateKey", ",", "nil", "\n", "}" ]
// generateCert generates a temporary certificate for plugin authentication. The // certificate and private key are returns in PEM format.
[ "generateCert", "generates", "a", "temporary", "certificate", "for", "plugin", "authentication", ".", "The", "certificate", "and", "private", "key", "are", "returns", "in", "PEM", "format", "." ]
5692942914bbdbc03558fde936b1f0bc2af365be
https://github.com/hashicorp/go-plugin/blob/5692942914bbdbc03558fde936b1f0bc2af365be/mtls.go#L17-L73
train
hashicorp/go-plugin
process_windows.go
_pidAlive
func _pidAlive(pid int) bool { h, err := syscall.OpenProcess(processDesiredAccess, false, uint32(pid)) if err != nil { return false } var ec uint32 if e := syscall.GetExitCodeProcess(h, &ec); e != nil { return false } return ec == exit_STILL_ACTIVE }
go
func _pidAlive(pid int) bool { h, err := syscall.OpenProcess(processDesiredAccess, false, uint32(pid)) if err != nil { return false } var ec uint32 if e := syscall.GetExitCodeProcess(h, &ec); e != nil { return false } return ec == exit_STILL_ACTIVE }
[ "func", "_pidAlive", "(", "pid", "int", ")", "bool", "{", "h", ",", "err", ":=", "syscall", ".", "OpenProcess", "(", "processDesiredAccess", ",", "false", ",", "uint32", "(", "pid", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "false", "\n", "}", "\n\n", "var", "ec", "uint32", "\n", "if", "e", ":=", "syscall", ".", "GetExitCodeProcess", "(", "h", ",", "&", "ec", ")", ";", "e", "!=", "nil", "{", "return", "false", "\n", "}", "\n\n", "return", "ec", "==", "exit_STILL_ACTIVE", "\n", "}" ]
// _pidAlive tests whether a process is alive or not
[ "_pidAlive", "tests", "whether", "a", "process", "is", "alive", "or", "not" ]
5692942914bbdbc03558fde936b1f0bc2af365be
https://github.com/hashicorp/go-plugin/blob/5692942914bbdbc03558fde936b1f0bc2af365be/process_windows.go#L17-L29
train
hashicorp/go-plugin
grpc_server.go
Config
func (s *GRPCServer) Config() string { // Create a buffer that will contain our final contents var buf bytes.Buffer // Wrap the base64 encoding with JSON encoding. if err := json.NewEncoder(&buf).Encode(s.config); err != nil { // We panic since ths shouldn't happen under any scenario. We // carefully control the structure being encoded here and it should // always be successful. panic(err) } return buf.String() }
go
func (s *GRPCServer) Config() string { // Create a buffer that will contain our final contents var buf bytes.Buffer // Wrap the base64 encoding with JSON encoding. if err := json.NewEncoder(&buf).Encode(s.config); err != nil { // We panic since ths shouldn't happen under any scenario. We // carefully control the structure being encoded here and it should // always be successful. panic(err) } return buf.String() }
[ "func", "(", "s", "*", "GRPCServer", ")", "Config", "(", ")", "string", "{", "// Create a buffer that will contain our final contents", "var", "buf", "bytes", ".", "Buffer", "\n\n", "// Wrap the base64 encoding with JSON encoding.", "if", "err", ":=", "json", ".", "NewEncoder", "(", "&", "buf", ")", ".", "Encode", "(", "s", ".", "config", ")", ";", "err", "!=", "nil", "{", "// We panic since ths shouldn't happen under any scenario. We", "// carefully control the structure being encoded here and it should", "// always be successful.", "panic", "(", "err", ")", "\n", "}", "\n\n", "return", "buf", ".", "String", "(", ")", "\n", "}" ]
// Config is the GRPCServerConfig encoded as JSON then base64.
[ "Config", "is", "the", "GRPCServerConfig", "encoded", "as", "JSON", "then", "base64", "." ]
5692942914bbdbc03558fde936b1f0bc2af365be
https://github.com/hashicorp/go-plugin/blob/5692942914bbdbc03558fde936b1f0bc2af365be/grpc_server.go#L114-L127
train
hashicorp/go-plugin
rpc_client.go
newRPCClient
func newRPCClient(c *Client) (*RPCClient, error) { // Connect to the client conn, err := net.Dial(c.address.Network(), c.address.String()) if err != nil { return nil, err } if tcpConn, ok := conn.(*net.TCPConn); ok { // Make sure to set keep alive so that the connection doesn't die tcpConn.SetKeepAlive(true) } if c.config.TLSConfig != nil { conn = tls.Client(conn, c.config.TLSConfig) } // Create the actual RPC client result, err := NewRPCClient(conn, c.config.Plugins) if err != nil { conn.Close() return nil, err } // Begin the stream syncing so that stdin, out, err work properly err = result.SyncStreams( c.config.SyncStdout, c.config.SyncStderr) if err != nil { result.Close() return nil, err } return result, nil }
go
func newRPCClient(c *Client) (*RPCClient, error) { // Connect to the client conn, err := net.Dial(c.address.Network(), c.address.String()) if err != nil { return nil, err } if tcpConn, ok := conn.(*net.TCPConn); ok { // Make sure to set keep alive so that the connection doesn't die tcpConn.SetKeepAlive(true) } if c.config.TLSConfig != nil { conn = tls.Client(conn, c.config.TLSConfig) } // Create the actual RPC client result, err := NewRPCClient(conn, c.config.Plugins) if err != nil { conn.Close() return nil, err } // Begin the stream syncing so that stdin, out, err work properly err = result.SyncStreams( c.config.SyncStdout, c.config.SyncStderr) if err != nil { result.Close() return nil, err } return result, nil }
[ "func", "newRPCClient", "(", "c", "*", "Client", ")", "(", "*", "RPCClient", ",", "error", ")", "{", "// Connect to the client", "conn", ",", "err", ":=", "net", ".", "Dial", "(", "c", ".", "address", ".", "Network", "(", ")", ",", "c", ".", "address", ".", "String", "(", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "if", "tcpConn", ",", "ok", ":=", "conn", ".", "(", "*", "net", ".", "TCPConn", ")", ";", "ok", "{", "// Make sure to set keep alive so that the connection doesn't die", "tcpConn", ".", "SetKeepAlive", "(", "true", ")", "\n", "}", "\n\n", "if", "c", ".", "config", ".", "TLSConfig", "!=", "nil", "{", "conn", "=", "tls", ".", "Client", "(", "conn", ",", "c", ".", "config", ".", "TLSConfig", ")", "\n", "}", "\n\n", "// Create the actual RPC client", "result", ",", "err", ":=", "NewRPCClient", "(", "conn", ",", "c", ".", "config", ".", "Plugins", ")", "\n", "if", "err", "!=", "nil", "{", "conn", ".", "Close", "(", ")", "\n", "return", "nil", ",", "err", "\n", "}", "\n\n", "// Begin the stream syncing so that stdin, out, err work properly", "err", "=", "result", ".", "SyncStreams", "(", "c", ".", "config", ".", "SyncStdout", ",", "c", ".", "config", ".", "SyncStderr", ")", "\n", "if", "err", "!=", "nil", "{", "result", ".", "Close", "(", ")", "\n", "return", "nil", ",", "err", "\n", "}", "\n\n", "return", "result", ",", "nil", "\n", "}" ]
// newRPCClient creates a new RPCClient. The Client argument is expected // to be successfully started already with a lock held.
[ "newRPCClient", "creates", "a", "new", "RPCClient", ".", "The", "Client", "argument", "is", "expected", "to", "be", "successfully", "started", "already", "with", "a", "lock", "held", "." ]
5692942914bbdbc03558fde936b1f0bc2af365be
https://github.com/hashicorp/go-plugin/blob/5692942914bbdbc03558fde936b1f0bc2af365be/rpc_client.go#L25-L57
train
hashicorp/go-plugin
rpc_client.go
NewRPCClient
func NewRPCClient(conn io.ReadWriteCloser, plugins map[string]Plugin) (*RPCClient, error) { // Create the yamux client so we can multiplex mux, err := yamux.Client(conn, nil) if err != nil { conn.Close() return nil, err } // Connect to the control stream. control, err := mux.Open() if err != nil { mux.Close() return nil, err } // Connect stdout, stderr streams stdstream := make([]net.Conn, 2) for i, _ := range stdstream { stdstream[i], err = mux.Open() if err != nil { mux.Close() return nil, err } } // Create the broker and start it up broker := newMuxBroker(mux) go broker.Run() // Build the client using our broker and control channel. return &RPCClient{ broker: broker, control: rpc.NewClient(control), plugins: plugins, stdout: stdstream[0], stderr: stdstream[1], }, nil }
go
func NewRPCClient(conn io.ReadWriteCloser, plugins map[string]Plugin) (*RPCClient, error) { // Create the yamux client so we can multiplex mux, err := yamux.Client(conn, nil) if err != nil { conn.Close() return nil, err } // Connect to the control stream. control, err := mux.Open() if err != nil { mux.Close() return nil, err } // Connect stdout, stderr streams stdstream := make([]net.Conn, 2) for i, _ := range stdstream { stdstream[i], err = mux.Open() if err != nil { mux.Close() return nil, err } } // Create the broker and start it up broker := newMuxBroker(mux) go broker.Run() // Build the client using our broker and control channel. return &RPCClient{ broker: broker, control: rpc.NewClient(control), plugins: plugins, stdout: stdstream[0], stderr: stdstream[1], }, nil }
[ "func", "NewRPCClient", "(", "conn", "io", ".", "ReadWriteCloser", ",", "plugins", "map", "[", "string", "]", "Plugin", ")", "(", "*", "RPCClient", ",", "error", ")", "{", "// Create the yamux client so we can multiplex", "mux", ",", "err", ":=", "yamux", ".", "Client", "(", "conn", ",", "nil", ")", "\n", "if", "err", "!=", "nil", "{", "conn", ".", "Close", "(", ")", "\n", "return", "nil", ",", "err", "\n", "}", "\n\n", "// Connect to the control stream.", "control", ",", "err", ":=", "mux", ".", "Open", "(", ")", "\n", "if", "err", "!=", "nil", "{", "mux", ".", "Close", "(", ")", "\n", "return", "nil", ",", "err", "\n", "}", "\n\n", "// Connect stdout, stderr streams", "stdstream", ":=", "make", "(", "[", "]", "net", ".", "Conn", ",", "2", ")", "\n", "for", "i", ",", "_", ":=", "range", "stdstream", "{", "stdstream", "[", "i", "]", ",", "err", "=", "mux", ".", "Open", "(", ")", "\n", "if", "err", "!=", "nil", "{", "mux", ".", "Close", "(", ")", "\n", "return", "nil", ",", "err", "\n", "}", "\n", "}", "\n\n", "// Create the broker and start it up", "broker", ":=", "newMuxBroker", "(", "mux", ")", "\n", "go", "broker", ".", "Run", "(", ")", "\n\n", "// Build the client using our broker and control channel.", "return", "&", "RPCClient", "{", "broker", ":", "broker", ",", "control", ":", "rpc", ".", "NewClient", "(", "control", ")", ",", "plugins", ":", "plugins", ",", "stdout", ":", "stdstream", "[", "0", "]", ",", "stderr", ":", "stdstream", "[", "1", "]", ",", "}", ",", "nil", "\n", "}" ]
// NewRPCClient creates a client from an already-open connection-like value. // Dial is typically used instead.
[ "NewRPCClient", "creates", "a", "client", "from", "an", "already", "-", "open", "connection", "-", "like", "value", ".", "Dial", "is", "typically", "used", "instead", "." ]
5692942914bbdbc03558fde936b1f0bc2af365be
https://github.com/hashicorp/go-plugin/blob/5692942914bbdbc03558fde936b1f0bc2af365be/rpc_client.go#L61-L98
train
hashicorp/go-plugin
rpc_client.go
SyncStreams
func (c *RPCClient) SyncStreams(stdout io.Writer, stderr io.Writer) error { go copyStream("stdout", stdout, c.stdout) go copyStream("stderr", stderr, c.stderr) return nil }
go
func (c *RPCClient) SyncStreams(stdout io.Writer, stderr io.Writer) error { go copyStream("stdout", stdout, c.stdout) go copyStream("stderr", stderr, c.stderr) return nil }
[ "func", "(", "c", "*", "RPCClient", ")", "SyncStreams", "(", "stdout", "io", ".", "Writer", ",", "stderr", "io", ".", "Writer", ")", "error", "{", "go", "copyStream", "(", "\"", "\"", ",", "stdout", ",", "c", ".", "stdout", ")", "\n", "go", "copyStream", "(", "\"", "\"", ",", "stderr", ",", "c", ".", "stderr", ")", "\n", "return", "nil", "\n", "}" ]
// SyncStreams should be called to enable syncing of stdout, // stderr with the plugin. // // This will return immediately and the syncing will continue to happen // in the background. You do not need to launch this in a goroutine itself. // // This should never be called multiple times.
[ "SyncStreams", "should", "be", "called", "to", "enable", "syncing", "of", "stdout", "stderr", "with", "the", "plugin", ".", "This", "will", "return", "immediately", "and", "the", "syncing", "will", "continue", "to", "happen", "in", "the", "background", ".", "You", "do", "not", "need", "to", "launch", "this", "in", "a", "goroutine", "itself", ".", "This", "should", "never", "be", "called", "multiple", "times", "." ]
5692942914bbdbc03558fde936b1f0bc2af365be
https://github.com/hashicorp/go-plugin/blob/5692942914bbdbc03558fde936b1f0bc2af365be/rpc_client.go#L107-L111
train
hashicorp/go-plugin
rpc_client.go
Close
func (c *RPCClient) Close() error { // Call the control channel and ask it to gracefully exit. If this // errors, then we save it so that we always return an error but we // want to try to close the other channels anyways. var empty struct{} returnErr := c.control.Call("Control.Quit", true, &empty) // Close the other streams we have if err := c.control.Close(); err != nil { return err } if err := c.stdout.Close(); err != nil { return err } if err := c.stderr.Close(); err != nil { return err } if err := c.broker.Close(); err != nil { return err } // Return back the error we got from Control.Quit. This is very important // since we MUST return non-nil error if this fails so that Client.Kill // will properly try a process.Kill. return returnErr }
go
func (c *RPCClient) Close() error { // Call the control channel and ask it to gracefully exit. If this // errors, then we save it so that we always return an error but we // want to try to close the other channels anyways. var empty struct{} returnErr := c.control.Call("Control.Quit", true, &empty) // Close the other streams we have if err := c.control.Close(); err != nil { return err } if err := c.stdout.Close(); err != nil { return err } if err := c.stderr.Close(); err != nil { return err } if err := c.broker.Close(); err != nil { return err } // Return back the error we got from Control.Quit. This is very important // since we MUST return non-nil error if this fails so that Client.Kill // will properly try a process.Kill. return returnErr }
[ "func", "(", "c", "*", "RPCClient", ")", "Close", "(", ")", "error", "{", "// Call the control channel and ask it to gracefully exit. If this", "// errors, then we save it so that we always return an error but we", "// want to try to close the other channels anyways.", "var", "empty", "struct", "{", "}", "\n", "returnErr", ":=", "c", ".", "control", ".", "Call", "(", "\"", "\"", ",", "true", ",", "&", "empty", ")", "\n\n", "// Close the other streams we have", "if", "err", ":=", "c", ".", "control", ".", "Close", "(", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "if", "err", ":=", "c", ".", "stdout", ".", "Close", "(", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "if", "err", ":=", "c", ".", "stderr", ".", "Close", "(", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "if", "err", ":=", "c", ".", "broker", ".", "Close", "(", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "// Return back the error we got from Control.Quit. This is very important", "// since we MUST return non-nil error if this fails so that Client.Kill", "// will properly try a process.Kill.", "return", "returnErr", "\n", "}" ]
// Close closes the connection. The client is no longer usable after this // is called.
[ "Close", "closes", "the", "connection", ".", "The", "client", "is", "no", "longer", "usable", "after", "this", "is", "called", "." ]
5692942914bbdbc03558fde936b1f0bc2af365be
https://github.com/hashicorp/go-plugin/blob/5692942914bbdbc03558fde936b1f0bc2af365be/rpc_client.go#L115-L140
train
hashicorp/go-plugin
rpc_client.go
Ping
func (c *RPCClient) Ping() error { var empty struct{} return c.control.Call("Control.Ping", true, &empty) }
go
func (c *RPCClient) Ping() error { var empty struct{} return c.control.Call("Control.Ping", true, &empty) }
[ "func", "(", "c", "*", "RPCClient", ")", "Ping", "(", ")", "error", "{", "var", "empty", "struct", "{", "}", "\n", "return", "c", ".", "control", ".", "Call", "(", "\"", "\"", ",", "true", ",", "&", "empty", ")", "\n", "}" ]
// Ping pings the connection to ensure it is still alive. // // The error from the RPC call is returned exactly if you want to inspect // it for further error analysis. Any error returned from here would indicate // that the connection to the plugin is not healthy.
[ "Ping", "pings", "the", "connection", "to", "ensure", "it", "is", "still", "alive", ".", "The", "error", "from", "the", "RPC", "call", "is", "returned", "exactly", "if", "you", "want", "to", "inspect", "it", "for", "further", "error", "analysis", ".", "Any", "error", "returned", "from", "here", "would", "indicate", "that", "the", "connection", "to", "the", "plugin", "is", "not", "healthy", "." ]
5692942914bbdbc03558fde936b1f0bc2af365be
https://github.com/hashicorp/go-plugin/blob/5692942914bbdbc03558fde936b1f0bc2af365be/rpc_client.go#L167-L170
train
hashicorp/go-plugin
rpc_server.go
ServeConn
func (s *RPCServer) ServeConn(conn io.ReadWriteCloser) { // First create the yamux server to wrap this connection mux, err := yamux.Server(conn, nil) if err != nil { conn.Close() log.Printf("[ERR] plugin: error creating yamux server: %s", err) return } // Accept the control connection control, err := mux.Accept() if err != nil { mux.Close() if err != io.EOF { log.Printf("[ERR] plugin: error accepting control connection: %s", err) } return } // Connect the stdstreams (in, out, err) stdstream := make([]net.Conn, 2) for i, _ := range stdstream { stdstream[i], err = mux.Accept() if err != nil { mux.Close() log.Printf("[ERR] plugin: accepting stream %d: %s", i, err) return } } // Copy std streams out to the proper place go copyStream("stdout", stdstream[0], s.Stdout) go copyStream("stderr", stdstream[1], s.Stderr) // Create the broker and start it up broker := newMuxBroker(mux) go broker.Run() // Use the control connection to build the dispenser and serve the // connection. server := rpc.NewServer() server.RegisterName("Control", &controlServer{ server: s, }) server.RegisterName("Dispenser", &dispenseServer{ broker: broker, plugins: s.Plugins, }) server.ServeConn(control) }
go
func (s *RPCServer) ServeConn(conn io.ReadWriteCloser) { // First create the yamux server to wrap this connection mux, err := yamux.Server(conn, nil) if err != nil { conn.Close() log.Printf("[ERR] plugin: error creating yamux server: %s", err) return } // Accept the control connection control, err := mux.Accept() if err != nil { mux.Close() if err != io.EOF { log.Printf("[ERR] plugin: error accepting control connection: %s", err) } return } // Connect the stdstreams (in, out, err) stdstream := make([]net.Conn, 2) for i, _ := range stdstream { stdstream[i], err = mux.Accept() if err != nil { mux.Close() log.Printf("[ERR] plugin: accepting stream %d: %s", i, err) return } } // Copy std streams out to the proper place go copyStream("stdout", stdstream[0], s.Stdout) go copyStream("stderr", stdstream[1], s.Stderr) // Create the broker and start it up broker := newMuxBroker(mux) go broker.Run() // Use the control connection to build the dispenser and serve the // connection. server := rpc.NewServer() server.RegisterName("Control", &controlServer{ server: s, }) server.RegisterName("Dispenser", &dispenseServer{ broker: broker, plugins: s.Plugins, }) server.ServeConn(control) }
[ "func", "(", "s", "*", "RPCServer", ")", "ServeConn", "(", "conn", "io", ".", "ReadWriteCloser", ")", "{", "// First create the yamux server to wrap this connection", "mux", ",", "err", ":=", "yamux", ".", "Server", "(", "conn", ",", "nil", ")", "\n", "if", "err", "!=", "nil", "{", "conn", ".", "Close", "(", ")", "\n", "log", ".", "Printf", "(", "\"", "\"", ",", "err", ")", "\n", "return", "\n", "}", "\n\n", "// Accept the control connection", "control", ",", "err", ":=", "mux", ".", "Accept", "(", ")", "\n", "if", "err", "!=", "nil", "{", "mux", ".", "Close", "(", ")", "\n", "if", "err", "!=", "io", ".", "EOF", "{", "log", ".", "Printf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n\n", "return", "\n", "}", "\n\n", "// Connect the stdstreams (in, out, err)", "stdstream", ":=", "make", "(", "[", "]", "net", ".", "Conn", ",", "2", ")", "\n", "for", "i", ",", "_", ":=", "range", "stdstream", "{", "stdstream", "[", "i", "]", ",", "err", "=", "mux", ".", "Accept", "(", ")", "\n", "if", "err", "!=", "nil", "{", "mux", ".", "Close", "(", ")", "\n", "log", ".", "Printf", "(", "\"", "\"", ",", "i", ",", "err", ")", "\n", "return", "\n", "}", "\n", "}", "\n\n", "// Copy std streams out to the proper place", "go", "copyStream", "(", "\"", "\"", ",", "stdstream", "[", "0", "]", ",", "s", ".", "Stdout", ")", "\n", "go", "copyStream", "(", "\"", "\"", ",", "stdstream", "[", "1", "]", ",", "s", ".", "Stderr", ")", "\n\n", "// Create the broker and start it up", "broker", ":=", "newMuxBroker", "(", "mux", ")", "\n", "go", "broker", ".", "Run", "(", ")", "\n\n", "// Use the control connection to build the dispenser and serve the", "// connection.", "server", ":=", "rpc", ".", "NewServer", "(", ")", "\n", "server", ".", "RegisterName", "(", "\"", "\"", ",", "&", "controlServer", "{", "server", ":", "s", ",", "}", ")", "\n", "server", ".", "RegisterName", "(", "\"", "\"", ",", "&", "dispenseServer", "{", "broker", ":", "broker", ",", "plugins", ":", "s", ".", "Plugins", ",", "}", ")", "\n", "server", ".", "ServeConn", "(", "control", ")", "\n", "}" ]
// ServeConn runs a single connection. // // ServeConn blocks, serving the connection until the client hangs up.
[ "ServeConn", "runs", "a", "single", "connection", ".", "ServeConn", "blocks", "serving", "the", "connection", "until", "the", "client", "hangs", "up", "." ]
5692942914bbdbc03558fde936b1f0bc2af365be
https://github.com/hashicorp/go-plugin/blob/5692942914bbdbc03558fde936b1f0bc2af365be/rpc_server.go#L59-L109
train
hashicorp/go-plugin
rpc_server.go
done
func (s *RPCServer) done() { s.lock.Lock() defer s.lock.Unlock() if s.DoneCh != nil { close(s.DoneCh) s.DoneCh = nil } }
go
func (s *RPCServer) done() { s.lock.Lock() defer s.lock.Unlock() if s.DoneCh != nil { close(s.DoneCh) s.DoneCh = nil } }
[ "func", "(", "s", "*", "RPCServer", ")", "done", "(", ")", "{", "s", ".", "lock", ".", "Lock", "(", ")", "\n", "defer", "s", ".", "lock", ".", "Unlock", "(", ")", "\n\n", "if", "s", ".", "DoneCh", "!=", "nil", "{", "close", "(", "s", ".", "DoneCh", ")", "\n", "s", ".", "DoneCh", "=", "nil", "\n", "}", "\n", "}" ]
// done is called internally by the control server to trigger the // doneCh to close which is listened to by the main process to cleanly // exit.
[ "done", "is", "called", "internally", "by", "the", "control", "server", "to", "trigger", "the", "doneCh", "to", "close", "which", "is", "listened", "to", "by", "the", "main", "process", "to", "cleanly", "exit", "." ]
5692942914bbdbc03558fde936b1f0bc2af365be
https://github.com/hashicorp/go-plugin/blob/5692942914bbdbc03558fde936b1f0bc2af365be/rpc_server.go#L114-L122
train
hashicorp/go-plugin
server.go
protocolVersion
func protocolVersion(opts *ServeConfig) (int, Protocol, PluginSet) { protoVersion := int(opts.ProtocolVersion) pluginSet := opts.Plugins protoType := ProtocolNetRPC // Check if the client sent a list of acceptable versions var clientVersions []int if vs := os.Getenv("PLUGIN_PROTOCOL_VERSIONS"); vs != "" { for _, s := range strings.Split(vs, ",") { v, err := strconv.Atoi(s) if err != nil { fmt.Fprintf(os.Stderr, "server sent invalid plugin version %q", s) continue } clientVersions = append(clientVersions, v) } } // We want to iterate in reverse order, to ensure we match the newest // compatible plugin version. sort.Sort(sort.Reverse(sort.IntSlice(clientVersions))) // set the old un-versioned fields as if they were versioned plugins if opts.VersionedPlugins == nil { opts.VersionedPlugins = make(map[int]PluginSet) } if pluginSet != nil { opts.VersionedPlugins[protoVersion] = pluginSet } // Sort the version to make sure we match the latest first var versions []int for v := range opts.VersionedPlugins { versions = append(versions, v) } sort.Sort(sort.Reverse(sort.IntSlice(versions))) // See if we have multiple versions of Plugins to choose from for _, version := range versions { // Record each version, since we guarantee that this returns valid // values even if they are not a protocol match. protoVersion = version pluginSet = opts.VersionedPlugins[version] // If we have a configured gRPC server we should select a protocol if opts.GRPCServer != nil { // All plugins in a set must use the same transport, so check the first // for the protocol type for _, p := range pluginSet { switch p.(type) { case GRPCPlugin: protoType = ProtocolGRPC default: protoType = ProtocolNetRPC } break } } for _, clientVersion := range clientVersions { if clientVersion == protoVersion { return protoVersion, protoType, pluginSet } } } // Return the lowest version as the fallback. // Since we iterated over all the versions in reverse order above, these // values are from the lowest version number plugins (which may be from // a combination of the Handshake.ProtocolVersion and ServeConfig.Plugins // fields). This allows serving the oldest version of our plugins to a // legacy client that did not send a PLUGIN_PROTOCOL_VERSIONS list. return protoVersion, protoType, pluginSet }
go
func protocolVersion(opts *ServeConfig) (int, Protocol, PluginSet) { protoVersion := int(opts.ProtocolVersion) pluginSet := opts.Plugins protoType := ProtocolNetRPC // Check if the client sent a list of acceptable versions var clientVersions []int if vs := os.Getenv("PLUGIN_PROTOCOL_VERSIONS"); vs != "" { for _, s := range strings.Split(vs, ",") { v, err := strconv.Atoi(s) if err != nil { fmt.Fprintf(os.Stderr, "server sent invalid plugin version %q", s) continue } clientVersions = append(clientVersions, v) } } // We want to iterate in reverse order, to ensure we match the newest // compatible plugin version. sort.Sort(sort.Reverse(sort.IntSlice(clientVersions))) // set the old un-versioned fields as if they were versioned plugins if opts.VersionedPlugins == nil { opts.VersionedPlugins = make(map[int]PluginSet) } if pluginSet != nil { opts.VersionedPlugins[protoVersion] = pluginSet } // Sort the version to make sure we match the latest first var versions []int for v := range opts.VersionedPlugins { versions = append(versions, v) } sort.Sort(sort.Reverse(sort.IntSlice(versions))) // See if we have multiple versions of Plugins to choose from for _, version := range versions { // Record each version, since we guarantee that this returns valid // values even if they are not a protocol match. protoVersion = version pluginSet = opts.VersionedPlugins[version] // If we have a configured gRPC server we should select a protocol if opts.GRPCServer != nil { // All plugins in a set must use the same transport, so check the first // for the protocol type for _, p := range pluginSet { switch p.(type) { case GRPCPlugin: protoType = ProtocolGRPC default: protoType = ProtocolNetRPC } break } } for _, clientVersion := range clientVersions { if clientVersion == protoVersion { return protoVersion, protoType, pluginSet } } } // Return the lowest version as the fallback. // Since we iterated over all the versions in reverse order above, these // values are from the lowest version number plugins (which may be from // a combination of the Handshake.ProtocolVersion and ServeConfig.Plugins // fields). This allows serving the oldest version of our plugins to a // legacy client that did not send a PLUGIN_PROTOCOL_VERSIONS list. return protoVersion, protoType, pluginSet }
[ "func", "protocolVersion", "(", "opts", "*", "ServeConfig", ")", "(", "int", ",", "Protocol", ",", "PluginSet", ")", "{", "protoVersion", ":=", "int", "(", "opts", ".", "ProtocolVersion", ")", "\n", "pluginSet", ":=", "opts", ".", "Plugins", "\n", "protoType", ":=", "ProtocolNetRPC", "\n", "// Check if the client sent a list of acceptable versions", "var", "clientVersions", "[", "]", "int", "\n", "if", "vs", ":=", "os", ".", "Getenv", "(", "\"", "\"", ")", ";", "vs", "!=", "\"", "\"", "{", "for", "_", ",", "s", ":=", "range", "strings", ".", "Split", "(", "vs", ",", "\"", "\"", ")", "{", "v", ",", "err", ":=", "strconv", ".", "Atoi", "(", "s", ")", "\n", "if", "err", "!=", "nil", "{", "fmt", ".", "Fprintf", "(", "os", ".", "Stderr", ",", "\"", "\"", ",", "s", ")", "\n", "continue", "\n", "}", "\n", "clientVersions", "=", "append", "(", "clientVersions", ",", "v", ")", "\n", "}", "\n", "}", "\n\n", "// We want to iterate in reverse order, to ensure we match the newest", "// compatible plugin version.", "sort", ".", "Sort", "(", "sort", ".", "Reverse", "(", "sort", ".", "IntSlice", "(", "clientVersions", ")", ")", ")", "\n\n", "// set the old un-versioned fields as if they were versioned plugins", "if", "opts", ".", "VersionedPlugins", "==", "nil", "{", "opts", ".", "VersionedPlugins", "=", "make", "(", "map", "[", "int", "]", "PluginSet", ")", "\n", "}", "\n\n", "if", "pluginSet", "!=", "nil", "{", "opts", ".", "VersionedPlugins", "[", "protoVersion", "]", "=", "pluginSet", "\n", "}", "\n\n", "// Sort the version to make sure we match the latest first", "var", "versions", "[", "]", "int", "\n", "for", "v", ":=", "range", "opts", ".", "VersionedPlugins", "{", "versions", "=", "append", "(", "versions", ",", "v", ")", "\n", "}", "\n\n", "sort", ".", "Sort", "(", "sort", ".", "Reverse", "(", "sort", ".", "IntSlice", "(", "versions", ")", ")", ")", "\n\n", "// See if we have multiple versions of Plugins to choose from", "for", "_", ",", "version", ":=", "range", "versions", "{", "// Record each version, since we guarantee that this returns valid", "// values even if they are not a protocol match.", "protoVersion", "=", "version", "\n", "pluginSet", "=", "opts", ".", "VersionedPlugins", "[", "version", "]", "\n\n", "// If we have a configured gRPC server we should select a protocol", "if", "opts", ".", "GRPCServer", "!=", "nil", "{", "// All plugins in a set must use the same transport, so check the first", "// for the protocol type", "for", "_", ",", "p", ":=", "range", "pluginSet", "{", "switch", "p", ".", "(", "type", ")", "{", "case", "GRPCPlugin", ":", "protoType", "=", "ProtocolGRPC", "\n", "default", ":", "protoType", "=", "ProtocolNetRPC", "\n", "}", "\n", "break", "\n", "}", "\n", "}", "\n\n", "for", "_", ",", "clientVersion", ":=", "range", "clientVersions", "{", "if", "clientVersion", "==", "protoVersion", "{", "return", "protoVersion", ",", "protoType", ",", "pluginSet", "\n", "}", "\n", "}", "\n", "}", "\n\n", "// Return the lowest version as the fallback.", "// Since we iterated over all the versions in reverse order above, these", "// values are from the lowest version number plugins (which may be from", "// a combination of the Handshake.ProtocolVersion and ServeConfig.Plugins", "// fields). This allows serving the oldest version of our plugins to a", "// legacy client that did not send a PLUGIN_PROTOCOL_VERSIONS list.", "return", "protoVersion", ",", "protoType", ",", "pluginSet", "\n", "}" ]
// protocolVersion determines the protocol version and plugin set to be used by // the server. In the event that there is no suitable version, the last version // in the config is returned leaving the client to report the incompatibility.
[ "protocolVersion", "determines", "the", "protocol", "version", "and", "plugin", "set", "to", "be", "used", "by", "the", "server", ".", "In", "the", "event", "that", "there", "is", "no", "suitable", "version", "the", "last", "version", "in", "the", "config", "is", "returned", "leaving", "the", "client", "to", "report", "the", "incompatibility", "." ]
5692942914bbdbc03558fde936b1f0bc2af365be
https://github.com/hashicorp/go-plugin/blob/5692942914bbdbc03558fde936b1f0bc2af365be/server.go#L93-L167
train
hashicorp/go-plugin
process_posix.go
_pidAlive
func _pidAlive(pid int) bool { proc, err := os.FindProcess(pid) if err == nil { err = proc.Signal(syscall.Signal(0)) } return err == nil }
go
func _pidAlive(pid int) bool { proc, err := os.FindProcess(pid) if err == nil { err = proc.Signal(syscall.Signal(0)) } return err == nil }
[ "func", "_pidAlive", "(", "pid", "int", ")", "bool", "{", "proc", ",", "err", ":=", "os", ".", "FindProcess", "(", "pid", ")", "\n", "if", "err", "==", "nil", "{", "err", "=", "proc", ".", "Signal", "(", "syscall", ".", "Signal", "(", "0", ")", ")", "\n", "}", "\n\n", "return", "err", "==", "nil", "\n", "}" ]
// _pidAlive tests whether a process is alive or not by sending it Signal 0, // since Go otherwise has no way to test this.
[ "_pidAlive", "tests", "whether", "a", "process", "is", "alive", "or", "not", "by", "sending", "it", "Signal", "0", "since", "Go", "otherwise", "has", "no", "way", "to", "test", "this", "." ]
5692942914bbdbc03558fde936b1f0bc2af365be
https://github.com/hashicorp/go-plugin/blob/5692942914bbdbc03558fde936b1f0bc2af365be/process_posix.go#L12-L19
train
hashicorp/go-plugin
mux_broker.go
AcceptAndServe
func (m *MuxBroker) AcceptAndServe(id uint32, v interface{}) { conn, err := m.Accept(id) if err != nil { log.Printf("[ERR] plugin: plugin acceptAndServe error: %s", err) return } serve(conn, "Plugin", v) }
go
func (m *MuxBroker) AcceptAndServe(id uint32, v interface{}) { conn, err := m.Accept(id) if err != nil { log.Printf("[ERR] plugin: plugin acceptAndServe error: %s", err) return } serve(conn, "Plugin", v) }
[ "func", "(", "m", "*", "MuxBroker", ")", "AcceptAndServe", "(", "id", "uint32", ",", "v", "interface", "{", "}", ")", "{", "conn", ",", "err", ":=", "m", ".", "Accept", "(", "id", ")", "\n", "if", "err", "!=", "nil", "{", "log", ".", "Printf", "(", "\"", "\"", ",", "err", ")", "\n", "return", "\n", "}", "\n\n", "serve", "(", "conn", ",", "\"", "\"", ",", "v", ")", "\n", "}" ]
// AcceptAndServe is used to accept a specific stream ID and immediately // serve an RPC server on that stream ID. This is used to easily serve // complex arguments. // // The served interface is always registered to the "Plugin" name.
[ "AcceptAndServe", "is", "used", "to", "accept", "a", "specific", "stream", "ID", "and", "immediately", "serve", "an", "RPC", "server", "on", "that", "stream", "ID", ".", "This", "is", "used", "to", "easily", "serve", "complex", "arguments", ".", "The", "served", "interface", "is", "always", "registered", "to", "the", "Plugin", "name", "." ]
5692942914bbdbc03558fde936b1f0bc2af365be
https://github.com/hashicorp/go-plugin/blob/5692942914bbdbc03558fde936b1f0bc2af365be/mux_broker.go#L80-L88
train
hashicorp/go-plugin
process.go
pidWait
func pidWait(pid int) error { ticker := time.NewTicker(1 * time.Second) defer ticker.Stop() for range ticker.C { if !pidAlive(pid) { break } } return nil }
go
func pidWait(pid int) error { ticker := time.NewTicker(1 * time.Second) defer ticker.Stop() for range ticker.C { if !pidAlive(pid) { break } } return nil }
[ "func", "pidWait", "(", "pid", "int", ")", "error", "{", "ticker", ":=", "time", ".", "NewTicker", "(", "1", "*", "time", ".", "Second", ")", "\n", "defer", "ticker", ".", "Stop", "(", ")", "\n\n", "for", "range", "ticker", ".", "C", "{", "if", "!", "pidAlive", "(", "pid", ")", "{", "break", "\n", "}", "\n", "}", "\n\n", "return", "nil", "\n", "}" ]
// pidWait blocks for a process to exit.
[ "pidWait", "blocks", "for", "a", "process", "to", "exit", "." ]
5692942914bbdbc03558fde936b1f0bc2af365be
https://github.com/hashicorp/go-plugin/blob/5692942914bbdbc03558fde936b1f0bc2af365be/process.go#L13-L24
train
hashicorp/go-plugin
grpc_controller.go
Shutdown
func (s *grpcControllerServer) Shutdown(ctx context.Context, _ *plugin.Empty) (*plugin.Empty, error) { resp := &plugin.Empty{} // TODO: figure out why GracefullStop doesn't work. s.server.Stop() return resp, nil }
go
func (s *grpcControllerServer) Shutdown(ctx context.Context, _ *plugin.Empty) (*plugin.Empty, error) { resp := &plugin.Empty{} // TODO: figure out why GracefullStop doesn't work. s.server.Stop() return resp, nil }
[ "func", "(", "s", "*", "grpcControllerServer", ")", "Shutdown", "(", "ctx", "context", ".", "Context", ",", "_", "*", "plugin", ".", "Empty", ")", "(", "*", "plugin", ".", "Empty", ",", "error", ")", "{", "resp", ":=", "&", "plugin", ".", "Empty", "{", "}", "\n\n", "// TODO: figure out why GracefullStop doesn't work.", "s", ".", "server", ".", "Stop", "(", ")", "\n", "return", "resp", ",", "nil", "\n", "}" ]
// Shutdown stops the grpc server. It first will attempt a graceful stop, then a // full stop on the server.
[ "Shutdown", "stops", "the", "grpc", "server", ".", "It", "first", "will", "attempt", "a", "graceful", "stop", "then", "a", "full", "stop", "on", "the", "server", "." ]
5692942914bbdbc03558fde936b1f0bc2af365be
https://github.com/hashicorp/go-plugin/blob/5692942914bbdbc03558fde936b1f0bc2af365be/grpc_controller.go#L17-L23
train
nareix/joy4
av/av.go
IsPlanar
func (self SampleFormat) IsPlanar() bool { switch self { case S16P, S32P, FLTP, DBLP: return true default: return false } }
go
func (self SampleFormat) IsPlanar() bool { switch self { case S16P, S32P, FLTP, DBLP: return true default: return false } }
[ "func", "(", "self", "SampleFormat", ")", "IsPlanar", "(", ")", "bool", "{", "switch", "self", "{", "case", "S16P", ",", "S32P", ",", "FLTP", ",", "DBLP", ":", "return", "true", "\n", "default", ":", "return", "false", "\n", "}", "\n", "}" ]
// Check if this sample format is in planar.
[ "Check", "if", "this", "sample", "format", "is", "in", "planar", "." ]
3ddbc8f9d4316ab2bbec2bc9ee98127862e3af02
https://github.com/nareix/joy4/blob/3ddbc8f9d4316ab2bbec2bc9ee98127862e3af02/av/av.go#L70-L77
train
nareix/joy4
av/av.go
MakeAudioCodecType
func MakeAudioCodecType(base uint32) (c CodecType) { c = CodecType(base)<<codecTypeOtherBits | CodecType(codecTypeAudioBit) return }
go
func MakeAudioCodecType(base uint32) (c CodecType) { c = CodecType(base)<<codecTypeOtherBits | CodecType(codecTypeAudioBit) return }
[ "func", "MakeAudioCodecType", "(", "base", "uint32", ")", "(", "c", "CodecType", ")", "{", "c", "=", "CodecType", "(", "base", ")", "<<", "codecTypeOtherBits", "|", "CodecType", "(", "codecTypeAudioBit", ")", "\n", "return", "\n", "}" ]
// Make a new audio codec type.
[ "Make", "a", "new", "audio", "codec", "type", "." ]
3ddbc8f9d4316ab2bbec2bc9ee98127862e3af02
https://github.com/nareix/joy4/blob/3ddbc8f9d4316ab2bbec2bc9ee98127862e3af02/av/av.go#L157-L160
train
nareix/joy4
av/av.go
HasSameFormat
func (self AudioFrame) HasSameFormat(other AudioFrame) bool { if self.SampleRate != other.SampleRate { return false } if self.ChannelLayout != other.ChannelLayout { return false } if self.SampleFormat != other.SampleFormat { return false } return true }
go
func (self AudioFrame) HasSameFormat(other AudioFrame) bool { if self.SampleRate != other.SampleRate { return false } if self.ChannelLayout != other.ChannelLayout { return false } if self.SampleFormat != other.SampleFormat { return false } return true }
[ "func", "(", "self", "AudioFrame", ")", "HasSameFormat", "(", "other", "AudioFrame", ")", "bool", "{", "if", "self", ".", "SampleRate", "!=", "other", ".", "SampleRate", "{", "return", "false", "\n", "}", "\n", "if", "self", ".", "ChannelLayout", "!=", "other", ".", "ChannelLayout", "{", "return", "false", "\n", "}", "\n", "if", "self", ".", "SampleFormat", "!=", "other", ".", "SampleFormat", "{", "return", "false", "\n", "}", "\n", "return", "true", "\n", "}" ]
// Check this audio frame has same format as other audio frame.
[ "Check", "this", "audio", "frame", "has", "same", "format", "as", "other", "audio", "frame", "." ]
3ddbc8f9d4316ab2bbec2bc9ee98127862e3af02
https://github.com/nareix/joy4/blob/3ddbc8f9d4316ab2bbec2bc9ee98127862e3af02/av/av.go#L252-L263
train
nareix/joy4
av/av.go
Slice
func (self AudioFrame) Slice(start int, end int) (out AudioFrame) { if start > end { panic(fmt.Sprintf("av: AudioFrame split failed start=%d end=%d invalid", start, end)) } out = self out.Data = append([][]byte(nil), out.Data...) out.SampleCount = end - start size := self.SampleFormat.BytesPerSample() for i := range out.Data { out.Data[i] = out.Data[i][start*size : end*size] } return }
go
func (self AudioFrame) Slice(start int, end int) (out AudioFrame) { if start > end { panic(fmt.Sprintf("av: AudioFrame split failed start=%d end=%d invalid", start, end)) } out = self out.Data = append([][]byte(nil), out.Data...) out.SampleCount = end - start size := self.SampleFormat.BytesPerSample() for i := range out.Data { out.Data[i] = out.Data[i][start*size : end*size] } return }
[ "func", "(", "self", "AudioFrame", ")", "Slice", "(", "start", "int", ",", "end", "int", ")", "(", "out", "AudioFrame", ")", "{", "if", "start", ">", "end", "{", "panic", "(", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "start", ",", "end", ")", ")", "\n", "}", "\n", "out", "=", "self", "\n", "out", ".", "Data", "=", "append", "(", "[", "]", "[", "]", "byte", "(", "nil", ")", ",", "out", ".", "Data", "...", ")", "\n", "out", ".", "SampleCount", "=", "end", "-", "start", "\n", "size", ":=", "self", ".", "SampleFormat", ".", "BytesPerSample", "(", ")", "\n", "for", "i", ":=", "range", "out", ".", "Data", "{", "out", ".", "Data", "[", "i", "]", "=", "out", ".", "Data", "[", "i", "]", "[", "start", "*", "size", ":", "end", "*", "size", "]", "\n", "}", "\n", "return", "\n", "}" ]
// Split sample audio sample from this frame.
[ "Split", "sample", "audio", "sample", "from", "this", "frame", "." ]
3ddbc8f9d4316ab2bbec2bc9ee98127862e3af02
https://github.com/nareix/joy4/blob/3ddbc8f9d4316ab2bbec2bc9ee98127862e3af02/av/av.go#L266-L278
train
nareix/joy4
av/av.go
Concat
func (self AudioFrame) Concat(in AudioFrame) (out AudioFrame) { out = self out.Data = append([][]byte(nil), out.Data...) out.SampleCount += in.SampleCount for i := range out.Data { out.Data[i] = append(out.Data[i], in.Data[i]...) } return }
go
func (self AudioFrame) Concat(in AudioFrame) (out AudioFrame) { out = self out.Data = append([][]byte(nil), out.Data...) out.SampleCount += in.SampleCount for i := range out.Data { out.Data[i] = append(out.Data[i], in.Data[i]...) } return }
[ "func", "(", "self", "AudioFrame", ")", "Concat", "(", "in", "AudioFrame", ")", "(", "out", "AudioFrame", ")", "{", "out", "=", "self", "\n", "out", ".", "Data", "=", "append", "(", "[", "]", "[", "]", "byte", "(", "nil", ")", ",", "out", ".", "Data", "...", ")", "\n", "out", ".", "SampleCount", "+=", "in", ".", "SampleCount", "\n", "for", "i", ":=", "range", "out", ".", "Data", "{", "out", ".", "Data", "[", "i", "]", "=", "append", "(", "out", ".", "Data", "[", "i", "]", ",", "in", ".", "Data", "[", "i", "]", "...", ")", "\n", "}", "\n", "return", "\n", "}" ]
// Concat two audio frames.
[ "Concat", "two", "audio", "frames", "." ]
3ddbc8f9d4316ab2bbec2bc9ee98127862e3af02
https://github.com/nareix/joy4/blob/3ddbc8f9d4316ab2bbec2bc9ee98127862e3af02/av/av.go#L281-L289
train
nareix/joy4
av/transcode/transcode.go
Do
func (self *Transcoder) Do(pkt av.Packet) (out []av.Packet, err error) { stream := self.streams[pkt.Idx] if stream.aenc != nil && stream.adec != nil { if out, err = stream.audioDecodeAndEncode(pkt); err != nil { return } } else { out = append(out, pkt) } return }
go
func (self *Transcoder) Do(pkt av.Packet) (out []av.Packet, err error) { stream := self.streams[pkt.Idx] if stream.aenc != nil && stream.adec != nil { if out, err = stream.audioDecodeAndEncode(pkt); err != nil { return } } else { out = append(out, pkt) } return }
[ "func", "(", "self", "*", "Transcoder", ")", "Do", "(", "pkt", "av", ".", "Packet", ")", "(", "out", "[", "]", "av", ".", "Packet", ",", "err", "error", ")", "{", "stream", ":=", "self", ".", "streams", "[", "pkt", ".", "Idx", "]", "\n", "if", "stream", ".", "aenc", "!=", "nil", "&&", "stream", ".", "adec", "!=", "nil", "{", "if", "out", ",", "err", "=", "stream", ".", "audioDecodeAndEncode", "(", "pkt", ")", ";", "err", "!=", "nil", "{", "return", "\n", "}", "\n", "}", "else", "{", "out", "=", "append", "(", "out", ",", "pkt", ")", "\n", "}", "\n", "return", "\n", "}" ]
// Do the transcode. // // In audio transcoding one Packet may transcode into many Packets // packet time will be adjusted automatically.
[ "Do", "the", "transcode", ".", "In", "audio", "transcoding", "one", "Packet", "may", "transcode", "into", "many", "Packets", "packet", "time", "will", "be", "adjusted", "automatically", "." ]
3ddbc8f9d4316ab2bbec2bc9ee98127862e3af02
https://github.com/nareix/joy4/blob/3ddbc8f9d4316ab2bbec2bc9ee98127862e3af02/av/transcode/transcode.go#L114-L124
train
nareix/joy4
av/transcode/transcode.go
Streams
func (self *Transcoder) Streams() (streams []av.CodecData, err error) { for _, stream := range self.streams { streams = append(streams, stream.codec) } return }
go
func (self *Transcoder) Streams() (streams []av.CodecData, err error) { for _, stream := range self.streams { streams = append(streams, stream.codec) } return }
[ "func", "(", "self", "*", "Transcoder", ")", "Streams", "(", ")", "(", "streams", "[", "]", "av", ".", "CodecData", ",", "err", "error", ")", "{", "for", "_", ",", "stream", ":=", "range", "self", ".", "streams", "{", "streams", "=", "append", "(", "streams", ",", "stream", ".", "codec", ")", "\n", "}", "\n", "return", "\n", "}" ]
// Get CodecDatas after transcoding.
[ "Get", "CodecDatas", "after", "transcoding", "." ]
3ddbc8f9d4316ab2bbec2bc9ee98127862e3af02
https://github.com/nareix/joy4/blob/3ddbc8f9d4316ab2bbec2bc9ee98127862e3af02/av/transcode/transcode.go#L127-L132
train
nareix/joy4
av/transcode/transcode.go
Close
func (self *Transcoder) Close() (err error) { for _, stream := range self.streams { if stream.aenc != nil { stream.aenc.Close() stream.aenc = nil } if stream.adec != nil { stream.adec.Close() stream.adec = nil } } self.streams = nil return }
go
func (self *Transcoder) Close() (err error) { for _, stream := range self.streams { if stream.aenc != nil { stream.aenc.Close() stream.aenc = nil } if stream.adec != nil { stream.adec.Close() stream.adec = nil } } self.streams = nil return }
[ "func", "(", "self", "*", "Transcoder", ")", "Close", "(", ")", "(", "err", "error", ")", "{", "for", "_", ",", "stream", ":=", "range", "self", ".", "streams", "{", "if", "stream", ".", "aenc", "!=", "nil", "{", "stream", ".", "aenc", ".", "Close", "(", ")", "\n", "stream", ".", "aenc", "=", "nil", "\n", "}", "\n", "if", "stream", ".", "adec", "!=", "nil", "{", "stream", ".", "adec", ".", "Close", "(", ")", "\n", "stream", ".", "adec", "=", "nil", "\n", "}", "\n", "}", "\n", "self", ".", "streams", "=", "nil", "\n", "return", "\n", "}" ]
// Close transcoder, close related encoder and decoders.
[ "Close", "transcoder", "close", "related", "encoder", "and", "decoders", "." ]
3ddbc8f9d4316ab2bbec2bc9ee98127862e3af02
https://github.com/nareix/joy4/blob/3ddbc8f9d4316ab2bbec2bc9ee98127862e3af02/av/transcode/transcode.go#L135-L148
train
nareix/joy4
av/pubsub/queue.go
WritePacket
func (self *Queue) WritePacket(pkt av.Packet) (err error) { self.lock.Lock() self.buf.Push(pkt) if pkt.Idx == int8(self.videoidx) && pkt.IsKeyFrame { self.curgopcount++ } for self.curgopcount >= self.maxgopcount && self.buf.Count > 1 { pkt := self.buf.Pop() if pkt.Idx == int8(self.videoidx) && pkt.IsKeyFrame { self.curgopcount-- } if self.curgopcount < self.maxgopcount { break } } //println("shrink", self.curgopcount, self.maxgopcount, self.buf.Head, self.buf.Tail, "count", self.buf.Count, "size", self.buf.Size) self.cond.Broadcast() self.lock.Unlock() return }
go
func (self *Queue) WritePacket(pkt av.Packet) (err error) { self.lock.Lock() self.buf.Push(pkt) if pkt.Idx == int8(self.videoidx) && pkt.IsKeyFrame { self.curgopcount++ } for self.curgopcount >= self.maxgopcount && self.buf.Count > 1 { pkt := self.buf.Pop() if pkt.Idx == int8(self.videoidx) && pkt.IsKeyFrame { self.curgopcount-- } if self.curgopcount < self.maxgopcount { break } } //println("shrink", self.curgopcount, self.maxgopcount, self.buf.Head, self.buf.Tail, "count", self.buf.Count, "size", self.buf.Size) self.cond.Broadcast() self.lock.Unlock() return }
[ "func", "(", "self", "*", "Queue", ")", "WritePacket", "(", "pkt", "av", ".", "Packet", ")", "(", "err", "error", ")", "{", "self", ".", "lock", ".", "Lock", "(", ")", "\n\n", "self", ".", "buf", ".", "Push", "(", "pkt", ")", "\n", "if", "pkt", ".", "Idx", "==", "int8", "(", "self", ".", "videoidx", ")", "&&", "pkt", ".", "IsKeyFrame", "{", "self", ".", "curgopcount", "++", "\n", "}", "\n\n", "for", "self", ".", "curgopcount", ">=", "self", ".", "maxgopcount", "&&", "self", ".", "buf", ".", "Count", ">", "1", "{", "pkt", ":=", "self", ".", "buf", ".", "Pop", "(", ")", "\n", "if", "pkt", ".", "Idx", "==", "int8", "(", "self", ".", "videoidx", ")", "&&", "pkt", ".", "IsKeyFrame", "{", "self", ".", "curgopcount", "--", "\n", "}", "\n", "if", "self", ".", "curgopcount", "<", "self", ".", "maxgopcount", "{", "break", "\n", "}", "\n", "}", "\n", "//println(\"shrink\", self.curgopcount, self.maxgopcount, self.buf.Head, self.buf.Tail, \"count\", self.buf.Count, \"size\", self.buf.Size)", "self", ".", "cond", ".", "Broadcast", "(", ")", "\n\n", "self", ".", "lock", ".", "Unlock", "(", ")", "\n", "return", "\n", "}" ]
// Put packet into buffer, old packets will be discared.
[ "Put", "packet", "into", "buffer", "old", "packets", "will", "be", "discared", "." ]
3ddbc8f9d4316ab2bbec2bc9ee98127862e3af02
https://github.com/nareix/joy4/blob/3ddbc8f9d4316ab2bbec2bc9ee98127862e3af02/av/pubsub/queue.go#L83-L106
train
nareix/joy4
av/pubsub/queue.go
Oldest
func (self *Queue) Oldest() *QueueCursor { cursor := self.newCursor() cursor.init = func(buf *pktque.Buf, videoidx int) pktque.BufPos { return buf.Head } return cursor }
go
func (self *Queue) Oldest() *QueueCursor { cursor := self.newCursor() cursor.init = func(buf *pktque.Buf, videoidx int) pktque.BufPos { return buf.Head } return cursor }
[ "func", "(", "self", "*", "Queue", ")", "Oldest", "(", ")", "*", "QueueCursor", "{", "cursor", ":=", "self", ".", "newCursor", "(", ")", "\n", "cursor", ".", "init", "=", "func", "(", "buf", "*", "pktque", ".", "Buf", ",", "videoidx", "int", ")", "pktque", ".", "BufPos", "{", "return", "buf", ".", "Head", "\n", "}", "\n", "return", "cursor", "\n", "}" ]
// Create cursor position at oldest buffered packet.
[ "Create", "cursor", "position", "at", "oldest", "buffered", "packet", "." ]
3ddbc8f9d4316ab2bbec2bc9ee98127862e3af02
https://github.com/nareix/joy4/blob/3ddbc8f9d4316ab2bbec2bc9ee98127862e3af02/av/pubsub/queue.go#L131-L137
train
nareix/joy4
av/pubsub/queue.go
DelayedTime
func (self *Queue) DelayedTime(dur time.Duration) *QueueCursor { cursor := self.newCursor() cursor.init = func(buf *pktque.Buf, videoidx int) pktque.BufPos { i := buf.Tail - 1 if buf.IsValidPos(i) { end := buf.Get(i) for buf.IsValidPos(i) { if end.Time-buf.Get(i).Time > dur { break } i-- } } return i } return cursor }
go
func (self *Queue) DelayedTime(dur time.Duration) *QueueCursor { cursor := self.newCursor() cursor.init = func(buf *pktque.Buf, videoidx int) pktque.BufPos { i := buf.Tail - 1 if buf.IsValidPos(i) { end := buf.Get(i) for buf.IsValidPos(i) { if end.Time-buf.Get(i).Time > dur { break } i-- } } return i } return cursor }
[ "func", "(", "self", "*", "Queue", ")", "DelayedTime", "(", "dur", "time", ".", "Duration", ")", "*", "QueueCursor", "{", "cursor", ":=", "self", ".", "newCursor", "(", ")", "\n", "cursor", ".", "init", "=", "func", "(", "buf", "*", "pktque", ".", "Buf", ",", "videoidx", "int", ")", "pktque", ".", "BufPos", "{", "i", ":=", "buf", ".", "Tail", "-", "1", "\n", "if", "buf", ".", "IsValidPos", "(", "i", ")", "{", "end", ":=", "buf", ".", "Get", "(", "i", ")", "\n", "for", "buf", ".", "IsValidPos", "(", "i", ")", "{", "if", "end", ".", "Time", "-", "buf", ".", "Get", "(", "i", ")", ".", "Time", ">", "dur", "{", "break", "\n", "}", "\n", "i", "--", "\n", "}", "\n", "}", "\n", "return", "i", "\n", "}", "\n", "return", "cursor", "\n", "}" ]
// Create cursor position at specific time in buffered packets.
[ "Create", "cursor", "position", "at", "specific", "time", "in", "buffered", "packets", "." ]
3ddbc8f9d4316ab2bbec2bc9ee98127862e3af02
https://github.com/nareix/joy4/blob/3ddbc8f9d4316ab2bbec2bc9ee98127862e3af02/av/pubsub/queue.go#L140-L156
train
nareix/joy4
av/pubsub/queue.go
DelayedGopCount
func (self *Queue) DelayedGopCount(n int) *QueueCursor { cursor := self.newCursor() cursor.init = func(buf *pktque.Buf, videoidx int) pktque.BufPos { i := buf.Tail - 1 if videoidx != -1 { for gop := 0; buf.IsValidPos(i) && gop < n; i-- { pkt := buf.Get(i) if pkt.Idx == int8(self.videoidx) && pkt.IsKeyFrame { gop++ } } } return i } return cursor }
go
func (self *Queue) DelayedGopCount(n int) *QueueCursor { cursor := self.newCursor() cursor.init = func(buf *pktque.Buf, videoidx int) pktque.BufPos { i := buf.Tail - 1 if videoidx != -1 { for gop := 0; buf.IsValidPos(i) && gop < n; i-- { pkt := buf.Get(i) if pkt.Idx == int8(self.videoidx) && pkt.IsKeyFrame { gop++ } } } return i } return cursor }
[ "func", "(", "self", "*", "Queue", ")", "DelayedGopCount", "(", "n", "int", ")", "*", "QueueCursor", "{", "cursor", ":=", "self", ".", "newCursor", "(", ")", "\n", "cursor", ".", "init", "=", "func", "(", "buf", "*", "pktque", ".", "Buf", ",", "videoidx", "int", ")", "pktque", ".", "BufPos", "{", "i", ":=", "buf", ".", "Tail", "-", "1", "\n", "if", "videoidx", "!=", "-", "1", "{", "for", "gop", ":=", "0", ";", "buf", ".", "IsValidPos", "(", "i", ")", "&&", "gop", "<", "n", ";", "i", "--", "{", "pkt", ":=", "buf", ".", "Get", "(", "i", ")", "\n", "if", "pkt", ".", "Idx", "==", "int8", "(", "self", ".", "videoidx", ")", "&&", "pkt", ".", "IsKeyFrame", "{", "gop", "++", "\n", "}", "\n", "}", "\n", "}", "\n", "return", "i", "\n", "}", "\n", "return", "cursor", "\n", "}" ]
// Create cursor position at specific delayed GOP count in buffered packets.
[ "Create", "cursor", "position", "at", "specific", "delayed", "GOP", "count", "in", "buffered", "packets", "." ]
3ddbc8f9d4316ab2bbec2bc9ee98127862e3af02
https://github.com/nareix/joy4/blob/3ddbc8f9d4316ab2bbec2bc9ee98127862e3af02/av/pubsub/queue.go#L159-L174
train
nareix/joy4
av/pubsub/queue.go
ReadPacket
func (self *QueueCursor) ReadPacket() (pkt av.Packet, err error) { self.que.cond.L.Lock() buf := self.que.buf if !self.gotpos { self.pos = self.init(buf, self.que.videoidx) self.gotpos = true } for { if self.pos.LT(buf.Head) { self.pos = buf.Head } else if self.pos.GT(buf.Tail) { self.pos = buf.Tail } if buf.IsValidPos(self.pos) { pkt = buf.Get(self.pos) self.pos++ break } if self.que.closed { err = io.EOF break } self.que.cond.Wait() } self.que.cond.L.Unlock() return }
go
func (self *QueueCursor) ReadPacket() (pkt av.Packet, err error) { self.que.cond.L.Lock() buf := self.que.buf if !self.gotpos { self.pos = self.init(buf, self.que.videoidx) self.gotpos = true } for { if self.pos.LT(buf.Head) { self.pos = buf.Head } else if self.pos.GT(buf.Tail) { self.pos = buf.Tail } if buf.IsValidPos(self.pos) { pkt = buf.Get(self.pos) self.pos++ break } if self.que.closed { err = io.EOF break } self.que.cond.Wait() } self.que.cond.L.Unlock() return }
[ "func", "(", "self", "*", "QueueCursor", ")", "ReadPacket", "(", ")", "(", "pkt", "av", ".", "Packet", ",", "err", "error", ")", "{", "self", ".", "que", ".", "cond", ".", "L", ".", "Lock", "(", ")", "\n", "buf", ":=", "self", ".", "que", ".", "buf", "\n", "if", "!", "self", ".", "gotpos", "{", "self", ".", "pos", "=", "self", ".", "init", "(", "buf", ",", "self", ".", "que", ".", "videoidx", ")", "\n", "self", ".", "gotpos", "=", "true", "\n", "}", "\n", "for", "{", "if", "self", ".", "pos", ".", "LT", "(", "buf", ".", "Head", ")", "{", "self", ".", "pos", "=", "buf", ".", "Head", "\n", "}", "else", "if", "self", ".", "pos", ".", "GT", "(", "buf", ".", "Tail", ")", "{", "self", ".", "pos", "=", "buf", ".", "Tail", "\n", "}", "\n", "if", "buf", ".", "IsValidPos", "(", "self", ".", "pos", ")", "{", "pkt", "=", "buf", ".", "Get", "(", "self", ".", "pos", ")", "\n", "self", ".", "pos", "++", "\n", "break", "\n", "}", "\n", "if", "self", ".", "que", ".", "closed", "{", "err", "=", "io", ".", "EOF", "\n", "break", "\n", "}", "\n", "self", ".", "que", ".", "cond", ".", "Wait", "(", ")", "\n", "}", "\n", "self", ".", "que", ".", "cond", ".", "L", ".", "Unlock", "(", ")", "\n", "return", "\n", "}" ]
// ReadPacket will not consume packets in Queue, it's just a cursor.
[ "ReadPacket", "will", "not", "consume", "packets", "in", "Queue", "it", "s", "just", "a", "cursor", "." ]
3ddbc8f9d4316ab2bbec2bc9ee98127862e3af02
https://github.com/nareix/joy4/blob/3ddbc8f9d4316ab2bbec2bc9ee98127862e3af02/av/pubsub/queue.go#L191-L217
train
go-martini/martini
martini.go
New
func New() *Martini { m := &Martini{Injector: inject.New(), action: func() {}, logger: log.New(os.Stdout, "[martini] ", 0)} m.Map(m.logger) m.Map(defaultReturnHandler()) return m }
go
func New() *Martini { m := &Martini{Injector: inject.New(), action: func() {}, logger: log.New(os.Stdout, "[martini] ", 0)} m.Map(m.logger) m.Map(defaultReturnHandler()) return m }
[ "func", "New", "(", ")", "*", "Martini", "{", "m", ":=", "&", "Martini", "{", "Injector", ":", "inject", ".", "New", "(", ")", ",", "action", ":", "func", "(", ")", "{", "}", ",", "logger", ":", "log", ".", "New", "(", "os", ".", "Stdout", ",", "\"", "\"", ",", "0", ")", "}", "\n", "m", ".", "Map", "(", "m", ".", "logger", ")", "\n", "m", ".", "Map", "(", "defaultReturnHandler", "(", ")", ")", "\n", "return", "m", "\n", "}" ]
// New creates a bare bones Martini instance. Use this method if you want to have full control over the middleware that is used.
[ "New", "creates", "a", "bare", "bones", "Martini", "instance", ".", "Use", "this", "method", "if", "you", "want", "to", "have", "full", "control", "over", "the", "middleware", "that", "is", "used", "." ]
22fa46961aabd2665cf3f1343b146d20028f5071
https://github.com/go-martini/martini/blob/22fa46961aabd2665cf3f1343b146d20028f5071/martini.go#L38-L43
train
go-martini/martini
martini.go
Logger
func (m *Martini) Logger(logger *log.Logger) { m.logger = logger m.Map(m.logger) }
go
func (m *Martini) Logger(logger *log.Logger) { m.logger = logger m.Map(m.logger) }
[ "func", "(", "m", "*", "Martini", ")", "Logger", "(", "logger", "*", "log", ".", "Logger", ")", "{", "m", ".", "logger", "=", "logger", "\n", "m", ".", "Map", "(", "m", ".", "logger", ")", "\n", "}" ]
// Logger sets the logger
[ "Logger", "sets", "the", "logger" ]
22fa46961aabd2665cf3f1343b146d20028f5071
https://github.com/go-martini/martini/blob/22fa46961aabd2665cf3f1343b146d20028f5071/martini.go#L61-L64
train
go-martini/martini
martini.go
Use
func (m *Martini) Use(handler Handler) { validateHandler(handler) m.handlers = append(m.handlers, handler) }
go
func (m *Martini) Use(handler Handler) { validateHandler(handler) m.handlers = append(m.handlers, handler) }
[ "func", "(", "m", "*", "Martini", ")", "Use", "(", "handler", "Handler", ")", "{", "validateHandler", "(", "handler", ")", "\n\n", "m", ".", "handlers", "=", "append", "(", "m", ".", "handlers", ",", "handler", ")", "\n", "}" ]
// Use adds a middleware Handler to the stack. Will panic if the handler is not a callable func. Middleware Handlers are invoked in the order that they are added.
[ "Use", "adds", "a", "middleware", "Handler", "to", "the", "stack", ".", "Will", "panic", "if", "the", "handler", "is", "not", "a", "callable", "func", ".", "Middleware", "Handlers", "are", "invoked", "in", "the", "order", "that", "they", "are", "added", "." ]
22fa46961aabd2665cf3f1343b146d20028f5071
https://github.com/go-martini/martini/blob/22fa46961aabd2665cf3f1343b146d20028f5071/martini.go#L67-L71
train
go-martini/martini
martini.go
ServeHTTP
func (m *Martini) ServeHTTP(res http.ResponseWriter, req *http.Request) { m.createContext(res, req).run() }
go
func (m *Martini) ServeHTTP(res http.ResponseWriter, req *http.Request) { m.createContext(res, req).run() }
[ "func", "(", "m", "*", "Martini", ")", "ServeHTTP", "(", "res", "http", ".", "ResponseWriter", ",", "req", "*", "http", ".", "Request", ")", "{", "m", ".", "createContext", "(", "res", ",", "req", ")", ".", "run", "(", ")", "\n", "}" ]
// ServeHTTP is the HTTP Entry point for a Martini instance. Useful if you want to control your own HTTP server.
[ "ServeHTTP", "is", "the", "HTTP", "Entry", "point", "for", "a", "Martini", "instance", ".", "Useful", "if", "you", "want", "to", "control", "your", "own", "HTTP", "server", "." ]
22fa46961aabd2665cf3f1343b146d20028f5071
https://github.com/go-martini/martini/blob/22fa46961aabd2665cf3f1343b146d20028f5071/martini.go#L74-L76
train
go-martini/martini
martini.go
RunOnAddr
func (m *Martini) RunOnAddr(addr string) { // TODO: Should probably be implemented using a new instance of http.Server in place of // calling http.ListenAndServer directly, so that it could be stored in the martini struct for later use. // This would also allow to improve testing when a custom host and port are passed. logger := m.Injector.Get(reflect.TypeOf(m.logger)).Interface().(*log.Logger) logger.Printf("listening on %s (%s)\n", addr, Env) logger.Fatalln(http.ListenAndServe(addr, m)) }
go
func (m *Martini) RunOnAddr(addr string) { // TODO: Should probably be implemented using a new instance of http.Server in place of // calling http.ListenAndServer directly, so that it could be stored in the martini struct for later use. // This would also allow to improve testing when a custom host and port are passed. logger := m.Injector.Get(reflect.TypeOf(m.logger)).Interface().(*log.Logger) logger.Printf("listening on %s (%s)\n", addr, Env) logger.Fatalln(http.ListenAndServe(addr, m)) }
[ "func", "(", "m", "*", "Martini", ")", "RunOnAddr", "(", "addr", "string", ")", "{", "// TODO: Should probably be implemented using a new instance of http.Server in place of", "// calling http.ListenAndServer directly, so that it could be stored in the martini struct for later use.", "// This would also allow to improve testing when a custom host and port are passed.", "logger", ":=", "m", ".", "Injector", ".", "Get", "(", "reflect", ".", "TypeOf", "(", "m", ".", "logger", ")", ")", ".", "Interface", "(", ")", ".", "(", "*", "log", ".", "Logger", ")", "\n", "logger", ".", "Printf", "(", "\"", "\\n", "\"", ",", "addr", ",", "Env", ")", "\n", "logger", ".", "Fatalln", "(", "http", ".", "ListenAndServe", "(", "addr", ",", "m", ")", ")", "\n", "}" ]
// Run the http server on a given host and port.
[ "Run", "the", "http", "server", "on", "a", "given", "host", "and", "port", "." ]
22fa46961aabd2665cf3f1343b146d20028f5071
https://github.com/go-martini/martini/blob/22fa46961aabd2665cf3f1343b146d20028f5071/martini.go#L79-L87
train
go-martini/martini
martini.go
Classic
func Classic() *ClassicMartini { r := NewRouter() m := New() m.Use(Logger()) m.Use(Recovery()) m.Use(Static("public")) m.MapTo(r, (*Routes)(nil)) m.Action(r.Handle) return &ClassicMartini{m, r} }
go
func Classic() *ClassicMartini { r := NewRouter() m := New() m.Use(Logger()) m.Use(Recovery()) m.Use(Static("public")) m.MapTo(r, (*Routes)(nil)) m.Action(r.Handle) return &ClassicMartini{m, r} }
[ "func", "Classic", "(", ")", "*", "ClassicMartini", "{", "r", ":=", "NewRouter", "(", ")", "\n", "m", ":=", "New", "(", ")", "\n", "m", ".", "Use", "(", "Logger", "(", ")", ")", "\n", "m", ".", "Use", "(", "Recovery", "(", ")", ")", "\n", "m", ".", "Use", "(", "Static", "(", "\"", "\"", ")", ")", "\n", "m", ".", "MapTo", "(", "r", ",", "(", "*", "Routes", ")", "(", "nil", ")", ")", "\n", "m", ".", "Action", "(", "r", ".", "Handle", ")", "\n", "return", "&", "ClassicMartini", "{", "m", ",", "r", "}", "\n", "}" ]
// Classic creates a classic Martini with some basic default middleware - martini.Logger, martini.Recovery and martini.Static. // Classic also maps martini.Routes as a service.
[ "Classic", "creates", "a", "classic", "Martini", "with", "some", "basic", "default", "middleware", "-", "martini", ".", "Logger", "martini", ".", "Recovery", "and", "martini", ".", "Static", ".", "Classic", "also", "maps", "martini", ".", "Routes", "as", "a", "service", "." ]
22fa46961aabd2665cf3f1343b146d20028f5071
https://github.com/go-martini/martini/blob/22fa46961aabd2665cf3f1343b146d20028f5071/martini.go#L118-L127
train
go-martini/martini
router.go
URLWith
func (r *route) URLWith(args []string) string { if len(args) > 0 { argCount := len(args) i := 0 url := urlReg.ReplaceAllStringFunc(r.pattern, func(m string) string { var val interface{} if i < argCount { val = args[i] } else { val = m } i += 1 return fmt.Sprintf(`%v`, val) }) return url } return r.pattern }
go
func (r *route) URLWith(args []string) string { if len(args) > 0 { argCount := len(args) i := 0 url := urlReg.ReplaceAllStringFunc(r.pattern, func(m string) string { var val interface{} if i < argCount { val = args[i] } else { val = m } i += 1 return fmt.Sprintf(`%v`, val) }) return url } return r.pattern }
[ "func", "(", "r", "*", "route", ")", "URLWith", "(", "args", "[", "]", "string", ")", "string", "{", "if", "len", "(", "args", ")", ">", "0", "{", "argCount", ":=", "len", "(", "args", ")", "\n", "i", ":=", "0", "\n", "url", ":=", "urlReg", ".", "ReplaceAllStringFunc", "(", "r", ".", "pattern", ",", "func", "(", "m", "string", ")", "string", "{", "var", "val", "interface", "{", "}", "\n", "if", "i", "<", "argCount", "{", "val", "=", "args", "[", "i", "]", "\n", "}", "else", "{", "val", "=", "m", "\n", "}", "\n", "i", "+=", "1", "\n", "return", "fmt", ".", "Sprintf", "(", "`%v`", ",", "val", ")", "\n", "}", ")", "\n\n", "return", "url", "\n", "}", "\n", "return", "r", ".", "pattern", "\n", "}" ]
// URLWith returns the url pattern replacing the parameters for its values
[ "URLWith", "returns", "the", "url", "pattern", "replacing", "the", "parameters", "for", "its", "values" ]
22fa46961aabd2665cf3f1343b146d20028f5071
https://github.com/go-martini/martini/blob/22fa46961aabd2665cf3f1343b146d20028f5071/router.go#L291-L309
train
go-martini/martini
router.go
URLFor
func (r *router) URLFor(name string, params ...interface{}) string { route := r.findRoute(name) if route == nil { panic("route not found") } var args []string for _, param := range params { switch v := param.(type) { case int: args = append(args, strconv.FormatInt(int64(v), 10)) case string: args = append(args, v) default: if v != nil { panic("Arguments passed to URLFor must be integers or strings") } } } return route.URLWith(args) }
go
func (r *router) URLFor(name string, params ...interface{}) string { route := r.findRoute(name) if route == nil { panic("route not found") } var args []string for _, param := range params { switch v := param.(type) { case int: args = append(args, strconv.FormatInt(int64(v), 10)) case string: args = append(args, v) default: if v != nil { panic("Arguments passed to URLFor must be integers or strings") } } } return route.URLWith(args) }
[ "func", "(", "r", "*", "router", ")", "URLFor", "(", "name", "string", ",", "params", "...", "interface", "{", "}", ")", "string", "{", "route", ":=", "r", ".", "findRoute", "(", "name", ")", "\n\n", "if", "route", "==", "nil", "{", "panic", "(", "\"", "\"", ")", "\n", "}", "\n\n", "var", "args", "[", "]", "string", "\n", "for", "_", ",", "param", ":=", "range", "params", "{", "switch", "v", ":=", "param", ".", "(", "type", ")", "{", "case", "int", ":", "args", "=", "append", "(", "args", ",", "strconv", ".", "FormatInt", "(", "int64", "(", "v", ")", ",", "10", ")", ")", "\n", "case", "string", ":", "args", "=", "append", "(", "args", ",", "v", ")", "\n", "default", ":", "if", "v", "!=", "nil", "{", "panic", "(", "\"", "\"", ")", "\n", "}", "\n", "}", "\n", "}", "\n\n", "return", "route", ".", "URLWith", "(", "args", ")", "\n", "}" ]
// URLFor returns the url for the given route name.
[ "URLFor", "returns", "the", "url", "for", "the", "given", "route", "name", "." ]
22fa46961aabd2665cf3f1343b146d20028f5071
https://github.com/go-martini/martini/blob/22fa46961aabd2665cf3f1343b146d20028f5071/router.go#L338-L360
train
go-martini/martini
router.go
MethodsFor
func (r *router) MethodsFor(path string) []string { methods := []string{} for _, route := range r.getRoutes() { matches := route.regex.FindStringSubmatch(path) if len(matches) > 0 && matches[0] == path && !hasMethod(methods, route.method) { methods = append(methods, route.method) } } return methods }
go
func (r *router) MethodsFor(path string) []string { methods := []string{} for _, route := range r.getRoutes() { matches := route.regex.FindStringSubmatch(path) if len(matches) > 0 && matches[0] == path && !hasMethod(methods, route.method) { methods = append(methods, route.method) } } return methods }
[ "func", "(", "r", "*", "router", ")", "MethodsFor", "(", "path", "string", ")", "[", "]", "string", "{", "methods", ":=", "[", "]", "string", "{", "}", "\n", "for", "_", ",", "route", ":=", "range", "r", ".", "getRoutes", "(", ")", "{", "matches", ":=", "route", ".", "regex", ".", "FindStringSubmatch", "(", "path", ")", "\n", "if", "len", "(", "matches", ")", ">", "0", "&&", "matches", "[", "0", "]", "==", "path", "&&", "!", "hasMethod", "(", "methods", ",", "route", ".", "method", ")", "{", "methods", "=", "append", "(", "methods", ",", "route", ".", "method", ")", "\n", "}", "\n", "}", "\n", "return", "methods", "\n", "}" ]
// MethodsFor returns all methods available for path
[ "MethodsFor", "returns", "all", "methods", "available", "for", "path" ]
22fa46961aabd2665cf3f1343b146d20028f5071
https://github.com/go-martini/martini/blob/22fa46961aabd2665cf3f1343b146d20028f5071/router.go#L383-L392
train
go-martini/martini
logger.go
Logger
func Logger() Handler { return func(res http.ResponseWriter, req *http.Request, c Context, log *log.Logger) { start := time.Now() addr := req.Header.Get("X-Real-IP") if addr == "" { addr = req.Header.Get("X-Forwarded-For") if addr == "" { addr = req.RemoteAddr } } log.Printf("Started %s %s for %s", req.Method, req.URL.Path, addr) rw := res.(ResponseWriter) c.Next() log.Printf("Completed %v %s in %v\n", rw.Status(), http.StatusText(rw.Status()), time.Since(start)) } }
go
func Logger() Handler { return func(res http.ResponseWriter, req *http.Request, c Context, log *log.Logger) { start := time.Now() addr := req.Header.Get("X-Real-IP") if addr == "" { addr = req.Header.Get("X-Forwarded-For") if addr == "" { addr = req.RemoteAddr } } log.Printf("Started %s %s for %s", req.Method, req.URL.Path, addr) rw := res.(ResponseWriter) c.Next() log.Printf("Completed %v %s in %v\n", rw.Status(), http.StatusText(rw.Status()), time.Since(start)) } }
[ "func", "Logger", "(", ")", "Handler", "{", "return", "func", "(", "res", "http", ".", "ResponseWriter", ",", "req", "*", "http", ".", "Request", ",", "c", "Context", ",", "log", "*", "log", ".", "Logger", ")", "{", "start", ":=", "time", ".", "Now", "(", ")", "\n\n", "addr", ":=", "req", ".", "Header", ".", "Get", "(", "\"", "\"", ")", "\n", "if", "addr", "==", "\"", "\"", "{", "addr", "=", "req", ".", "Header", ".", "Get", "(", "\"", "\"", ")", "\n", "if", "addr", "==", "\"", "\"", "{", "addr", "=", "req", ".", "RemoteAddr", "\n", "}", "\n", "}", "\n\n", "log", ".", "Printf", "(", "\"", "\"", ",", "req", ".", "Method", ",", "req", ".", "URL", ".", "Path", ",", "addr", ")", "\n\n", "rw", ":=", "res", ".", "(", "ResponseWriter", ")", "\n", "c", ".", "Next", "(", ")", "\n\n", "log", ".", "Printf", "(", "\"", "\\n", "\"", ",", "rw", ".", "Status", "(", ")", ",", "http", ".", "StatusText", "(", "rw", ".", "Status", "(", ")", ")", ",", "time", ".", "Since", "(", "start", ")", ")", "\n", "}", "\n", "}" ]
// Logger returns a middleware handler that logs the request as it goes in and the response as it goes out.
[ "Logger", "returns", "a", "middleware", "handler", "that", "logs", "the", "request", "as", "it", "goes", "in", "and", "the", "response", "as", "it", "goes", "out", "." ]
22fa46961aabd2665cf3f1343b146d20028f5071
https://github.com/go-martini/martini/blob/22fa46961aabd2665cf3f1343b146d20028f5071/logger.go#L10-L29
train