element_type
stringclasses
2 values
project_name
stringclasses
2 values
uuid
stringlengths
36
36
name
stringlengths
3
29
imports
stringlengths
0
312
structs
stringclasses
7 values
interfaces
stringclasses
1 value
file_location
stringlengths
58
108
code
stringlengths
41
7.22k
global_vars
stringclasses
3 values
package
stringclasses
11 values
tags
stringclasses
1 value
file
flightctl/test
aff77152-419a-4026-b474-ad2c9c7ed20a
app.go
import ( "fmt" "net/http" )
github.com/flightctl/test//tmp/repos/example/appengine-hello/app.go
// Copyright 2023 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // Package hello is a simple App Engine application that replies to requests // on /hello with a welcoming message. package hello import ( "fmt" "net/http" ) // init is run before the application starts serving. func init() { // Handle all requests with path /hello with the helloHandler function. http.HandleFunc("/hello", helloHandler) } func helloHandler(w http.ResponseWriter, r *http.Request) { fmt.Fprintln(w, "Hello from the Go app") }
package hello
function
flightctl/test
33b13e28-b164-4022-ae4e-64e051666113
init
['"net/http"']
github.com/flightctl/test//tmp/repos/example/appengine-hello/app.go
func init() { // Handle all requests with path /hello with the helloHandler function. http.HandleFunc("/hello", helloHandler) }
hello
function
flightctl/test
3835848d-adad-42d1-9a8c-92598834aa78
helloHandler
['"fmt"', '"net/http"']
github.com/flightctl/test//tmp/repos/example/appengine-hello/app.go
func helloHandler(w http.ResponseWriter, r *http.Request) { fmt.Fprintln(w, "Hello from the Go app") }
hello
file
flightctl/test
220df757-95a9-43f9-a971-2787d6919986
main.go
import ( "fmt" "go/ast" "go/importer" "go/parser" "go/token" "go/types" "log" )
github.com/flightctl/test//tmp/repos/example/gotypes/defsuses/main.go
package main import ( "fmt" "go/ast" "go/importer" "go/parser" "go/token" "go/types" "log" ) const hello = `package main import "fmt" func main() { fmt.Println("Hello, world") } ` // !+ func PrintDefsUses(fset *token.FileSet, files ...*ast.File) error { conf := types.Config{Importer: importer.Default()} info := &types.Info{ Defs: make(map[*ast.Ident]types.Object), Uses: make(map[*ast.Ident]types.Object), } _, err := conf.Check("hello", fset, files, info) if err != nil { return err // type error } for id, obj := range info.Defs { fmt.Printf("%s: %q defines %v\n", fset.Position(id.Pos()), id.Name, obj) } for id, obj := range info.Uses { fmt.Printf("%s: %q uses %v\n", fset.Position(id.Pos()), id.Name, obj) } return nil } //!- func main() { // Parse one file. fset := token.NewFileSet() f, err := parser.ParseFile(fset, "hello.go", hello, 0) if err != nil { log.Fatal(err) // parse error } if err := PrintDefsUses(fset, f); err != nil { log.Fatal(err) // type error } } /* //!+output $ go build golang.org/x/example/gotypes/defsuses $ ./defsuses hello.go:1:9: "main" defines <nil> hello.go:5:6: "main" defines func hello.main() hello.go:6:9: "fmt" uses package fmt hello.go:6:13: "Println" uses func fmt.Println(a ...interface{}) (n int, err error) //!-output */
package main
function
flightctl/test
065f41b3-1709-4f85-91ab-ff12eb6eb053
PrintDefsUses
['"fmt"', '"go/ast"', '"go/importer"', '"go/token"', '"go/types"']
github.com/flightctl/test//tmp/repos/example/gotypes/defsuses/main.go
func PrintDefsUses(fset *token.FileSet, files ...*ast.File) error { conf := types.Config{Importer: importer.Default()} info := &types.Info{ Defs: make(map[*ast.Ident]types.Object), Uses: make(map[*ast.Ident]types.Object), } _, err := conf.Check("hello", fset, files, info) if err != nil { return err // type error } for id, obj := range info.Defs { fmt.Printf("%s: %q defines %v\n", fset.Position(id.Pos()), id.Name, obj) } for id, obj := range info.Uses { fmt.Printf("%s: %q uses %v\n", fset.Position(id.Pos()), id.Name, obj) } return nil }
main
function
flightctl/test
827980b3-2da1-447e-996e-cde075912651
main
['"go/parser"', '"go/token"', '"log"']
github.com/flightctl/test//tmp/repos/example/gotypes/defsuses/main.go
func main() { // Parse one file. fset := token.NewFileSet() f, err := parser.ParseFile(fset, "hello.go", hello, 0) if err != nil { log.Fatal(err) // parse error } if err := PrintDefsUses(fset, f); err != nil { log.Fatal(err) // type error } }
main
file
flightctl/test
24aa19a1-0158-4984-b8c0-28ddf2d4bd87
main.go
import ( "fmt" "go/ast" "log" "os" "golang.org/x/tools/go/ast/astutil" "golang.org/x/tools/go/packages" "golang.org/x/tools/go/types/typeutil" )
github.com/flightctl/test//tmp/repos/example/gotypes/doc/main.go
// The doc command prints the doc comment of a package-level object. package main import ( "fmt" "go/ast" "log" "os" "golang.org/x/tools/go/ast/astutil" "golang.org/x/tools/go/packages" "golang.org/x/tools/go/types/typeutil" ) func main() { if len(os.Args) != 3 { log.Fatal("Usage: doc <package> <object>") } //!+part1 pkgpath, name := os.Args[1], os.Args[2] // Load complete type information for the specified packages, // along with type-annotated syntax. // Types for dependencies are loaded from export data. conf := &packages.Config{Mode: packages.LoadSyntax} pkgs, err := packages.Load(conf, pkgpath) if err != nil { log.Fatal(err) // failed to load anything } if packages.PrintErrors(pkgs) > 0 { os.Exit(1) // some packages contained errors } // Find the package and package-level object. pkg := pkgs[0] obj := pkg.Types.Scope().Lookup(name) if obj == nil { log.Fatalf("%s.%s not found", pkg.Types.Path(), name) } //!-part1 //!+part2 // Print the object and its methods (incl. location of definition). fmt.Println(obj) for _, sel := range typeutil.IntuitiveMethodSet(obj.Type(), nil) { fmt.Printf("%s: %s\n", pkg.Fset.Position(sel.Obj().Pos()), sel) } // Find the path from the root of the AST to the object's position. // Walk up to the enclosing ast.Decl for the doc comment. for _, file := range pkg.Syntax { pos := obj.Pos() if !(file.FileStart <= pos && pos < file.FileEnd) { continue // not in this file } path, _ := astutil.PathEnclosingInterval(file, pos, pos) for _, n := range path { switch n := n.(type) { case *ast.GenDecl: fmt.Println("\n", n.Doc.Text()) return case *ast.FuncDecl: fmt.Println("\n", n.Doc.Text()) return } } } //!-part2 } // (The $GOROOT below is the actual string that appears in file names // loaded from export data for packages in the standard library.) /* //!+output $ ./doc net/http File type net/http.File interface{Readdir(count int) ([]os.FileInfo, error); Seek(offset int64, whence int) (int64, error); Stat() (os.FileInfo, error); io.Closer; io.Reader} $GOROOT/src/io/io.go:92:2: method (net/http.File) Close() error $GOROOT/src/io/io.go:71:2: method (net/http.File) Read(p []byte) (n int, err error) /go/src/net/http/fs.go:65:2: method (net/http.File) Readdir(count int) ([]os.FileInfo, error) $GOROOT/src/net/http/fs.go:66:2: method (net/http.File) Seek(offset int64, whence int) (int64, error) /go/src/net/http/fs.go:67:2: method (net/http.File) Stat() (os.FileInfo, error) A File is returned by a FileSystem's Open method and can be served by the FileServer implementation. The methods should behave the same as those on an *os.File. //!-output */
package main
function
flightctl/test
06321b20-6092-463b-bd39-cc7cf1c49227
main
['"fmt"', '"go/ast"', '"log"', '"os"', '"golang.org/x/tools/go/ast/astutil"', '"golang.org/x/tools/go/packages"', '"golang.org/x/tools/go/types/typeutil"']
github.com/flightctl/test//tmp/repos/example/gotypes/doc/main.go
func main() { if len(os.Args) != 3 { log.Fatal("Usage: doc <package> <object>") } //!+part1 pkgpath, name := os.Args[1], os.Args[2] // Load complete type information for the specified packages, // along with type-annotated syntax. // Types for dependencies are loaded from export data. conf := &packages.Config{Mode: packages.LoadSyntax} pkgs, err := packages.Load(conf, pkgpath) if err != nil { log.Fatal(err) // failed to load anything } if packages.PrintErrors(pkgs) > 0 { os.Exit(1) // some packages contained errors } // Find the package and package-level object. pkg := pkgs[0] obj := pkg.Types.Scope().Lookup(name) if obj == nil { log.Fatalf("%s.%s not found", pkg.Types.Path(), name) } //!-part1 //!+part2 // Print the object and its methods (incl. location of definition). fmt.Println(obj) for _, sel := range typeutil.IntuitiveMethodSet(obj.Type(), nil) { fmt.Printf("%s: %s\n", pkg.Fset.Position(sel.Obj().Pos()), sel) } // Find the path from the root of the AST to the object's position. // Walk up to the enclosing ast.Decl for the doc comment. for _, file := range pkg.Syntax { pos := obj.Pos() if !(file.FileStart <= pos && pos < file.FileEnd) { continue // not in this file } path, _ := astutil.PathEnclosingInterval(file, pos, pos) for _, n := range path { switch n := n.(type) { case *ast.GenDecl: fmt.Println("\n", n.Doc.Text()) return case *ast.FuncDecl: fmt.Println("\n", n.Doc.Text()) return } } } //!-part2 }
main
file
flightctl/test
055a9263-7da9-4606-9c90-8a5dc5f19e0c
gen.go
github.com/flightctl/test//tmp/repos/example/gotypes/gen.go
//go:generate bash -c "go run ../internal/cmd/weave/weave.go ./go-types.md > README.md" package gotypes
package gotypes
file
flightctl/test
082bab20-4a7e-450e-b7b2-a00b9de05d1a
hello.go
import "fmt"
github.com/flightctl/test//tmp/repos/example/gotypes/hello/hello.go
// !+ package main import "fmt" func main() { fmt.Println("Hello, 世界") } //!-
package main
function
flightctl/test
54bbfd5d-7ee3-4f52-81e6-29d950e11ed9
main
github.com/flightctl/test//tmp/repos/example/gotypes/hello/hello.go
func main() { fmt.Println("Hello, 世界") }
main
file
flightctl/test
85f31eb9-eb56-48ee-a86f-caf0185e944d
main.go
import ( "flag" "fmt" "go/ast" "go/token" "go/types" "log" "os" "golang.org/x/tools/go/packages" )
github.com/flightctl/test//tmp/repos/example/gotypes/hugeparam/main.go
// The hugeparam command identifies by-value parameters that are larger than n bytes. // // Example: // // $ ./hugeparams encoding/xml package main import ( "flag" "fmt" "go/ast" "go/token" "go/types" "log" "os" "golang.org/x/tools/go/packages" ) // !+ var bytesFlag = flag.Int("bytes", 48, "maximum parameter size in bytes") func PrintHugeParams(fset *token.FileSet, info *types.Info, sizes types.Sizes, files []*ast.File) { checkTuple := func(descr string, tuple *types.Tuple) { for i := 0; i < tuple.Len(); i++ { v := tuple.At(i) if sz := sizes.Sizeof(v.Type()); sz > int64(*bytesFlag) { fmt.Printf("%s: %q %s: %s = %d bytes\n", fset.Position(v.Pos()), v.Name(), descr, v.Type(), sz) } } } checkSig := func(sig *types.Signature) { checkTuple("parameter", sig.Params()) checkTuple("result", sig.Results()) } for _, file := range files { ast.Inspect(file, func(n ast.Node) bool { switch n := n.(type) { case *ast.FuncDecl: checkSig(info.Defs[n.Name].Type().(*types.Signature)) case *ast.FuncLit: checkSig(info.Types[n.Type].Type.(*types.Signature)) } return true }) } } //!- func main() { flag.Parse() // Load complete type information for the specified packages, // along with type-annotated syntax and the "sizeof" function. // Types for dependencies are loaded from export data. conf := &packages.Config{Mode: packages.LoadSyntax} pkgs, err := packages.Load(conf, flag.Args()...) if err != nil { log.Fatal(err) // failed to load anything } if packages.PrintErrors(pkgs) > 0 { os.Exit(1) // some packages contained errors } for _, pkg := range pkgs { PrintHugeParams(pkg.Fset, pkg.TypesInfo, pkg.TypesSizes, pkg.Syntax) } } /* //!+output % ./hugeparam encoding/xml /go/src/encoding/xml/marshal.go:167:50: "start" parameter: encoding/xml.StartElement = 56 bytes /go/src/encoding/xml/marshal.go:734:97: "" result: encoding/xml.StartElement = 56 bytes /go/src/encoding/xml/marshal.go:761:51: "start" parameter: encoding/xml.StartElement = 56 bytes /go/src/encoding/xml/marshal.go:781:68: "start" parameter: encoding/xml.StartElement = 56 bytes /go/src/encoding/xml/xml.go:72:30: "" result: encoding/xml.StartElement = 56 bytes //!-output */
package main
function
flightctl/test
3a9d387b-412a-4d54-8162-68372c00992f
PrintHugeParams
['"fmt"', '"go/ast"', '"go/token"', '"go/types"']
github.com/flightctl/test//tmp/repos/example/gotypes/hugeparam/main.go
func PrintHugeParams(fset *token.FileSet, info *types.Info, sizes types.Sizes, files []*ast.File) { checkTuple := func(descr string, tuple *types.Tuple) { for i := 0; i < tuple.Len(); i++ { v := tuple.At(i) if sz := sizes.Sizeof(v.Type()); sz > int64(*bytesFlag) { fmt.Printf("%s: %q %s: %s = %d bytes\n", fset.Position(v.Pos()), v.Name(), descr, v.Type(), sz) } } } checkSig := func(sig *types.Signature) { checkTuple("parameter", sig.Params()) checkTuple("result", sig.Results()) } for _, file := range files { ast.Inspect(file, func(n ast.Node) bool { switch n := n.(type) { case *ast.FuncDecl: checkSig(info.Defs[n.Name].Type().(*types.Signature)) case *ast.FuncLit: checkSig(info.Types[n.Type].Type.(*types.Signature)) } return true }) } }
{'bytesFlag': 'flag.Int("bytes", 48, "maximum parameter size in bytes")'}
main
function
flightctl/test
d3f7be96-c7e7-4ae8-be2b-5f649faf4624
main
['"flag"', '"log"', '"os"', '"golang.org/x/tools/go/packages"']
github.com/flightctl/test//tmp/repos/example/gotypes/hugeparam/main.go
func main() { flag.Parse() // Load complete type information for the specified packages, // along with type-annotated syntax and the "sizeof" function. // Types for dependencies are loaded from export data. conf := &packages.Config{Mode: packages.LoadSyntax} pkgs, err := packages.Load(conf, flag.Args()...) if err != nil { log.Fatal(err) // failed to load anything } if packages.PrintErrors(pkgs) > 0 { os.Exit(1) // some packages contained errors } for _, pkg := range pkgs { PrintHugeParams(pkg.Fset, pkg.TypesInfo, pkg.TypesSizes, pkg.Syntax) } }
main
file
flightctl/test
cfac8e1b-dcc6-459b-90ed-11e86aee9462
main.go
import ( "fmt" "go/ast" "go/importer" "go/parser" "go/token" "go/types" "log" )
github.com/flightctl/test//tmp/repos/example/gotypes/implements/main.go
package main import ( "fmt" "go/ast" "go/importer" "go/parser" "go/token" "go/types" "log" ) // !+input const input = `package main type A struct{} func (*A) f() type B int func (B) f() func (*B) g() type I interface { f() } type J interface { g() } ` //!-input func main() { // Parse one file. fset := token.NewFileSet() f, err := parser.ParseFile(fset, "input.go", input, 0) if err != nil { log.Fatal(err) // parse error } conf := types.Config{Importer: importer.Default()} pkg, err := conf.Check("hello", fset, []*ast.File{f}, nil) if err != nil { log.Fatal(err) // type error } //!+implements // Find all named types at package level. var allNamed []*types.Named for _, name := range pkg.Scope().Names() { if obj, ok := pkg.Scope().Lookup(name).(*types.TypeName); ok { allNamed = append(allNamed, obj.Type().(*types.Named)) } } // Test assignability of all distinct pairs of // named types (T, U) where U is an interface. for _, T := range allNamed { for _, U := range allNamed { if T == U || !types.IsInterface(U) { continue } if types.AssignableTo(T, U) { fmt.Printf("%s satisfies %s\n", T, U) } else if !types.IsInterface(T) && types.AssignableTo(types.NewPointer(T), U) { fmt.Printf("%s satisfies %s\n", types.NewPointer(T), U) } } } //!-implements } /* //!+output $ go build golang.org/x/example/gotypes/implements $ ./implements *hello.A satisfies hello.I hello.B satisfies hello.I *hello.B satisfies hello.J //!-output */
package main
function
flightctl/test
ce6138ec-bd6f-420b-b2b8-9efcc3a70b53
main
['"fmt"', '"go/ast"', '"go/importer"', '"go/parser"', '"go/token"', '"go/types"', '"log"']
github.com/flightctl/test//tmp/repos/example/gotypes/implements/main.go
func main() { // Parse one file. fset := token.NewFileSet() f, err := parser.ParseFile(fset, "input.go", input, 0) if err != nil { log.Fatal(err) // parse error } conf := types.Config{Importer: importer.Default()} pkg, err := conf.Check("hello", fset, []*ast.File{f}, nil) if err != nil { log.Fatal(err) // type error } //!+implements // Find all named types at package level. var allNamed []*types.Named for _, name := range pkg.Scope().Names() { if obj, ok := pkg.Scope().Lookup(name).(*types.TypeName); ok { allNamed = append(allNamed, obj.Type().(*types.Named)) } } // Test assignability of all distinct pairs of // named types (T, U) where U is an interface. for _, T := range allNamed { for _, U := range allNamed { if T == U || !types.IsInterface(U) { continue } if types.AssignableTo(T, U) { fmt.Printf("%s satisfies %s\n", T, U) } else if !types.IsInterface(T) && types.AssignableTo(types.NewPointer(T), U) { fmt.Printf("%s satisfies %s\n", types.NewPointer(T), U) } } } //!-implements }
main
file
flightctl/test
91bc238e-8588-453b-888e-3e91c12f623d
lookup.go
import ( "fmt" "go/ast" "go/importer" "go/parser" "go/token" "go/types" "log" "strings" )
github.com/flightctl/test//tmp/repos/example/gotypes/lookup/lookup.go
package main import ( "fmt" "go/ast" "go/importer" "go/parser" "go/token" "go/types" "log" "strings" ) // !+input const hello = ` package main import "fmt" // append func main() { // fmt fmt.Println("Hello, world") // main main, x := 1, 2 // main print(main, x) // x } // x ` //!-input // !+main func main() { fset := token.NewFileSet() f, err := parser.ParseFile(fset, "hello.go", hello, parser.ParseComments) if err != nil { log.Fatal(err) // parse error } conf := types.Config{Importer: importer.Default()} pkg, err := conf.Check("cmd/hello", fset, []*ast.File{f}, nil) if err != nil { log.Fatal(err) // type error } // Each comment contains a name. // Look up that name in the innermost scope enclosing the comment. for _, comment := range f.Comments { pos := comment.Pos() name := strings.TrimSpace(comment.Text()) fmt.Printf("At %s,\t%q = ", fset.Position(pos), name) inner := pkg.Scope().Innermost(pos) if _, obj := inner.LookupParent(name, pos); obj != nil { fmt.Println(obj) } else { fmt.Println("not found") } } } //!-main /* //!+output $ go build golang.org/x/example/gotypes/lookup $ ./lookup At hello.go:6:1, "append" = builtin append At hello.go:8:9, "fmt" = package fmt At hello.go:10:9, "main" = func cmd/hello.main() At hello.go:12:9, "main" = var main int At hello.go:14:9, "x" = var x int At hello.go:16:1, "x" = not found //!-output */
package main
function
flightctl/test
90581d41-af99-4624-a0a4-dd15952342cf
main
['"fmt"', '"go/ast"', '"go/importer"', '"go/parser"', '"go/token"', '"go/types"', '"log"', '"strings"']
github.com/flightctl/test//tmp/repos/example/gotypes/lookup/lookup.go
func main() { fset := token.NewFileSet() f, err := parser.ParseFile(fset, "hello.go", hello, parser.ParseComments) if err != nil { log.Fatal(err) // parse error } conf := types.Config{Importer: importer.Default()} pkg, err := conf.Check("cmd/hello", fset, []*ast.File{f}, nil) if err != nil { log.Fatal(err) // type error } // Each comment contains a name. // Look up that name in the innermost scope enclosing the comment. for _, comment := range f.Comments { pos := comment.Pos() name := strings.TrimSpace(comment.Text()) fmt.Printf("At %s,\t%q = ", fset.Position(pos), name) inner := pkg.Scope().Innermost(pos) if _, obj := inner.LookupParent(name, pos); obj != nil { fmt.Println(obj) } else { fmt.Println("not found") } } }
main
file
flightctl/test
6f8b713f-27ed-4b8e-bc5f-395127fb5701
main.go
import ( "fmt" "go/ast" "go/importer" "go/parser" "go/token" "go/types" "log" )
github.com/flightctl/test//tmp/repos/example/gotypes/nilfunc/main.go
package main import ( "fmt" "go/ast" "go/importer" "go/parser" "go/token" "go/types" "log" ) // !+input const input = `package main import "bytes" func main() { var buf bytes.Buffer if buf.Bytes == nil && bytes.Repeat != nil && main == nil { // ... } } ` //!-input var fset = token.NewFileSet() func main() { f, err := parser.ParseFile(fset, "input.go", input, 0) if err != nil { log.Fatal(err) // parse error } conf := types.Config{Importer: importer.Default()} info := &types.Info{ Defs: make(map[*ast.Ident]types.Object), Uses: make(map[*ast.Ident]types.Object), Types: make(map[ast.Expr]types.TypeAndValue), } if _, err = conf.Check("cmd/hello", fset, []*ast.File{f}, info); err != nil { log.Fatal(err) // type error } ast.Inspect(f, func(n ast.Node) bool { if n != nil { CheckNilFuncComparison(info, n) } return true }) } // !+ // CheckNilFuncComparison reports unintended comparisons // of functions against nil, e.g., "if x.Method == nil {". func CheckNilFuncComparison(info *types.Info, n ast.Node) { e, ok := n.(*ast.BinaryExpr) if !ok { return // not a binary operation } if e.Op != token.EQL && e.Op != token.NEQ { return // not a comparison } // If this is a comparison against nil, find the other operand. var other ast.Expr if info.Types[e.X].IsNil() { other = e.Y } else if info.Types[e.Y].IsNil() { other = e.X } else { return // not a comparison against nil } // Find the object. var obj types.Object switch v := other.(type) { case *ast.Ident: obj = info.Uses[v] case *ast.SelectorExpr: obj = info.Uses[v.Sel] default: return // not an identifier or selection } if _, ok := obj.(*types.Func); !ok { return // not a function or method } fmt.Printf("%s: comparison of function %v %v nil is always %v\n", fset.Position(e.Pos()), obj.Name(), e.Op, e.Op == token.NEQ) } //!- /* //!+output $ go build golang.org/x/example/gotypes/nilfunc $ ./nilfunc input.go:7:5: comparison of function Bytes == nil is always false input.go:7:25: comparison of function Repeat != nil is always true input.go:7:48: comparison of function main == nil is always false //!-output */
package main
function
flightctl/test
c33f15bb-af0f-4269-ad72-8fd3d0ea02cd
main
['"go/ast"', '"go/importer"', '"go/parser"', '"go/types"', '"log"']
github.com/flightctl/test//tmp/repos/example/gotypes/nilfunc/main.go
func main() { f, err := parser.ParseFile(fset, "input.go", input, 0) if err != nil { log.Fatal(err) // parse error } conf := types.Config{Importer: importer.Default()} info := &types.Info{ Defs: make(map[*ast.Ident]types.Object), Uses: make(map[*ast.Ident]types.Object), Types: make(map[ast.Expr]types.TypeAndValue), } if _, err = conf.Check("cmd/hello", fset, []*ast.File{f}, info); err != nil { log.Fatal(err) // type error } ast.Inspect(f, func(n ast.Node) bool { if n != nil { CheckNilFuncComparison(info, n) } return true }) }
{'fset': 'token.NewFileSet()'}
main
function
flightctl/test
e1f188e1-0299-49da-bece-cdad3bf8b321
CheckNilFuncComparison
['"fmt"', '"go/ast"', '"go/token"', '"go/types"']
github.com/flightctl/test//tmp/repos/example/gotypes/nilfunc/main.go
func CheckNilFuncComparison(info *types.Info, n ast.Node) { e, ok := n.(*ast.BinaryExpr) if !ok { return // not a binary operation } if e.Op != token.EQL && e.Op != token.NEQ { return // not a comparison } // If this is a comparison against nil, find the other operand. var other ast.Expr if info.Types[e.X].IsNil() { other = e.Y } else if info.Types[e.Y].IsNil() { other = e.X } else { return // not a comparison against nil } // Find the object. var obj types.Object switch v := other.(type) { case *ast.Ident: obj = info.Uses[v] case *ast.SelectorExpr: obj = info.Uses[v.Sel] default: return // not an identifier or selection } if _, ok := obj.(*types.Func); !ok { return // not a function or method } fmt.Printf("%s: comparison of function %v %v nil is always %v\n", fset.Position(e.Pos()), obj.Name(), e.Op, e.Op == token.NEQ) }
{'fset': 'token.NewFileSet()'}
main
file
flightctl/test
710f06e9-ca1a-44f4-b262-92893ef9895f
main.go
import ( "fmt" "go/ast" "go/importer" "go/parser" "go/token" "go/types" "log" )
github.com/flightctl/test//tmp/repos/example/gotypes/pkginfo/main.go
// !+ package main import ( "fmt" "go/ast" "go/importer" "go/parser" "go/token" "go/types" "log" ) const hello = `package main import "fmt" func main() { fmt.Println("Hello, world") }` func main() { fset := token.NewFileSet() // Parse the input string, []byte, or io.Reader, // recording position information in fset. // ParseFile returns an *ast.File, a syntax tree. f, err := parser.ParseFile(fset, "hello.go", hello, 0) if err != nil { log.Fatal(err) // parse error } // A Config controls various options of the type checker. // The defaults work fine except for one setting: // we must specify how to deal with imports. conf := types.Config{Importer: importer.Default()} // Type-check the package containing only file f. // Check returns a *types.Package. pkg, err := conf.Check("cmd/hello", fset, []*ast.File{f}, nil) if err != nil { log.Fatal(err) // type error } fmt.Printf("Package %q\n", pkg.Path()) fmt.Printf("Name: %s\n", pkg.Name()) fmt.Printf("Imports: %s\n", pkg.Imports()) fmt.Printf("Scope: %s\n", pkg.Scope()) } //!- /* //!+output $ go build golang.org/x/example/gotypes/pkginfo $ ./pkginfo Package "cmd/hello" Name: main Imports: [package fmt ("fmt")] Scope: package "cmd/hello" scope 0x820533590 { . func cmd/hello.main() } //!-output */
package main
function
flightctl/test
29fa69b0-0073-4056-816b-8ed514cd407c
main
['"fmt"', '"go/ast"', '"go/importer"', '"go/parser"', '"go/token"', '"go/types"', '"log"']
github.com/flightctl/test//tmp/repos/example/gotypes/pkginfo/main.go
func main() { fset := token.NewFileSet() // Parse the input string, []byte, or io.Reader, // recording position information in fset. // ParseFile returns an *ast.File, a syntax tree. f, err := parser.ParseFile(fset, "hello.go", hello, 0) if err != nil { log.Fatal(err) // parse error } // A Config controls various options of the type checker. // The defaults work fine except for one setting: // we must specify how to deal with imports. conf := types.Config{Importer: importer.Default()} // Type-check the package containing only file f. // Check returns a *types.Package. pkg, err := conf.Check("cmd/hello", fset, []*ast.File{f}, nil) if err != nil { log.Fatal(err) // type error } fmt.Printf("Package %q\n", pkg.Path()) fmt.Printf("Name: %s\n", pkg.Name()) fmt.Printf("Imports: %s\n", pkg.Imports()) fmt.Printf("Scope: %s\n", pkg.Scope()) }
main
file
flightctl/test
828a67e4-c87b-44cc-ae6a-0f55fdcc7700
main.go
import ( "fmt" "go/types" "log" "os" "strings" "unicode" "unicode/utf8" "golang.org/x/tools/go/packages" )
github.com/flightctl/test//tmp/repos/example/gotypes/skeleton/main.go
// The skeleton command prints the boilerplate for a concrete type // that implements the specified interface type. // // Example: // // $ ./skeleton io ReadWriteCloser buffer // // *buffer implements io.ReadWriteCloser. // type buffer struct{ /* ... */ } // func (b *buffer) Close() error { panic("unimplemented") } // func (b *buffer) Read(p []byte) (n int, err error) { panic("unimplemented") } // func (b *buffer) Write(p []byte) (n int, err error) { panic("unimplemented") } package main import ( "fmt" "go/types" "log" "os" "strings" "unicode" "unicode/utf8" "golang.org/x/tools/go/packages" ) const usage = "Usage: skeleton <package> <interface> <concrete>" // !+ func PrintSkeleton(pkg *types.Package, ifacename, concname string) error { obj := pkg.Scope().Lookup(ifacename) if obj == nil { return fmt.Errorf("%s.%s not found", pkg.Path(), ifacename) } if _, ok := obj.(*types.TypeName); !ok { return fmt.Errorf("%v is not a named type", obj) } iface, ok := obj.Type().Underlying().(*types.Interface) if !ok { return fmt.Errorf("type %v is a %T, not an interface", obj, obj.Type().Underlying()) } // Use first letter of type name as receiver parameter. if !isValidIdentifier(concname) { return fmt.Errorf("invalid concrete type name: %q", concname) } r, _ := utf8.DecodeRuneInString(concname) fmt.Printf("// *%s implements %s.%s.\n", concname, pkg.Path(), ifacename) fmt.Printf("type %s struct{}\n", concname) mset := types.NewMethodSet(iface) for i := 0; i < mset.Len(); i++ { meth := mset.At(i).Obj() sig := types.TypeString(meth.Type(), (*types.Package).Name) fmt.Printf("func (%c *%s) %s%s {\n\tpanic(\"unimplemented\")\n}\n", r, concname, meth.Name(), strings.TrimPrefix(sig, "func")) } return nil } //!- func isValidIdentifier(id string) bool { for i, r := range id { if !unicode.IsLetter(r) && !(i > 0 && unicode.IsDigit(r)) { return false } } return id != "" } func main() { if len(os.Args) != 4 { log.Fatal(usage) } pkgpath, ifacename, concname := os.Args[1], os.Args[2], os.Args[3] // Load only exported type information for the specified package. conf := &packages.Config{Mode: packages.NeedTypes} pkgs, err := packages.Load(conf, pkgpath) if err != nil { log.Fatal(err) // failed to load anything } if packages.PrintErrors(pkgs) > 0 { os.Exit(1) // some packages contained errors } if err := PrintSkeleton(pkgs[0].Types, ifacename, concname); err != nil { log.Fatal(err) } } /* //!+output1 $ ./skeleton io ReadWriteCloser buffer // *buffer implements io.ReadWriteCloser. type buffer struct{} func (b *buffer) Close() error { panic("unimplemented") } func (b *buffer) Read(p []byte) (n int, err error) { panic("unimplemented") } func (b *buffer) Write(p []byte) (n int, err error) { panic("unimplemented") } //!-output1 //!+output2 $ ./skeleton net/http Handler myHandler // *myHandler implements net/http.Handler. type myHandler struct{} func (m *myHandler) ServeHTTP(http.ResponseWriter, *http.Request) { panic("unimplemented") } //!-output2 */
package main
function
flightctl/test
3507dc64-8155-4a9b-a1a6-b5479226b5d4
PrintSkeleton
['"fmt"', '"go/types"', '"strings"', '"unicode/utf8"']
github.com/flightctl/test//tmp/repos/example/gotypes/skeleton/main.go
func PrintSkeleton(pkg *types.Package, ifacename, concname string) error { obj := pkg.Scope().Lookup(ifacename) if obj == nil { return fmt.Errorf("%s.%s not found", pkg.Path(), ifacename) } if _, ok := obj.(*types.TypeName); !ok { return fmt.Errorf("%v is not a named type", obj) } iface, ok := obj.Type().Underlying().(*types.Interface) if !ok { return fmt.Errorf("type %v is a %T, not an interface", obj, obj.Type().Underlying()) } // Use first letter of type name as receiver parameter. if !isValidIdentifier(concname) { return fmt.Errorf("invalid concrete type name: %q", concname) } r, _ := utf8.DecodeRuneInString(concname) fmt.Printf("// *%s implements %s.%s.\n", concname, pkg.Path(), ifacename) fmt.Printf("type %s struct{}\n", concname) mset := types.NewMethodSet(iface) for i := 0; i < mset.Len(); i++ { meth := mset.At(i).Obj() sig := types.TypeString(meth.Type(), (*types.Package).Name) fmt.Printf("func (%c *%s) %s%s {\n\tpanic(\"unimplemented\")\n}\n", r, concname, meth.Name(), strings.TrimPrefix(sig, "func")) } return nil }
main
function
flightctl/test
e250faf2-d0e9-4d3c-9ab4-03317b4c9f11
isValidIdentifier
['"unicode"']
github.com/flightctl/test//tmp/repos/example/gotypes/skeleton/main.go
func isValidIdentifier(id string) bool { for i, r := range id { if !unicode.IsLetter(r) && !(i > 0 && unicode.IsDigit(r)) { return false } } return id != "" }
main
function
flightctl/test
432b7863-53aa-404b-a8b3-29a09b008e9e
main
['"log"', '"os"', '"golang.org/x/tools/go/packages"']
github.com/flightctl/test//tmp/repos/example/gotypes/skeleton/main.go
func main() { if len(os.Args) != 4 { log.Fatal(usage) } pkgpath, ifacename, concname := os.Args[1], os.Args[2], os.Args[3] // Load only exported type information for the specified package. conf := &packages.Config{Mode: packages.NeedTypes} pkgs, err := packages.Load(conf, pkgpath) if err != nil { log.Fatal(err) // failed to load anything } if packages.PrintErrors(pkgs) > 0 { os.Exit(1) // some packages contained errors } if err := PrintSkeleton(pkgs[0].Types, ifacename, concname); err != nil { log.Fatal(err) } }
main
file
flightctl/test
72d9a912-9dfb-4845-b902-1b56dba7416d
main.go
import ( "bytes" "fmt" "go/ast" "go/format" "go/importer" "go/parser" "go/token" "go/types" "log" )
github.com/flightctl/test//tmp/repos/example/gotypes/typeandvalue/main.go
package main import ( "bytes" "fmt" "go/ast" "go/format" "go/importer" "go/parser" "go/token" "go/types" "log" ) // !+input const input = ` package main var m = make(map[string]int) func main() { v, ok := m["hello, " + "world"] print(rune(v), ok) } ` //!-input var fset = token.NewFileSet() func main() { f, err := parser.ParseFile(fset, "hello.go", input, 0) if err != nil { log.Fatal(err) // parse error } conf := types.Config{Importer: importer.Default()} info := &types.Info{Types: make(map[ast.Expr]types.TypeAndValue)} if _, err := conf.Check("cmd/hello", fset, []*ast.File{f}, info); err != nil { log.Fatal(err) // type error } //!+inspect // f is a parsed, type-checked *ast.File. ast.Inspect(f, func(n ast.Node) bool { if expr, ok := n.(ast.Expr); ok { if tv, ok := info.Types[expr]; ok { fmt.Printf("%-24s\tmode: %s\n", nodeString(expr), mode(tv)) fmt.Printf("\t\t\t\ttype: %v\n", tv.Type) if tv.Value != nil { fmt.Printf("\t\t\t\tvalue: %v\n", tv.Value) } } } return true }) //!-inspect } // nodeString formats a syntax tree in the style of gofmt. func nodeString(n ast.Node) string { var buf bytes.Buffer format.Node(&buf, fset, n) return buf.String() } // mode returns a string describing the mode of an expression. func mode(tv types.TypeAndValue) string { s := "" if tv.IsVoid() { s += ",void" } if tv.IsType() { s += ",type" } if tv.IsBuiltin() { s += ",builtin" } if tv.IsValue() { s += ",value" } if tv.IsNil() { s += ",nil" } if tv.Addressable() { s += ",addressable" } if tv.Assignable() { s += ",assignable" } if tv.HasOk() { s += ",ok" } return s[1:] } /* //!+output $ go build golang.org/x/example/gotypes/typeandvalue $ ./typeandvalue make(map[string]int) mode: value type: map[string]int make mode: builtin type: func(map[string]int) map[string]int map[string]int mode: type type: map[string]int string mode: type type: string int mode: type type: int m["hello, "+"world"] mode: value,assignable,ok type: (int, bool) m mode: value,addressable,assignable type: map[string]int "hello, " + "world" mode: value type: string value: "hello, world" "hello, " mode: value type: untyped string value: "hello, " "world" mode: value type: untyped string value: "world" print(rune(v), ok) mode: void type: () print mode: builtin type: func(rune, bool) rune(v) mode: value type: rune rune mode: type type: rune ...more not shown... //!-output */
package main
function
flightctl/test
3ce79319-2531-43ce-bee1-ceab00a4e22f
main
['"fmt"', '"go/ast"', '"go/importer"', '"go/parser"', '"go/types"', '"log"']
github.com/flightctl/test//tmp/repos/example/gotypes/typeandvalue/main.go
func main() { f, err := parser.ParseFile(fset, "hello.go", input, 0) if err != nil { log.Fatal(err) // parse error } conf := types.Config{Importer: importer.Default()} info := &types.Info{Types: make(map[ast.Expr]types.TypeAndValue)} if _, err := conf.Check("cmd/hello", fset, []*ast.File{f}, info); err != nil { log.Fatal(err) // type error } //!+inspect // f is a parsed, type-checked *ast.File. ast.Inspect(f, func(n ast.Node) bool { if expr, ok := n.(ast.Expr); ok { if tv, ok := info.Types[expr]; ok { fmt.Printf("%-24s\tmode: %s\n", nodeString(expr), mode(tv)) fmt.Printf("\t\t\t\ttype: %v\n", tv.Type) if tv.Value != nil { fmt.Printf("\t\t\t\tvalue: %v\n", tv.Value) } } } return true }) //!-inspect }
{'fset': 'token.NewFileSet()'}
main
function
flightctl/test
9beb2665-4476-4b62-8d6e-63ad65916165
nodeString
['"bytes"', '"go/ast"', '"go/format"']
github.com/flightctl/test//tmp/repos/example/gotypes/typeandvalue/main.go
func nodeString(n ast.Node) string { var buf bytes.Buffer format.Node(&buf, fset, n) return buf.String() }
{'fset': 'token.NewFileSet()'}
main
function
flightctl/test
b860b0a5-cb1c-443a-a905-17aa68c8579f
mode
['"go/types"']
github.com/flightctl/test//tmp/repos/example/gotypes/typeandvalue/main.go
func mode(tv types.TypeAndValue) string { s := "" if tv.IsVoid() { s += ",void" } if tv.IsType() { s += ",type" } if tv.IsBuiltin() { s += ",builtin" } if tv.IsValue() { s += ",value" } if tv.IsNil() { s += ",nil" } if tv.Addressable() { s += ",addressable" } if tv.Assignable() { s += ",assignable" } if tv.HasOk() { s += ",ok" } return s[1:] }
main
file
flightctl/test
9323729c-68b1-4821-8164-121cd011a4a1
hello.go
import ( "flag" "fmt" "log" "os" "golang.org/x/example/hello/reverse" )
github.com/flightctl/test//tmp/repos/example/hello/hello.go
// Copyright 2023 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // Hello is a hello, world program, demonstrating // how to write a simple command-line program. // // Usage: // // hello [options] [name] // // The options are: // // -g greeting // Greet with the given greeting, instead of "Hello". // // -r // Greet in reverse. // // By default, hello greets the world. // If a name is specified, hello greets that name instead. package main import ( "flag" "fmt" "log" "os" "golang.org/x/example/hello/reverse" ) func usage() { fmt.Fprintf(os.Stderr, "usage: hello [options] [name]\n") flag.PrintDefaults() os.Exit(2) } var ( greeting = flag.String("g", "Hello", "Greet with `greeting`") reverseFlag = flag.Bool("r", false, "Greet in reverse") ) func main() { // Configure logging for a command-line program. log.SetFlags(0) log.SetPrefix("hello: ") // Parse flags. flag.Usage = usage flag.Parse() // Parse and validate arguments. name := "world" args := flag.Args() if len(args) >= 2 { usage() } if len(args) >= 1 { name = args[0] } if name == "" { // hello '' is an error log.Fatalf("invalid name %q", name) } // Run actual logic. if *reverseFlag { fmt.Printf("%s, %s!\n", reverse.String(*greeting), reverse.String(name)) return } fmt.Printf("%s, %s!\n", *greeting, name) }
package main
function
flightctl/test
cf5db83b-96d5-49c8-834d-10f7517bede8
usage
['"flag"', '"fmt"', '"os"']
github.com/flightctl/test//tmp/repos/example/hello/hello.go
func usage() { fmt.Fprintf(os.Stderr, "usage: hello [options] [name]\n") flag.PrintDefaults() os.Exit(2) }
main
function
flightctl/test
3842a86b-6609-49bf-8d70-1dea39e3839a
main
['"flag"', '"fmt"', '"log"', '"golang.org/x/example/hello/reverse"']
github.com/flightctl/test//tmp/repos/example/hello/hello.go
func main() { // Configure logging for a command-line program. log.SetFlags(0) log.SetPrefix("hello: ") // Parse flags. flag.Usage = usage flag.Parse() // Parse and validate arguments. name := "world" args := flag.Args() if len(args) >= 2 { usage() } if len(args) >= 1 { name = args[0] } if name == "" { // hello '' is an error log.Fatalf("invalid name %q", name) } // Run actual logic. if *reverseFlag { fmt.Printf("%s, %s!\n", reverse.String(*greeting), reverse.String(name)) return } fmt.Printf("%s, %s!\n", *greeting, name) }
main
file
flightctl/test
289c8def-db4f-4c0c-a0cb-2521935ffd35
example_test.go
import ( "fmt" "golang.org/x/example/hello/reverse" )
github.com/flightctl/test//tmp/repos/example/hello/reverse/example_test.go
// Copyright 2023 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package reverse_test import ( "fmt" "golang.org/x/example/hello/reverse" ) func ExampleString() { fmt.Println(reverse.String("hello")) // Output: olleh }
package reverse_test
function
flightctl/test
82c375de-2c4a-44f5-b083-df78340da8b4
ExampleString
['"fmt"', '"golang.org/x/example/hello/reverse"']
github.com/flightctl/test//tmp/repos/example/hello/reverse/example_test.go
func ExampleString() { fmt.Println(reverse.String("hello")) // Output: olleh }
reverse_test
file
flightctl/test
cf2f6fd7-788c-4872-b0a0-fbb607b1bec8
reverse.go
github.com/flightctl/test//tmp/repos/example/hello/reverse/reverse.go
// Copyright 2023 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // Package reverse can reverse things, particularly strings. package reverse // String returns its argument string reversed rune-wise left to right. func String(s string) string { r := []rune(s) for i, j := 0, len(r)-1; i < len(r)/2; i, j = i+1, j-1 { r[i], r[j] = r[j], r[i] } return string(r) }
package reverse
function
flightctl/test
d87b0624-429e-4bab-929a-4b3193b1441d
String
github.com/flightctl/test//tmp/repos/example/hello/reverse/reverse.go
func String(s string) string { r := []rune(s) for i, j := 0, len(r)-1; i < len(r)/2; i, j = i+1, j-1 { r[i], r[j] = r[j], r[i] } return string(r) }
reverse
file
flightctl/test
4a966f10-adf8-4df1-ab88-859c2bda699c
reverse_test.go
import "testing"
github.com/flightctl/test//tmp/repos/example/hello/reverse/reverse_test.go
// Copyright 2023 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package reverse import "testing" func TestString(t *testing.T) { for _, c := range []struct { in, want string }{ {"Hello, world", "dlrow ,olleH"}, {"Hello, 世界", "界世 ,olleH"}, {"", ""}, } { got := String(c.in) if got != c.want { t.Errorf("String(%q) == %q, want %q", c.in, got, c.want) } } }
package reverse
function
flightctl/test
273990a4-0d9c-4feb-ad38-2e0b66e67a78
TestString
github.com/flightctl/test//tmp/repos/example/hello/reverse/reverse_test.go
func TestString(t *testing.T) { for _, c := range []struct { in, want string }{ {"Hello, world", "dlrow ,olleH"}, {"Hello, 世界", "界世 ,olleH"}, {"", ""}, } { got := String(c.in) if got != c.want { t.Errorf("String(%q) == %q, want %q", c.in, got, c.want) } } }
reverse
file
flightctl/test
af137d20-eda5-4939-b569-bf228035bb1b
server.go
import ( "flag" "fmt" "html" "log" "net/http" "os" "runtime/debug" "strings" )
github.com/flightctl/test//tmp/repos/example/helloserver/server.go
// Copyright 2023 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // Hello is a simple hello, world demonstration web server. // // It serves version information on /version and answers // any other request like /name by saying "Hello, name!". // // See golang.org/x/example/outyet for a more sophisticated server. package main import ( "flag" "fmt" "html" "log" "net/http" "os" "runtime/debug" "strings" ) func usage() { fmt.Fprintf(os.Stderr, "usage: helloserver [options]\n") flag.PrintDefaults() os.Exit(2) } var ( greeting = flag.String("g", "Hello", "Greet with `greeting`") addr = flag.String("addr", "localhost:8080", "address to serve") ) func main() { // Parse flags. flag.Usage = usage flag.Parse() // Parse and validate arguments (none). args := flag.Args() if len(args) != 0 { usage() } // Register handlers. // All requests not otherwise mapped with go to greet. // /version is mapped specifically to version. http.HandleFunc("/", greet) http.HandleFunc("/version", version) log.Printf("serving http://%s\n", *addr) log.Fatal(http.ListenAndServe(*addr, nil)) } func version(w http.ResponseWriter, r *http.Request) { info, ok := debug.ReadBuildInfo() if !ok { http.Error(w, "no build information available", 500) return } fmt.Fprintf(w, "<!DOCTYPE html>\n<pre>\n") fmt.Fprintf(w, "%s\n", html.EscapeString(info.String())) } func greet(w http.ResponseWriter, r *http.Request) { name := strings.Trim(r.URL.Path, "/") if name == "" { name = "Gopher" } fmt.Fprintf(w, "<!DOCTYPE html>\n") fmt.Fprintf(w, "%s, %s!\n", *greeting, html.EscapeString(name)) }
package main
function
flightctl/test
dbbbda4d-7d41-4bd2-bd42-81678921491c
usage
['"flag"', '"fmt"', '"os"']
github.com/flightctl/test//tmp/repos/example/helloserver/server.go
func usage() { fmt.Fprintf(os.Stderr, "usage: helloserver [options]\n") flag.PrintDefaults() os.Exit(2) }
main
function
flightctl/test
f7d6307a-8e6b-4050-8423-daf14dd81e79
main
['"flag"', '"log"', '"net/http"']
github.com/flightctl/test//tmp/repos/example/helloserver/server.go
func main() { // Parse flags. flag.Usage = usage flag.Parse() // Parse and validate arguments (none). args := flag.Args() if len(args) != 0 { usage() } // Register handlers. // All requests not otherwise mapped with go to greet. // /version is mapped specifically to version. http.HandleFunc("/", greet) http.HandleFunc("/version", version) log.Printf("serving http://%s\n", *addr) log.Fatal(http.ListenAndServe(*addr, nil)) }
main
function
flightctl/test
d757539a-0fc9-4dc6-a1b3-b73e1607d313
version
['"fmt"', '"html"', '"net/http"', '"runtime/debug"']
github.com/flightctl/test//tmp/repos/example/helloserver/server.go
func version(w http.ResponseWriter, r *http.Request) { info, ok := debug.ReadBuildInfo() if !ok { http.Error(w, "no build information available", 500) return } fmt.Fprintf(w, "<!DOCTYPE html>\n<pre>\n") fmt.Fprintf(w, "%s\n", html.EscapeString(info.String())) }
main
function
flightctl/test
e1533996-f738-48d0-8177-595adf7810df
greet
['"fmt"', '"html"', '"net/http"', '"strings"']
github.com/flightctl/test//tmp/repos/example/helloserver/server.go
func greet(w http.ResponseWriter, r *http.Request) { name := strings.Trim(r.URL.Path, "/") if name == "" { name = "Gopher" } fmt.Fprintf(w, "<!DOCTYPE html>\n") fmt.Fprintf(w, "%s, %s!\n", *greeting, html.EscapeString(name)) }
main
file
flightctl/test
878ae366-fdf5-4e82-8c6b-dd79068f6c5c
weave.go
import ( "bufio" "bytes" "fmt" "log" "os" "path/filepath" "regexp" "strings" )
github.com/flightctl/test//tmp/repos/example/internal/cmd/weave/weave.go
// The weave command is a simple preprocessor for markdown files. // It builds a table of contents and processes %include directives. // // Example usage: // // $ go run internal/cmd/weave go-types.md > README.md // // The weave command copies lines of the input file to standard output, with two // exceptions: // // If a line begins with "%toc", it is replaced with a table of contents // consisting of links to the top two levels of headers ("#" and "##"). // // If a line begins with "%include FILENAME TAG", it is replaced with the lines // of the file between lines containing "!+TAG" and "!-TAG". TAG can be omitted, // in which case the delimiters are simply "!+" and "!-". // // Before the included lines, a line of the form // // // go get PACKAGE // // is output, where PACKAGE is constructed from the module path, the // base name of the current directory, and the directory of FILENAME. // This caption can be suppressed by putting "-" as the final word of the %include line. package main import ( "bufio" "bytes" "fmt" "log" "os" "path/filepath" "regexp" "strings" ) func main() { log.SetFlags(0) log.SetPrefix("weave: ") if len(os.Args) != 2 { log.Fatal("usage: weave input.md\n") } f, err := os.Open(os.Args[1]) if err != nil { log.Fatal(err) } defer f.Close() wd, err := os.Getwd() if err != nil { log.Fatal(err) } curDir := filepath.Base(wd) fmt.Println("<!-- Autogenerated by weave; DO NOT EDIT -->") // Pass 1: extract table of contents. var toc []string in := bufio.NewScanner(f) for in.Scan() { line := in.Text() if line == "" || (line[0] != '#' && line[0] != '%') { continue } line = strings.TrimSpace(line) if line == "%toc" { toc = nil } else if strings.HasPrefix(line, "# ") || strings.HasPrefix(line, "## ") { words := strings.Fields(line) depth := len(words[0]) words = words[1:] text := strings.Join(words, " ") for i := range words { words[i] = strings.ToLower(words[i]) } line = fmt.Sprintf("%s1. [%s](#%s)", strings.Repeat("\t", depth-1), text, strings.Join(words, "-")) toc = append(toc, line) } } if in.Err() != nil { log.Fatal(in.Err()) } // Pass 2. if _, err := f.Seek(0, os.SEEK_SET); err != nil { log.Fatalf("can't rewind input: %v", err) } in = bufio.NewScanner(f) for in.Scan() { line := in.Text() switch { case strings.HasPrefix(line, "%toc"): // ToC for _, h := range toc { fmt.Println(h) } case strings.HasPrefix(line, "%include"): words := strings.Fields(line) if len(words) < 2 { log.Fatal(line) } filename := words[1] // Show caption unless '-' follows. if len(words) < 4 || words[3] != "-" { fmt.Printf(" // go get golang.org/x/example/%s/%s\n\n", curDir, filepath.Dir(filename)) } section := "" if len(words) > 2 { section = words[2] } s, err := include(filename, section) if err != nil { log.Fatal(err) } fmt.Println("```") fmt.Println(cleanListing(s)) // TODO(adonovan): escape /^```/ in s fmt.Println("```") default: fmt.Println(line) } } if in.Err() != nil { log.Fatal(in.Err()) } } // include processes an included file, and returns the included text. // Only lines between those matching !+tag and !-tag will be returned. // This is true even if tag=="". func include(file, tag string) (string, error) { f, err := os.Open(file) if err != nil { return "", err } defer f.Close() startre, err := regexp.Compile("!\\+" + tag + "$") if err != nil { return "", err } endre, err := regexp.Compile("!\\-" + tag + "$") if err != nil { return "", err } var text bytes.Buffer in := bufio.NewScanner(f) var on bool for in.Scan() { line := in.Text() switch { case startre.MatchString(line): on = true case endre.MatchString(line): on = false case on: text.WriteByte('\t') text.WriteString(line) text.WriteByte('\n') } } if in.Err() != nil { return "", in.Err() } if text.Len() == 0 { return "", fmt.Errorf("no lines of %s matched tag %q", file, tag) } return text.String(), nil } func isBlank(line string) bool { return strings.TrimSpace(line) == "" } func indented(line string) bool { return strings.HasPrefix(line, " ") || strings.HasPrefix(line, "\t") } // cleanListing removes entirely blank leading and trailing lines from // text, and removes n leading tabs. func cleanListing(text string) string { lines := strings.Split(text, "\n") // remove minimum number of leading tabs from all non-blank lines tabs := 999 for i, line := range lines { if strings.TrimSpace(line) == "" { lines[i] = "" } else { if n := leadingTabs(line); n < tabs { tabs = n } } } for i, line := range lines { if line != "" { line := line[tabs:] lines[i] = line // remove leading tabs } } // remove leading blank lines for len(lines) > 0 && lines[0] == "" { lines = lines[1:] } // remove trailing blank lines for len(lines) > 0 && lines[len(lines)-1] == "" { lines = lines[:len(lines)-1] } return strings.Join(lines, "\n") } func leadingTabs(s string) int { var i int for i = 0; i < len(s); i++ { if s[i] != '\t' { break } } return i }
package main
function
flightctl/test
16b8ae9a-3804-4e89-933d-fb3071fedca7
main
['"bufio"', '"fmt"', '"log"', '"os"', '"path/filepath"', '"strings"']
github.com/flightctl/test//tmp/repos/example/internal/cmd/weave/weave.go
func main() { log.SetFlags(0) log.SetPrefix("weave: ") if len(os.Args) != 2 { log.Fatal("usage: weave input.md\n") } f, err := os.Open(os.Args[1]) if err != nil { log.Fatal(err) } defer f.Close() wd, err := os.Getwd() if err != nil { log.Fatal(err) } curDir := filepath.Base(wd) fmt.Println("<!-- Autogenerated by weave; DO NOT EDIT -->") // Pass 1: extract table of contents. var toc []string in := bufio.NewScanner(f) for in.Scan() { line := in.Text() if line == "" || (line[0] != '#' && line[0] != '%') { continue } line = strings.TrimSpace(line) if line == "%toc" { toc = nil } else if strings.HasPrefix(line, "# ") || strings.HasPrefix(line, "## ") { words := strings.Fields(line) depth := len(words[0]) words = words[1:] text := strings.Join(words, " ") for i := range words { words[i] = strings.ToLower(words[i]) } line = fmt.Sprintf("%s1. [%s](#%s)", strings.Repeat("\t", depth-1), text, strings.Join(words, "-")) toc = append(toc, line) } } if in.Err() != nil { log.Fatal(in.Err()) } // Pass 2. if _, err := f.Seek(0, os.SEEK_SET); err != nil { log.Fatalf("can't rewind input: %v", err) } in = bufio.NewScanner(f) for in.Scan() { line := in.Text() switch { case strings.HasPrefix(line, "%toc"): // ToC for _, h := range toc { fmt.Println(h) } case strings.HasPrefix(line, "%include"): words := strings.Fields(line) if len(words) < 2 { log.Fatal(line) } filename := words[1] // Show caption unless '-' follows. if len(words) < 4 || words[3] != "-" { fmt.Printf(" // go get golang.org/x/example/%s/%s\n\n", curDir, filepath.Dir(filename)) } section := "" if len(words) > 2 { section = words[2] } s, err := include(filename, section) if err != nil { log.Fatal(err) } fmt.Println("```") fmt.Println(cleanListing(s)) // TODO(adonovan): escape /^```/ in s fmt.Println("```") default: fmt.Println(line) } } if in.Err() != nil { log.Fatal(in.Err()) } }
main
function
flightctl/test
7ffeb10c-4c7e-42be-ad55-f6ead17808db
include
['"bufio"', '"bytes"', '"fmt"', '"os"', '"regexp"']
github.com/flightctl/test//tmp/repos/example/internal/cmd/weave/weave.go
func include(file, tag string) (string, error) { f, err := os.Open(file) if err != nil { return "", err } defer f.Close() startre, err := regexp.Compile("!\\+" + tag + "$") if err != nil { return "", err } endre, err := regexp.Compile("!\\-" + tag + "$") if err != nil { return "", err } var text bytes.Buffer in := bufio.NewScanner(f) var on bool for in.Scan() { line := in.Text() switch { case startre.MatchString(line): on = true case endre.MatchString(line): on = false case on: text.WriteByte('\t') text.WriteString(line) text.WriteByte('\n') } } if in.Err() != nil { return "", in.Err() } if text.Len() == 0 { return "", fmt.Errorf("no lines of %s matched tag %q", file, tag) } return text.String(), nil }
main
function
flightctl/test
e406026c-a950-4b9e-b20c-9df4631cbab2
isBlank
['"strings"']
github.com/flightctl/test//tmp/repos/example/internal/cmd/weave/weave.go
func isBlank(line string) bool { return strings.TrimSpace(line) == "" }
main
function
flightctl/test
0e6bd921-bf4f-4722-a392-11a89fe6760b
indented
['"strings"']
github.com/flightctl/test//tmp/repos/example/internal/cmd/weave/weave.go
func indented(line string) bool { return strings.HasPrefix(line, " ") || strings.HasPrefix(line, "\t") }
main
function
flightctl/test
c19eb70a-6c14-45e8-9c2d-bd2a9fb4794c
cleanListing
['"strings"']
github.com/flightctl/test//tmp/repos/example/internal/cmd/weave/weave.go
func cleanListing(text string) string { lines := strings.Split(text, "\n") // remove minimum number of leading tabs from all non-blank lines tabs := 999 for i, line := range lines { if strings.TrimSpace(line) == "" { lines[i] = "" } else { if n := leadingTabs(line); n < tabs { tabs = n } } } for i, line := range lines { if line != "" { line := line[tabs:] lines[i] = line // remove leading tabs } } // remove leading blank lines for len(lines) > 0 && lines[0] == "" { lines = lines[1:] } // remove trailing blank lines for len(lines) > 0 && lines[len(lines)-1] == "" { lines = lines[:len(lines)-1] } return strings.Join(lines, "\n") }
main
function
flightctl/test
ccae3985-dd2b-44e7-8d4c-31c61a2e67bf
leadingTabs
github.com/flightctl/test//tmp/repos/example/internal/cmd/weave/weave.go
func leadingTabs(s string) int { var i int for i = 0; i < len(s); i++ { if s[i] != '\t' { break } } return i }
main
file
flightctl/test
a7c483d1-cdb2-4ee4-998b-2613f8acea0e
main.go
import ( "expvar" "flag" "fmt" "html/template" "log" "net/http" "sync" "time" )
github.com/flightctl/test//tmp/repos/example/outyet/main.go
// Copyright 2023 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // Outyet is a web server that announces whether or not a particular Go version // has been tagged. package main import ( "expvar" "flag" "fmt" "html/template" "log" "net/http" "sync" "time" ) // Command-line flags. var ( httpAddr = flag.String("http", "localhost:8080", "Listen address") pollPeriod = flag.Duration("poll", 5*time.Second, "Poll period") version = flag.String("version", "1.4", "Go version") ) const baseChangeURL = "https://go.googlesource.com/go/+/" func main() { flag.Parse() changeURL := fmt.Sprintf("%sgo%s", baseChangeURL, *version) http.Handle("/", NewServer(*version, changeURL, *pollPeriod)) log.Printf("serving http://%s", *httpAddr) log.Fatal(http.ListenAndServe(*httpAddr, nil)) } // Exported variables for monitoring the server. // These are exported via HTTP as a JSON object at /debug/vars. var ( hitCount = expvar.NewInt("hitCount") pollCount = expvar.NewInt("pollCount") pollError = expvar.NewString("pollError") pollErrorCount = expvar.NewInt("pollErrorCount") ) // Server implements the outyet server. // It serves the user interface (it's an http.Handler) // and polls the remote repository for changes. type Server struct { version string url string period time.Duration mu sync.RWMutex // protects the yes variable yes bool } // NewServer returns an initialized outyet server. func NewServer(version, url string, period time.Duration) *Server { s := &Server{version: version, url: url, period: period} go s.poll() return s } // poll polls the change URL for the specified period until the tag exists. // Then it sets the Server's yes field true and exits. func (s *Server) poll() { for !isTagged(s.url) { pollSleep(s.period) } s.mu.Lock() s.yes = true s.mu.Unlock() pollDone() } // Hooks that may be overridden for integration tests. var ( pollSleep = time.Sleep pollDone = func() {} ) // isTagged makes an HTTP HEAD request to the given URL and reports whether it // returned a 200 OK response. func isTagged(url string) bool { pollCount.Add(1) r, err := http.Head(url) if err != nil { log.Print(err) pollError.Set(err.Error()) pollErrorCount.Add(1) return false } return r.StatusCode == http.StatusOK } // ServeHTTP implements the HTTP user interface. func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) { hitCount.Add(1) s.mu.RLock() data := struct { URL string Version string Yes bool }{ s.url, s.version, s.yes, } s.mu.RUnlock() err := tmpl.Execute(w, data) if err != nil { log.Print(err) } } // tmpl is the HTML template that drives the user interface. var tmpl = template.Must(template.New("tmpl").Parse(` <!DOCTYPE html><html><body><center> <h2>Is Go {{.Version}} out yet?</h2> <h1> {{if .Yes}} <a href="{{.URL}}">YES!</a> {{else}} No. :-( {{end}} </h1> </center></body></html> `))
package main
function
flightctl/test
9c04ff97-94d4-4096-8969-3af84fa0734d
main
['"flag"', '"fmt"', '"log"', '"net/http"']
github.com/flightctl/test//tmp/repos/example/outyet/main.go
func main() { flag.Parse() changeURL := fmt.Sprintf("%sgo%s", baseChangeURL, *version) http.Handle("/", NewServer(*version, changeURL, *pollPeriod)) log.Printf("serving http://%s", *httpAddr) log.Fatal(http.ListenAndServe(*httpAddr, nil)) }
main
function
flightctl/test
d43ac5e3-23bb-4ec8-8467-684357955d7b
NewServer
['"time"']
['Server']
github.com/flightctl/test//tmp/repos/example/outyet/main.go
func NewServer(version, url string, period time.Duration) *Server { s := &Server{version: version, url: url, period: period} go s.poll() return s }
main
function
flightctl/test
725692a9-b7d6-4183-9540-efc2b60c61e9
poll
['Server']
github.com/flightctl/test//tmp/repos/example/outyet/main.go
func (s *Server) poll() { for !isTagged(s.url) { pollSleep(s.period) } s.mu.Lock() s.yes = true s.mu.Unlock() pollDone() }
main
function
flightctl/test
071329df-84ea-43ff-b7aa-3b5320437c57
isTagged
['"log"', '"net/http"']
github.com/flightctl/test//tmp/repos/example/outyet/main.go
func isTagged(url string) bool { pollCount.Add(1) r, err := http.Head(url) if err != nil { log.Print(err) pollError.Set(err.Error()) pollErrorCount.Add(1) return false } return r.StatusCode == http.StatusOK }
main
function
flightctl/test
a5149f5e-679f-462c-afd1-abae04becd6a
ServeHTTP
['"log"', '"net/http"']
['Server']
github.com/flightctl/test//tmp/repos/example/outyet/main.go
func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) { hitCount.Add(1) s.mu.RLock() data := struct { URL string Version string Yes bool }{ s.url, s.version, s.yes, } s.mu.RUnlock() err := tmpl.Execute(w, data) if err != nil { log.Print(err) } }
main
file
flightctl/test
62e5f929-b60a-491e-9c8a-cca9f01d5ed0
main_test.go
import ( "net/http" "net/http/httptest" "strings" "testing" "time" )
github.com/flightctl/test//tmp/repos/example/outyet/main_test.go
// Copyright 2023 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package main import ( "net/http" "net/http/httptest" "strings" "testing" "time" ) // statusHandler is an http.Handler that writes an empty response using itself // as the response status code. type statusHandler int func (h *statusHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) { w.WriteHeader(int(*h)) } func TestIsTagged(t *testing.T) { // Set up a fake "Google Code" web server reporting 404 not found. status := statusHandler(http.StatusNotFound) s := httptest.NewServer(&status) defer s.Close() if isTagged(s.URL) { t.Fatal("isTagged == true, want false") } // Change fake server status to 200 OK and try again. status = http.StatusOK if !isTagged(s.URL) { t.Fatal("isTagged == false, want true") } } func TestIntegration(t *testing.T) { status := statusHandler(http.StatusNotFound) ts := httptest.NewServer(&status) defer ts.Close() // Replace the pollSleep with a closure that we can block and unblock. sleep := make(chan bool) pollSleep = func(time.Duration) { sleep <- true sleep <- true } // Replace pollDone with a closure that will tell us when the poller is // exiting. done := make(chan bool) pollDone = func() { done <- true } // Put things as they were when the test finishes. defer func() { pollSleep = time.Sleep pollDone = func() {} }() s := NewServer("1.x", ts.URL, 1*time.Millisecond) <-sleep // Wait for poll loop to start sleeping. // Make first request to the server. r, _ := http.NewRequest("GET", "/", nil) w := httptest.NewRecorder() s.ServeHTTP(w, r) if b := w.Body.String(); !strings.Contains(b, "No.") { t.Fatalf("body = %s, want no", b) } status = http.StatusOK <-sleep // Permit poll loop to stop sleeping. <-done // Wait for poller to see the "OK" status and exit. // Make second request to the server. w = httptest.NewRecorder() s.ServeHTTP(w, r) if b := w.Body.String(); !strings.Contains(b, "YES!") { t.Fatalf("body = %q, want yes", b) } }
package main
function
flightctl/test
b61bfc04-d335-49bf-ad50-7bde545bad6c
ServeHTTP
['"net/http"']
github.com/flightctl/test//tmp/repos/example/outyet/main_test.go
func (h *statusHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) { w.WriteHeader(int(*h)) }
main
function
flightctl/test
a8f38b5b-443b-4d80-8a05-b1947ca8cc74
TestIsTagged
['"net/http"', '"net/http/httptest"', '"testing"']
github.com/flightctl/test//tmp/repos/example/outyet/main_test.go
func TestIsTagged(t *testing.T) { // Set up a fake "Google Code" web server reporting 404 not found. status := statusHandler(http.StatusNotFound) s := httptest.NewServer(&status) defer s.Close() if isTagged(s.URL) { t.Fatal("isTagged == true, want false") } // Change fake server status to 200 OK and try again. status = http.StatusOK if !isTagged(s.URL) { t.Fatal("isTagged == false, want true") } }
main
function
flightctl/test
e740f784-048a-4257-b6c3-aea380f84be4
TestIntegration
['"net/http"', '"net/http/httptest"', '"strings"', '"testing"', '"time"']
github.com/flightctl/test//tmp/repos/example/outyet/main_test.go
func TestIntegration(t *testing.T) { status := statusHandler(http.StatusNotFound) ts := httptest.NewServer(&status) defer ts.Close() // Replace the pollSleep with a closure that we can block and unblock. sleep := make(chan bool) pollSleep = func(time.Duration) { sleep <- true sleep <- true } // Replace pollDone with a closure that will tell us when the poller is // exiting. done := make(chan bool) pollDone = func() { done <- true } // Put things as they were when the test finishes. defer func() { pollSleep = time.Sleep pollDone = func() {} }() s := NewServer("1.x", ts.URL, 1*time.Millisecond) <-sleep // Wait for poll loop to start sleeping. // Make first request to the server. r, _ := http.NewRequest("GET", "/", nil) w := httptest.NewRecorder() s.ServeHTTP(w, r) if b := w.Body.String(); !strings.Contains(b, "No.") { t.Fatalf("body = %s, want no", b) } status = http.StatusOK <-sleep // Permit poll loop to stop sleeping. <-done // Wait for poller to see the "OK" status and exit. // Make second request to the server. w = httptest.NewRecorder() s.ServeHTTP(w, r) if b := w.Body.String(); !strings.Contains(b, "YES!") { t.Fatalf("body = %q, want yes", b) } }
main
file
flightctl/test
29f32c71-6405-4ccf-8d6c-d29a9fd8e11f
json.go
import ( "encoding/json" "fmt" "mime" "net/http" )
github.com/flightctl/test//tmp/repos/example/ragserver/ragserver-genkit/json.go
// Copyright 2024 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package main import ( "encoding/json" "fmt" "mime" "net/http" ) // readRequestJSON expects req to have a JSON content type with a body that // contains a JSON-encoded value complying with the underlying type of target. // It populates target, or returns an error. func readRequestJSON(req *http.Request, target any) error { contentType := req.Header.Get("Content-Type") mediaType, _, err := mime.ParseMediaType(contentType) if err != nil { return err } if mediaType != "application/json" { return fmt.Errorf("expect application/json Content-Type, got %s", mediaType) } dec := json.NewDecoder(req.Body) dec.DisallowUnknownFields() return dec.Decode(target) } // renderJSON renders 'v' as JSON and writes it as a response into w. func renderJSON(w http.ResponseWriter, v any) { js, err := json.Marshal(v) if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return } w.Header().Set("Content-Type", "application/json") w.Write(js) }
package main
function
flightctl/test
921c10a9-3a49-496a-88d6-8b73a0539005
readRequestJSON
['"encoding/json"', '"fmt"', '"mime"', '"net/http"']
github.com/flightctl/test//tmp/repos/example/ragserver/ragserver-genkit/json.go
func readRequestJSON(req *http.Request, target any) error { contentType := req.Header.Get("Content-Type") mediaType, _, err := mime.ParseMediaType(contentType) if err != nil { return err } if mediaType != "application/json" { return fmt.Errorf("expect application/json Content-Type, got %s", mediaType) } dec := json.NewDecoder(req.Body) dec.DisallowUnknownFields() return dec.Decode(target) }
main
function
flightctl/test
e479bdff-aa05-4e98-9deb-72a8a64918b3
renderJSON
['"encoding/json"', '"net/http"']
github.com/flightctl/test//tmp/repos/example/ragserver/ragserver-genkit/json.go
func renderJSON(w http.ResponseWriter, v any) { js, err := json.Marshal(v) if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return } w.Header().Set("Content-Type", "application/json") w.Write(js) }
main
file
flightctl/test
92c15ce2-fe38-4326-beca-87c9da4336de
main.go
import ( "cmp" "context" "fmt" "log" "net/http" "os" "strings" "github.com/firebase/genkit/go/ai" "github.com/firebase/genkit/go/plugins/googleai" "github.com/firebase/genkit/go/plugins/weaviate" )
github.com/flightctl/test//tmp/repos/example/ragserver/ragserver-genkit/main.go
// Copyright 2024 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // Command ragserver is an HTTP server that implements RAG (Retrieval // Augmented Generation) using the Gemini model and Weaviate, which // are accessed using the Genkit package. See the accompanying README file for // additional details. package main import ( "cmp" "context" "fmt" "log" "net/http" "os" "strings" "github.com/firebase/genkit/go/ai" "github.com/firebase/genkit/go/plugins/googleai" "github.com/firebase/genkit/go/plugins/weaviate" ) const generativeModelName = "gemini-1.5-flash" const embeddingModelName = "text-embedding-004" // This is a standard Go HTTP server. Server state is in the ragServer struct. // The `main` function connects to the required services (Weaviate and Google // AI), initializes the server state and registers HTTP handlers. func main() { ctx := context.Background() err := googleai.Init(ctx, &googleai.Config{ APIKey: os.Getenv("GEMINI_API_KEY"), }) if err != nil { log.Fatal(err) } wvConfig := &weaviate.ClientConfig{ Scheme: "http", Addr: "localhost:" + cmp.Or(os.Getenv("WVPORT"), "9035"), } _, err = weaviate.Init(ctx, wvConfig) if err != nil { log.Fatal(err) } classConfig := &weaviate.ClassConfig{ Class: "Document", Embedder: googleai.Embedder(embeddingModelName), } indexer, retriever, err := weaviate.DefineIndexerAndRetriever(ctx, *classConfig) if err != nil { log.Fatal(err) } model := googleai.Model(generativeModelName) if model == nil { log.Fatal("unable to set up gemini-1.5-flash model") } server := &ragServer{ ctx: ctx, indexer: indexer, retriever: retriever, model: model, } mux := http.NewServeMux() mux.HandleFunc("POST /add/", server.addDocumentsHandler) mux.HandleFunc("POST /query/", server.queryHandler) port := cmp.Or(os.Getenv("SERVERPORT"), "9020") address := "localhost:" + port log.Println("listening on", address) log.Fatal(http.ListenAndServe(address, mux)) } type ragServer struct { ctx context.Context indexer ai.Indexer retriever ai.Retriever model ai.Model } func (rs *ragServer) addDocumentsHandler(w http.ResponseWriter, req *http.Request) { // Parse HTTP request from JSON. type document struct { Text string } type addRequest struct { Documents []document } ar := &addRequest{} err := readRequestJSON(req, ar) if err != nil { http.Error(w, err.Error(), http.StatusBadRequest) return } // Convert request documents into Weaviate documents used for embedding. var wvDocs []*ai.Document for _, doc := range ar.Documents { wvDocs = append(wvDocs, ai.DocumentFromText(doc.Text, nil)) } // Index the requested documents. err = ai.Index(rs.ctx, rs.indexer, ai.WithIndexerDocs(wvDocs...)) if err != nil { http.Error(w, fmt.Errorf("indexing: %w", err).Error(), http.StatusInternalServerError) return } } func (rs *ragServer) queryHandler(w http.ResponseWriter, req *http.Request) { // Parse HTTP request from JSON. type queryRequest struct { Content string } qr := &queryRequest{} err := readRequestJSON(req, qr) if err != nil { http.Error(w, err.Error(), http.StatusBadRequest) return } // Find the most similar documents using the retriever. resp, err := ai.Retrieve(rs.ctx, rs.retriever, ai.WithRetrieverDoc(ai.DocumentFromText(qr.Content, nil)), ai.WithRetrieverOpts(&weaviate.RetrieverOptions{ Count: 3, })) if err != nil { http.Error(w, fmt.Errorf("retrieval: %w", err).Error(), http.StatusInternalServerError) return } var docsContents []string for _, d := range resp.Documents { docsContents = append(docsContents, d.Content[0].Text) } // Create a RAG query for the LLM with the most relevant documents as // context. ragQuery := fmt.Sprintf(ragTemplateStr, qr.Content, strings.Join(docsContents, "\n")) genResp, err := ai.Generate(rs.ctx, rs.model, ai.WithTextPrompt(ragQuery)) if err != nil { log.Printf("calling generative model: %v", err.Error()) http.Error(w, "generative model error", http.StatusInternalServerError) return } if len(genResp.Candidates) != 1 { log.Printf("got %v candidates, expected 1", len(genResp.Candidates)) http.Error(w, "generative model error", http.StatusInternalServerError) return } renderJSON(w, genResp.Text()) } const ragTemplateStr = ` I will ask you a question and will provide some additional context information. Assume this context information is factual and correct, as part of internal documentation. If the question relates to the context, answer it using the context. If the question does not relate to the context, answer it as normal. For example, let's say the context has nothing in it about tropical flowers; then if I ask you about tropical flowers, just answer what you know about them without referring to the context. For example, if the context does mention minerology and I ask you about that, provide information from the context along with general knowledge. Question: %s Context: %s `
package main
function
flightctl/test
9c1aa2d4-f82c-4075-bbf3-54dc2eec1e00
main
['"cmp"', '"context"', '"log"', '"net/http"', '"os"', '"github.com/firebase/genkit/go/plugins/googleai"', '"github.com/firebase/genkit/go/plugins/weaviate"']
['ragServer']
github.com/flightctl/test//tmp/repos/example/ragserver/ragserver-genkit/main.go
func main() { ctx := context.Background() err := googleai.Init(ctx, &googleai.Config{ APIKey: os.Getenv("GEMINI_API_KEY"), }) if err != nil { log.Fatal(err) } wvConfig := &weaviate.ClientConfig{ Scheme: "http", Addr: "localhost:" + cmp.Or(os.Getenv("WVPORT"), "9035"), } _, err = weaviate.Init(ctx, wvConfig) if err != nil { log.Fatal(err) } classConfig := &weaviate.ClassConfig{ Class: "Document", Embedder: googleai.Embedder(embeddingModelName), } indexer, retriever, err := weaviate.DefineIndexerAndRetriever(ctx, *classConfig) if err != nil { log.Fatal(err) } model := googleai.Model(generativeModelName) if model == nil { log.Fatal("unable to set up gemini-1.5-flash model") } server := &ragServer{ ctx: ctx, indexer: indexer, retriever: retriever, model: model, } mux := http.NewServeMux() mux.HandleFunc("POST /add/", server.addDocumentsHandler) mux.HandleFunc("POST /query/", server.queryHandler) port := cmp.Or(os.Getenv("SERVERPORT"), "9020") address := "localhost:" + port log.Println("listening on", address) log.Fatal(http.ListenAndServe(address, mux)) }
main
function
flightctl/test
3a0fee89-44cd-467b-ac00-ada4340e725e
addDocumentsHandler
['"fmt"', '"net/http"', '"github.com/firebase/genkit/go/ai"']
['ragServer']
github.com/flightctl/test//tmp/repos/example/ragserver/ragserver-genkit/main.go
func (rs *ragServer) addDocumentsHandler(w http.ResponseWriter, req *http.Request) { // Parse HTTP request from JSON. type document struct { Text string } type addRequest struct { Documents []document } ar := &addRequest{} err := readRequestJSON(req, ar) if err != nil { http.Error(w, err.Error(), http.StatusBadRequest) return } // Convert request documents into Weaviate documents used for embedding. var wvDocs []*ai.Document for _, doc := range ar.Documents { wvDocs = append(wvDocs, ai.DocumentFromText(doc.Text, nil)) } // Index the requested documents. err = ai.Index(rs.ctx, rs.indexer, ai.WithIndexerDocs(wvDocs...)) if err != nil { http.Error(w, fmt.Errorf("indexing: %w", err).Error(), http.StatusInternalServerError) return } }
main
function
flightctl/test
714406c6-c283-4a97-854e-92d6de53a8f8
queryHandler
['"context"', '"fmt"', '"log"', '"net/http"', '"strings"', '"github.com/firebase/genkit/go/ai"', '"github.com/firebase/genkit/go/plugins/weaviate"']
['ragServer']
github.com/flightctl/test//tmp/repos/example/ragserver/ragserver-genkit/main.go
func (rs *ragServer) queryHandler(w http.ResponseWriter, req *http.Request) { // Parse HTTP request from JSON. type queryRequest struct { Content string } qr := &queryRequest{} err := readRequestJSON(req, qr) if err != nil { http.Error(w, err.Error(), http.StatusBadRequest) return } // Find the most similar documents using the retriever. resp, err := ai.Retrieve(rs.ctx, rs.retriever, ai.WithRetrieverDoc(ai.DocumentFromText(qr.Content, nil)), ai.WithRetrieverOpts(&weaviate.RetrieverOptions{ Count: 3, })) if err != nil { http.Error(w, fmt.Errorf("retrieval: %w", err).Error(), http.StatusInternalServerError) return } var docsContents []string for _, d := range resp.Documents { docsContents = append(docsContents, d.Content[0].Text) } // Create a RAG query for the LLM with the most relevant documents as // context. ragQuery := fmt.Sprintf(ragTemplateStr, qr.Content, strings.Join(docsContents, "\n")) genResp, err := ai.Generate(rs.ctx, rs.model, ai.WithTextPrompt(ragQuery)) if err != nil { log.Printf("calling generative model: %v", err.Error()) http.Error(w, "generative model error", http.StatusInternalServerError) return } if len(genResp.Candidates) != 1 { log.Printf("got %v candidates, expected 1", len(genResp.Candidates)) http.Error(w, "generative model error", http.StatusInternalServerError) return } renderJSON(w, genResp.Text()) }
main
file
flightctl/test
1fdc20b5-21b0-4b4f-9d6d-b4a5bf5134db
json.go
import ( "encoding/json" "fmt" "mime" "net/http" )
github.com/flightctl/test//tmp/repos/example/ragserver/ragserver-langchaingo/json.go
// Copyright 2024 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package main import ( "encoding/json" "fmt" "mime" "net/http" ) // readRequestJSON expects req to have a JSON content type with a body that // contains a JSON-encoded value complying with the underlying type of target. // It populates target, or returns an error. func readRequestJSON(req *http.Request, target any) error { contentType := req.Header.Get("Content-Type") mediaType, _, err := mime.ParseMediaType(contentType) if err != nil { return err } if mediaType != "application/json" { return fmt.Errorf("expect application/json Content-Type, got %s", mediaType) } dec := json.NewDecoder(req.Body) dec.DisallowUnknownFields() return dec.Decode(target) } // renderJSON renders 'v' as JSON and writes it as a response into w. func renderJSON(w http.ResponseWriter, v any) { js, err := json.Marshal(v) if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return } w.Header().Set("Content-Type", "application/json") w.Write(js) }
package main
function
flightctl/test
f0bbbce9-359a-477a-a83e-f6abc29ec354
readRequestJSON
['"encoding/json"', '"fmt"', '"mime"', '"net/http"']
github.com/flightctl/test//tmp/repos/example/ragserver/ragserver-langchaingo/json.go
func readRequestJSON(req *http.Request, target any) error { contentType := req.Header.Get("Content-Type") mediaType, _, err := mime.ParseMediaType(contentType) if err != nil { return err } if mediaType != "application/json" { return fmt.Errorf("expect application/json Content-Type, got %s", mediaType) } dec := json.NewDecoder(req.Body) dec.DisallowUnknownFields() return dec.Decode(target) }
main
function
flightctl/test
4fb0311a-3bd2-4cca-ad8b-4269c5db8569
renderJSON
['"encoding/json"', '"net/http"']
github.com/flightctl/test//tmp/repos/example/ragserver/ragserver-langchaingo/json.go
func renderJSON(w http.ResponseWriter, v any) { js, err := json.Marshal(v) if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return } w.Header().Set("Content-Type", "application/json") w.Write(js) }
main
file
flightctl/test
35cea53c-e98d-45e5-8572-3cca3695c7a0
main.go
import ( "cmp" "context" "fmt" "log" "net/http" "os" "strings" "github.com/tmc/langchaingo/embeddings" "github.com/tmc/langchaingo/llms" "github.com/tmc/langchaingo/llms/googleai" "github.com/tmc/langchaingo/schema" "github.com/tmc/langchaingo/vectorstores/weaviate" )
github.com/flightctl/test//tmp/repos/example/ragserver/ragserver-langchaingo/main.go
// Copyright 2024 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // Command ragserver is an HTTP server that implements RAG (Retrieval // Augmented Generation) using the Gemini model and Weaviate, which // are accessed using LangChainGo. See the accompanying README file for // additional details. package main import ( "cmp" "context" "fmt" "log" "net/http" "os" "strings" "github.com/tmc/langchaingo/embeddings" "github.com/tmc/langchaingo/llms" "github.com/tmc/langchaingo/llms/googleai" "github.com/tmc/langchaingo/schema" "github.com/tmc/langchaingo/vectorstores/weaviate" ) const generativeModelName = "gemini-1.5-flash" const embeddingModelName = "text-embedding-004" // This is a standard Go HTTP server. Server state is in the ragServer struct. // The `main` function connects to the required services (Weaviate and Google // AI), initializes the server state and registers HTTP handlers. func main() { ctx := context.Background() apiKey := os.Getenv("GEMINI_API_KEY") geminiClient, err := googleai.New(ctx, googleai.WithAPIKey(apiKey), googleai.WithDefaultEmbeddingModel(embeddingModelName)) if err != nil { log.Fatal(err) } emb, err := embeddings.NewEmbedder(geminiClient) if err != nil { log.Fatal(err) } wvStore, err := weaviate.New( weaviate.WithEmbedder(emb), weaviate.WithScheme("http"), weaviate.WithHost("localhost:"+cmp.Or(os.Getenv("WVPORT"), "9035")), weaviate.WithIndexName("Document"), ) server := &ragServer{ ctx: ctx, wvStore: wvStore, geminiClient: geminiClient, } mux := http.NewServeMux() mux.HandleFunc("POST /add/", server.addDocumentsHandler) mux.HandleFunc("POST /query/", server.queryHandler) port := cmp.Or(os.Getenv("SERVERPORT"), "9020") address := "localhost:" + port log.Println("listening on", address) log.Fatal(http.ListenAndServe(address, mux)) } type ragServer struct { ctx context.Context wvStore weaviate.Store geminiClient *googleai.GoogleAI } func (rs *ragServer) addDocumentsHandler(w http.ResponseWriter, req *http.Request) { // Parse HTTP request from JSON. type document struct { Text string } type addRequest struct { Documents []document } ar := &addRequest{} err := readRequestJSON(req, ar) if err != nil { http.Error(w, err.Error(), http.StatusBadRequest) return } // Store documents and their embeddings in weaviate var wvDocs []schema.Document for _, doc := range ar.Documents { wvDocs = append(wvDocs, schema.Document{PageContent: doc.Text}) } _, err = rs.wvStore.AddDocuments(rs.ctx, wvDocs) if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return } } func (rs *ragServer) queryHandler(w http.ResponseWriter, req *http.Request) { // Parse HTTP request from JSON. type queryRequest struct { Content string } qr := &queryRequest{} err := readRequestJSON(req, qr) if err != nil { http.Error(w, err.Error(), http.StatusBadRequest) return } // Find the most similar documents. docs, err := rs.wvStore.SimilaritySearch(rs.ctx, qr.Content, 3) if err != nil { http.Error(w, fmt.Errorf("similarity search: %w", err).Error(), http.StatusInternalServerError) return } var docsContents []string for _, doc := range docs { docsContents = append(docsContents, doc.PageContent) } // Create a RAG query for the LLM with the most relevant documents as // context. ragQuery := fmt.Sprintf(ragTemplateStr, qr.Content, strings.Join(docsContents, "\n")) respText, err := llms.GenerateFromSinglePrompt(rs.ctx, rs.geminiClient, ragQuery, llms.WithModel(generativeModelName)) if err != nil { log.Printf("calling generative model: %v", err.Error()) http.Error(w, "generative model error", http.StatusInternalServerError) return } renderJSON(w, respText) } const ragTemplateStr = ` I will ask you a question and will provide some additional context information. Assume this context information is factual and correct, as part of internal documentation. If the question relates to the context, answer it using the context. If the question does not relate to the context, answer it as normal. For example, let's say the context has nothing in it about tropical flowers; then if I ask you about tropical flowers, just answer what you know about them without referring to the context. For example, if the context does mention minerology and I ask you about that, provide information from the context along with general knowledge. Question: %s Context: %s `
package main
function
flightctl/test
985d60f0-5223-4fa2-bfd3-6d28256cfcc7
main
['"cmp"', '"context"', '"log"', '"net/http"', '"os"', '"github.com/tmc/langchaingo/embeddings"', '"github.com/tmc/langchaingo/llms/googleai"', '"github.com/tmc/langchaingo/vectorstores/weaviate"']
['ragServer']
github.com/flightctl/test//tmp/repos/example/ragserver/ragserver-langchaingo/main.go
func main() { ctx := context.Background() apiKey := os.Getenv("GEMINI_API_KEY") geminiClient, err := googleai.New(ctx, googleai.WithAPIKey(apiKey), googleai.WithDefaultEmbeddingModel(embeddingModelName)) if err != nil { log.Fatal(err) } emb, err := embeddings.NewEmbedder(geminiClient) if err != nil { log.Fatal(err) } wvStore, err := weaviate.New( weaviate.WithEmbedder(emb), weaviate.WithScheme("http"), weaviate.WithHost("localhost:"+cmp.Or(os.Getenv("WVPORT"), "9035")), weaviate.WithIndexName("Document"), ) server := &ragServer{ ctx: ctx, wvStore: wvStore, geminiClient: geminiClient, } mux := http.NewServeMux() mux.HandleFunc("POST /add/", server.addDocumentsHandler) mux.HandleFunc("POST /query/", server.queryHandler) port := cmp.Or(os.Getenv("SERVERPORT"), "9020") address := "localhost:" + port log.Println("listening on", address) log.Fatal(http.ListenAndServe(address, mux)) }
main
function
flightctl/test
5793c33e-ec1b-4809-a407-6ad01f61d3b2
addDocumentsHandler
['"net/http"', '"github.com/tmc/langchaingo/embeddings"', '"github.com/tmc/langchaingo/schema"', '"github.com/tmc/langchaingo/vectorstores/weaviate"']
['ragServer']
github.com/flightctl/test//tmp/repos/example/ragserver/ragserver-langchaingo/main.go
func (rs *ragServer) addDocumentsHandler(w http.ResponseWriter, req *http.Request) { // Parse HTTP request from JSON. type document struct { Text string } type addRequest struct { Documents []document } ar := &addRequest{} err := readRequestJSON(req, ar) if err != nil { http.Error(w, err.Error(), http.StatusBadRequest) return } // Store documents and their embeddings in weaviate var wvDocs []schema.Document for _, doc := range ar.Documents { wvDocs = append(wvDocs, schema.Document{PageContent: doc.Text}) } _, err = rs.wvStore.AddDocuments(rs.ctx, wvDocs) if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return } }
main
function
flightctl/test
f8dd6cd2-2c89-4c0d-9e4d-2bbdf72af10c
queryHandler
['"context"', '"fmt"', '"log"', '"net/http"', '"strings"', '"github.com/tmc/langchaingo/llms"']
['ragServer']
github.com/flightctl/test//tmp/repos/example/ragserver/ragserver-langchaingo/main.go
func (rs *ragServer) queryHandler(w http.ResponseWriter, req *http.Request) { // Parse HTTP request from JSON. type queryRequest struct { Content string } qr := &queryRequest{} err := readRequestJSON(req, qr) if err != nil { http.Error(w, err.Error(), http.StatusBadRequest) return } // Find the most similar documents. docs, err := rs.wvStore.SimilaritySearch(rs.ctx, qr.Content, 3) if err != nil { http.Error(w, fmt.Errorf("similarity search: %w", err).Error(), http.StatusInternalServerError) return } var docsContents []string for _, doc := range docs { docsContents = append(docsContents, doc.PageContent) } // Create a RAG query for the LLM with the most relevant documents as // context. ragQuery := fmt.Sprintf(ragTemplateStr, qr.Content, strings.Join(docsContents, "\n")) respText, err := llms.GenerateFromSinglePrompt(rs.ctx, rs.geminiClient, ragQuery, llms.WithModel(generativeModelName)) if err != nil { log.Printf("calling generative model: %v", err.Error()) http.Error(w, "generative model error", http.StatusInternalServerError) return } renderJSON(w, respText) }
main
file
flightctl/test
82038242-4f01-4bdc-92b4-90447f4e7a57
json.go
import ( "encoding/json" "fmt" "mime" "net/http" )
github.com/flightctl/test//tmp/repos/example/ragserver/ragserver/json.go
// Copyright 2024 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package main import ( "encoding/json" "fmt" "mime" "net/http" ) // readRequestJSON expects req to have a JSON content type with a body that // contains a JSON-encoded value complying with the underlying type of target. // It populates target, or returns an error. func readRequestJSON(req *http.Request, target any) error { contentType := req.Header.Get("Content-Type") mediaType, _, err := mime.ParseMediaType(contentType) if err != nil { return err } if mediaType != "application/json" { return fmt.Errorf("expect application/json Content-Type, got %s", mediaType) } dec := json.NewDecoder(req.Body) dec.DisallowUnknownFields() return dec.Decode(target) } // renderJSON renders 'v' as JSON and writes it as a response into w. func renderJSON(w http.ResponseWriter, v any) { js, err := json.Marshal(v) if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return } w.Header().Set("Content-Type", "application/json") w.Write(js) }
package main
function
flightctl/test
2bc28b4a-2c1b-4c7a-8f10-1d0ad00c4641
readRequestJSON
['"encoding/json"', '"fmt"', '"mime"', '"net/http"']
github.com/flightctl/test//tmp/repos/example/ragserver/ragserver/json.go
func readRequestJSON(req *http.Request, target any) error { contentType := req.Header.Get("Content-Type") mediaType, _, err := mime.ParseMediaType(contentType) if err != nil { return err } if mediaType != "application/json" { return fmt.Errorf("expect application/json Content-Type, got %s", mediaType) } dec := json.NewDecoder(req.Body) dec.DisallowUnknownFields() return dec.Decode(target) }
main
function
flightctl/test
81b51870-aeaf-483d-b4f8-b7f77e39a636
renderJSON
['"encoding/json"', '"net/http"']
github.com/flightctl/test//tmp/repos/example/ragserver/ragserver/json.go
func renderJSON(w http.ResponseWriter, v any) { js, err := json.Marshal(v) if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return } w.Header().Set("Content-Type", "application/json") w.Write(js) }
main
file
flightctl/test
08bd95d7-384f-4d08-8e71-77e8fdaccbf6
main.go
import ( "cmp" "context" "fmt" "log" "net/http" "os" "strings" "github.com/google/generative-ai-go/genai" "github.com/weaviate/weaviate-go-client/v4/weaviate" "github.com/weaviate/weaviate-go-client/v4/weaviate/graphql" "github.com/weaviate/weaviate/entities/models" "google.golang.org/api/option" )
github.com/flightctl/test//tmp/repos/example/ragserver/ragserver/main.go
// Copyright 2024 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // Command ragserver is an HTTP server that implements RAG (Retrieval // Augmented Generation) using the Gemini model and Weaviate. See the // accompanying README file for additional details. package main import ( "cmp" "context" "fmt" "log" "net/http" "os" "strings" "github.com/google/generative-ai-go/genai" "github.com/weaviate/weaviate-go-client/v4/weaviate" "github.com/weaviate/weaviate-go-client/v4/weaviate/graphql" "github.com/weaviate/weaviate/entities/models" "google.golang.org/api/option" ) const generativeModelName = "gemini-1.5-flash" const embeddingModelName = "text-embedding-004" // This is a standard Go HTTP server. Server state is in the ragServer struct. // The `main` function connects to the required services (Weaviate and Google // AI), initializes the server state and registers HTTP handlers. func main() { ctx := context.Background() wvClient, err := initWeaviate(ctx) if err != nil { log.Fatal(err) } apiKey := os.Getenv("GEMINI_API_KEY") genaiClient, err := genai.NewClient(ctx, option.WithAPIKey(apiKey)) if err != nil { log.Fatal(err) } defer genaiClient.Close() server := &ragServer{ ctx: ctx, wvClient: wvClient, genModel: genaiClient.GenerativeModel(generativeModelName), embModel: genaiClient.EmbeddingModel(embeddingModelName), } mux := http.NewServeMux() mux.HandleFunc("POST /add/", server.addDocumentsHandler) mux.HandleFunc("POST /query/", server.queryHandler) port := cmp.Or(os.Getenv("SERVERPORT"), "9020") address := "localhost:" + port log.Println("listening on", address) log.Fatal(http.ListenAndServe(address, mux)) } type ragServer struct { ctx context.Context wvClient *weaviate.Client genModel *genai.GenerativeModel embModel *genai.EmbeddingModel } func (rs *ragServer) addDocumentsHandler(w http.ResponseWriter, req *http.Request) { // Parse HTTP request from JSON. type document struct { Text string } type addRequest struct { Documents []document } ar := &addRequest{} err := readRequestJSON(req, ar) if err != nil { http.Error(w, err.Error(), http.StatusBadRequest) return } // Use the batch embedding API to embed all documents at once. batch := rs.embModel.NewBatch() for _, doc := range ar.Documents { batch.AddContent(genai.Text(doc.Text)) } log.Printf("invoking embedding model with %v documents", len(ar.Documents)) rsp, err := rs.embModel.BatchEmbedContents(rs.ctx, batch) if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return } if len(rsp.Embeddings) != len(ar.Documents) { http.Error(w, "embedded batch size mismatch", http.StatusInternalServerError) return } // Convert our documents - along with their embedding vectors - into types // used by the Weaviate client library. objects := make([]*models.Object, len(ar.Documents)) for i, doc := range ar.Documents { objects[i] = &models.Object{ Class: "Document", Properties: map[string]any{ "text": doc.Text, }, Vector: rsp.Embeddings[i].Values, } } // Store documents with embeddings in the Weaviate DB. log.Printf("storing %v objects in weaviate", len(objects)) _, err = rs.wvClient.Batch().ObjectsBatcher().WithObjects(objects...).Do(rs.ctx) if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return } } func (rs *ragServer) queryHandler(w http.ResponseWriter, req *http.Request) { // Parse HTTP request from JSON. type queryRequest struct { Content string } qr := &queryRequest{} err := readRequestJSON(req, qr) if err != nil { http.Error(w, err.Error(), http.StatusBadRequest) return } // Embed the query contents. rsp, err := rs.embModel.EmbedContent(rs.ctx, genai.Text(qr.Content)) if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return } // Search weaviate to find the most relevant (closest in vector space) // documents to the query. gql := rs.wvClient.GraphQL() result, err := gql.Get(). WithNearVector( gql.NearVectorArgBuilder().WithVector(rsp.Embedding.Values)). WithClassName("Document"). WithFields(graphql.Field{Name: "text"}). WithLimit(3). Do(rs.ctx) if werr := combinedWeaviateError(result, err); werr != nil { http.Error(w, werr.Error(), http.StatusInternalServerError) return } contents, err := decodeGetResults(result) if err != nil { http.Error(w, fmt.Errorf("reading weaviate response: %w", err).Error(), http.StatusInternalServerError) return } // Create a RAG query for the LLM with the most relevant documents as // context. ragQuery := fmt.Sprintf(ragTemplateStr, qr.Content, strings.Join(contents, "\n")) resp, err := rs.genModel.GenerateContent(rs.ctx, genai.Text(ragQuery)) if err != nil { log.Printf("calling generative model: %v", err.Error()) http.Error(w, "generative model error", http.StatusInternalServerError) return } if len(resp.Candidates) != 1 { log.Printf("got %v candidates, expected 1", len(resp.Candidates)) http.Error(w, "generative model error", http.StatusInternalServerError) return } var respTexts []string for _, part := range resp.Candidates[0].Content.Parts { if pt, ok := part.(genai.Text); ok { respTexts = append(respTexts, string(pt)) } else { log.Printf("bad type of part: %v", pt) http.Error(w, "generative model error", http.StatusInternalServerError) return } } renderJSON(w, strings.Join(respTexts, "\n")) } const ragTemplateStr = ` I will ask you a question and will provide some additional context information. Assume this context information is factual and correct, as part of internal documentation. If the question relates to the context, answer it using the context. If the question does not relate to the context, answer it as normal. For example, let's say the context has nothing in it about tropical flowers; then if I ask you about tropical flowers, just answer what you know about them without referring to the context. For example, if the context does mention minerology and I ask you about that, provide information from the context along with general knowledge. Question: %s Context: %s ` // decodeGetResults decodes the result returned by Weaviate's GraphQL Get // query; these are returned as a nested map[string]any (just like JSON // unmarshaled into a map[string]any). We have to extract all document contents // as a list of strings. func decodeGetResults(result *models.GraphQLResponse) ([]string, error) { data, ok := result.Data["Get"] if !ok { return nil, fmt.Errorf("Get key not found in result") } doc, ok := data.(map[string]any) if !ok { return nil, fmt.Errorf("Get key unexpected type") } slc, ok := doc["Document"].([]any) if !ok { return nil, fmt.Errorf("Document is not a list of results") } var out []string for _, s := range slc { smap, ok := s.(map[string]any) if !ok { return nil, fmt.Errorf("invalid element in list of documents") } s, ok := smap["text"].(string) if !ok { return nil, fmt.Errorf("expected string in list of documents") } out = append(out, s) } return out, nil }
package main
function
flightctl/test
b6dd0373-aa2e-4a2c-b4df-0dc19324bd7d
main
['"cmp"', '"context"', '"log"', '"net/http"', '"os"', '"github.com/google/generative-ai-go/genai"', '"google.golang.org/api/option"']
['ragServer']
github.com/flightctl/test//tmp/repos/example/ragserver/ragserver/main.go
func main() { ctx := context.Background() wvClient, err := initWeaviate(ctx) if err != nil { log.Fatal(err) } apiKey := os.Getenv("GEMINI_API_KEY") genaiClient, err := genai.NewClient(ctx, option.WithAPIKey(apiKey)) if err != nil { log.Fatal(err) } defer genaiClient.Close() server := &ragServer{ ctx: ctx, wvClient: wvClient, genModel: genaiClient.GenerativeModel(generativeModelName), embModel: genaiClient.EmbeddingModel(embeddingModelName), } mux := http.NewServeMux() mux.HandleFunc("POST /add/", server.addDocumentsHandler) mux.HandleFunc("POST /query/", server.queryHandler) port := cmp.Or(os.Getenv("SERVERPORT"), "9020") address := "localhost:" + port log.Println("listening on", address) log.Fatal(http.ListenAndServe(address, mux)) }
main
function
flightctl/test
3f9c0d99-7ed3-4813-be13-69a998bf0960
addDocumentsHandler
['"log"', '"net/http"', '"github.com/google/generative-ai-go/genai"', '"github.com/weaviate/weaviate-go-client/v4/weaviate"', '"github.com/weaviate/weaviate/entities/models"']
['ragServer']
github.com/flightctl/test//tmp/repos/example/ragserver/ragserver/main.go
func (rs *ragServer) addDocumentsHandler(w http.ResponseWriter, req *http.Request) { // Parse HTTP request from JSON. type document struct { Text string } type addRequest struct { Documents []document } ar := &addRequest{} err := readRequestJSON(req, ar) if err != nil { http.Error(w, err.Error(), http.StatusBadRequest) return } // Use the batch embedding API to embed all documents at once. batch := rs.embModel.NewBatch() for _, doc := range ar.Documents { batch.AddContent(genai.Text(doc.Text)) } log.Printf("invoking embedding model with %v documents", len(ar.Documents)) rsp, err := rs.embModel.BatchEmbedContents(rs.ctx, batch) if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return } if len(rsp.Embeddings) != len(ar.Documents) { http.Error(w, "embedded batch size mismatch", http.StatusInternalServerError) return } // Convert our documents - along with their embedding vectors - into types // used by the Weaviate client library. objects := make([]*models.Object, len(ar.Documents)) for i, doc := range ar.Documents { objects[i] = &models.Object{ Class: "Document", Properties: map[string]any{ "text": doc.Text, }, Vector: rsp.Embeddings[i].Values, } } // Store documents with embeddings in the Weaviate DB. log.Printf("storing %v objects in weaviate", len(objects)) _, err = rs.wvClient.Batch().ObjectsBatcher().WithObjects(objects...).Do(rs.ctx) if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return } }
main
function
flightctl/test
58e1e191-0ca6-4c69-a7e2-90f97622c4a8
queryHandler
['"context"', '"fmt"', '"log"', '"net/http"', '"strings"', '"github.com/google/generative-ai-go/genai"', '"github.com/weaviate/weaviate-go-client/v4/weaviate"', '"github.com/weaviate/weaviate-go-client/v4/weaviate/graphql"']
['ragServer']
github.com/flightctl/test//tmp/repos/example/ragserver/ragserver/main.go
func (rs *ragServer) queryHandler(w http.ResponseWriter, req *http.Request) { // Parse HTTP request from JSON. type queryRequest struct { Content string } qr := &queryRequest{} err := readRequestJSON(req, qr) if err != nil { http.Error(w, err.Error(), http.StatusBadRequest) return } // Embed the query contents. rsp, err := rs.embModel.EmbedContent(rs.ctx, genai.Text(qr.Content)) if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return } // Search weaviate to find the most relevant (closest in vector space) // documents to the query. gql := rs.wvClient.GraphQL() result, err := gql.Get(). WithNearVector( gql.NearVectorArgBuilder().WithVector(rsp.Embedding.Values)). WithClassName("Document"). WithFields(graphql.Field{Name: "text"}). WithLimit(3). Do(rs.ctx) if werr := combinedWeaviateError(result, err); werr != nil { http.Error(w, werr.Error(), http.StatusInternalServerError) return } contents, err := decodeGetResults(result) if err != nil { http.Error(w, fmt.Errorf("reading weaviate response: %w", err).Error(), http.StatusInternalServerError) return } // Create a RAG query for the LLM with the most relevant documents as // context. ragQuery := fmt.Sprintf(ragTemplateStr, qr.Content, strings.Join(contents, "\n")) resp, err := rs.genModel.GenerateContent(rs.ctx, genai.Text(ragQuery)) if err != nil { log.Printf("calling generative model: %v", err.Error()) http.Error(w, "generative model error", http.StatusInternalServerError) return } if len(resp.Candidates) != 1 { log.Printf("got %v candidates, expected 1", len(resp.Candidates)) http.Error(w, "generative model error", http.StatusInternalServerError) return } var respTexts []string for _, part := range resp.Candidates[0].Content.Parts { if pt, ok := part.(genai.Text); ok { respTexts = append(respTexts, string(pt)) } else { log.Printf("bad type of part: %v", pt) http.Error(w, "generative model error", http.StatusInternalServerError) return } } renderJSON(w, strings.Join(respTexts, "\n")) }
main
function
flightctl/test
43f1c333-7dc1-446a-b109-b209011c30d4
decodeGetResults
['"fmt"', '"github.com/weaviate/weaviate/entities/models"']
github.com/flightctl/test//tmp/repos/example/ragserver/ragserver/main.go
func decodeGetResults(result *models.GraphQLResponse) ([]string, error) { data, ok := result.Data["Get"] if !ok { return nil, fmt.Errorf("Get key not found in result") } doc, ok := data.(map[string]any) if !ok { return nil, fmt.Errorf("Get key unexpected type") } slc, ok := doc["Document"].([]any) if !ok { return nil, fmt.Errorf("Document is not a list of results") } var out []string for _, s := range slc { smap, ok := s.(map[string]any) if !ok { return nil, fmt.Errorf("invalid element in list of documents") } s, ok := smap["text"].(string) if !ok { return nil, fmt.Errorf("expected string in list of documents") } out = append(out, s) } return out, nil }
main
file
flightctl/test
f54cabd7-3f5b-48b3-a48c-2f6ae1eeddcc
weaviate.go
import ( "cmp" "context" "fmt" "os" "github.com/weaviate/weaviate-go-client/v4/weaviate" "github.com/weaviate/weaviate/entities/models" )
github.com/flightctl/test//tmp/repos/example/ragserver/ragserver/weaviate.go
// Copyright 2024 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package main // Utilities for working with Weaviate. import ( "cmp" "context" "fmt" "os" "github.com/weaviate/weaviate-go-client/v4/weaviate" "github.com/weaviate/weaviate/entities/models" ) // initWeaviate initializes a weaviate client for our application. func initWeaviate(ctx context.Context) (*weaviate.Client, error) { client, err := weaviate.NewClient(weaviate.Config{ Host: "localhost:" + cmp.Or(os.Getenv("WVPORT"), "9035"), Scheme: "http", }) if err != nil { return nil, fmt.Errorf("initializing weaviate: %w", err) } // Create a new class (collection) in weaviate if it doesn't exist yet. cls := &models.Class{ Class: "Document", Vectorizer: "none", } exists, err := client.Schema().ClassExistenceChecker().WithClassName(cls.Class).Do(ctx) if err != nil { return nil, fmt.Errorf("weaviate error: %w", err) } if !exists { err = client.Schema().ClassCreator().WithClass(cls).Do(ctx) if err != nil { return nil, fmt.Errorf("weaviate error: %w", err) } } return client, nil } // combinedWeaviateError generates an error if err is non-nil or result has // errors, and returns an error (or nil if there's no error). It's useful for // the results of the Weaviate GraphQL API's "Do" calls. func combinedWeaviateError(result *models.GraphQLResponse, err error) error { if err != nil { return err } if len(result.Errors) != 0 { var ss []string for _, e := range result.Errors { ss = append(ss, e.Message) } return fmt.Errorf("weaviate error: %v", ss) } return nil }
package main
function
flightctl/test
f0d09d3c-6fe3-4257-b163-fcc74467dbe0
initWeaviate
['"cmp"', '"context"', '"fmt"', '"os"', '"github.com/weaviate/weaviate-go-client/v4/weaviate"', '"github.com/weaviate/weaviate/entities/models"']
github.com/flightctl/test//tmp/repos/example/ragserver/ragserver/weaviate.go
func initWeaviate(ctx context.Context) (*weaviate.Client, error) { client, err := weaviate.NewClient(weaviate.Config{ Host: "localhost:" + cmp.Or(os.Getenv("WVPORT"), "9035"), Scheme: "http", }) if err != nil { return nil, fmt.Errorf("initializing weaviate: %w", err) } // Create a new class (collection) in weaviate if it doesn't exist yet. cls := &models.Class{ Class: "Document", Vectorizer: "none", } exists, err := client.Schema().ClassExistenceChecker().WithClassName(cls.Class).Do(ctx) if err != nil { return nil, fmt.Errorf("weaviate error: %w", err) } if !exists { err = client.Schema().ClassCreator().WithClass(cls).Do(ctx) if err != nil { return nil, fmt.Errorf("weaviate error: %w", err) } } return client, nil }
main
function
flightctl/test
53d7f4a8-6fab-4024-a804-be4fda2f44f5
combinedWeaviateError
['"fmt"', '"github.com/weaviate/weaviate-go-client/v4/weaviate"', '"github.com/weaviate/weaviate/entities/models"']
github.com/flightctl/test//tmp/repos/example/ragserver/ragserver/weaviate.go
func combinedWeaviateError(result *models.GraphQLResponse, err error) error { if err != nil { return err } if len(result.Errors) != 0 { var ss []string for _, e := range result.Errors { ss = append(ss, e.Message) } return fmt.Errorf("weaviate error: %v", ss) } return nil }
main
file
flightctl/test
25f3316e-bc42-4036-98fd-1d02c7bb4b70
indent_handler.go
import ( "context" "fmt" "io" "log/slog" "runtime" "sync" "time" )
github.com/flightctl/test//tmp/repos/example/slog-handler-guide/indenthandler1/indent_handler.go
//go:build go1.21 package indenthandler import ( "context" "fmt" "io" "log/slog" "runtime" "sync" "time" ) // !+types type IndentHandler struct { opts Options // TODO: state for WithGroup and WithAttrs mu *sync.Mutex out io.Writer } type Options struct { // Level reports the minimum level to log. // Levels with lower levels are discarded. // If nil, the Handler uses [slog.LevelInfo]. Level slog.Leveler } func New(out io.Writer, opts *Options) *IndentHandler { h := &IndentHandler{out: out, mu: &sync.Mutex{}} if opts != nil { h.opts = *opts } if h.opts.Level == nil { h.opts.Level = slog.LevelInfo } return h } //!-types // !+enabled func (h *IndentHandler) Enabled(ctx context.Context, level slog.Level) bool { return level >= h.opts.Level.Level() } //!-enabled func (h *IndentHandler) WithGroup(name string) slog.Handler { // TODO: implement. return h } func (h *IndentHandler) WithAttrs(attrs []slog.Attr) slog.Handler { // TODO: implement. return h } // !+handle func (h *IndentHandler) Handle(ctx context.Context, r slog.Record) error { buf := make([]byte, 0, 1024) if !r.Time.IsZero() { buf = h.appendAttr(buf, slog.Time(slog.TimeKey, r.Time), 0) } buf = h.appendAttr(buf, slog.Any(slog.LevelKey, r.Level), 0) if r.PC != 0 { fs := runtime.CallersFrames([]uintptr{r.PC}) f, _ := fs.Next() buf = h.appendAttr(buf, slog.String(slog.SourceKey, fmt.Sprintf("%s:%d", f.File, f.Line)), 0) } buf = h.appendAttr(buf, slog.String(slog.MessageKey, r.Message), 0) indentLevel := 0 // TODO: output the Attrs and groups from WithAttrs and WithGroup. r.Attrs(func(a slog.Attr) bool { buf = h.appendAttr(buf, a, indentLevel) return true }) buf = append(buf, "---\n"...) h.mu.Lock() defer h.mu.Unlock() _, err := h.out.Write(buf) return err } //!-handle // !+appendAttr func (h *IndentHandler) appendAttr(buf []byte, a slog.Attr, indentLevel int) []byte { // Resolve the Attr's value before doing anything else. a.Value = a.Value.Resolve() // Ignore empty Attrs. if a.Equal(slog.Attr{}) { return buf } // Indent 4 spaces per level. buf = fmt.Appendf(buf, "%*s", indentLevel*4, "") switch a.Value.Kind() { case slog.KindString: // Quote string values, to make them easy to parse. buf = fmt.Appendf(buf, "%s: %q\n", a.Key, a.Value.String()) case slog.KindTime: // Write times in a standard way, without the monotonic time. buf = fmt.Appendf(buf, "%s: %s\n", a.Key, a.Value.Time().Format(time.RFC3339Nano)) case slog.KindGroup: attrs := a.Value.Group() // Ignore empty groups. if len(attrs) == 0 { return buf } // If the key is non-empty, write it out and indent the rest of the attrs. // Otherwise, inline the attrs. if a.Key != "" { buf = fmt.Appendf(buf, "%s:\n", a.Key) indentLevel++ } for _, ga := range attrs { buf = h.appendAttr(buf, ga, indentLevel) } default: buf = fmt.Appendf(buf, "%s: %s\n", a.Key, a.Value) } return buf } //!-appendAttr
package indenthandler
function
flightctl/test
4d7c559b-5e7c-46a5-8456-f19855348226
New
['"io"', '"log/slog"', '"sync"']
['IndentHandler', 'Options']
github.com/flightctl/test//tmp/repos/example/slog-handler-guide/indenthandler1/indent_handler.go
func New(out io.Writer, opts *Options) *IndentHandler { h := &IndentHandler{out: out, mu: &sync.Mutex{}} if opts != nil { h.opts = *opts } if h.opts.Level == nil { h.opts.Level = slog.LevelInfo } return h }
indenthandler
function
flightctl/test
374c76c6-8837-4dc2-9678-026bf65d176e
Enabled
['"context"', '"log/slog"']
['IndentHandler']
github.com/flightctl/test//tmp/repos/example/slog-handler-guide/indenthandler1/indent_handler.go
func (h *IndentHandler) Enabled(ctx context.Context, level slog.Level) bool { return level >= h.opts.Level.Level() }
indenthandler
function
flightctl/test
1ba6d4e9-642b-411a-8516-78d208bdead2
WithGroup
['"log/slog"']
['IndentHandler']
github.com/flightctl/test//tmp/repos/example/slog-handler-guide/indenthandler1/indent_handler.go
func (h *IndentHandler) WithGroup(name string) slog.Handler { // TODO: implement. return h }
indenthandler
function
flightctl/test
9b4211de-9824-4539-9c16-e28283c29d1f
WithAttrs
['"log/slog"']
['IndentHandler']
github.com/flightctl/test//tmp/repos/example/slog-handler-guide/indenthandler1/indent_handler.go
func (h *IndentHandler) WithAttrs(attrs []slog.Attr) slog.Handler { // TODO: implement. return h }
indenthandler
function
flightctl/test
15aff37e-66db-4280-81c7-440219db75fd
Handle
['"context"', '"fmt"', '"log/slog"', '"runtime"']
['IndentHandler']
github.com/flightctl/test//tmp/repos/example/slog-handler-guide/indenthandler1/indent_handler.go
func (h *IndentHandler) Handle(ctx context.Context, r slog.Record) error { buf := make([]byte, 0, 1024) if !r.Time.IsZero() { buf = h.appendAttr(buf, slog.Time(slog.TimeKey, r.Time), 0) } buf = h.appendAttr(buf, slog.Any(slog.LevelKey, r.Level), 0) if r.PC != 0 { fs := runtime.CallersFrames([]uintptr{r.PC}) f, _ := fs.Next() buf = h.appendAttr(buf, slog.String(slog.SourceKey, fmt.Sprintf("%s:%d", f.File, f.Line)), 0) } buf = h.appendAttr(buf, slog.String(slog.MessageKey, r.Message), 0) indentLevel := 0 // TODO: output the Attrs and groups from WithAttrs and WithGroup. r.Attrs(func(a slog.Attr) bool { buf = h.appendAttr(buf, a, indentLevel) return true }) buf = append(buf, "---\n"...) h.mu.Lock() defer h.mu.Unlock() _, err := h.out.Write(buf) return err }
indenthandler
function
flightctl/test
6884d0e6-5ad6-4a1d-b405-7b3444e20a72
appendAttr
['"fmt"', '"log/slog"', '"time"']
['IndentHandler']
github.com/flightctl/test//tmp/repos/example/slog-handler-guide/indenthandler1/indent_handler.go
func (h *IndentHandler) appendAttr(buf []byte, a slog.Attr, indentLevel int) []byte { // Resolve the Attr's value before doing anything else. a.Value = a.Value.Resolve() // Ignore empty Attrs. if a.Equal(slog.Attr{}) { return buf } // Indent 4 spaces per level. buf = fmt.Appendf(buf, "%*s", indentLevel*4, "") switch a.Value.Kind() { case slog.KindString: // Quote string values, to make them easy to parse. buf = fmt.Appendf(buf, "%s: %q\n", a.Key, a.Value.String()) case slog.KindTime: // Write times in a standard way, without the monotonic time. buf = fmt.Appendf(buf, "%s: %s\n", a.Key, a.Value.Time().Format(time.RFC3339Nano)) case slog.KindGroup: attrs := a.Value.Group() // Ignore empty groups. if len(attrs) == 0 { return buf } // If the key is non-empty, write it out and indent the rest of the attrs. // Otherwise, inline the attrs. if a.Key != "" { buf = fmt.Appendf(buf, "%s:\n", a.Key) indentLevel++ } for _, ga := range attrs { buf = h.appendAttr(buf, ga, indentLevel) } default: buf = fmt.Appendf(buf, "%s: %s\n", a.Key, a.Value) } return buf }
indenthandler
file
flightctl/test
38cdcb41-e93b-4f1e-882f-bbc6ceee40b8
indent_handler_test.go
import ( "bytes" "regexp" "testing" "log/slog" )
github.com/flightctl/test//tmp/repos/example/slog-handler-guide/indenthandler1/indent_handler_test.go
//go:build go1.21 package indenthandler import ( "bytes" "regexp" "testing" "log/slog" ) func Test(t *testing.T) { var buf bytes.Buffer l := slog.New(New(&buf, nil)) l.Info("hello", "a", 1, "b", true, "c", 3.14, slog.Group("g", "h", 1, "i", 2), "d", "NO") got := buf.String() wantre := `time: [-0-9T:.]+Z? level: INFO source: ".*/indent_handler_test.go:\d+" msg: "hello" a: 1 b: true c: 3.14 g: h: 1 i: 2 d: "NO" ` re := regexp.MustCompile(wantre) if !re.MatchString(got) { t.Errorf("\ngot:\n%q\nwant:\n%q", got, wantre) } buf.Reset() l.Debug("test") if got := buf.Len(); got != 0 { t.Errorf("got buf.Len() = %d, want 0", got) } }
package indenthandler
function
flightctl/test
e7a6c869-a17f-4a33-9b4c-35e5ecaa52e8
Test
['"bytes"', '"regexp"', '"testing"', '"log/slog"']
github.com/flightctl/test//tmp/repos/example/slog-handler-guide/indenthandler1/indent_handler_test.go
func Test(t *testing.T) { var buf bytes.Buffer l := slog.New(New(&buf, nil)) l.Info("hello", "a", 1, "b", true, "c", 3.14, slog.Group("g", "h", 1, "i", 2), "d", "NO") got := buf.String() wantre := `time: [-0-9T:.]+Z? level: INFO source: ".*/indent_handler_test.go:\d+" msg: "hello" a: 1 b: true c: 3.14 g: h: 1 i: 2 d: "NO" ` re := regexp.MustCompile(wantre) if !re.MatchString(got) { t.Errorf("\ngot:\n%q\nwant:\n%q", got, wantre) } buf.Reset() l.Debug("test") if got := buf.Len(); got != 0 { t.Errorf("got buf.Len() = %d, want 0", got) } }
indenthandler
file
flightctl/test
085d42f6-b0f3-465b-90e0-386c02735e5c
indent_handler.go
import ( "context" "fmt" "io" "log/slog" "runtime" "sync" "time" )
github.com/flightctl/test//tmp/repos/example/slog-handler-guide/indenthandler2/indent_handler.go
//go:build go1.21 package indenthandler import ( "context" "fmt" "io" "log/slog" "runtime" "sync" "time" ) // !+IndentHandler type IndentHandler struct { opts Options goas []groupOrAttrs mu *sync.Mutex out io.Writer } //!-IndentHandler type Options struct { // Level reports the minimum level to log. // Levels with lower levels are discarded. // If nil, the Handler uses [slog.LevelInfo]. Level slog.Leveler } // !+gora // groupOrAttrs holds either a group name or a list of slog.Attrs. type groupOrAttrs struct { group string // group name if non-empty attrs []slog.Attr // attrs if non-empty } //!-gora func New(out io.Writer, opts *Options) *IndentHandler { h := &IndentHandler{out: out, mu: &sync.Mutex{}} if opts != nil { h.opts = *opts } if h.opts.Level == nil { h.opts.Level = slog.LevelInfo } return h } func (h *IndentHandler) Enabled(ctx context.Context, level slog.Level) bool { return level >= h.opts.Level.Level() } // !+withs func (h *IndentHandler) WithGroup(name string) slog.Handler { if name == "" { return h } return h.withGroupOrAttrs(groupOrAttrs{group: name}) } func (h *IndentHandler) WithAttrs(attrs []slog.Attr) slog.Handler { if len(attrs) == 0 { return h } return h.withGroupOrAttrs(groupOrAttrs{attrs: attrs}) } //!-withs // !+withgora func (h *IndentHandler) withGroupOrAttrs(goa groupOrAttrs) *IndentHandler { h2 := *h h2.goas = make([]groupOrAttrs, len(h.goas)+1) copy(h2.goas, h.goas) h2.goas[len(h2.goas)-1] = goa return &h2 } //!-withgora // !+handle func (h *IndentHandler) Handle(ctx context.Context, r slog.Record) error { buf := make([]byte, 0, 1024) if !r.Time.IsZero() { buf = h.appendAttr(buf, slog.Time(slog.TimeKey, r.Time), 0) } buf = h.appendAttr(buf, slog.Any(slog.LevelKey, r.Level), 0) if r.PC != 0 { fs := runtime.CallersFrames([]uintptr{r.PC}) f, _ := fs.Next() buf = h.appendAttr(buf, slog.String(slog.SourceKey, fmt.Sprintf("%s:%d", f.File, f.Line)), 0) } buf = h.appendAttr(buf, slog.String(slog.MessageKey, r.Message), 0) indentLevel := 0 // Handle state from WithGroup and WithAttrs. goas := h.goas if r.NumAttrs() == 0 { // If the record has no Attrs, remove groups at the end of the list; they are empty. for len(goas) > 0 && goas[len(goas)-1].group != "" { goas = goas[:len(goas)-1] } } for _, goa := range goas { if goa.group != "" { buf = fmt.Appendf(buf, "%*s%s:\n", indentLevel*4, "", goa.group) indentLevel++ } else { for _, a := range goa.attrs { buf = h.appendAttr(buf, a, indentLevel) } } } r.Attrs(func(a slog.Attr) bool { buf = h.appendAttr(buf, a, indentLevel) return true }) buf = append(buf, "---\n"...) h.mu.Lock() defer h.mu.Unlock() _, err := h.out.Write(buf) return err } //!-handle func (h *IndentHandler) appendAttr(buf []byte, a slog.Attr, indentLevel int) []byte { // Resolve the Attr's value before doing anything else. a.Value = a.Value.Resolve() // Ignore empty Attrs. if a.Equal(slog.Attr{}) { return buf } // Indent 4 spaces per level. buf = fmt.Appendf(buf, "%*s", indentLevel*4, "") switch a.Value.Kind() { case slog.KindString: // Quote string values, to make them easy to parse. buf = fmt.Appendf(buf, "%s: %q\n", a.Key, a.Value.String()) case slog.KindTime: // Write times in a standard way, without the monotonic time. buf = fmt.Appendf(buf, "%s: %s\n", a.Key, a.Value.Time().Format(time.RFC3339Nano)) case slog.KindGroup: attrs := a.Value.Group() // Ignore empty groups. if len(attrs) == 0 { return buf } // If the key is non-empty, write it out and indent the rest of the attrs. // Otherwise, inline the attrs. if a.Key != "" { buf = fmt.Appendf(buf, "%s:\n", a.Key) indentLevel++ } for _, ga := range attrs { buf = h.appendAttr(buf, ga, indentLevel) } default: buf = fmt.Appendf(buf, "%s: %s\n", a.Key, a.Value) } return buf }
package indenthandler
function
flightctl/test
ab002b84-6870-4a9f-8ef7-361cad29ee2b
New
['"io"', '"log/slog"', '"sync"']
['IndentHandler', 'Options']
github.com/flightctl/test//tmp/repos/example/slog-handler-guide/indenthandler2/indent_handler.go
func New(out io.Writer, opts *Options) *IndentHandler { h := &IndentHandler{out: out, mu: &sync.Mutex{}} if opts != nil { h.opts = *opts } if h.opts.Level == nil { h.opts.Level = slog.LevelInfo } return h }
indenthandler
function
flightctl/test
42a6d0a2-33fe-400b-a7ac-99fb49ac1841
Enabled
['"context"', '"log/slog"']
['IndentHandler']
github.com/flightctl/test//tmp/repos/example/slog-handler-guide/indenthandler2/indent_handler.go
func (h *IndentHandler) Enabled(ctx context.Context, level slog.Level) bool { return level >= h.opts.Level.Level() }
indenthandler
function
flightctl/test
f32c8034-30e8-423e-9d0d-4afa23a0eaf6
WithGroup
['"log/slog"']
['IndentHandler', 'groupOrAttrs']
github.com/flightctl/test//tmp/repos/example/slog-handler-guide/indenthandler2/indent_handler.go
func (h *IndentHandler) WithGroup(name string) slog.Handler { if name == "" { return h } return h.withGroupOrAttrs(groupOrAttrs{group: name}) }
indenthandler