|
{"element_type":"file","project_name":"finalHFtest","uuid":"b99a2d2c-e0d0-4387-b8f8-bd08353d5cee","name":"app.go","imports":"import (\n\t\"fmt\"\n\t\"net\/http\"\n)","structs":"","interfaces":"","file_location":"github.com\/finalHFtest\/\/tmp\/repos\/example\/appengine-hello\/app.go","code":"\/\/ Copyright 2023 The Go Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style\n\/\/ license that can be found in the LICENSE file.\n\n\/\/ Package hello is a simple App Engine application that replies to requests\n\/\/ on \/hello with a welcoming message.\npackage hello\n\nimport (\n\t\"fmt\"\n\t\"net\/http\"\n)\n\n\/\/ init is run before the application starts serving.\nfunc init() {\n\t\/\/ Handle all requests with path \/hello with the helloHandler function.\n\thttp.HandleFunc(\"\/hello\", helloHandler)\n}\n\nfunc helloHandler(w http.ResponseWriter, r *http.Request) {\n\tfmt.Fprintln(w, \"Hello from the Go app\")\n}\n","global_vars":"","package":"package hello","tags":""} |
|
{"element_type":"function","project_name":"finalHFtest","uuid":"76af9cd0-6ca6-461c-941e-a2cd2f8f543d","name":"init","imports":"['\"net\/http\"']","structs":"","interfaces":"","file_location":"github.com\/finalHFtest\/\/tmp\/repos\/example\/appengine-hello\/app.go","code":"func init() {\n\t\/\/ Handle all requests with path \/hello with the helloHandler function.\n\thttp.HandleFunc(\"\/hello\", helloHandler)\n}","global_vars":"","package":"hello","tags":""} |
|
{"element_type":"function","project_name":"finalHFtest","uuid":"03727714-07db-4ef9-b28c-68ca64ccabbe","name":"helloHandler","imports":"['\"fmt\"', '\"net\/http\"']","structs":"","interfaces":"","file_location":"github.com\/finalHFtest\/\/tmp\/repos\/example\/appengine-hello\/app.go","code":"func helloHandler(w http.ResponseWriter, r *http.Request) {\n\tfmt.Fprintln(w, \"Hello from the Go app\")\n}","global_vars":"","package":"hello","tags":""} |
|
{"element_type":"file","project_name":"finalHFtest","uuid":"27624040-7bc2-48ae-b8f6-fa1666c08f82","name":"main.go","imports":"import (\n\t\"fmt\"\n\t\"go\/ast\"\n\t\"go\/importer\"\n\t\"go\/parser\"\n\t\"go\/token\"\n\t\"go\/types\"\n\t\"log\"\n)","structs":"","interfaces":"","file_location":"github.com\/finalHFtest\/\/tmp\/repos\/example\/gotypes\/defsuses\/main.go","code":"package main\n\nimport (\n\t\"fmt\"\n\t\"go\/ast\"\n\t\"go\/importer\"\n\t\"go\/parser\"\n\t\"go\/token\"\n\t\"go\/types\"\n\t\"log\"\n)\n\nconst hello = `package main\n\nimport \"fmt\"\n\nfunc main() {\n fmt.Println(\"Hello, world\")\n}\n`\n\n\/\/ !+\nfunc PrintDefsUses(fset *token.FileSet, files ...*ast.File) error {\n\tconf := types.Config{Importer: importer.Default()}\n\tinfo := &types.Info{\n\t\tDefs: make(map[*ast.Ident]types.Object),\n\t\tUses: make(map[*ast.Ident]types.Object),\n\t}\n\t_, err := conf.Check(\"hello\", fset, files, info)\n\tif err != nil {\n\t\treturn err \/\/ type error\n\t}\n\n\tfor id, obj := range info.Defs {\n\t\tfmt.Printf(\"%s: %q defines %v\\n\",\n\t\t\tfset.Position(id.Pos()), id.Name, obj)\n\t}\n\tfor id, obj := range info.Uses {\n\t\tfmt.Printf(\"%s: %q uses %v\\n\",\n\t\t\tfset.Position(id.Pos()), id.Name, obj)\n\t}\n\treturn nil\n}\n\n\/\/!-\n\nfunc main() {\n\t\/\/ Parse one file.\n\tfset := token.NewFileSet()\n\tf, err := parser.ParseFile(fset, \"hello.go\", hello, 0)\n\tif err != nil {\n\t\tlog.Fatal(err) \/\/ parse error\n\t}\n\tif err := PrintDefsUses(fset, f); err != nil {\n\t\tlog.Fatal(err) \/\/ type error\n\t}\n}\n\n\/*\n\/\/!+output\n$ go build golang.org\/x\/example\/gotypes\/defsuses\n$ .\/defsuses\nhello.go:1:9: \"main\" defines <nil>\nhello.go:5:6: \"main\" defines func hello.main()\nhello.go:6:9: \"fmt\" uses package fmt\nhello.go:6:13: \"Println\" uses func fmt.Println(a ...interface{}) (n int, err error)\n\/\/!-output\n*\/\n","global_vars":"","package":"package main","tags":""} |
|
{"element_type":"function","project_name":"finalHFtest","uuid":"9298e5ca-4f5b-4b66-870c-658732c2b498","name":"PrintDefsUses","imports":"['\"fmt\"', '\"go\/ast\"', '\"go\/importer\"', '\"go\/token\"', '\"go\/types\"']","structs":"","interfaces":"","file_location":"github.com\/finalHFtest\/\/tmp\/repos\/example\/gotypes\/defsuses\/main.go","code":"func PrintDefsUses(fset *token.FileSet, files ...*ast.File) error {\n\tconf := types.Config{Importer: importer.Default()}\n\tinfo := &types.Info{\n\t\tDefs: make(map[*ast.Ident]types.Object),\n\t\tUses: make(map[*ast.Ident]types.Object),\n\t}\n\t_, err := conf.Check(\"hello\", fset, files, info)\n\tif err != nil {\n\t\treturn err \/\/ type error\n\t}\n\n\tfor id, obj := range info.Defs {\n\t\tfmt.Printf(\"%s: %q defines %v\\n\",\n\t\t\tfset.Position(id.Pos()), id.Name, obj)\n\t}\n\tfor id, obj := range info.Uses {\n\t\tfmt.Printf(\"%s: %q uses %v\\n\",\n\t\t\tfset.Position(id.Pos()), id.Name, obj)\n\t}\n\treturn nil\n}","global_vars":"","package":"main","tags":""} |
|
{"element_type":"function","project_name":"finalHFtest","uuid":"8e141c6e-fe56-40f4-8434-a62782b1bbb8","name":"main","imports":"['\"go\/parser\"', '\"go\/token\"', '\"log\"']","structs":"","interfaces":"","file_location":"github.com\/finalHFtest\/\/tmp\/repos\/example\/gotypes\/defsuses\/main.go","code":"func main() {\n\t\/\/ Parse one file.\n\tfset := token.NewFileSet()\n\tf, err := parser.ParseFile(fset, \"hello.go\", hello, 0)\n\tif err != nil {\n\t\tlog.Fatal(err) \/\/ parse error\n\t}\n\tif err := PrintDefsUses(fset, f); err != nil {\n\t\tlog.Fatal(err) \/\/ type error\n\t}\n}","global_vars":"","package":"main","tags":""} |
|
{"element_type":"file","project_name":"finalHFtest","uuid":"ef5b56f1-717e-48e8-83e9-e892e7d33299","name":"main.go","imports":"import (\n\t\"fmt\"\n\t\"go\/ast\"\n\t\"log\"\n\t\"os\"\n\n\t\"golang.org\/x\/tools\/go\/ast\/astutil\"\n\t\"golang.org\/x\/tools\/go\/packages\"\n\t\"golang.org\/x\/tools\/go\/types\/typeutil\"\n)","structs":"","interfaces":"","file_location":"github.com\/finalHFtest\/\/tmp\/repos\/example\/gotypes\/doc\/main.go","code":"\/\/ The doc command prints the doc comment of a package-level object.\npackage main\n\nimport (\n\t\"fmt\"\n\t\"go\/ast\"\n\t\"log\"\n\t\"os\"\n\n\t\"golang.org\/x\/tools\/go\/ast\/astutil\"\n\t\"golang.org\/x\/tools\/go\/packages\"\n\t\"golang.org\/x\/tools\/go\/types\/typeutil\"\n)\n\nfunc main() {\n\tif len(os.Args) != 3 {\n\t\tlog.Fatal(\"Usage: doc <package> <object>\")\n\t}\n\t\/\/!+part1\n\tpkgpath, name := os.Args[1], os.Args[2]\n\n\t\/\/ Load complete type information for the specified packages,\n\t\/\/ along with type-annotated syntax.\n\t\/\/ Types for dependencies are loaded from export data.\n\tconf := &packages.Config{Mode: packages.LoadSyntax}\n\tpkgs, err := packages.Load(conf, pkgpath)\n\tif err != nil {\n\t\tlog.Fatal(err) \/\/ failed to load anything\n\t}\n\tif packages.PrintErrors(pkgs) > 0 {\n\t\tos.Exit(1) \/\/ some packages contained errors\n\t}\n\n\t\/\/ Find the package and package-level object.\n\tpkg := pkgs[0]\n\tobj := pkg.Types.Scope().Lookup(name)\n\tif obj == nil {\n\t\tlog.Fatalf(\"%s.%s not found\", pkg.Types.Path(), name)\n\t}\n\t\/\/!-part1\n\t\/\/!+part2\n\n\t\/\/ Print the object and its methods (incl. location of definition).\n\tfmt.Println(obj)\n\tfor _, sel := range typeutil.IntuitiveMethodSet(obj.Type(), nil) {\n\t\tfmt.Printf(\"%s: %s\\n\", pkg.Fset.Position(sel.Obj().Pos()), sel)\n\t}\n\n\t\/\/ Find the path from the root of the AST to the object's position.\n\t\/\/ Walk up to the enclosing ast.Decl for the doc comment.\n\tfor _, file := range pkg.Syntax {\n\t\tpos := obj.Pos()\n\t\tif !(file.FileStart <= pos && pos < file.FileEnd) {\n\t\t\tcontinue \/\/ not in this file\n\t\t}\n\t\tpath, _ := astutil.PathEnclosingInterval(file, pos, pos)\n\t\tfor _, n := range path {\n\t\t\tswitch n := n.(type) {\n\t\t\tcase *ast.GenDecl:\n\t\t\t\tfmt.Println(\"\\n\", n.Doc.Text())\n\t\t\t\treturn\n\t\t\tcase *ast.FuncDecl:\n\t\t\t\tfmt.Println(\"\\n\", n.Doc.Text())\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}\n\t\/\/!-part2\n}\n\n\/\/ (The $GOROOT below is the actual string that appears in file names\n\/\/ loaded from export data for packages in the standard library.)\n\n\/*\n\/\/!+output\n$ .\/doc net\/http File\ntype 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}\n$GOROOT\/src\/io\/io.go:92:2: method (net\/http.File) Close() error\n$GOROOT\/src\/io\/io.go:71:2: method (net\/http.File) Read(p []byte) (n int, err error)\n\/go\/src\/net\/http\/fs.go:65:2: method (net\/http.File) Readdir(count int) ([]os.FileInfo, error)\n$GOROOT\/src\/net\/http\/fs.go:66:2: method (net\/http.File) Seek(offset int64, whence int) (int64, error)\n\/go\/src\/net\/http\/fs.go:67:2: method (net\/http.File) Stat() (os.FileInfo, error)\n\n A File is returned by a FileSystem's Open method and can be\nserved by the FileServer implementation.\n\nThe methods should behave the same as those on an *os.File.\n\/\/!-output\n*\/\n","global_vars":"","package":"package main","tags":""} |
|
{"element_type":"function","project_name":"finalHFtest","uuid":"4fcd973f-9566-4c69-8820-5f38247e6632","name":"main","imports":"['\"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\"']","structs":"","interfaces":"","file_location":"github.com\/finalHFtest\/\/tmp\/repos\/example\/gotypes\/doc\/main.go","code":"func main() {\n\tif len(os.Args) != 3 {\n\t\tlog.Fatal(\"Usage: doc <package> <object>\")\n\t}\n\t\/\/!+part1\n\tpkgpath, name := os.Args[1], os.Args[2]\n\n\t\/\/ Load complete type information for the specified packages,\n\t\/\/ along with type-annotated syntax.\n\t\/\/ Types for dependencies are loaded from export data.\n\tconf := &packages.Config{Mode: packages.LoadSyntax}\n\tpkgs, err := packages.Load(conf, pkgpath)\n\tif err != nil {\n\t\tlog.Fatal(err) \/\/ failed to load anything\n\t}\n\tif packages.PrintErrors(pkgs) > 0 {\n\t\tos.Exit(1) \/\/ some packages contained errors\n\t}\n\n\t\/\/ Find the package and package-level object.\n\tpkg := pkgs[0]\n\tobj := pkg.Types.Scope().Lookup(name)\n\tif obj == nil {\n\t\tlog.Fatalf(\"%s.%s not found\", pkg.Types.Path(), name)\n\t}\n\t\/\/!-part1\n\t\/\/!+part2\n\n\t\/\/ Print the object and its methods (incl. location of definition).\n\tfmt.Println(obj)\n\tfor _, sel := range typeutil.IntuitiveMethodSet(obj.Type(), nil) {\n\t\tfmt.Printf(\"%s: %s\\n\", pkg.Fset.Position(sel.Obj().Pos()), sel)\n\t}\n\n\t\/\/ Find the path from the root of the AST to the object's position.\n\t\/\/ Walk up to the enclosing ast.Decl for the doc comment.\n\tfor _, file := range pkg.Syntax {\n\t\tpos := obj.Pos()\n\t\tif !(file.FileStart <= pos && pos < file.FileEnd) {\n\t\t\tcontinue \/\/ not in this file\n\t\t}\n\t\tpath, _ := astutil.PathEnclosingInterval(file, pos, pos)\n\t\tfor _, n := range path {\n\t\t\tswitch n := n.(type) {\n\t\t\tcase *ast.GenDecl:\n\t\t\t\tfmt.Println(\"\\n\", n.Doc.Text())\n\t\t\t\treturn\n\t\t\tcase *ast.FuncDecl:\n\t\t\t\tfmt.Println(\"\\n\", n.Doc.Text())\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}\n\t\/\/!-part2\n}","global_vars":"","package":"main","tags":""} |
|
{"element_type":"file","project_name":"finalHFtest","uuid":"b7c84059-d495-4bf8-a7d0-b7d5bd425afc","name":"gen.go","imports":"","structs":"","interfaces":"","file_location":"github.com\/finalHFtest\/\/tmp\/repos\/example\/gotypes\/gen.go","code":"\/\/go:generate bash -c \"go run ..\/internal\/cmd\/weave\/weave.go .\/go-types.md > README.md\"\n\npackage gotypes\n","global_vars":"","package":"package gotypes","tags":""} |
|
{"element_type":"file","project_name":"finalHFtest","uuid":"036d8d34-e9cf-42f2-83ae-7c75c1aec79a","name":"hello.go","imports":"import \"fmt\"","structs":"","interfaces":"","file_location":"github.com\/finalHFtest\/\/tmp\/repos\/example\/gotypes\/hello\/hello.go","code":"\/\/ !+\npackage main\n\nimport \"fmt\"\n\nfunc main() {\n\tfmt.Println(\"Hello, \u4e16\u754c\")\n}\n\n\/\/!-\n","global_vars":"","package":"package main","tags":""} |
|
{"element_type":"function","project_name":"finalHFtest","uuid":"e679fc5f-5973-4b25-8019-fe452bd24e80","name":"main","imports":"","structs":"","interfaces":"","file_location":"github.com\/finalHFtest\/\/tmp\/repos\/example\/gotypes\/hello\/hello.go","code":"func main() {\n\tfmt.Println(\"Hello, \u4e16\u754c\")\n}","global_vars":"","package":"main","tags":""} |
|
{"element_type":"file","project_name":"finalHFtest","uuid":"ced53bff-4047-41ba-99ea-de968314b62e","name":"main.go","imports":"import (\n\t\"flag\"\n\t\"fmt\"\n\t\"go\/ast\"\n\t\"go\/token\"\n\t\"go\/types\"\n\t\"log\"\n\t\"os\"\n\n\t\"golang.org\/x\/tools\/go\/packages\"\n)","structs":"","interfaces":"","file_location":"github.com\/finalHFtest\/\/tmp\/repos\/example\/gotypes\/hugeparam\/main.go","code":"\/\/ The hugeparam command identifies by-value parameters that are larger than n bytes.\n\/\/\n\/\/ Example:\n\/\/\n\/\/\t$ .\/hugeparams encoding\/xml\npackage main\n\nimport (\n\t\"flag\"\n\t\"fmt\"\n\t\"go\/ast\"\n\t\"go\/token\"\n\t\"go\/types\"\n\t\"log\"\n\t\"os\"\n\n\t\"golang.org\/x\/tools\/go\/packages\"\n)\n\n\/\/ !+\nvar bytesFlag = flag.Int(\"bytes\", 48, \"maximum parameter size in bytes\")\n\nfunc PrintHugeParams(fset *token.FileSet, info *types.Info, sizes types.Sizes, files []*ast.File) {\n\tcheckTuple := func(descr string, tuple *types.Tuple) {\n\t\tfor i := 0; i < tuple.Len(); i++ {\n\t\t\tv := tuple.At(i)\n\t\t\tif sz := sizes.Sizeof(v.Type()); sz > int64(*bytesFlag) {\n\t\t\t\tfmt.Printf(\"%s: %q %s: %s = %d bytes\\n\",\n\t\t\t\t\tfset.Position(v.Pos()),\n\t\t\t\t\tv.Name(), descr, v.Type(), sz)\n\t\t\t}\n\t\t}\n\t}\n\tcheckSig := func(sig *types.Signature) {\n\t\tcheckTuple(\"parameter\", sig.Params())\n\t\tcheckTuple(\"result\", sig.Results())\n\t}\n\tfor _, file := range files {\n\t\tast.Inspect(file, func(n ast.Node) bool {\n\t\t\tswitch n := n.(type) {\n\t\t\tcase *ast.FuncDecl:\n\t\t\t\tcheckSig(info.Defs[n.Name].Type().(*types.Signature))\n\t\t\tcase *ast.FuncLit:\n\t\t\t\tcheckSig(info.Types[n.Type].Type.(*types.Signature))\n\t\t\t}\n\t\t\treturn true\n\t\t})\n\t}\n}\n\n\/\/!-\n\nfunc main() {\n\tflag.Parse()\n\n\t\/\/ Load complete type information for the specified packages,\n\t\/\/ along with type-annotated syntax and the \"sizeof\" function.\n\t\/\/ Types for dependencies are loaded from export data.\n\tconf := &packages.Config{Mode: packages.LoadSyntax}\n\tpkgs, err := packages.Load(conf, flag.Args()...)\n\tif err != nil {\n\t\tlog.Fatal(err) \/\/ failed to load anything\n\t}\n\tif packages.PrintErrors(pkgs) > 0 {\n\t\tos.Exit(1) \/\/ some packages contained errors\n\t}\n\n\tfor _, pkg := range pkgs {\n\t\tPrintHugeParams(pkg.Fset, pkg.TypesInfo, pkg.TypesSizes, pkg.Syntax)\n\t}\n}\n\n\/*\n\/\/!+output\n% .\/hugeparam encoding\/xml\n\/go\/src\/encoding\/xml\/marshal.go:167:50: \"start\" parameter: encoding\/xml.StartElement = 56 bytes\n\/go\/src\/encoding\/xml\/marshal.go:734:97: \"\" result: encoding\/xml.StartElement = 56 bytes\n\/go\/src\/encoding\/xml\/marshal.go:761:51: \"start\" parameter: encoding\/xml.StartElement = 56 bytes\n\/go\/src\/encoding\/xml\/marshal.go:781:68: \"start\" parameter: encoding\/xml.StartElement = 56 bytes\n\/go\/src\/encoding\/xml\/xml.go:72:30: \"\" result: encoding\/xml.StartElement = 56 bytes\n\/\/!-output\n*\/\n","global_vars":"","package":"package main","tags":""} |
|
{"element_type":"function","project_name":"finalHFtest","uuid":"a3eb6ac5-b58a-4b4f-b402-266eb34bb0e8","name":"PrintHugeParams","imports":"['\"fmt\"', '\"go\/ast\"', '\"go\/token\"', '\"go\/types\"']","structs":"","interfaces":"","file_location":"github.com\/finalHFtest\/\/tmp\/repos\/example\/gotypes\/hugeparam\/main.go","code":"func PrintHugeParams(fset *token.FileSet, info *types.Info, sizes types.Sizes, files []*ast.File) {\n\tcheckTuple := func(descr string, tuple *types.Tuple) {\n\t\tfor i := 0; i < tuple.Len(); i++ {\n\t\t\tv := tuple.At(i)\n\t\t\tif sz := sizes.Sizeof(v.Type()); sz > int64(*bytesFlag) {\n\t\t\t\tfmt.Printf(\"%s: %q %s: %s = %d bytes\\n\",\n\t\t\t\t\tfset.Position(v.Pos()),\n\t\t\t\t\tv.Name(), descr, v.Type(), sz)\n\t\t\t}\n\t\t}\n\t}\n\tcheckSig := func(sig *types.Signature) {\n\t\tcheckTuple(\"parameter\", sig.Params())\n\t\tcheckTuple(\"result\", sig.Results())\n\t}\n\tfor _, file := range files {\n\t\tast.Inspect(file, func(n ast.Node) bool {\n\t\t\tswitch n := n.(type) {\n\t\t\tcase *ast.FuncDecl:\n\t\t\t\tcheckSig(info.Defs[n.Name].Type().(*types.Signature))\n\t\t\tcase *ast.FuncLit:\n\t\t\t\tcheckSig(info.Types[n.Type].Type.(*types.Signature))\n\t\t\t}\n\t\t\treturn true\n\t\t})\n\t}\n}","global_vars":"{'bytesFlag': 'flag.Int(\"bytes\", 48, \"maximum parameter size in bytes\")'}","package":"main","tags":""} |
|
{"element_type":"function","project_name":"finalHFtest","uuid":"de341aa9-0c27-41ad-a26f-67d822eca9e7","name":"main","imports":"['\"flag\"', '\"log\"', '\"os\"', '\"golang.org\/x\/tools\/go\/packages\"']","structs":"","interfaces":"","file_location":"github.com\/finalHFtest\/\/tmp\/repos\/example\/gotypes\/hugeparam\/main.go","code":"func main() {\n\tflag.Parse()\n\n\t\/\/ Load complete type information for the specified packages,\n\t\/\/ along with type-annotated syntax and the \"sizeof\" function.\n\t\/\/ Types for dependencies are loaded from export data.\n\tconf := &packages.Config{Mode: packages.LoadSyntax}\n\tpkgs, err := packages.Load(conf, flag.Args()...)\n\tif err != nil {\n\t\tlog.Fatal(err) \/\/ failed to load anything\n\t}\n\tif packages.PrintErrors(pkgs) > 0 {\n\t\tos.Exit(1) \/\/ some packages contained errors\n\t}\n\n\tfor _, pkg := range pkgs {\n\t\tPrintHugeParams(pkg.Fset, pkg.TypesInfo, pkg.TypesSizes, pkg.Syntax)\n\t}\n}","global_vars":"","package":"main","tags":""} |
|
{"element_type":"file","project_name":"finalHFtest","uuid":"1ddd3d33-d2be-4c54-9159-0ad9a7c8de87","name":"main.go","imports":"import (\n\t\"fmt\"\n\t\"go\/ast\"\n\t\"go\/importer\"\n\t\"go\/parser\"\n\t\"go\/token\"\n\t\"go\/types\"\n\t\"log\"\n)","structs":"","interfaces":"","file_location":"github.com\/finalHFtest\/\/tmp\/repos\/example\/gotypes\/implements\/main.go","code":"package main\n\nimport (\n\t\"fmt\"\n\t\"go\/ast\"\n\t\"go\/importer\"\n\t\"go\/parser\"\n\t\"go\/token\"\n\t\"go\/types\"\n\t\"log\"\n)\n\n\/\/ !+input\nconst input = `package main\n\ntype A struct{}\nfunc (*A) f()\n\ntype B int\nfunc (B) f()\nfunc (*B) g()\n\ntype I interface { f() }\ntype J interface { g() }\n`\n\n\/\/!-input\n\nfunc main() {\n\t\/\/ Parse one file.\n\tfset := token.NewFileSet()\n\tf, err := parser.ParseFile(fset, \"input.go\", input, 0)\n\tif err != nil {\n\t\tlog.Fatal(err) \/\/ parse error\n\t}\n\tconf := types.Config{Importer: importer.Default()}\n\tpkg, err := conf.Check(\"hello\", fset, []*ast.File{f}, nil)\n\tif err != nil {\n\t\tlog.Fatal(err) \/\/ type error\n\t}\n\n\t\/\/!+implements\n\t\/\/ Find all named types at package level.\n\tvar allNamed []*types.Named\n\tfor _, name := range pkg.Scope().Names() {\n\t\tif obj, ok := pkg.Scope().Lookup(name).(*types.TypeName); ok {\n\t\t\tallNamed = append(allNamed, obj.Type().(*types.Named))\n\t\t}\n\t}\n\n\t\/\/ Test assignability of all distinct pairs of\n\t\/\/ named types (T, U) where U is an interface.\n\tfor _, T := range allNamed {\n\t\tfor _, U := range allNamed {\n\t\t\tif T == U || !types.IsInterface(U) {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif types.AssignableTo(T, U) {\n\t\t\t\tfmt.Printf(\"%s satisfies %s\\n\", T, U)\n\t\t\t} else if !types.IsInterface(T) &&\n\t\t\t\ttypes.AssignableTo(types.NewPointer(T), U) {\n\t\t\t\tfmt.Printf(\"%s satisfies %s\\n\", types.NewPointer(T), U)\n\t\t\t}\n\t\t}\n\t}\n\t\/\/!-implements\n}\n\n\/*\n\/\/!+output\n$ go build golang.org\/x\/example\/gotypes\/implements\n$ .\/implements\n*hello.A satisfies hello.I\nhello.B satisfies hello.I\n*hello.B satisfies hello.J\n\/\/!-output\n*\/\n","global_vars":"","package":"package main","tags":""} |
|
{"element_type":"function","project_name":"finalHFtest","uuid":"9b038aed-ae81-4429-9888-e01ca0bc0eb7","name":"main","imports":"['\"fmt\"', '\"go\/ast\"', '\"go\/importer\"', '\"go\/parser\"', '\"go\/token\"', '\"go\/types\"', '\"log\"']","structs":"","interfaces":"","file_location":"github.com\/finalHFtest\/\/tmp\/repos\/example\/gotypes\/implements\/main.go","code":"func main() {\n\t\/\/ Parse one file.\n\tfset := token.NewFileSet()\n\tf, err := parser.ParseFile(fset, \"input.go\", input, 0)\n\tif err != nil {\n\t\tlog.Fatal(err) \/\/ parse error\n\t}\n\tconf := types.Config{Importer: importer.Default()}\n\tpkg, err := conf.Check(\"hello\", fset, []*ast.File{f}, nil)\n\tif err != nil {\n\t\tlog.Fatal(err) \/\/ type error\n\t}\n\n\t\/\/!+implements\n\t\/\/ Find all named types at package level.\n\tvar allNamed []*types.Named\n\tfor _, name := range pkg.Scope().Names() {\n\t\tif obj, ok := pkg.Scope().Lookup(name).(*types.TypeName); ok {\n\t\t\tallNamed = append(allNamed, obj.Type().(*types.Named))\n\t\t}\n\t}\n\n\t\/\/ Test assignability of all distinct pairs of\n\t\/\/ named types (T, U) where U is an interface.\n\tfor _, T := range allNamed {\n\t\tfor _, U := range allNamed {\n\t\t\tif T == U || !types.IsInterface(U) {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif types.AssignableTo(T, U) {\n\t\t\t\tfmt.Printf(\"%s satisfies %s\\n\", T, U)\n\t\t\t} else if !types.IsInterface(T) &&\n\t\t\t\ttypes.AssignableTo(types.NewPointer(T), U) {\n\t\t\t\tfmt.Printf(\"%s satisfies %s\\n\", types.NewPointer(T), U)\n\t\t\t}\n\t\t}\n\t}\n\t\/\/!-implements\n}","global_vars":"","package":"main","tags":""} |
|
{"element_type":"file","project_name":"finalHFtest","uuid":"56d6ac89-3be6-463a-934c-742eb09e3b72","name":"lookup.go","imports":"import (\n\t\"fmt\"\n\t\"go\/ast\"\n\t\"go\/importer\"\n\t\"go\/parser\"\n\t\"go\/token\"\n\t\"go\/types\"\n\t\"log\"\n\t\"strings\"\n)","structs":"","interfaces":"","file_location":"github.com\/finalHFtest\/\/tmp\/repos\/example\/gotypes\/lookup\/lookup.go","code":"package main\n\nimport (\n\t\"fmt\"\n\t\"go\/ast\"\n\t\"go\/importer\"\n\t\"go\/parser\"\n\t\"go\/token\"\n\t\"go\/types\"\n\t\"log\"\n\t\"strings\"\n)\n\n\/\/ !+input\nconst hello = `\npackage main\n\nimport \"fmt\"\n\n\/\/ append\nfunc main() {\n \/\/ fmt\n fmt.Println(\"Hello, world\")\n \/\/ main\n main, x := 1, 2\n \/\/ main\n print(main, x)\n \/\/ x\n}\n\/\/ x\n`\n\n\/\/!-input\n\n\/\/ !+main\nfunc main() {\n\tfset := token.NewFileSet()\n\tf, err := parser.ParseFile(fset, \"hello.go\", hello, parser.ParseComments)\n\tif err != nil {\n\t\tlog.Fatal(err) \/\/ parse error\n\t}\n\n\tconf := types.Config{Importer: importer.Default()}\n\tpkg, err := conf.Check(\"cmd\/hello\", fset, []*ast.File{f}, nil)\n\tif err != nil {\n\t\tlog.Fatal(err) \/\/ type error\n\t}\n\n\t\/\/ Each comment contains a name.\n\t\/\/ Look up that name in the innermost scope enclosing the comment.\n\tfor _, comment := range f.Comments {\n\t\tpos := comment.Pos()\n\t\tname := strings.TrimSpace(comment.Text())\n\t\tfmt.Printf(\"At %s,\\t%q = \", fset.Position(pos), name)\n\t\tinner := pkg.Scope().Innermost(pos)\n\t\tif _, obj := inner.LookupParent(name, pos); obj != nil {\n\t\t\tfmt.Println(obj)\n\t\t} else {\n\t\t\tfmt.Println(\"not found\")\n\t\t}\n\t}\n}\n\n\/\/!-main\n\n\/*\n\/\/!+output\n$ go build golang.org\/x\/example\/gotypes\/lookup\n$ .\/lookup\nAt hello.go:6:1, \"append\" = builtin append\nAt hello.go:8:9, \"fmt\" = package fmt\nAt hello.go:10:9, \"main\" = func cmd\/hello.main()\nAt hello.go:12:9, \"main\" = var main int\nAt hello.go:14:9, \"x\" = var x int\nAt hello.go:16:1, \"x\" = not found\n\/\/!-output\n*\/\n","global_vars":"","package":"package main","tags":""} |
|
{"element_type":"function","project_name":"finalHFtest","uuid":"4b21ef99-aa64-4588-894b-7936735e21aa","name":"main","imports":"['\"fmt\"', '\"go\/ast\"', '\"go\/importer\"', '\"go\/parser\"', '\"go\/token\"', '\"go\/types\"', '\"log\"', '\"strings\"']","structs":"","interfaces":"","file_location":"github.com\/finalHFtest\/\/tmp\/repos\/example\/gotypes\/lookup\/lookup.go","code":"func main() {\n\tfset := token.NewFileSet()\n\tf, err := parser.ParseFile(fset, \"hello.go\", hello, parser.ParseComments)\n\tif err != nil {\n\t\tlog.Fatal(err) \/\/ parse error\n\t}\n\n\tconf := types.Config{Importer: importer.Default()}\n\tpkg, err := conf.Check(\"cmd\/hello\", fset, []*ast.File{f}, nil)\n\tif err != nil {\n\t\tlog.Fatal(err) \/\/ type error\n\t}\n\n\t\/\/ Each comment contains a name.\n\t\/\/ Look up that name in the innermost scope enclosing the comment.\n\tfor _, comment := range f.Comments {\n\t\tpos := comment.Pos()\n\t\tname := strings.TrimSpace(comment.Text())\n\t\tfmt.Printf(\"At %s,\\t%q = \", fset.Position(pos), name)\n\t\tinner := pkg.Scope().Innermost(pos)\n\t\tif _, obj := inner.LookupParent(name, pos); obj != nil {\n\t\t\tfmt.Println(obj)\n\t\t} else {\n\t\t\tfmt.Println(\"not found\")\n\t\t}\n\t}\n}","global_vars":"","package":"main","tags":""} |
|
{"element_type":"file","project_name":"finalHFtest","uuid":"592c0e0c-f0b5-4ba5-a65a-3cbbe6c9938a","name":"main.go","imports":"import (\n\t\"fmt\"\n\t\"go\/ast\"\n\t\"go\/importer\"\n\t\"go\/parser\"\n\t\"go\/token\"\n\t\"go\/types\"\n\t\"log\"\n)","structs":"","interfaces":"","file_location":"github.com\/finalHFtest\/\/tmp\/repos\/example\/gotypes\/nilfunc\/main.go","code":"package main\n\nimport (\n\t\"fmt\"\n\t\"go\/ast\"\n\t\"go\/importer\"\n\t\"go\/parser\"\n\t\"go\/token\"\n\t\"go\/types\"\n\t\"log\"\n)\n\n\/\/ !+input\nconst input = `package main\n\nimport \"bytes\"\n\nfunc main() {\n\tvar buf bytes.Buffer\n\tif buf.Bytes == nil && bytes.Repeat != nil && main == nil {\n\t\t\/\/ ...\n\t}\n}\n`\n\n\/\/!-input\n\nvar fset = token.NewFileSet()\n\nfunc main() {\n\tf, err := parser.ParseFile(fset, \"input.go\", input, 0)\n\tif err != nil {\n\t\tlog.Fatal(err) \/\/ parse error\n\t}\n\tconf := types.Config{Importer: importer.Default()}\n\tinfo := &types.Info{\n\t\tDefs: make(map[*ast.Ident]types.Object),\n\t\tUses: make(map[*ast.Ident]types.Object),\n\t\tTypes: make(map[ast.Expr]types.TypeAndValue),\n\t}\n\tif _, err = conf.Check(\"cmd\/hello\", fset, []*ast.File{f}, info); err != nil {\n\t\tlog.Fatal(err) \/\/ type error\n\t}\n\n\tast.Inspect(f, func(n ast.Node) bool {\n\t\tif n != nil {\n\t\t\tCheckNilFuncComparison(info, n)\n\t\t}\n\t\treturn true\n\t})\n}\n\n\/\/ !+\n\/\/ CheckNilFuncComparison reports unintended comparisons\n\/\/ of functions against nil, e.g., \"if x.Method == nil {\".\nfunc CheckNilFuncComparison(info *types.Info, n ast.Node) {\n\te, ok := n.(*ast.BinaryExpr)\n\tif !ok {\n\t\treturn \/\/ not a binary operation\n\t}\n\tif e.Op != token.EQL && e.Op != token.NEQ {\n\t\treturn \/\/ not a comparison\n\t}\n\n\t\/\/ If this is a comparison against nil, find the other operand.\n\tvar other ast.Expr\n\tif info.Types[e.X].IsNil() {\n\t\tother = e.Y\n\t} else if info.Types[e.Y].IsNil() {\n\t\tother = e.X\n\t} else {\n\t\treturn \/\/ not a comparison against nil\n\t}\n\n\t\/\/ Find the object.\n\tvar obj types.Object\n\tswitch v := other.(type) {\n\tcase *ast.Ident:\n\t\tobj = info.Uses[v]\n\tcase *ast.SelectorExpr:\n\t\tobj = info.Uses[v.Sel]\n\tdefault:\n\t\treturn \/\/ not an identifier or selection\n\t}\n\n\tif _, ok := obj.(*types.Func); !ok {\n\t\treturn \/\/ not a function or method\n\t}\n\n\tfmt.Printf(\"%s: comparison of function %v %v nil is always %v\\n\",\n\t\tfset.Position(e.Pos()), obj.Name(), e.Op, e.Op == token.NEQ)\n}\n\n\/\/!-\n\n\/*\n\/\/!+output\n$ go build golang.org\/x\/example\/gotypes\/nilfunc\n$ .\/nilfunc\ninput.go:7:5: comparison of function Bytes == nil is always false\ninput.go:7:25: comparison of function Repeat != nil is always true\ninput.go:7:48: comparison of function main == nil is always false\n\/\/!-output\n*\/\n","global_vars":"","package":"package main","tags":""} |
|
{"element_type":"function","project_name":"finalHFtest","uuid":"5510105a-5a4e-4346-9824-0a1cd15c5527","name":"main","imports":"['\"go\/ast\"', '\"go\/importer\"', '\"go\/parser\"', '\"go\/types\"', '\"log\"']","structs":"","interfaces":"","file_location":"github.com\/finalHFtest\/\/tmp\/repos\/example\/gotypes\/nilfunc\/main.go","code":"func main() {\n\tf, err := parser.ParseFile(fset, \"input.go\", input, 0)\n\tif err != nil {\n\t\tlog.Fatal(err) \/\/ parse error\n\t}\n\tconf := types.Config{Importer: importer.Default()}\n\tinfo := &types.Info{\n\t\tDefs: make(map[*ast.Ident]types.Object),\n\t\tUses: make(map[*ast.Ident]types.Object),\n\t\tTypes: make(map[ast.Expr]types.TypeAndValue),\n\t}\n\tif _, err = conf.Check(\"cmd\/hello\", fset, []*ast.File{f}, info); err != nil {\n\t\tlog.Fatal(err) \/\/ type error\n\t}\n\n\tast.Inspect(f, func(n ast.Node) bool {\n\t\tif n != nil {\n\t\t\tCheckNilFuncComparison(info, n)\n\t\t}\n\t\treturn true\n\t})\n}","global_vars":"{'fset': 'token.NewFileSet()'}","package":"main","tags":""} |
|
{"element_type":"function","project_name":"finalHFtest","uuid":"88520da1-b835-425d-8863-3c63e5829e3f","name":"CheckNilFuncComparison","imports":"['\"fmt\"', '\"go\/ast\"', '\"go\/token\"', '\"go\/types\"']","structs":"","interfaces":"","file_location":"github.com\/finalHFtest\/\/tmp\/repos\/example\/gotypes\/nilfunc\/main.go","code":"func CheckNilFuncComparison(info *types.Info, n ast.Node) {\n\te, ok := n.(*ast.BinaryExpr)\n\tif !ok {\n\t\treturn \/\/ not a binary operation\n\t}\n\tif e.Op != token.EQL && e.Op != token.NEQ {\n\t\treturn \/\/ not a comparison\n\t}\n\n\t\/\/ If this is a comparison against nil, find the other operand.\n\tvar other ast.Expr\n\tif info.Types[e.X].IsNil() {\n\t\tother = e.Y\n\t} else if info.Types[e.Y].IsNil() {\n\t\tother = e.X\n\t} else {\n\t\treturn \/\/ not a comparison against nil\n\t}\n\n\t\/\/ Find the object.\n\tvar obj types.Object\n\tswitch v := other.(type) {\n\tcase *ast.Ident:\n\t\tobj = info.Uses[v]\n\tcase *ast.SelectorExpr:\n\t\tobj = info.Uses[v.Sel]\n\tdefault:\n\t\treturn \/\/ not an identifier or selection\n\t}\n\n\tif _, ok := obj.(*types.Func); !ok {\n\t\treturn \/\/ not a function or method\n\t}\n\n\tfmt.Printf(\"%s: comparison of function %v %v nil is always %v\\n\",\n\t\tfset.Position(e.Pos()), obj.Name(), e.Op, e.Op == token.NEQ)\n}","global_vars":"{'fset': 'token.NewFileSet()'}","package":"main","tags":""} |
|
{"element_type":"file","project_name":"finalHFtest","uuid":"51091e58-9637-49d7-83a3-16e9d90814f6","name":"main.go","imports":"import (\n\t\"fmt\"\n\t\"go\/ast\"\n\t\"go\/importer\"\n\t\"go\/parser\"\n\t\"go\/token\"\n\t\"go\/types\"\n\t\"log\"\n)","structs":"","interfaces":"","file_location":"github.com\/finalHFtest\/\/tmp\/repos\/example\/gotypes\/pkginfo\/main.go","code":"\/\/ !+\npackage main\n\nimport (\n\t\"fmt\"\n\t\"go\/ast\"\n\t\"go\/importer\"\n\t\"go\/parser\"\n\t\"go\/token\"\n\t\"go\/types\"\n\t\"log\"\n)\n\nconst hello = `package main\n\nimport \"fmt\"\n\nfunc main() {\n fmt.Println(\"Hello, world\")\n}`\n\nfunc main() {\n\tfset := token.NewFileSet()\n\n\t\/\/ Parse the input string, []byte, or io.Reader,\n\t\/\/ recording position information in fset.\n\t\/\/ ParseFile returns an *ast.File, a syntax tree.\n\tf, err := parser.ParseFile(fset, \"hello.go\", hello, 0)\n\tif err != nil {\n\t\tlog.Fatal(err) \/\/ parse error\n\t}\n\n\t\/\/ A Config controls various options of the type checker.\n\t\/\/ The defaults work fine except for one setting:\n\t\/\/ we must specify how to deal with imports.\n\tconf := types.Config{Importer: importer.Default()}\n\n\t\/\/ Type-check the package containing only file f.\n\t\/\/ Check returns a *types.Package.\n\tpkg, err := conf.Check(\"cmd\/hello\", fset, []*ast.File{f}, nil)\n\tif err != nil {\n\t\tlog.Fatal(err) \/\/ type error\n\t}\n\n\tfmt.Printf(\"Package %q\\n\", pkg.Path())\n\tfmt.Printf(\"Name: %s\\n\", pkg.Name())\n\tfmt.Printf(\"Imports: %s\\n\", pkg.Imports())\n\tfmt.Printf(\"Scope: %s\\n\", pkg.Scope())\n}\n\n\/\/!-\n\n\/*\n\/\/!+output\n$ go build golang.org\/x\/example\/gotypes\/pkginfo\n$ .\/pkginfo\nPackage \"cmd\/hello\"\nName: main\nImports: [package fmt (\"fmt\")]\nScope: package \"cmd\/hello\" scope 0x820533590 {\n. func cmd\/hello.main()\n}\n\/\/!-output\n*\/\n","global_vars":"","package":"package main","tags":""} |
|
{"element_type":"function","project_name":"finalHFtest","uuid":"87d68038-25de-4bff-9680-7714abe8f915","name":"main","imports":"['\"fmt\"', '\"go\/ast\"', '\"go\/importer\"', '\"go\/parser\"', '\"go\/token\"', '\"go\/types\"', '\"log\"']","structs":"","interfaces":"","file_location":"github.com\/finalHFtest\/\/tmp\/repos\/example\/gotypes\/pkginfo\/main.go","code":"func main() {\n\tfset := token.NewFileSet()\n\n\t\/\/ Parse the input string, []byte, or io.Reader,\n\t\/\/ recording position information in fset.\n\t\/\/ ParseFile returns an *ast.File, a syntax tree.\n\tf, err := parser.ParseFile(fset, \"hello.go\", hello, 0)\n\tif err != nil {\n\t\tlog.Fatal(err) \/\/ parse error\n\t}\n\n\t\/\/ A Config controls various options of the type checker.\n\t\/\/ The defaults work fine except for one setting:\n\t\/\/ we must specify how to deal with imports.\n\tconf := types.Config{Importer: importer.Default()}\n\n\t\/\/ Type-check the package containing only file f.\n\t\/\/ Check returns a *types.Package.\n\tpkg, err := conf.Check(\"cmd\/hello\", fset, []*ast.File{f}, nil)\n\tif err != nil {\n\t\tlog.Fatal(err) \/\/ type error\n\t}\n\n\tfmt.Printf(\"Package %q\\n\", pkg.Path())\n\tfmt.Printf(\"Name: %s\\n\", pkg.Name())\n\tfmt.Printf(\"Imports: %s\\n\", pkg.Imports())\n\tfmt.Printf(\"Scope: %s\\n\", pkg.Scope())\n}","global_vars":"","package":"main","tags":""} |
|
{"element_type":"file","project_name":"finalHFtest","uuid":"a80de6d2-69af-45e5-b3a7-7508083a65ed","name":"main.go","imports":"import (\n\t\"fmt\"\n\t\"go\/types\"\n\t\"log\"\n\t\"os\"\n\t\"strings\"\n\t\"unicode\"\n\t\"unicode\/utf8\"\n\n\t\"golang.org\/x\/tools\/go\/packages\"\n)","structs":"","interfaces":"","file_location":"github.com\/finalHFtest\/\/tmp\/repos\/example\/gotypes\/skeleton\/main.go","code":"\/\/ The skeleton command prints the boilerplate for a concrete type\n\/\/ that implements the specified interface type.\n\/\/\n\/\/ Example:\n\/\/\n\/\/\t$ .\/skeleton io ReadWriteCloser buffer\n\/\/\t\/\/ *buffer implements io.ReadWriteCloser.\n\/\/\ttype buffer struct{ \/* ... *\/ }\n\/\/\tfunc (b *buffer) Close() error { panic(\"unimplemented\") }\n\/\/\tfunc (b *buffer) Read(p []byte) (n int, err error) { panic(\"unimplemented\") }\n\/\/\tfunc (b *buffer) Write(p []byte) (n int, err error) { panic(\"unimplemented\") }\npackage main\n\nimport (\n\t\"fmt\"\n\t\"go\/types\"\n\t\"log\"\n\t\"os\"\n\t\"strings\"\n\t\"unicode\"\n\t\"unicode\/utf8\"\n\n\t\"golang.org\/x\/tools\/go\/packages\"\n)\n\nconst usage = \"Usage: skeleton <package> <interface> <concrete>\"\n\n\/\/ !+\nfunc PrintSkeleton(pkg *types.Package, ifacename, concname string) error {\n\tobj := pkg.Scope().Lookup(ifacename)\n\tif obj == nil {\n\t\treturn fmt.Errorf(\"%s.%s not found\", pkg.Path(), ifacename)\n\t}\n\tif _, ok := obj.(*types.TypeName); !ok {\n\t\treturn fmt.Errorf(\"%v is not a named type\", obj)\n\t}\n\tiface, ok := obj.Type().Underlying().(*types.Interface)\n\tif !ok {\n\t\treturn fmt.Errorf(\"type %v is a %T, not an interface\",\n\t\t\tobj, obj.Type().Underlying())\n\t}\n\t\/\/ Use first letter of type name as receiver parameter.\n\tif !isValidIdentifier(concname) {\n\t\treturn fmt.Errorf(\"invalid concrete type name: %q\", concname)\n\t}\n\tr, _ := utf8.DecodeRuneInString(concname)\n\n\tfmt.Printf(\"\/\/ *%s implements %s.%s.\\n\", concname, pkg.Path(), ifacename)\n\tfmt.Printf(\"type %s struct{}\\n\", concname)\n\tmset := types.NewMethodSet(iface)\n\tfor i := 0; i < mset.Len(); i++ {\n\t\tmeth := mset.At(i).Obj()\n\t\tsig := types.TypeString(meth.Type(), (*types.Package).Name)\n\t\tfmt.Printf(\"func (%c *%s) %s%s {\\n\\tpanic(\\\"unimplemented\\\")\\n}\\n\",\n\t\t\tr, concname, meth.Name(),\n\t\t\tstrings.TrimPrefix(sig, \"func\"))\n\t}\n\treturn nil\n}\n\n\/\/!-\n\nfunc isValidIdentifier(id string) bool {\n\tfor i, r := range id {\n\t\tif !unicode.IsLetter(r) &&\n\t\t\t!(i > 0 && unicode.IsDigit(r)) {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn id != \"\"\n}\n\nfunc main() {\n\tif len(os.Args) != 4 {\n\t\tlog.Fatal(usage)\n\t}\n\tpkgpath, ifacename, concname := os.Args[1], os.Args[2], os.Args[3]\n\n\t\/\/ Load only exported type information for the specified package.\n\tconf := &packages.Config{Mode: packages.NeedTypes}\n\tpkgs, err := packages.Load(conf, pkgpath)\n\tif err != nil {\n\t\tlog.Fatal(err) \/\/ failed to load anything\n\t}\n\tif packages.PrintErrors(pkgs) > 0 {\n\t\tos.Exit(1) \/\/ some packages contained errors\n\t}\n\tif err := PrintSkeleton(pkgs[0].Types, ifacename, concname); err != nil {\n\t\tlog.Fatal(err)\n\t}\n}\n\n\/*\n\/\/!+output1\n$ .\/skeleton io ReadWriteCloser buffer\n\/\/ *buffer implements io.ReadWriteCloser.\ntype buffer struct{}\nfunc (b *buffer) Close() error {\n\tpanic(\"unimplemented\")\n}\nfunc (b *buffer) Read(p []byte) (n int, err error) {\n\tpanic(\"unimplemented\")\n}\nfunc (b *buffer) Write(p []byte) (n int, err error) {\n\tpanic(\"unimplemented\")\n}\n\/\/!-output1\n\n\/\/!+output2\n$ .\/skeleton net\/http Handler myHandler\n\/\/ *myHandler implements net\/http.Handler.\ntype myHandler struct{}\nfunc (m *myHandler) ServeHTTP(http.ResponseWriter, *http.Request) {\n\tpanic(\"unimplemented\")\n}\n\/\/!-output2\n*\/\n","global_vars":"","package":"package main","tags":""} |
|
{"element_type":"function","project_name":"finalHFtest","uuid":"645f3b99-d979-45b4-8285-984d15f478b5","name":"PrintSkeleton","imports":"['\"fmt\"', '\"go\/types\"', '\"strings\"', '\"unicode\/utf8\"']","structs":"","interfaces":"","file_location":"github.com\/finalHFtest\/\/tmp\/repos\/example\/gotypes\/skeleton\/main.go","code":"func PrintSkeleton(pkg *types.Package, ifacename, concname string) error {\n\tobj := pkg.Scope().Lookup(ifacename)\n\tif obj == nil {\n\t\treturn fmt.Errorf(\"%s.%s not found\", pkg.Path(), ifacename)\n\t}\n\tif _, ok := obj.(*types.TypeName); !ok {\n\t\treturn fmt.Errorf(\"%v is not a named type\", obj)\n\t}\n\tiface, ok := obj.Type().Underlying().(*types.Interface)\n\tif !ok {\n\t\treturn fmt.Errorf(\"type %v is a %T, not an interface\",\n\t\t\tobj, obj.Type().Underlying())\n\t}\n\t\/\/ Use first letter of type name as receiver parameter.\n\tif !isValidIdentifier(concname) {\n\t\treturn fmt.Errorf(\"invalid concrete type name: %q\", concname)\n\t}\n\tr, _ := utf8.DecodeRuneInString(concname)\n\n\tfmt.Printf(\"\/\/ *%s implements %s.%s.\\n\", concname, pkg.Path(), ifacename)\n\tfmt.Printf(\"type %s struct{}\\n\", concname)\n\tmset := types.NewMethodSet(iface)\n\tfor i := 0; i < mset.Len(); i++ {\n\t\tmeth := mset.At(i).Obj()\n\t\tsig := types.TypeString(meth.Type(), (*types.Package).Name)\n\t\tfmt.Printf(\"func (%c *%s) %s%s {\\n\\tpanic(\\\"unimplemented\\\")\\n}\\n\",\n\t\t\tr, concname, meth.Name(),\n\t\t\tstrings.TrimPrefix(sig, \"func\"))\n\t}\n\treturn nil\n}","global_vars":"","package":"main","tags":""} |
|
{"element_type":"function","project_name":"finalHFtest","uuid":"b46089a3-4f67-4f1a-95f6-2a4cd8b9388c","name":"isValidIdentifier","imports":"['\"unicode\"']","structs":"","interfaces":"","file_location":"github.com\/finalHFtest\/\/tmp\/repos\/example\/gotypes\/skeleton\/main.go","code":"func isValidIdentifier(id string) bool {\n\tfor i, r := range id {\n\t\tif !unicode.IsLetter(r) &&\n\t\t\t!(i > 0 && unicode.IsDigit(r)) {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn id != \"\"\n}","global_vars":"","package":"main","tags":""} |
|
{"element_type":"function","project_name":"finalHFtest","uuid":"96572b3f-a139-4d80-a404-5b6f615aa4b4","name":"main","imports":"['\"log\"', '\"os\"', '\"golang.org\/x\/tools\/go\/packages\"']","structs":"","interfaces":"","file_location":"github.com\/finalHFtest\/\/tmp\/repos\/example\/gotypes\/skeleton\/main.go","code":"func main() {\n\tif len(os.Args) != 4 {\n\t\tlog.Fatal(usage)\n\t}\n\tpkgpath, ifacename, concname := os.Args[1], os.Args[2], os.Args[3]\n\n\t\/\/ Load only exported type information for the specified package.\n\tconf := &packages.Config{Mode: packages.NeedTypes}\n\tpkgs, err := packages.Load(conf, pkgpath)\n\tif err != nil {\n\t\tlog.Fatal(err) \/\/ failed to load anything\n\t}\n\tif packages.PrintErrors(pkgs) > 0 {\n\t\tos.Exit(1) \/\/ some packages contained errors\n\t}\n\tif err := PrintSkeleton(pkgs[0].Types, ifacename, concname); err != nil {\n\t\tlog.Fatal(err)\n\t}\n}","global_vars":"","package":"main","tags":""} |
|
{"element_type":"file","project_name":"finalHFtest","uuid":"97fbb4ba-090f-475e-9b1f-aea2054b8d19","name":"main.go","imports":"import (\n\t\"bytes\"\n\t\"fmt\"\n\t\"go\/ast\"\n\t\"go\/format\"\n\t\"go\/importer\"\n\t\"go\/parser\"\n\t\"go\/token\"\n\t\"go\/types\"\n\t\"log\"\n)","structs":"","interfaces":"","file_location":"github.com\/finalHFtest\/\/tmp\/repos\/example\/gotypes\/typeandvalue\/main.go","code":"package main\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n\t\"go\/ast\"\n\t\"go\/format\"\n\t\"go\/importer\"\n\t\"go\/parser\"\n\t\"go\/token\"\n\t\"go\/types\"\n\t\"log\"\n)\n\n\/\/ !+input\nconst input = `\npackage main\n\nvar m = make(map[string]int)\n\nfunc main() {\n\tv, ok := m[\"hello, \" + \"world\"]\n\tprint(rune(v), ok)\n}\n`\n\n\/\/!-input\n\nvar fset = token.NewFileSet()\n\nfunc main() {\n\tf, err := parser.ParseFile(fset, \"hello.go\", input, 0)\n\tif err != nil {\n\t\tlog.Fatal(err) \/\/ parse error\n\t}\n\n\tconf := types.Config{Importer: importer.Default()}\n\tinfo := &types.Info{Types: make(map[ast.Expr]types.TypeAndValue)}\n\tif _, err := conf.Check(\"cmd\/hello\", fset, []*ast.File{f}, info); err != nil {\n\t\tlog.Fatal(err) \/\/ type error\n\t}\n\n\t\/\/!+inspect\n\t\/\/ f is a parsed, type-checked *ast.File.\n\tast.Inspect(f, func(n ast.Node) bool {\n\t\tif expr, ok := n.(ast.Expr); ok {\n\t\t\tif tv, ok := info.Types[expr]; ok {\n\t\t\t\tfmt.Printf(\"%-24s\\tmode: %s\\n\", nodeString(expr), mode(tv))\n\t\t\t\tfmt.Printf(\"\\t\\t\\t\\ttype: %v\\n\", tv.Type)\n\t\t\t\tif tv.Value != nil {\n\t\t\t\t\tfmt.Printf(\"\\t\\t\\t\\tvalue: %v\\n\", tv.Value)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn true\n\t})\n\t\/\/!-inspect\n}\n\n\/\/ nodeString formats a syntax tree in the style of gofmt.\nfunc nodeString(n ast.Node) string {\n\tvar buf bytes.Buffer\n\tformat.Node(&buf, fset, n)\n\treturn buf.String()\n}\n\n\/\/ mode returns a string describing the mode of an expression.\nfunc mode(tv types.TypeAndValue) string {\n\ts := \"\"\n\tif tv.IsVoid() {\n\t\ts += \",void\"\n\t}\n\tif tv.IsType() {\n\t\ts += \",type\"\n\t}\n\tif tv.IsBuiltin() {\n\t\ts += \",builtin\"\n\t}\n\tif tv.IsValue() {\n\t\ts += \",value\"\n\t}\n\tif tv.IsNil() {\n\t\ts += \",nil\"\n\t}\n\tif tv.Addressable() {\n\t\ts += \",addressable\"\n\t}\n\tif tv.Assignable() {\n\t\ts += \",assignable\"\n\t}\n\tif tv.HasOk() {\n\t\ts += \",ok\"\n\t}\n\treturn s[1:]\n}\n\n\/*\n\/\/!+output\n$ go build golang.org\/x\/example\/gotypes\/typeandvalue\n$ .\/typeandvalue\nmake(map[string]int) mode: value\n type: map[string]int\nmake mode: builtin\n type: func(map[string]int) map[string]int\nmap[string]int mode: type\n type: map[string]int\nstring mode: type\n type: string\nint mode: type\n type: int\nm[\"hello, \"+\"world\"] mode: value,assignable,ok\n type: (int, bool)\nm mode: value,addressable,assignable\n type: map[string]int\n\"hello, \" + \"world\" mode: value\n type: string\n value: \"hello, world\"\n\"hello, \" mode: value\n type: untyped string\n value: \"hello, \"\n\"world\" mode: value\n type: untyped string\n value: \"world\"\nprint(rune(v), ok) mode: void\n type: ()\nprint mode: builtin\n type: func(rune, bool)\nrune(v) mode: value\n type: rune\nrune mode: type\n type: rune\n...more not shown...\n\/\/!-output\n*\/\n","global_vars":"","package":"package main","tags":""} |
|
{"element_type":"function","project_name":"finalHFtest","uuid":"3674270f-a944-48bc-834b-e55ffe6eda78","name":"main","imports":"['\"fmt\"', '\"go\/ast\"', '\"go\/importer\"', '\"go\/parser\"', '\"go\/types\"', '\"log\"']","structs":"","interfaces":"","file_location":"github.com\/finalHFtest\/\/tmp\/repos\/example\/gotypes\/typeandvalue\/main.go","code":"func main() {\n\tf, err := parser.ParseFile(fset, \"hello.go\", input, 0)\n\tif err != nil {\n\t\tlog.Fatal(err) \/\/ parse error\n\t}\n\n\tconf := types.Config{Importer: importer.Default()}\n\tinfo := &types.Info{Types: make(map[ast.Expr]types.TypeAndValue)}\n\tif _, err := conf.Check(\"cmd\/hello\", fset, []*ast.File{f}, info); err != nil {\n\t\tlog.Fatal(err) \/\/ type error\n\t}\n\n\t\/\/!+inspect\n\t\/\/ f is a parsed, type-checked *ast.File.\n\tast.Inspect(f, func(n ast.Node) bool {\n\t\tif expr, ok := n.(ast.Expr); ok {\n\t\t\tif tv, ok := info.Types[expr]; ok {\n\t\t\t\tfmt.Printf(\"%-24s\\tmode: %s\\n\", nodeString(expr), mode(tv))\n\t\t\t\tfmt.Printf(\"\\t\\t\\t\\ttype: %v\\n\", tv.Type)\n\t\t\t\tif tv.Value != nil {\n\t\t\t\t\tfmt.Printf(\"\\t\\t\\t\\tvalue: %v\\n\", tv.Value)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn true\n\t})\n\t\/\/!-inspect\n}","global_vars":"{'fset': 'token.NewFileSet()'}","package":"main","tags":""} |
|
{"element_type":"function","project_name":"finalHFtest","uuid":"fa26bf63-5336-4c48-b331-5c63a19bff72","name":"nodeString","imports":"['\"bytes\"', '\"go\/ast\"', '\"go\/format\"']","structs":"","interfaces":"","file_location":"github.com\/finalHFtest\/\/tmp\/repos\/example\/gotypes\/typeandvalue\/main.go","code":"func nodeString(n ast.Node) string {\n\tvar buf bytes.Buffer\n\tformat.Node(&buf, fset, n)\n\treturn buf.String()\n}","global_vars":"{'fset': 'token.NewFileSet()'}","package":"main","tags":""} |
|
{"element_type":"function","project_name":"finalHFtest","uuid":"a4b0168c-df1f-4894-8867-0da2f590a328","name":"mode","imports":"['\"go\/types\"']","structs":"","interfaces":"","file_location":"github.com\/finalHFtest\/\/tmp\/repos\/example\/gotypes\/typeandvalue\/main.go","code":"func mode(tv types.TypeAndValue) string {\n\ts := \"\"\n\tif tv.IsVoid() {\n\t\ts += \",void\"\n\t}\n\tif tv.IsType() {\n\t\ts += \",type\"\n\t}\n\tif tv.IsBuiltin() {\n\t\ts += \",builtin\"\n\t}\n\tif tv.IsValue() {\n\t\ts += \",value\"\n\t}\n\tif tv.IsNil() {\n\t\ts += \",nil\"\n\t}\n\tif tv.Addressable() {\n\t\ts += \",addressable\"\n\t}\n\tif tv.Assignable() {\n\t\ts += \",assignable\"\n\t}\n\tif tv.HasOk() {\n\t\ts += \",ok\"\n\t}\n\treturn s[1:]\n}","global_vars":"","package":"main","tags":""} |
|
{"element_type":"file","project_name":"finalHFtest","uuid":"ea1958a0-2db5-4bce-b8f6-599c5712f3a3","name":"hello.go","imports":"import (\n\t\"flag\"\n\t\"fmt\"\n\t\"log\"\n\t\"os\"\n\n\t\"golang.org\/x\/example\/hello\/reverse\"\n)","structs":"","interfaces":"","file_location":"github.com\/finalHFtest\/\/tmp\/repos\/example\/hello\/hello.go","code":"\/\/ Copyright 2023 The Go Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style\n\/\/ license that can be found in the LICENSE file.\n\n\/\/ Hello is a hello, world program, demonstrating\n\/\/ how to write a simple command-line program.\n\/\/\n\/\/ Usage:\n\/\/\n\/\/\thello [options] [name]\n\/\/\n\/\/ The options are:\n\/\/\n\/\/\t-g greeting\n\/\/\t\tGreet with the given greeting, instead of \"Hello\".\n\/\/\n\/\/\t-r\n\/\/\t\tGreet in reverse.\n\/\/\n\/\/ By default, hello greets the world.\n\/\/ If a name is specified, hello greets that name instead.\npackage main\n\nimport (\n\t\"flag\"\n\t\"fmt\"\n\t\"log\"\n\t\"os\"\n\n\t\"golang.org\/x\/example\/hello\/reverse\"\n)\n\nfunc usage() {\n\tfmt.Fprintf(os.Stderr, \"usage: hello [options] [name]\\n\")\n\tflag.PrintDefaults()\n\tos.Exit(2)\n}\n\nvar (\n\tgreeting = flag.String(\"g\", \"Hello\", \"Greet with `greeting`\")\n\treverseFlag = flag.Bool(\"r\", false, \"Greet in reverse\")\n)\n\nfunc main() {\n\t\/\/ Configure logging for a command-line program.\n\tlog.SetFlags(0)\n\tlog.SetPrefix(\"hello: \")\n\n\t\/\/ Parse flags.\n\tflag.Usage = usage\n\tflag.Parse()\n\n\t\/\/ Parse and validate arguments.\n\tname := \"world\"\n\targs := flag.Args()\n\tif len(args) >= 2 {\n\t\tusage()\n\t}\n\tif len(args) >= 1 {\n\t\tname = args[0]\n\t}\n\tif name == \"\" { \/\/ hello '' is an error\n\t\tlog.Fatalf(\"invalid name %q\", name)\n\t}\n\n\t\/\/ Run actual logic.\n\tif *reverseFlag {\n\t\tfmt.Printf(\"%s, %s!\\n\", reverse.String(*greeting), reverse.String(name))\n\t\treturn\n\t}\n\tfmt.Printf(\"%s, %s!\\n\", *greeting, name)\n}\n","global_vars":"","package":"package main","tags":""} |
|
{"element_type":"function","project_name":"finalHFtest","uuid":"dd5a7b4a-aad7-42ff-8036-7f3f7343559c","name":"usage","imports":"['\"flag\"', '\"fmt\"', '\"os\"']","structs":"","interfaces":"","file_location":"github.com\/finalHFtest\/\/tmp\/repos\/example\/hello\/hello.go","code":"func usage() {\n\tfmt.Fprintf(os.Stderr, \"usage: hello [options] [name]\\n\")\n\tflag.PrintDefaults()\n\tos.Exit(2)\n}","global_vars":"","package":"main","tags":""} |
|
{"element_type":"function","project_name":"finalHFtest","uuid":"be0401e6-f81c-49e9-a3ea-5e261e730d29","name":"main","imports":"['\"flag\"', '\"fmt\"', '\"log\"', '\"golang.org\/x\/example\/hello\/reverse\"']","structs":"","interfaces":"","file_location":"github.com\/finalHFtest\/\/tmp\/repos\/example\/hello\/hello.go","code":"func main() {\n\t\/\/ Configure logging for a command-line program.\n\tlog.SetFlags(0)\n\tlog.SetPrefix(\"hello: \")\n\n\t\/\/ Parse flags.\n\tflag.Usage = usage\n\tflag.Parse()\n\n\t\/\/ Parse and validate arguments.\n\tname := \"world\"\n\targs := flag.Args()\n\tif len(args) >= 2 {\n\t\tusage()\n\t}\n\tif len(args) >= 1 {\n\t\tname = args[0]\n\t}\n\tif name == \"\" { \/\/ hello '' is an error\n\t\tlog.Fatalf(\"invalid name %q\", name)\n\t}\n\n\t\/\/ Run actual logic.\n\tif *reverseFlag {\n\t\tfmt.Printf(\"%s, %s!\\n\", reverse.String(*greeting), reverse.String(name))\n\t\treturn\n\t}\n\tfmt.Printf(\"%s, %s!\\n\", *greeting, name)\n}","global_vars":"","package":"main","tags":""} |
|
{"element_type":"file","project_name":"finalHFtest","uuid":"9ebfa7f4-d6b9-43f4-bece-9bd5704dc7f5","name":"example_test.go","imports":"import (\n\t\"fmt\"\n\n\t\"golang.org\/x\/example\/hello\/reverse\"\n)","structs":"","interfaces":"","file_location":"github.com\/finalHFtest\/\/tmp\/repos\/example\/hello\/reverse\/example_test.go","code":"\/\/ Copyright 2023 The Go Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style\n\/\/ license that can be found in the LICENSE file.\n\npackage reverse_test\n\nimport (\n\t\"fmt\"\n\n\t\"golang.org\/x\/example\/hello\/reverse\"\n)\n\nfunc ExampleString() {\n\tfmt.Println(reverse.String(\"hello\"))\n\t\/\/ Output: olleh\n}\n","global_vars":"","package":"package reverse_test","tags":""} |
|
{"element_type":"function","project_name":"finalHFtest","uuid":"6cd3514d-d99c-43d4-b8e6-30b4f1c677ce","name":"ExampleString","imports":"['\"fmt\"', '\"golang.org\/x\/example\/hello\/reverse\"']","structs":"","interfaces":"","file_location":"github.com\/finalHFtest\/\/tmp\/repos\/example\/hello\/reverse\/example_test.go","code":"func ExampleString() {\n\tfmt.Println(reverse.String(\"hello\"))\n\t\/\/ Output: olleh\n}","global_vars":"","package":"reverse_test","tags":""} |
|
{"element_type":"file","project_name":"finalHFtest","uuid":"4da1091a-bafb-4a5a-b21f-0837a7ecf5f2","name":"reverse.go","imports":"","structs":"","interfaces":"","file_location":"github.com\/finalHFtest\/\/tmp\/repos\/example\/hello\/reverse\/reverse.go","code":"\/\/ Copyright 2023 The Go Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style\n\/\/ license that can be found in the LICENSE file.\n\n\/\/ Package reverse can reverse things, particularly strings.\npackage reverse\n\n\/\/ String returns its argument string reversed rune-wise left to right.\nfunc String(s string) string {\n\tr := []rune(s)\n\tfor i, j := 0, len(r)-1; i < len(r)\/2; i, j = i+1, j-1 {\n\t\tr[i], r[j] = r[j], r[i]\n\t}\n\treturn string(r)\n}\n","global_vars":"","package":"package reverse","tags":""} |
|
{"element_type":"function","project_name":"finalHFtest","uuid":"91238e00-4e9e-45f0-bcee-6f359bb537c4","name":"String","imports":"","structs":"","interfaces":"","file_location":"github.com\/finalHFtest\/\/tmp\/repos\/example\/hello\/reverse\/reverse.go","code":"func String(s string) string {\n\tr := []rune(s)\n\tfor i, j := 0, len(r)-1; i < len(r)\/2; i, j = i+1, j-1 {\n\t\tr[i], r[j] = r[j], r[i]\n\t}\n\treturn string(r)\n}","global_vars":"","package":"reverse","tags":""} |
|
{"element_type":"file","project_name":"finalHFtest","uuid":"3edd7c80-f9af-46cb-9452-82bb0967273a","name":"reverse_test.go","imports":"import \"testing\"","structs":"","interfaces":"","file_location":"github.com\/finalHFtest\/\/tmp\/repos\/example\/hello\/reverse\/reverse_test.go","code":"\/\/ Copyright 2023 The Go Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style\n\/\/ license that can be found in the LICENSE file.\n\npackage reverse\n\nimport \"testing\"\n\nfunc TestString(t *testing.T) {\n\tfor _, c := range []struct {\n\t\tin, want string\n\t}{\n\t\t{\"Hello, world\", \"dlrow ,olleH\"},\n\t\t{\"Hello, \u4e16\u754c\", \"\u754c\u4e16 ,olleH\"},\n\t\t{\"\", \"\"},\n\t} {\n\t\tgot := String(c.in)\n\t\tif got != c.want {\n\t\t\tt.Errorf(\"String(%q) == %q, want %q\", c.in, got, c.want)\n\t\t}\n\t}\n}\n","global_vars":"","package":"package reverse","tags":""} |
|
{"element_type":"function","project_name":"finalHFtest","uuid":"5e06968c-9321-40dc-bfcc-8e3097d09c36","name":"TestString","imports":"","structs":"","interfaces":"","file_location":"github.com\/finalHFtest\/\/tmp\/repos\/example\/hello\/reverse\/reverse_test.go","code":"func TestString(t *testing.T) {\n\tfor _, c := range []struct {\n\t\tin, want string\n\t}{\n\t\t{\"Hello, world\", \"dlrow ,olleH\"},\n\t\t{\"Hello, \u4e16\u754c\", \"\u754c\u4e16 ,olleH\"},\n\t\t{\"\", \"\"},\n\t} {\n\t\tgot := String(c.in)\n\t\tif got != c.want {\n\t\t\tt.Errorf(\"String(%q) == %q, want %q\", c.in, got, c.want)\n\t\t}\n\t}\n}","global_vars":"","package":"reverse","tags":""} |
|
{"element_type":"file","project_name":"finalHFtest","uuid":"99e0006a-2b79-4559-b2e8-ffa611f0e7e6","name":"server.go","imports":"import (\n\t\"flag\"\n\t\"fmt\"\n\t\"html\"\n\t\"log\"\n\t\"net\/http\"\n\t\"os\"\n\t\"runtime\/debug\"\n\t\"strings\"\n)","structs":"","interfaces":"","file_location":"github.com\/finalHFtest\/\/tmp\/repos\/example\/helloserver\/server.go","code":"\/\/ Copyright 2023 The Go Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style\n\/\/ license that can be found in the LICENSE file.\n\n\/\/ Hello is a simple hello, world demonstration web server.\n\/\/\n\/\/ It serves version information on \/version and answers\n\/\/ any other request like \/name by saying \"Hello, name!\".\n\/\/\n\/\/ See golang.org\/x\/example\/outyet for a more sophisticated server.\npackage main\n\nimport (\n\t\"flag\"\n\t\"fmt\"\n\t\"html\"\n\t\"log\"\n\t\"net\/http\"\n\t\"os\"\n\t\"runtime\/debug\"\n\t\"strings\"\n)\n\nfunc usage() {\n\tfmt.Fprintf(os.Stderr, \"usage: helloserver [options]\\n\")\n\tflag.PrintDefaults()\n\tos.Exit(2)\n}\n\nvar (\n\tgreeting = flag.String(\"g\", \"Hello\", \"Greet with `greeting`\")\n\taddr = flag.String(\"addr\", \"localhost:8080\", \"address to serve\")\n)\n\nfunc main() {\n\t\/\/ Parse flags.\n\tflag.Usage = usage\n\tflag.Parse()\n\n\t\/\/ Parse and validate arguments (none).\n\targs := flag.Args()\n\tif len(args) != 0 {\n\t\tusage()\n\t}\n\n\t\/\/ Register handlers.\n\t\/\/ All requests not otherwise mapped with go to greet.\n\t\/\/ \/version is mapped specifically to version.\n\thttp.HandleFunc(\"\/\", greet)\n\thttp.HandleFunc(\"\/version\", version)\n\n\tlog.Printf(\"serving http:\/\/%s\\n\", *addr)\n\tlog.Fatal(http.ListenAndServe(*addr, nil))\n}\n\nfunc version(w http.ResponseWriter, r *http.Request) {\n\tinfo, ok := debug.ReadBuildInfo()\n\tif !ok {\n\t\thttp.Error(w, \"no build information available\", 500)\n\t\treturn\n\t}\n\n\tfmt.Fprintf(w, \"<!DOCTYPE html>\\n<pre>\\n\")\n\tfmt.Fprintf(w, \"%s\\n\", html.EscapeString(info.String()))\n}\n\nfunc greet(w http.ResponseWriter, r *http.Request) {\n\tname := strings.Trim(r.URL.Path, \"\/\")\n\tif name == \"\" {\n\t\tname = \"Gopher\"\n\t}\n\n\tfmt.Fprintf(w, \"<!DOCTYPE html>\\n\")\n\tfmt.Fprintf(w, \"%s, %s!\\n\", *greeting, html.EscapeString(name))\n}\n","global_vars":"","package":"package main","tags":""} |
|
{"element_type":"function","project_name":"finalHFtest","uuid":"cbd6472e-028d-4f8c-98aa-6916e2b96e50","name":"usage","imports":"['\"flag\"', '\"fmt\"', '\"os\"']","structs":"","interfaces":"","file_location":"github.com\/finalHFtest\/\/tmp\/repos\/example\/helloserver\/server.go","code":"func usage() {\n\tfmt.Fprintf(os.Stderr, \"usage: helloserver [options]\\n\")\n\tflag.PrintDefaults()\n\tos.Exit(2)\n}","global_vars":"","package":"main","tags":""} |
|
{"element_type":"function","project_name":"finalHFtest","uuid":"0704b3c9-36db-4398-9a14-5018b39647c1","name":"main","imports":"['\"flag\"', '\"log\"', '\"net\/http\"']","structs":"","interfaces":"","file_location":"github.com\/finalHFtest\/\/tmp\/repos\/example\/helloserver\/server.go","code":"func main() {\n\t\/\/ Parse flags.\n\tflag.Usage = usage\n\tflag.Parse()\n\n\t\/\/ Parse and validate arguments (none).\n\targs := flag.Args()\n\tif len(args) != 0 {\n\t\tusage()\n\t}\n\n\t\/\/ Register handlers.\n\t\/\/ All requests not otherwise mapped with go to greet.\n\t\/\/ \/version is mapped specifically to version.\n\thttp.HandleFunc(\"\/\", greet)\n\thttp.HandleFunc(\"\/version\", version)\n\n\tlog.Printf(\"serving http:\/\/%s\\n\", *addr)\n\tlog.Fatal(http.ListenAndServe(*addr, nil))\n}","global_vars":"","package":"main","tags":""} |
|
{"element_type":"function","project_name":"finalHFtest","uuid":"7e4bf4c5-0e0c-499a-af66-53f1c983465b","name":"version","imports":"['\"fmt\"', '\"html\"', '\"net\/http\"', '\"runtime\/debug\"']","structs":"","interfaces":"","file_location":"github.com\/finalHFtest\/\/tmp\/repos\/example\/helloserver\/server.go","code":"func version(w http.ResponseWriter, r *http.Request) {\n\tinfo, ok := debug.ReadBuildInfo()\n\tif !ok {\n\t\thttp.Error(w, \"no build information available\", 500)\n\t\treturn\n\t}\n\n\tfmt.Fprintf(w, \"<!DOCTYPE html>\\n<pre>\\n\")\n\tfmt.Fprintf(w, \"%s\\n\", html.EscapeString(info.String()))\n}","global_vars":"","package":"main","tags":""} |
|
{"element_type":"function","project_name":"finalHFtest","uuid":"29dc24ae-9cf5-4e8c-b065-039b6fa565c4","name":"greet","imports":"['\"fmt\"', '\"html\"', '\"net\/http\"', '\"strings\"']","structs":"","interfaces":"","file_location":"github.com\/finalHFtest\/\/tmp\/repos\/example\/helloserver\/server.go","code":"func greet(w http.ResponseWriter, r *http.Request) {\n\tname := strings.Trim(r.URL.Path, \"\/\")\n\tif name == \"\" {\n\t\tname = \"Gopher\"\n\t}\n\n\tfmt.Fprintf(w, \"<!DOCTYPE html>\\n\")\n\tfmt.Fprintf(w, \"%s, %s!\\n\", *greeting, html.EscapeString(name))\n}","global_vars":"","package":"main","tags":""} |
|
{"element_type":"file","project_name":"finalHFtest","uuid":"82951b4a-510c-4a2a-a9d8-a8d043297ce4","name":"weave.go","imports":"import (\n\t\"bufio\"\n\t\"bytes\"\n\t\"fmt\"\n\t\"log\"\n\t\"os\"\n\t\"path\/filepath\"\n\t\"regexp\"\n\t\"strings\"\n)","structs":"","interfaces":"","file_location":"github.com\/finalHFtest\/\/tmp\/repos\/example\/internal\/cmd\/weave\/weave.go","code":"\/\/ The weave command is a simple preprocessor for markdown files.\n\/\/ It builds a table of contents and processes %include directives.\n\/\/\n\/\/ Example usage:\n\/\/\n\/\/\t$ go run internal\/cmd\/weave go-types.md > README.md\n\/\/\n\/\/ The weave command copies lines of the input file to standard output, with two\n\/\/ exceptions:\n\/\/\n\/\/ If a line begins with \"%toc\", it is replaced with a table of contents\n\/\/ consisting of links to the top two levels of headers (\"#\" and \"##\").\n\/\/\n\/\/ If a line begins with \"%include FILENAME TAG\", it is replaced with the lines\n\/\/ of the file between lines containing \"!+TAG\" and \"!-TAG\". TAG can be omitted,\n\/\/ in which case the delimiters are simply \"!+\" and \"!-\".\n\/\/\n\/\/ Before the included lines, a line of the form\n\/\/\n\/\/\t\/\/ go get PACKAGE\n\/\/\n\/\/ is output, where PACKAGE is constructed from the module path, the\n\/\/ base name of the current directory, and the directory of FILENAME.\n\/\/ This caption can be suppressed by putting \"-\" as the final word of the %include line.\npackage main\n\nimport (\n\t\"bufio\"\n\t\"bytes\"\n\t\"fmt\"\n\t\"log\"\n\t\"os\"\n\t\"path\/filepath\"\n\t\"regexp\"\n\t\"strings\"\n)\n\nfunc main() {\n\tlog.SetFlags(0)\n\tlog.SetPrefix(\"weave: \")\n\tif len(os.Args) != 2 {\n\t\tlog.Fatal(\"usage: weave input.md\\n\")\n\t}\n\n\tf, err := os.Open(os.Args[1])\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tdefer f.Close()\n\n\twd, err := os.Getwd()\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tcurDir := filepath.Base(wd)\n\n\tfmt.Println(\"<!-- Autogenerated by weave; DO NOT EDIT -->\")\n\n\t\/\/ Pass 1: extract table of contents.\n\tvar toc []string\n\tin := bufio.NewScanner(f)\n\tfor in.Scan() {\n\t\tline := in.Text()\n\t\tif line == \"\" || (line[0] != '#' && line[0] != '%') {\n\t\t\tcontinue\n\t\t}\n\t\tline = strings.TrimSpace(line)\n\t\tif line == \"%toc\" {\n\t\t\ttoc = nil\n\t\t} else if strings.HasPrefix(line, \"# \") || strings.HasPrefix(line, \"## \") {\n\t\t\twords := strings.Fields(line)\n\t\t\tdepth := len(words[0])\n\t\t\twords = words[1:]\n\t\t\ttext := strings.Join(words, \" \")\n\t\t\tfor i := range words {\n\t\t\t\twords[i] = strings.ToLower(words[i])\n\t\t\t}\n\t\t\tline = fmt.Sprintf(\"%s1. [%s](#%s)\",\n\t\t\t\tstrings.Repeat(\"\\t\", depth-1), text, strings.Join(words, \"-\"))\n\t\t\ttoc = append(toc, line)\n\t\t}\n\t}\n\tif in.Err() != nil {\n\t\tlog.Fatal(in.Err())\n\t}\n\n\t\/\/ Pass 2.\n\tif _, err := f.Seek(0, os.SEEK_SET); err != nil {\n\t\tlog.Fatalf(\"can't rewind input: %v\", err)\n\t}\n\tin = bufio.NewScanner(f)\n\tfor in.Scan() {\n\t\tline := in.Text()\n\t\tswitch {\n\t\tcase strings.HasPrefix(line, \"%toc\"): \/\/ ToC\n\t\t\tfor _, h := range toc {\n\t\t\t\tfmt.Println(h)\n\t\t\t}\n\t\tcase strings.HasPrefix(line, \"%include\"):\n\t\t\twords := strings.Fields(line)\n\t\t\tif len(words) < 2 {\n\t\t\t\tlog.Fatal(line)\n\t\t\t}\n\t\t\tfilename := words[1]\n\n\t\t\t\/\/ Show caption unless '-' follows.\n\t\t\tif len(words) < 4 || words[3] != \"-\" {\n\t\t\t\tfmt.Printf(\"\t\/\/ go get golang.org\/x\/example\/%s\/%s\\n\\n\",\n\t\t\t\t\tcurDir, filepath.Dir(filename))\n\t\t\t}\n\n\t\t\tsection := \"\"\n\t\t\tif len(words) > 2 {\n\t\t\t\tsection = words[2]\n\t\t\t}\n\t\t\ts, err := include(filename, section)\n\t\t\tif err != nil {\n\t\t\t\tlog.Fatal(err)\n\t\t\t}\n\t\t\tfmt.Println(\"```\")\n\t\t\tfmt.Println(cleanListing(s)) \/\/ TODO(adonovan): escape \/^```\/ in s\n\t\t\tfmt.Println(\"```\")\n\t\tdefault:\n\t\t\tfmt.Println(line)\n\t\t}\n\t}\n\tif in.Err() != nil {\n\t\tlog.Fatal(in.Err())\n\t}\n}\n\n\/\/ include processes an included file, and returns the included text.\n\/\/ Only lines between those matching !+tag and !-tag will be returned.\n\/\/ This is true even if tag==\"\".\nfunc include(file, tag string) (string, error) {\n\tf, err := os.Open(file)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tdefer f.Close()\n\n\tstartre, err := regexp.Compile(\"!\\\\+\" + tag + \"$\")\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tendre, err := regexp.Compile(\"!\\\\-\" + tag + \"$\")\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tvar text bytes.Buffer\n\tin := bufio.NewScanner(f)\n\tvar on bool\n\tfor in.Scan() {\n\t\tline := in.Text()\n\t\tswitch {\n\t\tcase startre.MatchString(line):\n\t\t\ton = true\n\t\tcase endre.MatchString(line):\n\t\t\ton = false\n\t\tcase on:\n\t\t\ttext.WriteByte('\\t')\n\t\t\ttext.WriteString(line)\n\t\t\ttext.WriteByte('\\n')\n\t\t}\n\t}\n\tif in.Err() != nil {\n\t\treturn \"\", in.Err()\n\t}\n\tif text.Len() == 0 {\n\t\treturn \"\", fmt.Errorf(\"no lines of %s matched tag %q\", file, tag)\n\t}\n\treturn text.String(), nil\n}\n\nfunc isBlank(line string) bool { return strings.TrimSpace(line) == \"\" }\n\nfunc indented(line string) bool {\n\treturn strings.HasPrefix(line, \" \") || strings.HasPrefix(line, \"\\t\")\n}\n\n\/\/ cleanListing removes entirely blank leading and trailing lines from\n\/\/ text, and removes n leading tabs.\nfunc cleanListing(text string) string {\n\tlines := strings.Split(text, \"\\n\")\n\n\t\/\/ remove minimum number of leading tabs from all non-blank lines\n\ttabs := 999\n\tfor i, line := range lines {\n\t\tif strings.TrimSpace(line) == \"\" {\n\t\t\tlines[i] = \"\"\n\t\t} else {\n\t\t\tif n := leadingTabs(line); n < tabs {\n\t\t\t\ttabs = n\n\t\t\t}\n\t\t}\n\t}\n\tfor i, line := range lines {\n\t\tif line != \"\" {\n\t\t\tline := line[tabs:]\n\t\t\tlines[i] = line \/\/ remove leading tabs\n\t\t}\n\t}\n\n\t\/\/ remove leading blank lines\n\tfor len(lines) > 0 && lines[0] == \"\" {\n\t\tlines = lines[1:]\n\t}\n\t\/\/ remove trailing blank lines\n\tfor len(lines) > 0 && lines[len(lines)-1] == \"\" {\n\t\tlines = lines[:len(lines)-1]\n\t}\n\treturn strings.Join(lines, \"\\n\")\n}\n\nfunc leadingTabs(s string) int {\n\tvar i int\n\tfor i = 0; i < len(s); i++ {\n\t\tif s[i] != '\\t' {\n\t\t\tbreak\n\t\t}\n\t}\n\treturn i\n}\n","global_vars":"","package":"package main","tags":""} |
|
{"element_type":"function","project_name":"finalHFtest","uuid":"59b99b1f-61fb-466b-9221-4a23a4ddf6e5","name":"main","imports":"['\"bufio\"', '\"fmt\"', '\"log\"', '\"os\"', '\"path\/filepath\"', '\"strings\"']","structs":"","interfaces":"","file_location":"github.com\/finalHFtest\/\/tmp\/repos\/example\/internal\/cmd\/weave\/weave.go","code":"func main() {\n\tlog.SetFlags(0)\n\tlog.SetPrefix(\"weave: \")\n\tif len(os.Args) != 2 {\n\t\tlog.Fatal(\"usage: weave input.md\\n\")\n\t}\n\n\tf, err := os.Open(os.Args[1])\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tdefer f.Close()\n\n\twd, err := os.Getwd()\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tcurDir := filepath.Base(wd)\n\n\tfmt.Println(\"<!-- Autogenerated by weave; DO NOT EDIT -->\")\n\n\t\/\/ Pass 1: extract table of contents.\n\tvar toc []string\n\tin := bufio.NewScanner(f)\n\tfor in.Scan() {\n\t\tline := in.Text()\n\t\tif line == \"\" || (line[0] != '#' && line[0] != '%') {\n\t\t\tcontinue\n\t\t}\n\t\tline = strings.TrimSpace(line)\n\t\tif line == \"%toc\" {\n\t\t\ttoc = nil\n\t\t} else if strings.HasPrefix(line, \"# \") || strings.HasPrefix(line, \"## \") {\n\t\t\twords := strings.Fields(line)\n\t\t\tdepth := len(words[0])\n\t\t\twords = words[1:]\n\t\t\ttext := strings.Join(words, \" \")\n\t\t\tfor i := range words {\n\t\t\t\twords[i] = strings.ToLower(words[i])\n\t\t\t}\n\t\t\tline = fmt.Sprintf(\"%s1. [%s](#%s)\",\n\t\t\t\tstrings.Repeat(\"\\t\", depth-1), text, strings.Join(words, \"-\"))\n\t\t\ttoc = append(toc, line)\n\t\t}\n\t}\n\tif in.Err() != nil {\n\t\tlog.Fatal(in.Err())\n\t}\n\n\t\/\/ Pass 2.\n\tif _, err := f.Seek(0, os.SEEK_SET); err != nil {\n\t\tlog.Fatalf(\"can't rewind input: %v\", err)\n\t}\n\tin = bufio.NewScanner(f)\n\tfor in.Scan() {\n\t\tline := in.Text()\n\t\tswitch {\n\t\tcase strings.HasPrefix(line, \"%toc\"): \/\/ ToC\n\t\t\tfor _, h := range toc {\n\t\t\t\tfmt.Println(h)\n\t\t\t}\n\t\tcase strings.HasPrefix(line, \"%include\"):\n\t\t\twords := strings.Fields(line)\n\t\t\tif len(words) < 2 {\n\t\t\t\tlog.Fatal(line)\n\t\t\t}\n\t\t\tfilename := words[1]\n\n\t\t\t\/\/ Show caption unless '-' follows.\n\t\t\tif len(words) < 4 || words[3] != \"-\" {\n\t\t\t\tfmt.Printf(\"\t\/\/ go get golang.org\/x\/example\/%s\/%s\\n\\n\",\n\t\t\t\t\tcurDir, filepath.Dir(filename))\n\t\t\t}\n\n\t\t\tsection := \"\"\n\t\t\tif len(words) > 2 {\n\t\t\t\tsection = words[2]\n\t\t\t}\n\t\t\ts, err := include(filename, section)\n\t\t\tif err != nil {\n\t\t\t\tlog.Fatal(err)\n\t\t\t}\n\t\t\tfmt.Println(\"```\")\n\t\t\tfmt.Println(cleanListing(s)) \/\/ TODO(adonovan): escape \/^```\/ in s\n\t\t\tfmt.Println(\"```\")\n\t\tdefault:\n\t\t\tfmt.Println(line)\n\t\t}\n\t}\n\tif in.Err() != nil {\n\t\tlog.Fatal(in.Err())\n\t}\n}","global_vars":"","package":"main","tags":""} |
|
{"element_type":"function","project_name":"finalHFtest","uuid":"5b908af4-1a47-446c-9562-50cd079c4554","name":"include","imports":"['\"bufio\"', '\"bytes\"', '\"fmt\"', '\"os\"', '\"regexp\"']","structs":"","interfaces":"","file_location":"github.com\/finalHFtest\/\/tmp\/repos\/example\/internal\/cmd\/weave\/weave.go","code":"func include(file, tag string) (string, error) {\n\tf, err := os.Open(file)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tdefer f.Close()\n\n\tstartre, err := regexp.Compile(\"!\\\\+\" + tag + \"$\")\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tendre, err := regexp.Compile(\"!\\\\-\" + tag + \"$\")\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tvar text bytes.Buffer\n\tin := bufio.NewScanner(f)\n\tvar on bool\n\tfor in.Scan() {\n\t\tline := in.Text()\n\t\tswitch {\n\t\tcase startre.MatchString(line):\n\t\t\ton = true\n\t\tcase endre.MatchString(line):\n\t\t\ton = false\n\t\tcase on:\n\t\t\ttext.WriteByte('\\t')\n\t\t\ttext.WriteString(line)\n\t\t\ttext.WriteByte('\\n')\n\t\t}\n\t}\n\tif in.Err() != nil {\n\t\treturn \"\", in.Err()\n\t}\n\tif text.Len() == 0 {\n\t\treturn \"\", fmt.Errorf(\"no lines of %s matched tag %q\", file, tag)\n\t}\n\treturn text.String(), nil\n}","global_vars":"","package":"main","tags":""} |
|
{"element_type":"function","project_name":"finalHFtest","uuid":"d5a23492-bb4f-4cdb-b4d9-57e78db87ab7","name":"isBlank","imports":"['\"strings\"']","structs":"","interfaces":"","file_location":"github.com\/finalHFtest\/\/tmp\/repos\/example\/internal\/cmd\/weave\/weave.go","code":"func isBlank(line string) bool { return strings.TrimSpace(line) == \"\" }","global_vars":"","package":"main","tags":""} |
|
{"element_type":"function","project_name":"finalHFtest","uuid":"b3baa6f4-9cb1-49ed-9e21-34caa4faeff0","name":"indented","imports":"['\"strings\"']","structs":"","interfaces":"","file_location":"github.com\/finalHFtest\/\/tmp\/repos\/example\/internal\/cmd\/weave\/weave.go","code":"func indented(line string) bool {\n\treturn strings.HasPrefix(line, \" \") || strings.HasPrefix(line, \"\\t\")\n}","global_vars":"","package":"main","tags":""} |
|
{"element_type":"function","project_name":"finalHFtest","uuid":"a8b93aa3-f2c8-46c3-9135-e680cb53d2d0","name":"cleanListing","imports":"['\"strings\"']","structs":"","interfaces":"","file_location":"github.com\/finalHFtest\/\/tmp\/repos\/example\/internal\/cmd\/weave\/weave.go","code":"func cleanListing(text string) string {\n\tlines := strings.Split(text, \"\\n\")\n\n\t\/\/ remove minimum number of leading tabs from all non-blank lines\n\ttabs := 999\n\tfor i, line := range lines {\n\t\tif strings.TrimSpace(line) == \"\" {\n\t\t\tlines[i] = \"\"\n\t\t} else {\n\t\t\tif n := leadingTabs(line); n < tabs {\n\t\t\t\ttabs = n\n\t\t\t}\n\t\t}\n\t}\n\tfor i, line := range lines {\n\t\tif line != \"\" {\n\t\t\tline := line[tabs:]\n\t\t\tlines[i] = line \/\/ remove leading tabs\n\t\t}\n\t}\n\n\t\/\/ remove leading blank lines\n\tfor len(lines) > 0 && lines[0] == \"\" {\n\t\tlines = lines[1:]\n\t}\n\t\/\/ remove trailing blank lines\n\tfor len(lines) > 0 && lines[len(lines)-1] == \"\" {\n\t\tlines = lines[:len(lines)-1]\n\t}\n\treturn strings.Join(lines, \"\\n\")\n}","global_vars":"","package":"main","tags":""} |
|
{"element_type":"function","project_name":"finalHFtest","uuid":"4c421ebd-5640-4b38-a7ae-81f5c30292ce","name":"leadingTabs","imports":"","structs":"","interfaces":"","file_location":"github.com\/finalHFtest\/\/tmp\/repos\/example\/internal\/cmd\/weave\/weave.go","code":"func leadingTabs(s string) int {\n\tvar i int\n\tfor i = 0; i < len(s); i++ {\n\t\tif s[i] != '\\t' {\n\t\t\tbreak\n\t\t}\n\t}\n\treturn i\n}","global_vars":"","package":"main","tags":""} |
|
{"element_type":"file","project_name":"finalHFtest","uuid":"1b3805d5-fa2e-4984-ad2c-94e898dbbe34","name":"main.go","imports":"import (\n\t\"expvar\"\n\t\"flag\"\n\t\"fmt\"\n\t\"html\/template\"\n\t\"log\"\n\t\"net\/http\"\n\t\"sync\"\n\t\"time\"\n)","structs":"","interfaces":"","file_location":"github.com\/finalHFtest\/\/tmp\/repos\/example\/outyet\/main.go","code":"\/\/ Copyright 2023 The Go Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style\n\/\/ license that can be found in the LICENSE file.\n\n\/\/ Outyet is a web server that announces whether or not a particular Go version\n\/\/ has been tagged.\npackage main\n\nimport (\n\t\"expvar\"\n\t\"flag\"\n\t\"fmt\"\n\t\"html\/template\"\n\t\"log\"\n\t\"net\/http\"\n\t\"sync\"\n\t\"time\"\n)\n\n\/\/ Command-line flags.\nvar (\n\thttpAddr = flag.String(\"http\", \"localhost:8080\", \"Listen address\")\n\tpollPeriod = flag.Duration(\"poll\", 5*time.Second, \"Poll period\")\n\tversion = flag.String(\"version\", \"1.4\", \"Go version\")\n)\n\nconst baseChangeURL = \"https:\/\/go.googlesource.com\/go\/+\/\"\n\nfunc main() {\n\tflag.Parse()\n\tchangeURL := fmt.Sprintf(\"%sgo%s\", baseChangeURL, *version)\n\thttp.Handle(\"\/\", NewServer(*version, changeURL, *pollPeriod))\n\tlog.Printf(\"serving http:\/\/%s\", *httpAddr)\n\tlog.Fatal(http.ListenAndServe(*httpAddr, nil))\n}\n\n\/\/ Exported variables for monitoring the server.\n\/\/ These are exported via HTTP as a JSON object at \/debug\/vars.\nvar (\n\thitCount = expvar.NewInt(\"hitCount\")\n\tpollCount = expvar.NewInt(\"pollCount\")\n\tpollError = expvar.NewString(\"pollError\")\n\tpollErrorCount = expvar.NewInt(\"pollErrorCount\")\n)\n\n\/\/ Server implements the outyet server.\n\/\/ It serves the user interface (it's an http.Handler)\n\/\/ and polls the remote repository for changes.\ntype Server struct {\n\tversion string\n\turl string\n\tperiod time.Duration\n\n\tmu sync.RWMutex \/\/ protects the yes variable\n\tyes bool\n}\n\n\/\/ NewServer returns an initialized outyet server.\nfunc NewServer(version, url string, period time.Duration) *Server {\n\ts := &Server{version: version, url: url, period: period}\n\tgo s.poll()\n\treturn s\n}\n\n\/\/ poll polls the change URL for the specified period until the tag exists.\n\/\/ Then it sets the Server's yes field true and exits.\nfunc (s *Server) poll() {\n\tfor !isTagged(s.url) {\n\t\tpollSleep(s.period)\n\t}\n\ts.mu.Lock()\n\ts.yes = true\n\ts.mu.Unlock()\n\tpollDone()\n}\n\n\/\/ Hooks that may be overridden for integration tests.\nvar (\n\tpollSleep = time.Sleep\n\tpollDone = func() {}\n)\n\n\/\/ isTagged makes an HTTP HEAD request to the given URL and reports whether it\n\/\/ returned a 200 OK response.\nfunc isTagged(url string) bool {\n\tpollCount.Add(1)\n\tr, err := http.Head(url)\n\tif err != nil {\n\t\tlog.Print(err)\n\t\tpollError.Set(err.Error())\n\t\tpollErrorCount.Add(1)\n\t\treturn false\n\t}\n\treturn r.StatusCode == http.StatusOK\n}\n\n\/\/ ServeHTTP implements the HTTP user interface.\nfunc (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {\n\thitCount.Add(1)\n\ts.mu.RLock()\n\tdata := struct {\n\t\tURL string\n\t\tVersion string\n\t\tYes bool\n\t}{\n\t\ts.url,\n\t\ts.version,\n\t\ts.yes,\n\t}\n\ts.mu.RUnlock()\n\terr := tmpl.Execute(w, data)\n\tif err != nil {\n\t\tlog.Print(err)\n\t}\n}\n\n\/\/ tmpl is the HTML template that drives the user interface.\nvar tmpl = template.Must(template.New(\"tmpl\").Parse(`\n<!DOCTYPE html><html><body><center>\n\t<h2>Is Go {{.Version}} out yet?<\/h2>\n\t<h1>\n\t{{if .Yes}}\n\t\t<a href=\"{{.URL}}\">YES!<\/a>\n\t{{else}}\n\t\tNo. :-(\n\t{{end}}\n\t<\/h1>\n<\/center><\/body><\/html>\n`))\n","global_vars":"","package":"package main","tags":""} |
|
{"element_type":"function","project_name":"finalHFtest","uuid":"e6d42aa9-e71f-4be5-be0b-6a6093069097","name":"main","imports":"['\"flag\"', '\"fmt\"', '\"log\"', '\"net\/http\"']","structs":"","interfaces":"","file_location":"github.com\/finalHFtest\/\/tmp\/repos\/example\/outyet\/main.go","code":"func main() {\n\tflag.Parse()\n\tchangeURL := fmt.Sprintf(\"%sgo%s\", baseChangeURL, *version)\n\thttp.Handle(\"\/\", NewServer(*version, changeURL, *pollPeriod))\n\tlog.Printf(\"serving http:\/\/%s\", *httpAddr)\n\tlog.Fatal(http.ListenAndServe(*httpAddr, nil))\n}","global_vars":"","package":"main","tags":""} |
|
{"element_type":"function","project_name":"finalHFtest","uuid":"6aa4b9c9-3754-44b5-87d5-f5edf7af98ba","name":"NewServer","imports":"['\"time\"']","structs":"['Server']","interfaces":"","file_location":"github.com\/finalHFtest\/\/tmp\/repos\/example\/outyet\/main.go","code":"func NewServer(version, url string, period time.Duration) *Server {\n\ts := &Server{version: version, url: url, period: period}\n\tgo s.poll()\n\treturn s\n}","global_vars":"","package":"main","tags":""} |
|
{"element_type":"function","project_name":"finalHFtest","uuid":"9bb8961b-d3cb-45a9-b36c-c545b5b74513","name":"poll","imports":"","structs":"['Server']","interfaces":"","file_location":"github.com\/finalHFtest\/\/tmp\/repos\/example\/outyet\/main.go","code":"func (s *Server) poll() {\n\tfor !isTagged(s.url) {\n\t\tpollSleep(s.period)\n\t}\n\ts.mu.Lock()\n\ts.yes = true\n\ts.mu.Unlock()\n\tpollDone()\n}","global_vars":"","package":"main","tags":""} |
|
{"element_type":"function","project_name":"finalHFtest","uuid":"3695c2bf-5180-4c71-b35b-56a0772db664","name":"isTagged","imports":"['\"log\"', '\"net\/http\"']","structs":"","interfaces":"","file_location":"github.com\/finalHFtest\/\/tmp\/repos\/example\/outyet\/main.go","code":"func isTagged(url string) bool {\n\tpollCount.Add(1)\n\tr, err := http.Head(url)\n\tif err != nil {\n\t\tlog.Print(err)\n\t\tpollError.Set(err.Error())\n\t\tpollErrorCount.Add(1)\n\t\treturn false\n\t}\n\treturn r.StatusCode == http.StatusOK\n}","global_vars":"","package":"main","tags":""} |
|
{"element_type":"function","project_name":"finalHFtest","uuid":"41b86e15-95b1-4248-a62b-e5143f2e6957","name":"ServeHTTP","imports":"['\"log\"', '\"net\/http\"']","structs":"['Server']","interfaces":"","file_location":"github.com\/finalHFtest\/\/tmp\/repos\/example\/outyet\/main.go","code":"func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {\n\thitCount.Add(1)\n\ts.mu.RLock()\n\tdata := struct {\n\t\tURL string\n\t\tVersion string\n\t\tYes bool\n\t}{\n\t\ts.url,\n\t\ts.version,\n\t\ts.yes,\n\t}\n\ts.mu.RUnlock()\n\terr := tmpl.Execute(w, data)\n\tif err != nil {\n\t\tlog.Print(err)\n\t}\n}","global_vars":"","package":"main","tags":""} |
|
{"element_type":"file","project_name":"finalHFtest","uuid":"741747cb-197b-4819-a92c-7cb3bef3ab2c","name":"main_test.go","imports":"import (\n\t\"net\/http\"\n\t\"net\/http\/httptest\"\n\t\"strings\"\n\t\"testing\"\n\t\"time\"\n)","structs":"","interfaces":"","file_location":"github.com\/finalHFtest\/\/tmp\/repos\/example\/outyet\/main_test.go","code":"\/\/ Copyright 2023 The Go Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style\n\/\/ license that can be found in the LICENSE file.\n\npackage main\n\nimport (\n\t\"net\/http\"\n\t\"net\/http\/httptest\"\n\t\"strings\"\n\t\"testing\"\n\t\"time\"\n)\n\n\/\/ statusHandler is an http.Handler that writes an empty response using itself\n\/\/ as the response status code.\ntype statusHandler int\n\nfunc (h *statusHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {\n\tw.WriteHeader(int(*h))\n}\n\nfunc TestIsTagged(t *testing.T) {\n\t\/\/ Set up a fake \"Google Code\" web server reporting 404 not found.\n\tstatus := statusHandler(http.StatusNotFound)\n\ts := httptest.NewServer(&status)\n\tdefer s.Close()\n\n\tif isTagged(s.URL) {\n\t\tt.Fatal(\"isTagged == true, want false\")\n\t}\n\n\t\/\/ Change fake server status to 200 OK and try again.\n\tstatus = http.StatusOK\n\n\tif !isTagged(s.URL) {\n\t\tt.Fatal(\"isTagged == false, want true\")\n\t}\n}\n\nfunc TestIntegration(t *testing.T) {\n\tstatus := statusHandler(http.StatusNotFound)\n\tts := httptest.NewServer(&status)\n\tdefer ts.Close()\n\n\t\/\/ Replace the pollSleep with a closure that we can block and unblock.\n\tsleep := make(chan bool)\n\tpollSleep = func(time.Duration) {\n\t\tsleep <- true\n\t\tsleep <- true\n\t}\n\n\t\/\/ Replace pollDone with a closure that will tell us when the poller is\n\t\/\/ exiting.\n\tdone := make(chan bool)\n\tpollDone = func() { done <- true }\n\n\t\/\/ Put things as they were when the test finishes.\n\tdefer func() {\n\t\tpollSleep = time.Sleep\n\t\tpollDone = func() {}\n\t}()\n\n\ts := NewServer(\"1.x\", ts.URL, 1*time.Millisecond)\n\n\t<-sleep \/\/ Wait for poll loop to start sleeping.\n\n\t\/\/ Make first request to the server.\n\tr, _ := http.NewRequest(\"GET\", \"\/\", nil)\n\tw := httptest.NewRecorder()\n\ts.ServeHTTP(w, r)\n\tif b := w.Body.String(); !strings.Contains(b, \"No.\") {\n\t\tt.Fatalf(\"body = %s, want no\", b)\n\t}\n\n\tstatus = http.StatusOK\n\n\t<-sleep \/\/ Permit poll loop to stop sleeping.\n\t<-done \/\/ Wait for poller to see the \"OK\" status and exit.\n\n\t\/\/ Make second request to the server.\n\tw = httptest.NewRecorder()\n\ts.ServeHTTP(w, r)\n\tif b := w.Body.String(); !strings.Contains(b, \"YES!\") {\n\t\tt.Fatalf(\"body = %q, want yes\", b)\n\t}\n}\n","global_vars":"","package":"package main","tags":""} |
|
{"element_type":"function","project_name":"finalHFtest","uuid":"e564da52-1074-4487-84b7-28b968de9dde","name":"ServeHTTP","imports":"['\"net\/http\"']","structs":"","interfaces":"","file_location":"github.com\/finalHFtest\/\/tmp\/repos\/example\/outyet\/main_test.go","code":"func (h *statusHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {\n\tw.WriteHeader(int(*h))\n}","global_vars":"","package":"main","tags":""} |
|
{"element_type":"function","project_name":"finalHFtest","uuid":"83beb2c0-a943-4ff8-9208-0561df003285","name":"TestIsTagged","imports":"['\"net\/http\"', '\"net\/http\/httptest\"', '\"testing\"']","structs":"","interfaces":"","file_location":"github.com\/finalHFtest\/\/tmp\/repos\/example\/outyet\/main_test.go","code":"func TestIsTagged(t *testing.T) {\n\t\/\/ Set up a fake \"Google Code\" web server reporting 404 not found.\n\tstatus := statusHandler(http.StatusNotFound)\n\ts := httptest.NewServer(&status)\n\tdefer s.Close()\n\n\tif isTagged(s.URL) {\n\t\tt.Fatal(\"isTagged == true, want false\")\n\t}\n\n\t\/\/ Change fake server status to 200 OK and try again.\n\tstatus = http.StatusOK\n\n\tif !isTagged(s.URL) {\n\t\tt.Fatal(\"isTagged == false, want true\")\n\t}\n}","global_vars":"","package":"main","tags":""} |
|
{"element_type":"function","project_name":"finalHFtest","uuid":"b85648d3-f4c4-4816-be35-af171063f8e9","name":"TestIntegration","imports":"['\"net\/http\"', '\"net\/http\/httptest\"', '\"strings\"', '\"testing\"', '\"time\"']","structs":"","interfaces":"","file_location":"github.com\/finalHFtest\/\/tmp\/repos\/example\/outyet\/main_test.go","code":"func TestIntegration(t *testing.T) {\n\tstatus := statusHandler(http.StatusNotFound)\n\tts := httptest.NewServer(&status)\n\tdefer ts.Close()\n\n\t\/\/ Replace the pollSleep with a closure that we can block and unblock.\n\tsleep := make(chan bool)\n\tpollSleep = func(time.Duration) {\n\t\tsleep <- true\n\t\tsleep <- true\n\t}\n\n\t\/\/ Replace pollDone with a closure that will tell us when the poller is\n\t\/\/ exiting.\n\tdone := make(chan bool)\n\tpollDone = func() { done <- true }\n\n\t\/\/ Put things as they were when the test finishes.\n\tdefer func() {\n\t\tpollSleep = time.Sleep\n\t\tpollDone = func() {}\n\t}()\n\n\ts := NewServer(\"1.x\", ts.URL, 1*time.Millisecond)\n\n\t<-sleep \/\/ Wait for poll loop to start sleeping.\n\n\t\/\/ Make first request to the server.\n\tr, _ := http.NewRequest(\"GET\", \"\/\", nil)\n\tw := httptest.NewRecorder()\n\ts.ServeHTTP(w, r)\n\tif b := w.Body.String(); !strings.Contains(b, \"No.\") {\n\t\tt.Fatalf(\"body = %s, want no\", b)\n\t}\n\n\tstatus = http.StatusOK\n\n\t<-sleep \/\/ Permit poll loop to stop sleeping.\n\t<-done \/\/ Wait for poller to see the \"OK\" status and exit.\n\n\t\/\/ Make second request to the server.\n\tw = httptest.NewRecorder()\n\ts.ServeHTTP(w, r)\n\tif b := w.Body.String(); !strings.Contains(b, \"YES!\") {\n\t\tt.Fatalf(\"body = %q, want yes\", b)\n\t}\n}","global_vars":"","package":"main","tags":""} |
|
{"element_type":"file","project_name":"finalHFtest","uuid":"401ef775-bda2-43b9-8d76-449c72eec18d","name":"json.go","imports":"import (\n\t\"encoding\/json\"\n\t\"fmt\"\n\t\"mime\"\n\t\"net\/http\"\n)","structs":"","interfaces":"","file_location":"github.com\/finalHFtest\/\/tmp\/repos\/example\/ragserver\/ragserver-genkit\/json.go","code":"\/\/ Copyright 2024 The Go Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style\n\/\/ license that can be found in the LICENSE file.\n\npackage main\n\nimport (\n\t\"encoding\/json\"\n\t\"fmt\"\n\t\"mime\"\n\t\"net\/http\"\n)\n\n\/\/ readRequestJSON expects req to have a JSON content type with a body that\n\/\/ contains a JSON-encoded value complying with the underlying type of target.\n\/\/ It populates target, or returns an error.\nfunc readRequestJSON(req *http.Request, target any) error {\n\tcontentType := req.Header.Get(\"Content-Type\")\n\tmediaType, _, err := mime.ParseMediaType(contentType)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif mediaType != \"application\/json\" {\n\t\treturn fmt.Errorf(\"expect application\/json Content-Type, got %s\", mediaType)\n\t}\n\n\tdec := json.NewDecoder(req.Body)\n\tdec.DisallowUnknownFields()\n\treturn dec.Decode(target)\n}\n\n\/\/ renderJSON renders 'v' as JSON and writes it as a response into w.\nfunc renderJSON(w http.ResponseWriter, v any) {\n\tjs, err := json.Marshal(v)\n\tif err != nil {\n\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t\treturn\n\t}\n\tw.Header().Set(\"Content-Type\", \"application\/json\")\n\tw.Write(js)\n}\n","global_vars":"","package":"package main","tags":""} |
|
{"element_type":"function","project_name":"finalHFtest","uuid":"9a8cf552-5678-4964-a43b-40c74e7b64f8","name":"readRequestJSON","imports":"['\"encoding\/json\"', '\"fmt\"', '\"mime\"', '\"net\/http\"']","structs":"","interfaces":"","file_location":"github.com\/finalHFtest\/\/tmp\/repos\/example\/ragserver\/ragserver-genkit\/json.go","code":"func readRequestJSON(req *http.Request, target any) error {\n\tcontentType := req.Header.Get(\"Content-Type\")\n\tmediaType, _, err := mime.ParseMediaType(contentType)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif mediaType != \"application\/json\" {\n\t\treturn fmt.Errorf(\"expect application\/json Content-Type, got %s\", mediaType)\n\t}\n\n\tdec := json.NewDecoder(req.Body)\n\tdec.DisallowUnknownFields()\n\treturn dec.Decode(target)\n}","global_vars":"","package":"main","tags":""} |
|
{"element_type":"function","project_name":"finalHFtest","uuid":"e5517227-6285-4bb4-8695-35979bb80080","name":"renderJSON","imports":"['\"encoding\/json\"', '\"net\/http\"']","structs":"","interfaces":"","file_location":"github.com\/finalHFtest\/\/tmp\/repos\/example\/ragserver\/ragserver-genkit\/json.go","code":"func renderJSON(w http.ResponseWriter, v any) {\n\tjs, err := json.Marshal(v)\n\tif err != nil {\n\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t\treturn\n\t}\n\tw.Header().Set(\"Content-Type\", \"application\/json\")\n\tw.Write(js)\n}","global_vars":"","package":"main","tags":""} |
|
{"element_type":"file","project_name":"finalHFtest","uuid":"8c1c6033-d960-42d8-9bfb-1c33853d6b7f","name":"main.go","imports":"import (\n\t\"cmp\"\n\t\"context\"\n\t\"fmt\"\n\t\"log\"\n\t\"net\/http\"\n\t\"os\"\n\t\"strings\"\n\n\t\"github.com\/firebase\/genkit\/go\/ai\"\n\t\"github.com\/firebase\/genkit\/go\/plugins\/googleai\"\n\t\"github.com\/firebase\/genkit\/go\/plugins\/weaviate\"\n)","structs":"","interfaces":"","file_location":"github.com\/finalHFtest\/\/tmp\/repos\/example\/ragserver\/ragserver-genkit\/main.go","code":"\/\/ Copyright 2024 The Go Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style\n\/\/ license that can be found in the LICENSE file.\n\n\/\/ Command ragserver is an HTTP server that implements RAG (Retrieval\n\/\/ Augmented Generation) using the Gemini model and Weaviate, which\n\/\/ are accessed using the Genkit package. See the accompanying README file for\n\/\/ additional details.\npackage main\n\nimport (\n\t\"cmp\"\n\t\"context\"\n\t\"fmt\"\n\t\"log\"\n\t\"net\/http\"\n\t\"os\"\n\t\"strings\"\n\n\t\"github.com\/firebase\/genkit\/go\/ai\"\n\t\"github.com\/firebase\/genkit\/go\/plugins\/googleai\"\n\t\"github.com\/firebase\/genkit\/go\/plugins\/weaviate\"\n)\n\nconst generativeModelName = \"gemini-1.5-flash\"\nconst embeddingModelName = \"text-embedding-004\"\n\n\/\/ This is a standard Go HTTP server. Server state is in the ragServer struct.\n\/\/ The `main` function connects to the required services (Weaviate and Google\n\/\/ AI), initializes the server state and registers HTTP handlers.\nfunc main() {\n\tctx := context.Background()\n\terr := googleai.Init(ctx, &googleai.Config{\n\t\tAPIKey: os.Getenv(\"GEMINI_API_KEY\"),\n\t})\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\twvConfig := &weaviate.ClientConfig{\n\t\tScheme: \"http\",\n\t\tAddr: \"localhost:\" + cmp.Or(os.Getenv(\"WVPORT\"), \"9035\"),\n\t}\n\t_, err = weaviate.Init(ctx, wvConfig)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tclassConfig := &weaviate.ClassConfig{\n\t\tClass: \"Document\",\n\t\tEmbedder: googleai.Embedder(embeddingModelName),\n\t}\n\tindexer, retriever, err := weaviate.DefineIndexerAndRetriever(ctx, *classConfig)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tmodel := googleai.Model(generativeModelName)\n\tif model == nil {\n\t\tlog.Fatal(\"unable to set up gemini-1.5-flash model\")\n\t}\n\n\tserver := &ragServer{\n\t\tctx: ctx,\n\t\tindexer: indexer,\n\t\tretriever: retriever,\n\t\tmodel: model,\n\t}\n\n\tmux := http.NewServeMux()\n\tmux.HandleFunc(\"POST \/add\/\", server.addDocumentsHandler)\n\tmux.HandleFunc(\"POST \/query\/\", server.queryHandler)\n\n\tport := cmp.Or(os.Getenv(\"SERVERPORT\"), \"9020\")\n\taddress := \"localhost:\" + port\n\tlog.Println(\"listening on\", address)\n\tlog.Fatal(http.ListenAndServe(address, mux))\n}\n\ntype ragServer struct {\n\tctx context.Context\n\tindexer ai.Indexer\n\tretriever ai.Retriever\n\tmodel ai.Model\n}\n\nfunc (rs *ragServer) addDocumentsHandler(w http.ResponseWriter, req *http.Request) {\n\t\/\/ Parse HTTP request from JSON.\n\ttype document struct {\n\t\tText string\n\t}\n\ttype addRequest struct {\n\t\tDocuments []document\n\t}\n\tar := &addRequest{}\n\terr := readRequestJSON(req, ar)\n\tif err != nil {\n\t\thttp.Error(w, err.Error(), http.StatusBadRequest)\n\t\treturn\n\t}\n\n\t\/\/ Convert request documents into Weaviate documents used for embedding.\n\tvar wvDocs []*ai.Document\n\tfor _, doc := range ar.Documents {\n\t\twvDocs = append(wvDocs, ai.DocumentFromText(doc.Text, nil))\n\t}\n\n\t\/\/ Index the requested documents.\n\terr = ai.Index(rs.ctx, rs.indexer, ai.WithIndexerDocs(wvDocs...))\n\tif err != nil {\n\t\thttp.Error(w, fmt.Errorf(\"indexing: %w\", err).Error(), http.StatusInternalServerError)\n\t\treturn\n\t}\n}\n\nfunc (rs *ragServer) queryHandler(w http.ResponseWriter, req *http.Request) {\n\t\/\/ Parse HTTP request from JSON.\n\ttype queryRequest struct {\n\t\tContent string\n\t}\n\tqr := &queryRequest{}\n\terr := readRequestJSON(req, qr)\n\tif err != nil {\n\t\thttp.Error(w, err.Error(), http.StatusBadRequest)\n\t\treturn\n\t}\n\n\t\/\/ Find the most similar documents using the retriever.\n\tresp, err := ai.Retrieve(rs.ctx,\n\t\trs.retriever,\n\t\tai.WithRetrieverDoc(ai.DocumentFromText(qr.Content, nil)),\n\t\tai.WithRetrieverOpts(&weaviate.RetrieverOptions{\n\t\t\tCount: 3,\n\t\t}))\n\tif err != nil {\n\t\thttp.Error(w, fmt.Errorf(\"retrieval: %w\", err).Error(), http.StatusInternalServerError)\n\t\treturn\n\t}\n\n\tvar docsContents []string\n\tfor _, d := range resp.Documents {\n\t\tdocsContents = append(docsContents, d.Content[0].Text)\n\t}\n\n\t\/\/ Create a RAG query for the LLM with the most relevant documents as\n\t\/\/ context.\n\tragQuery := fmt.Sprintf(ragTemplateStr, qr.Content, strings.Join(docsContents, \"\\n\"))\n\tgenResp, err := ai.Generate(rs.ctx, rs.model, ai.WithTextPrompt(ragQuery))\n\tif err != nil {\n\t\tlog.Printf(\"calling generative model: %v\", err.Error())\n\t\thttp.Error(w, \"generative model error\", http.StatusInternalServerError)\n\t\treturn\n\t}\n\n\tif len(genResp.Candidates) != 1 {\n\t\tlog.Printf(\"got %v candidates, expected 1\", len(genResp.Candidates))\n\t\thttp.Error(w, \"generative model error\", http.StatusInternalServerError)\n\t\treturn\n\t}\n\n\trenderJSON(w, genResp.Text())\n}\n\nconst ragTemplateStr = `\nI will ask you a question and will provide some additional context information.\nAssume this context information is factual and correct, as part of internal\ndocumentation.\nIf the question relates to the context, answer it using the context.\nIf the question does not relate to the context, answer it as normal.\n\nFor example, let's say the context has nothing in it about tropical flowers;\nthen if I ask you about tropical flowers, just answer what you know about them\nwithout referring to the context.\n\nFor example, if the context does mention minerology and I ask you about that,\nprovide information from the context along with general knowledge.\n\nQuestion:\n%s\n\nContext:\n%s\n`\n","global_vars":"","package":"package main","tags":""} |
|
{"element_type":"function","project_name":"finalHFtest","uuid":"5dd71861-1fdc-47d8-8466-83be048079c4","name":"main","imports":"['\"cmp\"', '\"context\"', '\"log\"', '\"net\/http\"', '\"os\"', '\"github.com\/firebase\/genkit\/go\/plugins\/googleai\"', '\"github.com\/firebase\/genkit\/go\/plugins\/weaviate\"']","structs":"['ragServer']","interfaces":"","file_location":"github.com\/finalHFtest\/\/tmp\/repos\/example\/ragserver\/ragserver-genkit\/main.go","code":"func main() {\n\tctx := context.Background()\n\terr := googleai.Init(ctx, &googleai.Config{\n\t\tAPIKey: os.Getenv(\"GEMINI_API_KEY\"),\n\t})\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\twvConfig := &weaviate.ClientConfig{\n\t\tScheme: \"http\",\n\t\tAddr: \"localhost:\" + cmp.Or(os.Getenv(\"WVPORT\"), \"9035\"),\n\t}\n\t_, err = weaviate.Init(ctx, wvConfig)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tclassConfig := &weaviate.ClassConfig{\n\t\tClass: \"Document\",\n\t\tEmbedder: googleai.Embedder(embeddingModelName),\n\t}\n\tindexer, retriever, err := weaviate.DefineIndexerAndRetriever(ctx, *classConfig)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tmodel := googleai.Model(generativeModelName)\n\tif model == nil {\n\t\tlog.Fatal(\"unable to set up gemini-1.5-flash model\")\n\t}\n\n\tserver := &ragServer{\n\t\tctx: ctx,\n\t\tindexer: indexer,\n\t\tretriever: retriever,\n\t\tmodel: model,\n\t}\n\n\tmux := http.NewServeMux()\n\tmux.HandleFunc(\"POST \/add\/\", server.addDocumentsHandler)\n\tmux.HandleFunc(\"POST \/query\/\", server.queryHandler)\n\n\tport := cmp.Or(os.Getenv(\"SERVERPORT\"), \"9020\")\n\taddress := \"localhost:\" + port\n\tlog.Println(\"listening on\", address)\n\tlog.Fatal(http.ListenAndServe(address, mux))\n}","global_vars":"","package":"main","tags":""} |
|
{"element_type":"function","project_name":"finalHFtest","uuid":"ada27926-d7af-4239-ac05-dbb06f28ddc4","name":"addDocumentsHandler","imports":"['\"fmt\"', '\"net\/http\"', '\"github.com\/firebase\/genkit\/go\/ai\"']","structs":"['ragServer']","interfaces":"","file_location":"github.com\/finalHFtest\/\/tmp\/repos\/example\/ragserver\/ragserver-genkit\/main.go","code":"func (rs *ragServer) addDocumentsHandler(w http.ResponseWriter, req *http.Request) {\n\t\/\/ Parse HTTP request from JSON.\n\ttype document struct {\n\t\tText string\n\t}\n\ttype addRequest struct {\n\t\tDocuments []document\n\t}\n\tar := &addRequest{}\n\terr := readRequestJSON(req, ar)\n\tif err != nil {\n\t\thttp.Error(w, err.Error(), http.StatusBadRequest)\n\t\treturn\n\t}\n\n\t\/\/ Convert request documents into Weaviate documents used for embedding.\n\tvar wvDocs []*ai.Document\n\tfor _, doc := range ar.Documents {\n\t\twvDocs = append(wvDocs, ai.DocumentFromText(doc.Text, nil))\n\t}\n\n\t\/\/ Index the requested documents.\n\terr = ai.Index(rs.ctx, rs.indexer, ai.WithIndexerDocs(wvDocs...))\n\tif err != nil {\n\t\thttp.Error(w, fmt.Errorf(\"indexing: %w\", err).Error(), http.StatusInternalServerError)\n\t\treturn\n\t}\n}","global_vars":"","package":"main","tags":""} |
|
{"element_type":"function","project_name":"finalHFtest","uuid":"e3fe37cc-1101-4e91-9260-893e1d581c97","name":"queryHandler","imports":"['\"context\"', '\"fmt\"', '\"log\"', '\"net\/http\"', '\"strings\"', '\"github.com\/firebase\/genkit\/go\/ai\"', '\"github.com\/firebase\/genkit\/go\/plugins\/weaviate\"']","structs":"['ragServer']","interfaces":"","file_location":"github.com\/finalHFtest\/\/tmp\/repos\/example\/ragserver\/ragserver-genkit\/main.go","code":"func (rs *ragServer) queryHandler(w http.ResponseWriter, req *http.Request) {\n\t\/\/ Parse HTTP request from JSON.\n\ttype queryRequest struct {\n\t\tContent string\n\t}\n\tqr := &queryRequest{}\n\terr := readRequestJSON(req, qr)\n\tif err != nil {\n\t\thttp.Error(w, err.Error(), http.StatusBadRequest)\n\t\treturn\n\t}\n\n\t\/\/ Find the most similar documents using the retriever.\n\tresp, err := ai.Retrieve(rs.ctx,\n\t\trs.retriever,\n\t\tai.WithRetrieverDoc(ai.DocumentFromText(qr.Content, nil)),\n\t\tai.WithRetrieverOpts(&weaviate.RetrieverOptions{\n\t\t\tCount: 3,\n\t\t}))\n\tif err != nil {\n\t\thttp.Error(w, fmt.Errorf(\"retrieval: %w\", err).Error(), http.StatusInternalServerError)\n\t\treturn\n\t}\n\n\tvar docsContents []string\n\tfor _, d := range resp.Documents {\n\t\tdocsContents = append(docsContents, d.Content[0].Text)\n\t}\n\n\t\/\/ Create a RAG query for the LLM with the most relevant documents as\n\t\/\/ context.\n\tragQuery := fmt.Sprintf(ragTemplateStr, qr.Content, strings.Join(docsContents, \"\\n\"))\n\tgenResp, err := ai.Generate(rs.ctx, rs.model, ai.WithTextPrompt(ragQuery))\n\tif err != nil {\n\t\tlog.Printf(\"calling generative model: %v\", err.Error())\n\t\thttp.Error(w, \"generative model error\", http.StatusInternalServerError)\n\t\treturn\n\t}\n\n\tif len(genResp.Candidates) != 1 {\n\t\tlog.Printf(\"got %v candidates, expected 1\", len(genResp.Candidates))\n\t\thttp.Error(w, \"generative model error\", http.StatusInternalServerError)\n\t\treturn\n\t}\n\n\trenderJSON(w, genResp.Text())\n}","global_vars":"","package":"main","tags":""} |
|
{"element_type":"file","project_name":"finalHFtest","uuid":"24f1d6ec-35f2-4a7a-887f-da58bb4e507e","name":"json.go","imports":"import (\n\t\"encoding\/json\"\n\t\"fmt\"\n\t\"mime\"\n\t\"net\/http\"\n)","structs":"","interfaces":"","file_location":"github.com\/finalHFtest\/\/tmp\/repos\/example\/ragserver\/ragserver-langchaingo\/json.go","code":"\/\/ Copyright 2024 The Go Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style\n\/\/ license that can be found in the LICENSE file.\n\npackage main\n\nimport (\n\t\"encoding\/json\"\n\t\"fmt\"\n\t\"mime\"\n\t\"net\/http\"\n)\n\n\/\/ readRequestJSON expects req to have a JSON content type with a body that\n\/\/ contains a JSON-encoded value complying with the underlying type of target.\n\/\/ It populates target, or returns an error.\nfunc readRequestJSON(req *http.Request, target any) error {\n\tcontentType := req.Header.Get(\"Content-Type\")\n\tmediaType, _, err := mime.ParseMediaType(contentType)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif mediaType != \"application\/json\" {\n\t\treturn fmt.Errorf(\"expect application\/json Content-Type, got %s\", mediaType)\n\t}\n\n\tdec := json.NewDecoder(req.Body)\n\tdec.DisallowUnknownFields()\n\treturn dec.Decode(target)\n}\n\n\/\/ renderJSON renders 'v' as JSON and writes it as a response into w.\nfunc renderJSON(w http.ResponseWriter, v any) {\n\tjs, err := json.Marshal(v)\n\tif err != nil {\n\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t\treturn\n\t}\n\tw.Header().Set(\"Content-Type\", \"application\/json\")\n\tw.Write(js)\n}\n","global_vars":"","package":"package main","tags":""} |
|
{"element_type":"function","project_name":"finalHFtest","uuid":"15a5fc86-eb9a-4fb6-8ce7-912d5cc55c77","name":"readRequestJSON","imports":"['\"encoding\/json\"', '\"fmt\"', '\"mime\"', '\"net\/http\"']","structs":"","interfaces":"","file_location":"github.com\/finalHFtest\/\/tmp\/repos\/example\/ragserver\/ragserver-langchaingo\/json.go","code":"func readRequestJSON(req *http.Request, target any) error {\n\tcontentType := req.Header.Get(\"Content-Type\")\n\tmediaType, _, err := mime.ParseMediaType(contentType)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif mediaType != \"application\/json\" {\n\t\treturn fmt.Errorf(\"expect application\/json Content-Type, got %s\", mediaType)\n\t}\n\n\tdec := json.NewDecoder(req.Body)\n\tdec.DisallowUnknownFields()\n\treturn dec.Decode(target)\n}","global_vars":"","package":"main","tags":""} |
|
{"element_type":"function","project_name":"finalHFtest","uuid":"8f2e358e-5e68-42b5-994d-de99d44faa53","name":"renderJSON","imports":"['\"encoding\/json\"', '\"net\/http\"']","structs":"","interfaces":"","file_location":"github.com\/finalHFtest\/\/tmp\/repos\/example\/ragserver\/ragserver-langchaingo\/json.go","code":"func renderJSON(w http.ResponseWriter, v any) {\n\tjs, err := json.Marshal(v)\n\tif err != nil {\n\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t\treturn\n\t}\n\tw.Header().Set(\"Content-Type\", \"application\/json\")\n\tw.Write(js)\n}","global_vars":"","package":"main","tags":""} |
|
{"element_type":"file","project_name":"finalHFtest","uuid":"404ed7f9-1815-4724-8047-d040bd935f57","name":"main.go","imports":"import (\n\t\"cmp\"\n\t\"context\"\n\t\"fmt\"\n\t\"log\"\n\t\"net\/http\"\n\t\"os\"\n\t\"strings\"\n\n\t\"github.com\/tmc\/langchaingo\/embeddings\"\n\t\"github.com\/tmc\/langchaingo\/llms\"\n\t\"github.com\/tmc\/langchaingo\/llms\/googleai\"\n\t\"github.com\/tmc\/langchaingo\/schema\"\n\t\"github.com\/tmc\/langchaingo\/vectorstores\/weaviate\"\n)","structs":"","interfaces":"","file_location":"github.com\/finalHFtest\/\/tmp\/repos\/example\/ragserver\/ragserver-langchaingo\/main.go","code":"\/\/ Copyright 2024 The Go Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style\n\/\/ license that can be found in the LICENSE file.\n\n\/\/ Command ragserver is an HTTP server that implements RAG (Retrieval\n\/\/ Augmented Generation) using the Gemini model and Weaviate, which\n\/\/ are accessed using LangChainGo. See the accompanying README file for\n\/\/ additional details.\npackage main\n\nimport (\n\t\"cmp\"\n\t\"context\"\n\t\"fmt\"\n\t\"log\"\n\t\"net\/http\"\n\t\"os\"\n\t\"strings\"\n\n\t\"github.com\/tmc\/langchaingo\/embeddings\"\n\t\"github.com\/tmc\/langchaingo\/llms\"\n\t\"github.com\/tmc\/langchaingo\/llms\/googleai\"\n\t\"github.com\/tmc\/langchaingo\/schema\"\n\t\"github.com\/tmc\/langchaingo\/vectorstores\/weaviate\"\n)\n\nconst generativeModelName = \"gemini-1.5-flash\"\nconst embeddingModelName = \"text-embedding-004\"\n\n\/\/ This is a standard Go HTTP server. Server state is in the ragServer struct.\n\/\/ The `main` function connects to the required services (Weaviate and Google\n\/\/ AI), initializes the server state and registers HTTP handlers.\nfunc main() {\n\tctx := context.Background()\n\tapiKey := os.Getenv(\"GEMINI_API_KEY\")\n\tgeminiClient, err := googleai.New(ctx,\n\t\tgoogleai.WithAPIKey(apiKey),\n\t\tgoogleai.WithDefaultEmbeddingModel(embeddingModelName))\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\temb, err := embeddings.NewEmbedder(geminiClient)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\twvStore, err := weaviate.New(\n\t\tweaviate.WithEmbedder(emb),\n\t\tweaviate.WithScheme(\"http\"),\n\t\tweaviate.WithHost(\"localhost:\"+cmp.Or(os.Getenv(\"WVPORT\"), \"9035\")),\n\t\tweaviate.WithIndexName(\"Document\"),\n\t)\n\n\tserver := &ragServer{\n\t\tctx: ctx,\n\t\twvStore: wvStore,\n\t\tgeminiClient: geminiClient,\n\t}\n\n\tmux := http.NewServeMux()\n\tmux.HandleFunc(\"POST \/add\/\", server.addDocumentsHandler)\n\tmux.HandleFunc(\"POST \/query\/\", server.queryHandler)\n\n\tport := cmp.Or(os.Getenv(\"SERVERPORT\"), \"9020\")\n\taddress := \"localhost:\" + port\n\tlog.Println(\"listening on\", address)\n\tlog.Fatal(http.ListenAndServe(address, mux))\n}\n\ntype ragServer struct {\n\tctx context.Context\n\twvStore weaviate.Store\n\tgeminiClient *googleai.GoogleAI\n}\n\nfunc (rs *ragServer) addDocumentsHandler(w http.ResponseWriter, req *http.Request) {\n\t\/\/ Parse HTTP request from JSON.\n\ttype document struct {\n\t\tText string\n\t}\n\ttype addRequest struct {\n\t\tDocuments []document\n\t}\n\tar := &addRequest{}\n\n\terr := readRequestJSON(req, ar)\n\tif err != nil {\n\t\thttp.Error(w, err.Error(), http.StatusBadRequest)\n\t\treturn\n\t}\n\n\t\/\/ Store documents and their embeddings in weaviate\n\tvar wvDocs []schema.Document\n\tfor _, doc := range ar.Documents {\n\t\twvDocs = append(wvDocs, schema.Document{PageContent: doc.Text})\n\t}\n\t_, err = rs.wvStore.AddDocuments(rs.ctx, wvDocs)\n\tif err != nil {\n\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t\treturn\n\t}\n}\n\nfunc (rs *ragServer) queryHandler(w http.ResponseWriter, req *http.Request) {\n\t\/\/ Parse HTTP request from JSON.\n\ttype queryRequest struct {\n\t\tContent string\n\t}\n\tqr := &queryRequest{}\n\terr := readRequestJSON(req, qr)\n\tif err != nil {\n\t\thttp.Error(w, err.Error(), http.StatusBadRequest)\n\t\treturn\n\t}\n\n\t\/\/ Find the most similar documents.\n\tdocs, err := rs.wvStore.SimilaritySearch(rs.ctx, qr.Content, 3)\n\tif err != nil {\n\t\thttp.Error(w, fmt.Errorf(\"similarity search: %w\", err).Error(), http.StatusInternalServerError)\n\t\treturn\n\t}\n\tvar docsContents []string\n\tfor _, doc := range docs {\n\t\tdocsContents = append(docsContents, doc.PageContent)\n\t}\n\n\t\/\/ Create a RAG query for the LLM with the most relevant documents as\n\t\/\/ context.\n\tragQuery := fmt.Sprintf(ragTemplateStr, qr.Content, strings.Join(docsContents, \"\\n\"))\n\trespText, err := llms.GenerateFromSinglePrompt(rs.ctx, rs.geminiClient, ragQuery, llms.WithModel(generativeModelName))\n\tif err != nil {\n\t\tlog.Printf(\"calling generative model: %v\", err.Error())\n\t\thttp.Error(w, \"generative model error\", http.StatusInternalServerError)\n\t\treturn\n\t}\n\n\trenderJSON(w, respText)\n}\n\nconst ragTemplateStr = `\nI will ask you a question and will provide some additional context information.\nAssume this context information is factual and correct, as part of internal\ndocumentation.\nIf the question relates to the context, answer it using the context.\nIf the question does not relate to the context, answer it as normal.\n\nFor example, let's say the context has nothing in it about tropical flowers;\nthen if I ask you about tropical flowers, just answer what you know about them\nwithout referring to the context.\n\nFor example, if the context does mention minerology and I ask you about that,\nprovide information from the context along with general knowledge.\n\nQuestion:\n%s\n\nContext:\n%s\n`\n","global_vars":"","package":"package main","tags":""} |
|
{"element_type":"function","project_name":"finalHFtest","uuid":"92895222-4b30-4106-ac67-201cf7e8984d","name":"main","imports":"['\"cmp\"', '\"context\"', '\"log\"', '\"net\/http\"', '\"os\"', '\"github.com\/tmc\/langchaingo\/embeddings\"', '\"github.com\/tmc\/langchaingo\/llms\/googleai\"', '\"github.com\/tmc\/langchaingo\/vectorstores\/weaviate\"']","structs":"['ragServer']","interfaces":"","file_location":"github.com\/finalHFtest\/\/tmp\/repos\/example\/ragserver\/ragserver-langchaingo\/main.go","code":"func main() {\n\tctx := context.Background()\n\tapiKey := os.Getenv(\"GEMINI_API_KEY\")\n\tgeminiClient, err := googleai.New(ctx,\n\t\tgoogleai.WithAPIKey(apiKey),\n\t\tgoogleai.WithDefaultEmbeddingModel(embeddingModelName))\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\temb, err := embeddings.NewEmbedder(geminiClient)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\twvStore, err := weaviate.New(\n\t\tweaviate.WithEmbedder(emb),\n\t\tweaviate.WithScheme(\"http\"),\n\t\tweaviate.WithHost(\"localhost:\"+cmp.Or(os.Getenv(\"WVPORT\"), \"9035\")),\n\t\tweaviate.WithIndexName(\"Document\"),\n\t)\n\n\tserver := &ragServer{\n\t\tctx: ctx,\n\t\twvStore: wvStore,\n\t\tgeminiClient: geminiClient,\n\t}\n\n\tmux := http.NewServeMux()\n\tmux.HandleFunc(\"POST \/add\/\", server.addDocumentsHandler)\n\tmux.HandleFunc(\"POST \/query\/\", server.queryHandler)\n\n\tport := cmp.Or(os.Getenv(\"SERVERPORT\"), \"9020\")\n\taddress := \"localhost:\" + port\n\tlog.Println(\"listening on\", address)\n\tlog.Fatal(http.ListenAndServe(address, mux))\n}","global_vars":"","package":"main","tags":""} |
|
{"element_type":"function","project_name":"finalHFtest","uuid":"d157be31-251d-476a-bfe3-0937f5d11d87","name":"addDocumentsHandler","imports":"['\"net\/http\"', '\"github.com\/tmc\/langchaingo\/embeddings\"', '\"github.com\/tmc\/langchaingo\/schema\"', '\"github.com\/tmc\/langchaingo\/vectorstores\/weaviate\"']","structs":"['ragServer']","interfaces":"","file_location":"github.com\/finalHFtest\/\/tmp\/repos\/example\/ragserver\/ragserver-langchaingo\/main.go","code":"func (rs *ragServer) addDocumentsHandler(w http.ResponseWriter, req *http.Request) {\n\t\/\/ Parse HTTP request from JSON.\n\ttype document struct {\n\t\tText string\n\t}\n\ttype addRequest struct {\n\t\tDocuments []document\n\t}\n\tar := &addRequest{}\n\n\terr := readRequestJSON(req, ar)\n\tif err != nil {\n\t\thttp.Error(w, err.Error(), http.StatusBadRequest)\n\t\treturn\n\t}\n\n\t\/\/ Store documents and their embeddings in weaviate\n\tvar wvDocs []schema.Document\n\tfor _, doc := range ar.Documents {\n\t\twvDocs = append(wvDocs, schema.Document{PageContent: doc.Text})\n\t}\n\t_, err = rs.wvStore.AddDocuments(rs.ctx, wvDocs)\n\tif err != nil {\n\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t\treturn\n\t}\n}","global_vars":"","package":"main","tags":""} |
|
{"element_type":"function","project_name":"finalHFtest","uuid":"00e83577-d7b2-40e5-a203-affb28d5f504","name":"queryHandler","imports":"['\"context\"', '\"fmt\"', '\"log\"', '\"net\/http\"', '\"strings\"', '\"github.com\/tmc\/langchaingo\/llms\"']","structs":"['ragServer']","interfaces":"","file_location":"github.com\/finalHFtest\/\/tmp\/repos\/example\/ragserver\/ragserver-langchaingo\/main.go","code":"func (rs *ragServer) queryHandler(w http.ResponseWriter, req *http.Request) {\n\t\/\/ Parse HTTP request from JSON.\n\ttype queryRequest struct {\n\t\tContent string\n\t}\n\tqr := &queryRequest{}\n\terr := readRequestJSON(req, qr)\n\tif err != nil {\n\t\thttp.Error(w, err.Error(), http.StatusBadRequest)\n\t\treturn\n\t}\n\n\t\/\/ Find the most similar documents.\n\tdocs, err := rs.wvStore.SimilaritySearch(rs.ctx, qr.Content, 3)\n\tif err != nil {\n\t\thttp.Error(w, fmt.Errorf(\"similarity search: %w\", err).Error(), http.StatusInternalServerError)\n\t\treturn\n\t}\n\tvar docsContents []string\n\tfor _, doc := range docs {\n\t\tdocsContents = append(docsContents, doc.PageContent)\n\t}\n\n\t\/\/ Create a RAG query for the LLM with the most relevant documents as\n\t\/\/ context.\n\tragQuery := fmt.Sprintf(ragTemplateStr, qr.Content, strings.Join(docsContents, \"\\n\"))\n\trespText, err := llms.GenerateFromSinglePrompt(rs.ctx, rs.geminiClient, ragQuery, llms.WithModel(generativeModelName))\n\tif err != nil {\n\t\tlog.Printf(\"calling generative model: %v\", err.Error())\n\t\thttp.Error(w, \"generative model error\", http.StatusInternalServerError)\n\t\treturn\n\t}\n\n\trenderJSON(w, respText)\n}","global_vars":"","package":"main","tags":""} |
|
{"element_type":"file","project_name":"finalHFtest","uuid":"1f7f810d-c7a0-4382-9272-f57c58bfb8ec","name":"json.go","imports":"import (\n\t\"encoding\/json\"\n\t\"fmt\"\n\t\"mime\"\n\t\"net\/http\"\n)","structs":"","interfaces":"","file_location":"github.com\/finalHFtest\/\/tmp\/repos\/example\/ragserver\/ragserver\/json.go","code":"\/\/ Copyright 2024 The Go Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style\n\/\/ license that can be found in the LICENSE file.\n\npackage main\n\nimport (\n\t\"encoding\/json\"\n\t\"fmt\"\n\t\"mime\"\n\t\"net\/http\"\n)\n\n\/\/ readRequestJSON expects req to have a JSON content type with a body that\n\/\/ contains a JSON-encoded value complying with the underlying type of target.\n\/\/ It populates target, or returns an error.\nfunc readRequestJSON(req *http.Request, target any) error {\n\tcontentType := req.Header.Get(\"Content-Type\")\n\tmediaType, _, err := mime.ParseMediaType(contentType)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif mediaType != \"application\/json\" {\n\t\treturn fmt.Errorf(\"expect application\/json Content-Type, got %s\", mediaType)\n\t}\n\n\tdec := json.NewDecoder(req.Body)\n\tdec.DisallowUnknownFields()\n\treturn dec.Decode(target)\n}\n\n\/\/ renderJSON renders 'v' as JSON and writes it as a response into w.\nfunc renderJSON(w http.ResponseWriter, v any) {\n\tjs, err := json.Marshal(v)\n\tif err != nil {\n\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t\treturn\n\t}\n\tw.Header().Set(\"Content-Type\", \"application\/json\")\n\tw.Write(js)\n}\n","global_vars":"","package":"package main","tags":""} |
|
{"element_type":"function","project_name":"finalHFtest","uuid":"dc70a9b5-987b-4733-bcf7-dd02141a8366","name":"readRequestJSON","imports":"['\"encoding\/json\"', '\"fmt\"', '\"mime\"', '\"net\/http\"']","structs":"","interfaces":"","file_location":"github.com\/finalHFtest\/\/tmp\/repos\/example\/ragserver\/ragserver\/json.go","code":"func readRequestJSON(req *http.Request, target any) error {\n\tcontentType := req.Header.Get(\"Content-Type\")\n\tmediaType, _, err := mime.ParseMediaType(contentType)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif mediaType != \"application\/json\" {\n\t\treturn fmt.Errorf(\"expect application\/json Content-Type, got %s\", mediaType)\n\t}\n\n\tdec := json.NewDecoder(req.Body)\n\tdec.DisallowUnknownFields()\n\treturn dec.Decode(target)\n}","global_vars":"","package":"main","tags":""} |
|
{"element_type":"function","project_name":"finalHFtest","uuid":"8d659af2-b353-45f8-9883-4ca628f3cdb1","name":"renderJSON","imports":"['\"encoding\/json\"', '\"net\/http\"']","structs":"","interfaces":"","file_location":"github.com\/finalHFtest\/\/tmp\/repos\/example\/ragserver\/ragserver\/json.go","code":"func renderJSON(w http.ResponseWriter, v any) {\n\tjs, err := json.Marshal(v)\n\tif err != nil {\n\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t\treturn\n\t}\n\tw.Header().Set(\"Content-Type\", \"application\/json\")\n\tw.Write(js)\n}","global_vars":"","package":"main","tags":""} |
|
{"element_type":"file","project_name":"finalHFtest","uuid":"93d38792-2a87-4945-94b6-6e6792cf7cbf","name":"main.go","imports":"import (\n\t\"cmp\"\n\t\"context\"\n\t\"fmt\"\n\t\"log\"\n\t\"net\/http\"\n\t\"os\"\n\t\"strings\"\n\n\t\"github.com\/google\/generative-ai-go\/genai\"\n\t\"github.com\/weaviate\/weaviate-go-client\/v4\/weaviate\"\n\t\"github.com\/weaviate\/weaviate-go-client\/v4\/weaviate\/graphql\"\n\t\"github.com\/weaviate\/weaviate\/entities\/models\"\n\t\"google.golang.org\/api\/option\"\n)","structs":"","interfaces":"","file_location":"github.com\/finalHFtest\/\/tmp\/repos\/example\/ragserver\/ragserver\/main.go","code":"\/\/ Copyright 2024 The Go Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style\n\/\/ license that can be found in the LICENSE file.\n\n\/\/ Command ragserver is an HTTP server that implements RAG (Retrieval\n\/\/ Augmented Generation) using the Gemini model and Weaviate. See the\n\/\/ accompanying README file for additional details.\npackage main\n\nimport (\n\t\"cmp\"\n\t\"context\"\n\t\"fmt\"\n\t\"log\"\n\t\"net\/http\"\n\t\"os\"\n\t\"strings\"\n\n\t\"github.com\/google\/generative-ai-go\/genai\"\n\t\"github.com\/weaviate\/weaviate-go-client\/v4\/weaviate\"\n\t\"github.com\/weaviate\/weaviate-go-client\/v4\/weaviate\/graphql\"\n\t\"github.com\/weaviate\/weaviate\/entities\/models\"\n\t\"google.golang.org\/api\/option\"\n)\n\nconst generativeModelName = \"gemini-1.5-flash\"\nconst embeddingModelName = \"text-embedding-004\"\n\n\/\/ This is a standard Go HTTP server. Server state is in the ragServer struct.\n\/\/ The `main` function connects to the required services (Weaviate and Google\n\/\/ AI), initializes the server state and registers HTTP handlers.\nfunc main() {\n\tctx := context.Background()\n\twvClient, err := initWeaviate(ctx)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tapiKey := os.Getenv(\"GEMINI_API_KEY\")\n\tgenaiClient, err := genai.NewClient(ctx, option.WithAPIKey(apiKey))\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tdefer genaiClient.Close()\n\n\tserver := &ragServer{\n\t\tctx: ctx,\n\t\twvClient: wvClient,\n\t\tgenModel: genaiClient.GenerativeModel(generativeModelName),\n\t\tembModel: genaiClient.EmbeddingModel(embeddingModelName),\n\t}\n\n\tmux := http.NewServeMux()\n\tmux.HandleFunc(\"POST \/add\/\", server.addDocumentsHandler)\n\tmux.HandleFunc(\"POST \/query\/\", server.queryHandler)\n\n\tport := cmp.Or(os.Getenv(\"SERVERPORT\"), \"9020\")\n\taddress := \"localhost:\" + port\n\tlog.Println(\"listening on\", address)\n\tlog.Fatal(http.ListenAndServe(address, mux))\n}\n\ntype ragServer struct {\n\tctx context.Context\n\twvClient *weaviate.Client\n\tgenModel *genai.GenerativeModel\n\tembModel *genai.EmbeddingModel\n}\n\nfunc (rs *ragServer) addDocumentsHandler(w http.ResponseWriter, req *http.Request) {\n\t\/\/ Parse HTTP request from JSON.\n\ttype document struct {\n\t\tText string\n\t}\n\ttype addRequest struct {\n\t\tDocuments []document\n\t}\n\tar := &addRequest{}\n\n\terr := readRequestJSON(req, ar)\n\tif err != nil {\n\t\thttp.Error(w, err.Error(), http.StatusBadRequest)\n\t\treturn\n\t}\n\n\t\/\/ Use the batch embedding API to embed all documents at once.\n\tbatch := rs.embModel.NewBatch()\n\tfor _, doc := range ar.Documents {\n\t\tbatch.AddContent(genai.Text(doc.Text))\n\t}\n\tlog.Printf(\"invoking embedding model with %v documents\", len(ar.Documents))\n\trsp, err := rs.embModel.BatchEmbedContents(rs.ctx, batch)\n\tif err != nil {\n\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t\treturn\n\t}\n\tif len(rsp.Embeddings) != len(ar.Documents) {\n\t\thttp.Error(w, \"embedded batch size mismatch\", http.StatusInternalServerError)\n\t\treturn\n\t}\n\n\t\/\/ Convert our documents - along with their embedding vectors - into types\n\t\/\/ used by the Weaviate client library.\n\tobjects := make([]*models.Object, len(ar.Documents))\n\tfor i, doc := range ar.Documents {\n\t\tobjects[i] = &models.Object{\n\t\t\tClass: \"Document\",\n\t\t\tProperties: map[string]any{\n\t\t\t\t\"text\": doc.Text,\n\t\t\t},\n\t\t\tVector: rsp.Embeddings[i].Values,\n\t\t}\n\t}\n\n\t\/\/ Store documents with embeddings in the Weaviate DB.\n\tlog.Printf(\"storing %v objects in weaviate\", len(objects))\n\t_, err = rs.wvClient.Batch().ObjectsBatcher().WithObjects(objects...).Do(rs.ctx)\n\tif err != nil {\n\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t\treturn\n\t}\n}\n\nfunc (rs *ragServer) queryHandler(w http.ResponseWriter, req *http.Request) {\n\t\/\/ Parse HTTP request from JSON.\n\ttype queryRequest struct {\n\t\tContent string\n\t}\n\tqr := &queryRequest{}\n\terr := readRequestJSON(req, qr)\n\tif err != nil {\n\t\thttp.Error(w, err.Error(), http.StatusBadRequest)\n\t\treturn\n\t}\n\n\t\/\/ Embed the query contents.\n\trsp, err := rs.embModel.EmbedContent(rs.ctx, genai.Text(qr.Content))\n\tif err != nil {\n\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t\treturn\n\t}\n\n\t\/\/ Search weaviate to find the most relevant (closest in vector space)\n\t\/\/ documents to the query.\n\tgql := rs.wvClient.GraphQL()\n\tresult, err := gql.Get().\n\t\tWithNearVector(\n\t\t\tgql.NearVectorArgBuilder().WithVector(rsp.Embedding.Values)).\n\t\tWithClassName(\"Document\").\n\t\tWithFields(graphql.Field{Name: \"text\"}).\n\t\tWithLimit(3).\n\t\tDo(rs.ctx)\n\tif werr := combinedWeaviateError(result, err); werr != nil {\n\t\thttp.Error(w, werr.Error(), http.StatusInternalServerError)\n\t\treturn\n\t}\n\n\tcontents, err := decodeGetResults(result)\n\tif err != nil {\n\t\thttp.Error(w, fmt.Errorf(\"reading weaviate response: %w\", err).Error(), http.StatusInternalServerError)\n\t\treturn\n\t}\n\n\t\/\/ Create a RAG query for the LLM with the most relevant documents as\n\t\/\/ context.\n\tragQuery := fmt.Sprintf(ragTemplateStr, qr.Content, strings.Join(contents, \"\\n\"))\n\tresp, err := rs.genModel.GenerateContent(rs.ctx, genai.Text(ragQuery))\n\tif err != nil {\n\t\tlog.Printf(\"calling generative model: %v\", err.Error())\n\t\thttp.Error(w, \"generative model error\", http.StatusInternalServerError)\n\t\treturn\n\t}\n\n\tif len(resp.Candidates) != 1 {\n\t\tlog.Printf(\"got %v candidates, expected 1\", len(resp.Candidates))\n\t\thttp.Error(w, \"generative model error\", http.StatusInternalServerError)\n\t\treturn\n\t}\n\n\tvar respTexts []string\n\tfor _, part := range resp.Candidates[0].Content.Parts {\n\t\tif pt, ok := part.(genai.Text); ok {\n\t\t\trespTexts = append(respTexts, string(pt))\n\t\t} else {\n\t\t\tlog.Printf(\"bad type of part: %v\", pt)\n\t\t\thttp.Error(w, \"generative model error\", http.StatusInternalServerError)\n\t\t\treturn\n\t\t}\n\t}\n\n\trenderJSON(w, strings.Join(respTexts, \"\\n\"))\n}\n\nconst ragTemplateStr = `\nI will ask you a question and will provide some additional context information.\nAssume this context information is factual and correct, as part of internal\ndocumentation.\nIf the question relates to the context, answer it using the context.\nIf the question does not relate to the context, answer it as normal.\n\nFor example, let's say the context has nothing in it about tropical flowers;\nthen if I ask you about tropical flowers, just answer what you know about them\nwithout referring to the context.\n\nFor example, if the context does mention minerology and I ask you about that,\nprovide information from the context along with general knowledge.\n\nQuestion:\n%s\n\nContext:\n%s\n`\n\n\/\/ decodeGetResults decodes the result returned by Weaviate's GraphQL Get\n\/\/ query; these are returned as a nested map[string]any (just like JSON\n\/\/ unmarshaled into a map[string]any). We have to extract all document contents\n\/\/ as a list of strings.\nfunc decodeGetResults(result *models.GraphQLResponse) ([]string, error) {\n\tdata, ok := result.Data[\"Get\"]\n\tif !ok {\n\t\treturn nil, fmt.Errorf(\"Get key not found in result\")\n\t}\n\tdoc, ok := data.(map[string]any)\n\tif !ok {\n\t\treturn nil, fmt.Errorf(\"Get key unexpected type\")\n\t}\n\tslc, ok := doc[\"Document\"].([]any)\n\tif !ok {\n\t\treturn nil, fmt.Errorf(\"Document is not a list of results\")\n\t}\n\n\tvar out []string\n\tfor _, s := range slc {\n\t\tsmap, ok := s.(map[string]any)\n\t\tif !ok {\n\t\t\treturn nil, fmt.Errorf(\"invalid element in list of documents\")\n\t\t}\n\t\ts, ok := smap[\"text\"].(string)\n\t\tif !ok {\n\t\t\treturn nil, fmt.Errorf(\"expected string in list of documents\")\n\t\t}\n\t\tout = append(out, s)\n\t}\n\treturn out, nil\n}\n","global_vars":"","package":"package main","tags":""} |
|
{"element_type":"function","project_name":"finalHFtest","uuid":"9656af8f-9433-4970-a5d3-1a3848ec1d0e","name":"main","imports":"['\"cmp\"', '\"context\"', '\"log\"', '\"net\/http\"', '\"os\"', '\"github.com\/google\/generative-ai-go\/genai\"', '\"google.golang.org\/api\/option\"']","structs":"['ragServer']","interfaces":"","file_location":"github.com\/finalHFtest\/\/tmp\/repos\/example\/ragserver\/ragserver\/main.go","code":"func main() {\n\tctx := context.Background()\n\twvClient, err := initWeaviate(ctx)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tapiKey := os.Getenv(\"GEMINI_API_KEY\")\n\tgenaiClient, err := genai.NewClient(ctx, option.WithAPIKey(apiKey))\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tdefer genaiClient.Close()\n\n\tserver := &ragServer{\n\t\tctx: ctx,\n\t\twvClient: wvClient,\n\t\tgenModel: genaiClient.GenerativeModel(generativeModelName),\n\t\tembModel: genaiClient.EmbeddingModel(embeddingModelName),\n\t}\n\n\tmux := http.NewServeMux()\n\tmux.HandleFunc(\"POST \/add\/\", server.addDocumentsHandler)\n\tmux.HandleFunc(\"POST \/query\/\", server.queryHandler)\n\n\tport := cmp.Or(os.Getenv(\"SERVERPORT\"), \"9020\")\n\taddress := \"localhost:\" + port\n\tlog.Println(\"listening on\", address)\n\tlog.Fatal(http.ListenAndServe(address, mux))\n}","global_vars":"","package":"main","tags":""} |
|
{"element_type":"function","project_name":"finalHFtest","uuid":"625d0328-8ca8-4381-92b5-8348fdb41111","name":"addDocumentsHandler","imports":"['\"log\"', '\"net\/http\"', '\"github.com\/google\/generative-ai-go\/genai\"', '\"github.com\/weaviate\/weaviate-go-client\/v4\/weaviate\"', '\"github.com\/weaviate\/weaviate\/entities\/models\"']","structs":"['ragServer']","interfaces":"","file_location":"github.com\/finalHFtest\/\/tmp\/repos\/example\/ragserver\/ragserver\/main.go","code":"func (rs *ragServer) addDocumentsHandler(w http.ResponseWriter, req *http.Request) {\n\t\/\/ Parse HTTP request from JSON.\n\ttype document struct {\n\t\tText string\n\t}\n\ttype addRequest struct {\n\t\tDocuments []document\n\t}\n\tar := &addRequest{}\n\n\terr := readRequestJSON(req, ar)\n\tif err != nil {\n\t\thttp.Error(w, err.Error(), http.StatusBadRequest)\n\t\treturn\n\t}\n\n\t\/\/ Use the batch embedding API to embed all documents at once.\n\tbatch := rs.embModel.NewBatch()\n\tfor _, doc := range ar.Documents {\n\t\tbatch.AddContent(genai.Text(doc.Text))\n\t}\n\tlog.Printf(\"invoking embedding model with %v documents\", len(ar.Documents))\n\trsp, err := rs.embModel.BatchEmbedContents(rs.ctx, batch)\n\tif err != nil {\n\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t\treturn\n\t}\n\tif len(rsp.Embeddings) != len(ar.Documents) {\n\t\thttp.Error(w, \"embedded batch size mismatch\", http.StatusInternalServerError)\n\t\treturn\n\t}\n\n\t\/\/ Convert our documents - along with their embedding vectors - into types\n\t\/\/ used by the Weaviate client library.\n\tobjects := make([]*models.Object, len(ar.Documents))\n\tfor i, doc := range ar.Documents {\n\t\tobjects[i] = &models.Object{\n\t\t\tClass: \"Document\",\n\t\t\tProperties: map[string]any{\n\t\t\t\t\"text\": doc.Text,\n\t\t\t},\n\t\t\tVector: rsp.Embeddings[i].Values,\n\t\t}\n\t}\n\n\t\/\/ Store documents with embeddings in the Weaviate DB.\n\tlog.Printf(\"storing %v objects in weaviate\", len(objects))\n\t_, err = rs.wvClient.Batch().ObjectsBatcher().WithObjects(objects...).Do(rs.ctx)\n\tif err != nil {\n\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t\treturn\n\t}\n}","global_vars":"","package":"main","tags":""} |
|
{"element_type":"function","project_name":"finalHFtest","uuid":"06526352-2b7f-4cb4-bcda-f7d0e51de2cc","name":"queryHandler","imports":"['\"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\"']","structs":"['ragServer']","interfaces":"","file_location":"github.com\/finalHFtest\/\/tmp\/repos\/example\/ragserver\/ragserver\/main.go","code":"func (rs *ragServer) queryHandler(w http.ResponseWriter, req *http.Request) {\n\t\/\/ Parse HTTP request from JSON.\n\ttype queryRequest struct {\n\t\tContent string\n\t}\n\tqr := &queryRequest{}\n\terr := readRequestJSON(req, qr)\n\tif err != nil {\n\t\thttp.Error(w, err.Error(), http.StatusBadRequest)\n\t\treturn\n\t}\n\n\t\/\/ Embed the query contents.\n\trsp, err := rs.embModel.EmbedContent(rs.ctx, genai.Text(qr.Content))\n\tif err != nil {\n\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t\treturn\n\t}\n\n\t\/\/ Search weaviate to find the most relevant (closest in vector space)\n\t\/\/ documents to the query.\n\tgql := rs.wvClient.GraphQL()\n\tresult, err := gql.Get().\n\t\tWithNearVector(\n\t\t\tgql.NearVectorArgBuilder().WithVector(rsp.Embedding.Values)).\n\t\tWithClassName(\"Document\").\n\t\tWithFields(graphql.Field{Name: \"text\"}).\n\t\tWithLimit(3).\n\t\tDo(rs.ctx)\n\tif werr := combinedWeaviateError(result, err); werr != nil {\n\t\thttp.Error(w, werr.Error(), http.StatusInternalServerError)\n\t\treturn\n\t}\n\n\tcontents, err := decodeGetResults(result)\n\tif err != nil {\n\t\thttp.Error(w, fmt.Errorf(\"reading weaviate response: %w\", err).Error(), http.StatusInternalServerError)\n\t\treturn\n\t}\n\n\t\/\/ Create a RAG query for the LLM with the most relevant documents as\n\t\/\/ context.\n\tragQuery := fmt.Sprintf(ragTemplateStr, qr.Content, strings.Join(contents, \"\\n\"))\n\tresp, err := rs.genModel.GenerateContent(rs.ctx, genai.Text(ragQuery))\n\tif err != nil {\n\t\tlog.Printf(\"calling generative model: %v\", err.Error())\n\t\thttp.Error(w, \"generative model error\", http.StatusInternalServerError)\n\t\treturn\n\t}\n\n\tif len(resp.Candidates) != 1 {\n\t\tlog.Printf(\"got %v candidates, expected 1\", len(resp.Candidates))\n\t\thttp.Error(w, \"generative model error\", http.StatusInternalServerError)\n\t\treturn\n\t}\n\n\tvar respTexts []string\n\tfor _, part := range resp.Candidates[0].Content.Parts {\n\t\tif pt, ok := part.(genai.Text); ok {\n\t\t\trespTexts = append(respTexts, string(pt))\n\t\t} else {\n\t\t\tlog.Printf(\"bad type of part: %v\", pt)\n\t\t\thttp.Error(w, \"generative model error\", http.StatusInternalServerError)\n\t\t\treturn\n\t\t}\n\t}\n\n\trenderJSON(w, strings.Join(respTexts, \"\\n\"))\n}","global_vars":"","package":"main","tags":""} |
|
{"element_type":"function","project_name":"finalHFtest","uuid":"a4cdb479-b145-49b0-8279-95c358ae08e4","name":"decodeGetResults","imports":"['\"fmt\"', '\"github.com\/weaviate\/weaviate\/entities\/models\"']","structs":"","interfaces":"","file_location":"github.com\/finalHFtest\/\/tmp\/repos\/example\/ragserver\/ragserver\/main.go","code":"func decodeGetResults(result *models.GraphQLResponse) ([]string, error) {\n\tdata, ok := result.Data[\"Get\"]\n\tif !ok {\n\t\treturn nil, fmt.Errorf(\"Get key not found in result\")\n\t}\n\tdoc, ok := data.(map[string]any)\n\tif !ok {\n\t\treturn nil, fmt.Errorf(\"Get key unexpected type\")\n\t}\n\tslc, ok := doc[\"Document\"].([]any)\n\tif !ok {\n\t\treturn nil, fmt.Errorf(\"Document is not a list of results\")\n\t}\n\n\tvar out []string\n\tfor _, s := range slc {\n\t\tsmap, ok := s.(map[string]any)\n\t\tif !ok {\n\t\t\treturn nil, fmt.Errorf(\"invalid element in list of documents\")\n\t\t}\n\t\ts, ok := smap[\"text\"].(string)\n\t\tif !ok {\n\t\t\treturn nil, fmt.Errorf(\"expected string in list of documents\")\n\t\t}\n\t\tout = append(out, s)\n\t}\n\treturn out, nil\n}","global_vars":"","package":"main","tags":""} |
|
{"element_type":"file","project_name":"finalHFtest","uuid":"11d5b9a1-9f32-4ce0-b124-30be8733f83c","name":"weaviate.go","imports":"import (\n\t\"cmp\"\n\t\"context\"\n\t\"fmt\"\n\t\"os\"\n\n\t\"github.com\/weaviate\/weaviate-go-client\/v4\/weaviate\"\n\t\"github.com\/weaviate\/weaviate\/entities\/models\"\n)","structs":"","interfaces":"","file_location":"github.com\/finalHFtest\/\/tmp\/repos\/example\/ragserver\/ragserver\/weaviate.go","code":"\/\/ Copyright 2024 The Go Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style\n\/\/ license that can be found in the LICENSE file.\n\npackage main\n\n\/\/ Utilities for working with Weaviate.\n\nimport (\n\t\"cmp\"\n\t\"context\"\n\t\"fmt\"\n\t\"os\"\n\n\t\"github.com\/weaviate\/weaviate-go-client\/v4\/weaviate\"\n\t\"github.com\/weaviate\/weaviate\/entities\/models\"\n)\n\n\/\/ initWeaviate initializes a weaviate client for our application.\nfunc initWeaviate(ctx context.Context) (*weaviate.Client, error) {\n\tclient, err := weaviate.NewClient(weaviate.Config{\n\t\tHost: \"localhost:\" + cmp.Or(os.Getenv(\"WVPORT\"), \"9035\"),\n\t\tScheme: \"http\",\n\t})\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"initializing weaviate: %w\", err)\n\t}\n\n\t\/\/ Create a new class (collection) in weaviate if it doesn't exist yet.\n\tcls := &models.Class{\n\t\tClass: \"Document\",\n\t\tVectorizer: \"none\",\n\t}\n\texists, err := client.Schema().ClassExistenceChecker().WithClassName(cls.Class).Do(ctx)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"weaviate error: %w\", err)\n\t}\n\tif !exists {\n\t\terr = client.Schema().ClassCreator().WithClass(cls).Do(ctx)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"weaviate error: %w\", err)\n\t\t}\n\t}\n\n\treturn client, nil\n}\n\n\/\/ combinedWeaviateError generates an error if err is non-nil or result has\n\/\/ errors, and returns an error (or nil if there's no error). It's useful for\n\/\/ the results of the Weaviate GraphQL API's \"Do\" calls.\nfunc combinedWeaviateError(result *models.GraphQLResponse, err error) error {\n\tif err != nil {\n\t\treturn err\n\t}\n\tif len(result.Errors) != 0 {\n\t\tvar ss []string\n\t\tfor _, e := range result.Errors {\n\t\t\tss = append(ss, e.Message)\n\t\t}\n\t\treturn fmt.Errorf(\"weaviate error: %v\", ss)\n\t}\n\treturn nil\n}\n","global_vars":"","package":"package main","tags":""} |
|
{"element_type":"function","project_name":"finalHFtest","uuid":"35d70080-7b70-4888-9e2a-44010ab5b81b","name":"initWeaviate","imports":"['\"cmp\"', '\"context\"', '\"fmt\"', '\"os\"', '\"github.com\/weaviate\/weaviate-go-client\/v4\/weaviate\"', '\"github.com\/weaviate\/weaviate\/entities\/models\"']","structs":"","interfaces":"","file_location":"github.com\/finalHFtest\/\/tmp\/repos\/example\/ragserver\/ragserver\/weaviate.go","code":"func initWeaviate(ctx context.Context) (*weaviate.Client, error) {\n\tclient, err := weaviate.NewClient(weaviate.Config{\n\t\tHost: \"localhost:\" + cmp.Or(os.Getenv(\"WVPORT\"), \"9035\"),\n\t\tScheme: \"http\",\n\t})\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"initializing weaviate: %w\", err)\n\t}\n\n\t\/\/ Create a new class (collection) in weaviate if it doesn't exist yet.\n\tcls := &models.Class{\n\t\tClass: \"Document\",\n\t\tVectorizer: \"none\",\n\t}\n\texists, err := client.Schema().ClassExistenceChecker().WithClassName(cls.Class).Do(ctx)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"weaviate error: %w\", err)\n\t}\n\tif !exists {\n\t\terr = client.Schema().ClassCreator().WithClass(cls).Do(ctx)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"weaviate error: %w\", err)\n\t\t}\n\t}\n\n\treturn client, nil\n}","global_vars":"","package":"main","tags":""} |
|
{"element_type":"function","project_name":"finalHFtest","uuid":"e41a6de1-c6ca-4f75-8920-28eb86ab3a54","name":"combinedWeaviateError","imports":"['\"fmt\"', '\"github.com\/weaviate\/weaviate-go-client\/v4\/weaviate\"', '\"github.com\/weaviate\/weaviate\/entities\/models\"']","structs":"","interfaces":"","file_location":"github.com\/finalHFtest\/\/tmp\/repos\/example\/ragserver\/ragserver\/weaviate.go","code":"func combinedWeaviateError(result *models.GraphQLResponse, err error) error {\n\tif err != nil {\n\t\treturn err\n\t}\n\tif len(result.Errors) != 0 {\n\t\tvar ss []string\n\t\tfor _, e := range result.Errors {\n\t\t\tss = append(ss, e.Message)\n\t\t}\n\t\treturn fmt.Errorf(\"weaviate error: %v\", ss)\n\t}\n\treturn nil\n}","global_vars":"","package":"main","tags":""} |
|
{"element_type":"file","project_name":"finalHFtest","uuid":"4043fa37-199a-4dbb-848f-fe142f607298","name":"indent_handler.go","imports":"import (\n\t\"context\"\n\t\"fmt\"\n\t\"io\"\n\t\"log\/slog\"\n\t\"runtime\"\n\t\"sync\"\n\t\"time\"\n)","structs":"","interfaces":"","file_location":"github.com\/finalHFtest\/\/tmp\/repos\/example\/slog-handler-guide\/indenthandler1\/indent_handler.go","code":"\/\/go:build go1.21\n\npackage indenthandler\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\t\"io\"\n\t\"log\/slog\"\n\t\"runtime\"\n\t\"sync\"\n\t\"time\"\n)\n\n\/\/ !+types\ntype IndentHandler struct {\n\topts Options\n\t\/\/ TODO: state for WithGroup and WithAttrs\n\tmu *sync.Mutex\n\tout io.Writer\n}\n\ntype Options struct {\n\t\/\/ Level reports the minimum level to log.\n\t\/\/ Levels with lower levels are discarded.\n\t\/\/ If nil, the Handler uses [slog.LevelInfo].\n\tLevel slog.Leveler\n}\n\nfunc New(out io.Writer, opts *Options) *IndentHandler {\n\th := &IndentHandler{out: out, mu: &sync.Mutex{}}\n\tif opts != nil {\n\t\th.opts = *opts\n\t}\n\tif h.opts.Level == nil {\n\t\th.opts.Level = slog.LevelInfo\n\t}\n\treturn h\n}\n\n\/\/!-types\n\n\/\/ !+enabled\nfunc (h *IndentHandler) Enabled(ctx context.Context, level slog.Level) bool {\n\treturn level >= h.opts.Level.Level()\n}\n\n\/\/!-enabled\n\nfunc (h *IndentHandler) WithGroup(name string) slog.Handler {\n\t\/\/ TODO: implement.\n\treturn h\n}\n\nfunc (h *IndentHandler) WithAttrs(attrs []slog.Attr) slog.Handler {\n\t\/\/ TODO: implement.\n\treturn h\n}\n\n\/\/ !+handle\nfunc (h *IndentHandler) Handle(ctx context.Context, r slog.Record) error {\n\tbuf := make([]byte, 0, 1024)\n\tif !r.Time.IsZero() {\n\t\tbuf = h.appendAttr(buf, slog.Time(slog.TimeKey, r.Time), 0)\n\t}\n\tbuf = h.appendAttr(buf, slog.Any(slog.LevelKey, r.Level), 0)\n\tif r.PC != 0 {\n\t\tfs := runtime.CallersFrames([]uintptr{r.PC})\n\t\tf, _ := fs.Next()\n\t\tbuf = h.appendAttr(buf, slog.String(slog.SourceKey, fmt.Sprintf(\"%s:%d\", f.File, f.Line)), 0)\n\t}\n\tbuf = h.appendAttr(buf, slog.String(slog.MessageKey, r.Message), 0)\n\tindentLevel := 0\n\t\/\/ TODO: output the Attrs and groups from WithAttrs and WithGroup.\n\tr.Attrs(func(a slog.Attr) bool {\n\t\tbuf = h.appendAttr(buf, a, indentLevel)\n\t\treturn true\n\t})\n\tbuf = append(buf, \"---\\n\"...)\n\th.mu.Lock()\n\tdefer h.mu.Unlock()\n\t_, err := h.out.Write(buf)\n\treturn err\n}\n\n\/\/!-handle\n\n\/\/ !+appendAttr\nfunc (h *IndentHandler) appendAttr(buf []byte, a slog.Attr, indentLevel int) []byte {\n\t\/\/ Resolve the Attr's value before doing anything else.\n\ta.Value = a.Value.Resolve()\n\t\/\/ Ignore empty Attrs.\n\tif a.Equal(slog.Attr{}) {\n\t\treturn buf\n\t}\n\t\/\/ Indent 4 spaces per level.\n\tbuf = fmt.Appendf(buf, \"%*s\", indentLevel*4, \"\")\n\tswitch a.Value.Kind() {\n\tcase slog.KindString:\n\t\t\/\/ Quote string values, to make them easy to parse.\n\t\tbuf = fmt.Appendf(buf, \"%s: %q\\n\", a.Key, a.Value.String())\n\tcase slog.KindTime:\n\t\t\/\/ Write times in a standard way, without the monotonic time.\n\t\tbuf = fmt.Appendf(buf, \"%s: %s\\n\", a.Key, a.Value.Time().Format(time.RFC3339Nano))\n\tcase slog.KindGroup:\n\t\tattrs := a.Value.Group()\n\t\t\/\/ Ignore empty groups.\n\t\tif len(attrs) == 0 {\n\t\t\treturn buf\n\t\t}\n\t\t\/\/ If the key is non-empty, write it out and indent the rest of the attrs.\n\t\t\/\/ Otherwise, inline the attrs.\n\t\tif a.Key != \"\" {\n\t\t\tbuf = fmt.Appendf(buf, \"%s:\\n\", a.Key)\n\t\t\tindentLevel++\n\t\t}\n\t\tfor _, ga := range attrs {\n\t\t\tbuf = h.appendAttr(buf, ga, indentLevel)\n\t\t}\n\tdefault:\n\t\tbuf = fmt.Appendf(buf, \"%s: %s\\n\", a.Key, a.Value)\n\t}\n\treturn buf\n}\n\n\/\/!-appendAttr\n","global_vars":"","package":"package indenthandler","tags":""} |
|
{"element_type":"function","project_name":"finalHFtest","uuid":"8d22ec78-2134-44bd-93bd-5ec9bd9b2423","name":"New","imports":"['\"io\"', '\"log\/slog\"', '\"sync\"']","structs":"['IndentHandler', 'Options']","interfaces":"","file_location":"github.com\/finalHFtest\/\/tmp\/repos\/example\/slog-handler-guide\/indenthandler1\/indent_handler.go","code":"func New(out io.Writer, opts *Options) *IndentHandler {\n\th := &IndentHandler{out: out, mu: &sync.Mutex{}}\n\tif opts != nil {\n\t\th.opts = *opts\n\t}\n\tif h.opts.Level == nil {\n\t\th.opts.Level = slog.LevelInfo\n\t}\n\treturn h\n}","global_vars":"","package":"indenthandler","tags":""} |
|
{"element_type":"function","project_name":"finalHFtest","uuid":"2761a0ef-0502-4e6c-b850-0550f26d2631","name":"Enabled","imports":"['\"context\"', '\"log\/slog\"']","structs":"['IndentHandler']","interfaces":"","file_location":"github.com\/finalHFtest\/\/tmp\/repos\/example\/slog-handler-guide\/indenthandler1\/indent_handler.go","code":"func (h *IndentHandler) Enabled(ctx context.Context, level slog.Level) bool {\n\treturn level >= h.opts.Level.Level()\n}","global_vars":"","package":"indenthandler","tags":""} |
|
{"element_type":"function","project_name":"finalHFtest","uuid":"71a5294e-7d82-4ae4-b948-8670eebf15ac","name":"WithGroup","imports":"['\"log\/slog\"']","structs":"['IndentHandler']","interfaces":"","file_location":"github.com\/finalHFtest\/\/tmp\/repos\/example\/slog-handler-guide\/indenthandler1\/indent_handler.go","code":"func (h *IndentHandler) WithGroup(name string) slog.Handler {\n\t\/\/ TODO: implement.\n\treturn h\n}","global_vars":"","package":"indenthandler","tags":""} |
|
{"element_type":"function","project_name":"finalHFtest","uuid":"0fe417b7-2d4b-42e1-bef3-bdfb325d0f63","name":"WithAttrs","imports":"['\"log\/slog\"']","structs":"['IndentHandler']","interfaces":"","file_location":"github.com\/finalHFtest\/\/tmp\/repos\/example\/slog-handler-guide\/indenthandler1\/indent_handler.go","code":"func (h *IndentHandler) WithAttrs(attrs []slog.Attr) slog.Handler {\n\t\/\/ TODO: implement.\n\treturn h\n}","global_vars":"","package":"indenthandler","tags":""} |
|
{"element_type":"function","project_name":"finalHFtest","uuid":"d4ddf1b5-f7fd-4a01-9f11-2e24341d344f","name":"Handle","imports":"['\"context\"', '\"fmt\"', '\"log\/slog\"', '\"runtime\"']","structs":"['IndentHandler']","interfaces":"","file_location":"github.com\/finalHFtest\/\/tmp\/repos\/example\/slog-handler-guide\/indenthandler1\/indent_handler.go","code":"func (h *IndentHandler) Handle(ctx context.Context, r slog.Record) error {\n\tbuf := make([]byte, 0, 1024)\n\tif !r.Time.IsZero() {\n\t\tbuf = h.appendAttr(buf, slog.Time(slog.TimeKey, r.Time), 0)\n\t}\n\tbuf = h.appendAttr(buf, slog.Any(slog.LevelKey, r.Level), 0)\n\tif r.PC != 0 {\n\t\tfs := runtime.CallersFrames([]uintptr{r.PC})\n\t\tf, _ := fs.Next()\n\t\tbuf = h.appendAttr(buf, slog.String(slog.SourceKey, fmt.Sprintf(\"%s:%d\", f.File, f.Line)), 0)\n\t}\n\tbuf = h.appendAttr(buf, slog.String(slog.MessageKey, r.Message), 0)\n\tindentLevel := 0\n\t\/\/ TODO: output the Attrs and groups from WithAttrs and WithGroup.\n\tr.Attrs(func(a slog.Attr) bool {\n\t\tbuf = h.appendAttr(buf, a, indentLevel)\n\t\treturn true\n\t})\n\tbuf = append(buf, \"---\\n\"...)\n\th.mu.Lock()\n\tdefer h.mu.Unlock()\n\t_, err := h.out.Write(buf)\n\treturn err\n}","global_vars":"","package":"indenthandler","tags":""} |
|
{"element_type":"function","project_name":"finalHFtest","uuid":"06d39cfc-189e-4d9a-a09f-4187a95c494b","name":"appendAttr","imports":"['\"fmt\"', '\"log\/slog\"', '\"time\"']","structs":"['IndentHandler']","interfaces":"","file_location":"github.com\/finalHFtest\/\/tmp\/repos\/example\/slog-handler-guide\/indenthandler1\/indent_handler.go","code":"func (h *IndentHandler) appendAttr(buf []byte, a slog.Attr, indentLevel int) []byte {\n\t\/\/ Resolve the Attr's value before doing anything else.\n\ta.Value = a.Value.Resolve()\n\t\/\/ Ignore empty Attrs.\n\tif a.Equal(slog.Attr{}) {\n\t\treturn buf\n\t}\n\t\/\/ Indent 4 spaces per level.\n\tbuf = fmt.Appendf(buf, \"%*s\", indentLevel*4, \"\")\n\tswitch a.Value.Kind() {\n\tcase slog.KindString:\n\t\t\/\/ Quote string values, to make them easy to parse.\n\t\tbuf = fmt.Appendf(buf, \"%s: %q\\n\", a.Key, a.Value.String())\n\tcase slog.KindTime:\n\t\t\/\/ Write times in a standard way, without the monotonic time.\n\t\tbuf = fmt.Appendf(buf, \"%s: %s\\n\", a.Key, a.Value.Time().Format(time.RFC3339Nano))\n\tcase slog.KindGroup:\n\t\tattrs := a.Value.Group()\n\t\t\/\/ Ignore empty groups.\n\t\tif len(attrs) == 0 {\n\t\t\treturn buf\n\t\t}\n\t\t\/\/ If the key is non-empty, write it out and indent the rest of the attrs.\n\t\t\/\/ Otherwise, inline the attrs.\n\t\tif a.Key != \"\" {\n\t\t\tbuf = fmt.Appendf(buf, \"%s:\\n\", a.Key)\n\t\t\tindentLevel++\n\t\t}\n\t\tfor _, ga := range attrs {\n\t\t\tbuf = h.appendAttr(buf, ga, indentLevel)\n\t\t}\n\tdefault:\n\t\tbuf = fmt.Appendf(buf, \"%s: %s\\n\", a.Key, a.Value)\n\t}\n\treturn buf\n}","global_vars":"","package":"indenthandler","tags":""} |
|
{"element_type":"file","project_name":"finalHFtest","uuid":"cf0411e1-a74b-4941-bc8e-408310c1d922","name":"indent_handler_test.go","imports":"import (\n\t\"bytes\"\n\t\"regexp\"\n\t\"testing\"\n\n\t\"log\/slog\"\n)","structs":"","interfaces":"","file_location":"github.com\/finalHFtest\/\/tmp\/repos\/example\/slog-handler-guide\/indenthandler1\/indent_handler_test.go","code":"\/\/go:build go1.21\n\npackage indenthandler\n\nimport (\n\t\"bytes\"\n\t\"regexp\"\n\t\"testing\"\n\n\t\"log\/slog\"\n)\n\nfunc Test(t *testing.T) {\n\tvar buf bytes.Buffer\n\tl := slog.New(New(&buf, nil))\n\tl.Info(\"hello\", \"a\", 1, \"b\", true, \"c\", 3.14, slog.Group(\"g\", \"h\", 1, \"i\", 2), \"d\", \"NO\")\n\tgot := buf.String()\n\twantre := `time: [-0-9T:.]+Z?\nlevel: INFO\nsource: \".*\/indent_handler_test.go:\\d+\"\nmsg: \"hello\"\na: 1\nb: true\nc: 3.14\ng:\n h: 1\n i: 2\nd: \"NO\"\n`\n\tre := regexp.MustCompile(wantre)\n\tif !re.MatchString(got) {\n\t\tt.Errorf(\"\\ngot:\\n%q\\nwant:\\n%q\", got, wantre)\n\t}\n\n\tbuf.Reset()\n\tl.Debug(\"test\")\n\tif got := buf.Len(); got != 0 {\n\t\tt.Errorf(\"got buf.Len() = %d, want 0\", got)\n\t}\n}\n","global_vars":"","package":"package indenthandler","tags":""} |
|
{"element_type":"function","project_name":"finalHFtest","uuid":"22d2b805-77b9-4a11-8005-4bd1b2a097d4","name":"Test","imports":"['\"bytes\"', '\"regexp\"', '\"testing\"', '\"log\/slog\"']","structs":"","interfaces":"","file_location":"github.com\/finalHFtest\/\/tmp\/repos\/example\/slog-handler-guide\/indenthandler1\/indent_handler_test.go","code":"func Test(t *testing.T) {\n\tvar buf bytes.Buffer\n\tl := slog.New(New(&buf, nil))\n\tl.Info(\"hello\", \"a\", 1, \"b\", true, \"c\", 3.14, slog.Group(\"g\", \"h\", 1, \"i\", 2), \"d\", \"NO\")\n\tgot := buf.String()\n\twantre := `time: [-0-9T:.]+Z?\nlevel: INFO\nsource: \".*\/indent_handler_test.go:\\d+\"\nmsg: \"hello\"\na: 1\nb: true\nc: 3.14\ng:\n h: 1\n i: 2\nd: \"NO\"\n`\n\tre := regexp.MustCompile(wantre)\n\tif !re.MatchString(got) {\n\t\tt.Errorf(\"\\ngot:\\n%q\\nwant:\\n%q\", got, wantre)\n\t}\n\n\tbuf.Reset()\n\tl.Debug(\"test\")\n\tif got := buf.Len(); got != 0 {\n\t\tt.Errorf(\"got buf.Len() = %d, want 0\", got)\n\t}\n}","global_vars":"","package":"indenthandler","tags":""} |
|
{"element_type":"file","project_name":"finalHFtest","uuid":"48039d37-caa4-45ed-abc9-93bd5e11cd12","name":"indent_handler.go","imports":"import (\n\t\"context\"\n\t\"fmt\"\n\t\"io\"\n\t\"log\/slog\"\n\t\"runtime\"\n\t\"sync\"\n\t\"time\"\n)","structs":"","interfaces":"","file_location":"github.com\/finalHFtest\/\/tmp\/repos\/example\/slog-handler-guide\/indenthandler2\/indent_handler.go","code":"\/\/go:build go1.21\n\npackage indenthandler\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\t\"io\"\n\t\"log\/slog\"\n\t\"runtime\"\n\t\"sync\"\n\t\"time\"\n)\n\n\/\/ !+IndentHandler\ntype IndentHandler struct {\n\topts Options\n\tgoas []groupOrAttrs\n\tmu *sync.Mutex\n\tout io.Writer\n}\n\n\/\/!-IndentHandler\n\ntype Options struct {\n\t\/\/ Level reports the minimum level to log.\n\t\/\/ Levels with lower levels are discarded.\n\t\/\/ If nil, the Handler uses [slog.LevelInfo].\n\tLevel slog.Leveler\n}\n\n\/\/ !+gora\n\/\/ groupOrAttrs holds either a group name or a list of slog.Attrs.\ntype groupOrAttrs struct {\n\tgroup string \/\/ group name if non-empty\n\tattrs []slog.Attr \/\/ attrs if non-empty\n}\n\n\/\/!-gora\n\nfunc New(out io.Writer, opts *Options) *IndentHandler {\n\th := &IndentHandler{out: out, mu: &sync.Mutex{}}\n\tif opts != nil {\n\t\th.opts = *opts\n\t}\n\tif h.opts.Level == nil {\n\t\th.opts.Level = slog.LevelInfo\n\t}\n\treturn h\n}\n\nfunc (h *IndentHandler) Enabled(ctx context.Context, level slog.Level) bool {\n\treturn level >= h.opts.Level.Level()\n}\n\n\/\/ !+withs\nfunc (h *IndentHandler) WithGroup(name string) slog.Handler {\n\tif name == \"\" {\n\t\treturn h\n\t}\n\treturn h.withGroupOrAttrs(groupOrAttrs{group: name})\n}\n\nfunc (h *IndentHandler) WithAttrs(attrs []slog.Attr) slog.Handler {\n\tif len(attrs) == 0 {\n\t\treturn h\n\t}\n\treturn h.withGroupOrAttrs(groupOrAttrs{attrs: attrs})\n}\n\n\/\/!-withs\n\n\/\/ !+withgora\nfunc (h *IndentHandler) withGroupOrAttrs(goa groupOrAttrs) *IndentHandler {\n\th2 := *h\n\th2.goas = make([]groupOrAttrs, len(h.goas)+1)\n\tcopy(h2.goas, h.goas)\n\th2.goas[len(h2.goas)-1] = goa\n\treturn &h2\n}\n\n\/\/!-withgora\n\n\/\/ !+handle\nfunc (h *IndentHandler) Handle(ctx context.Context, r slog.Record) error {\n\tbuf := make([]byte, 0, 1024)\n\tif !r.Time.IsZero() {\n\t\tbuf = h.appendAttr(buf, slog.Time(slog.TimeKey, r.Time), 0)\n\t}\n\tbuf = h.appendAttr(buf, slog.Any(slog.LevelKey, r.Level), 0)\n\tif r.PC != 0 {\n\t\tfs := runtime.CallersFrames([]uintptr{r.PC})\n\t\tf, _ := fs.Next()\n\t\tbuf = h.appendAttr(buf, slog.String(slog.SourceKey, fmt.Sprintf(\"%s:%d\", f.File, f.Line)), 0)\n\t}\n\tbuf = h.appendAttr(buf, slog.String(slog.MessageKey, r.Message), 0)\n\tindentLevel := 0\n\t\/\/ Handle state from WithGroup and WithAttrs.\n\tgoas := h.goas\n\tif r.NumAttrs() == 0 {\n\t\t\/\/ If the record has no Attrs, remove groups at the end of the list; they are empty.\n\t\tfor len(goas) > 0 && goas[len(goas)-1].group != \"\" {\n\t\t\tgoas = goas[:len(goas)-1]\n\t\t}\n\t}\n\tfor _, goa := range goas {\n\t\tif goa.group != \"\" {\n\t\t\tbuf = fmt.Appendf(buf, \"%*s%s:\\n\", indentLevel*4, \"\", goa.group)\n\t\t\tindentLevel++\n\t\t} else {\n\t\t\tfor _, a := range goa.attrs {\n\t\t\t\tbuf = h.appendAttr(buf, a, indentLevel)\n\t\t\t}\n\t\t}\n\t}\n\tr.Attrs(func(a slog.Attr) bool {\n\t\tbuf = h.appendAttr(buf, a, indentLevel)\n\t\treturn true\n\t})\n\tbuf = append(buf, \"---\\n\"...)\n\th.mu.Lock()\n\tdefer h.mu.Unlock()\n\t_, err := h.out.Write(buf)\n\treturn err\n}\n\n\/\/!-handle\n\nfunc (h *IndentHandler) appendAttr(buf []byte, a slog.Attr, indentLevel int) []byte {\n\t\/\/ Resolve the Attr's value before doing anything else.\n\ta.Value = a.Value.Resolve()\n\t\/\/ Ignore empty Attrs.\n\tif a.Equal(slog.Attr{}) {\n\t\treturn buf\n\t}\n\t\/\/ Indent 4 spaces per level.\n\tbuf = fmt.Appendf(buf, \"%*s\", indentLevel*4, \"\")\n\tswitch a.Value.Kind() {\n\tcase slog.KindString:\n\t\t\/\/ Quote string values, to make them easy to parse.\n\t\tbuf = fmt.Appendf(buf, \"%s: %q\\n\", a.Key, a.Value.String())\n\tcase slog.KindTime:\n\t\t\/\/ Write times in a standard way, without the monotonic time.\n\t\tbuf = fmt.Appendf(buf, \"%s: %s\\n\", a.Key, a.Value.Time().Format(time.RFC3339Nano))\n\tcase slog.KindGroup:\n\t\tattrs := a.Value.Group()\n\t\t\/\/ Ignore empty groups.\n\t\tif len(attrs) == 0 {\n\t\t\treturn buf\n\t\t}\n\t\t\/\/ If the key is non-empty, write it out and indent the rest of the attrs.\n\t\t\/\/ Otherwise, inline the attrs.\n\t\tif a.Key != \"\" {\n\t\t\tbuf = fmt.Appendf(buf, \"%s:\\n\", a.Key)\n\t\t\tindentLevel++\n\t\t}\n\t\tfor _, ga := range attrs {\n\t\t\tbuf = h.appendAttr(buf, ga, indentLevel)\n\t\t}\n\tdefault:\n\t\tbuf = fmt.Appendf(buf, \"%s: %s\\n\", a.Key, a.Value)\n\t}\n\treturn buf\n}\n","global_vars":"","package":"package indenthandler","tags":""} |
|
{"element_type":"function","project_name":"finalHFtest","uuid":"674be160-f755-48da-8b8b-7882554d7b50","name":"New","imports":"['\"io\"', '\"log\/slog\"', '\"sync\"']","structs":"['IndentHandler', 'Options']","interfaces":"","file_location":"github.com\/finalHFtest\/\/tmp\/repos\/example\/slog-handler-guide\/indenthandler2\/indent_handler.go","code":"func New(out io.Writer, opts *Options) *IndentHandler {\n\th := &IndentHandler{out: out, mu: &sync.Mutex{}}\n\tif opts != nil {\n\t\th.opts = *opts\n\t}\n\tif h.opts.Level == nil {\n\t\th.opts.Level = slog.LevelInfo\n\t}\n\treturn h\n}","global_vars":"","package":"indenthandler","tags":""} |
|
{"element_type":"function","project_name":"finalHFtest","uuid":"69d6d0f5-feab-4566-b915-11b02d3cc9ac","name":"Enabled","imports":"['\"context\"', '\"log\/slog\"']","structs":"['IndentHandler']","interfaces":"","file_location":"github.com\/finalHFtest\/\/tmp\/repos\/example\/slog-handler-guide\/indenthandler2\/indent_handler.go","code":"func (h *IndentHandler) Enabled(ctx context.Context, level slog.Level) bool {\n\treturn level >= h.opts.Level.Level()\n}","global_vars":"","package":"indenthandler","tags":""} |
|
{"element_type":"function","project_name":"finalHFtest","uuid":"129ffbb3-e793-41db-bb53-0758949c0000","name":"WithGroup","imports":"['\"log\/slog\"']","structs":"['IndentHandler', 'groupOrAttrs']","interfaces":"","file_location":"github.com\/finalHFtest\/\/tmp\/repos\/example\/slog-handler-guide\/indenthandler2\/indent_handler.go","code":"func (h *IndentHandler) WithGroup(name string) slog.Handler {\n\tif name == \"\" {\n\t\treturn h\n\t}\n\treturn h.withGroupOrAttrs(groupOrAttrs{group: name})\n}","global_vars":"","package":"indenthandler","tags":""} |
|
{"element_type":"function","project_name":"finalHFtest","uuid":"a8ed4318-5f54-4784-8ca5-e0d897365b50","name":"WithAttrs","imports":"['\"log\/slog\"']","structs":"['IndentHandler', 'groupOrAttrs']","interfaces":"","file_location":"github.com\/finalHFtest\/\/tmp\/repos\/example\/slog-handler-guide\/indenthandler2\/indent_handler.go","code":"func (h *IndentHandler) WithAttrs(attrs []slog.Attr) slog.Handler {\n\tif len(attrs) == 0 {\n\t\treturn h\n\t}\n\treturn h.withGroupOrAttrs(groupOrAttrs{attrs: attrs})\n}","global_vars":"","package":"indenthandler","tags":""} |
|
{"element_type":"function","project_name":"finalHFtest","uuid":"02f7c9ef-e4c8-4c45-8308-cffac4345db0","name":"withGroupOrAttrs","imports":"","structs":"['IndentHandler', 'groupOrAttrs']","interfaces":"","file_location":"github.com\/finalHFtest\/\/tmp\/repos\/example\/slog-handler-guide\/indenthandler2\/indent_handler.go","code":"func (h *IndentHandler) withGroupOrAttrs(goa groupOrAttrs) *IndentHandler {\n\th2 := *h\n\th2.goas = make([]groupOrAttrs, len(h.goas)+1)\n\tcopy(h2.goas, h.goas)\n\th2.goas[len(h2.goas)-1] = goa\n\treturn &h2\n}","global_vars":"","package":"indenthandler","tags":""} |
|
{"element_type":"function","project_name":"finalHFtest","uuid":"80c0c91a-58ba-481e-958c-426791a6ffac","name":"Handle","imports":"['\"context\"', '\"fmt\"', '\"log\/slog\"', '\"runtime\"']","structs":"['IndentHandler']","interfaces":"","file_location":"github.com\/finalHFtest\/\/tmp\/repos\/example\/slog-handler-guide\/indenthandler2\/indent_handler.go","code":"func (h *IndentHandler) Handle(ctx context.Context, r slog.Record) error {\n\tbuf := make([]byte, 0, 1024)\n\tif !r.Time.IsZero() {\n\t\tbuf = h.appendAttr(buf, slog.Time(slog.TimeKey, r.Time), 0)\n\t}\n\tbuf = h.appendAttr(buf, slog.Any(slog.LevelKey, r.Level), 0)\n\tif r.PC != 0 {\n\t\tfs := runtime.CallersFrames([]uintptr{r.PC})\n\t\tf, _ := fs.Next()\n\t\tbuf = h.appendAttr(buf, slog.String(slog.SourceKey, fmt.Sprintf(\"%s:%d\", f.File, f.Line)), 0)\n\t}\n\tbuf = h.appendAttr(buf, slog.String(slog.MessageKey, r.Message), 0)\n\tindentLevel := 0\n\t\/\/ Handle state from WithGroup and WithAttrs.\n\tgoas := h.goas\n\tif r.NumAttrs() == 0 {\n\t\t\/\/ If the record has no Attrs, remove groups at the end of the list; they are empty.\n\t\tfor len(goas) > 0 && goas[len(goas)-1].group != \"\" {\n\t\t\tgoas = goas[:len(goas)-1]\n\t\t}\n\t}\n\tfor _, goa := range goas {\n\t\tif goa.group != \"\" {\n\t\t\tbuf = fmt.Appendf(buf, \"%*s%s:\\n\", indentLevel*4, \"\", goa.group)\n\t\t\tindentLevel++\n\t\t} else {\n\t\t\tfor _, a := range goa.attrs {\n\t\t\t\tbuf = h.appendAttr(buf, a, indentLevel)\n\t\t\t}\n\t\t}\n\t}\n\tr.Attrs(func(a slog.Attr) bool {\n\t\tbuf = h.appendAttr(buf, a, indentLevel)\n\t\treturn true\n\t})\n\tbuf = append(buf, \"---\\n\"...)\n\th.mu.Lock()\n\tdefer h.mu.Unlock()\n\t_, err := h.out.Write(buf)\n\treturn err\n}","global_vars":"","package":"indenthandler","tags":""} |
|
{"element_type":"function","project_name":"finalHFtest","uuid":"0bc98dbd-1a6f-4496-8ff7-fb67196e2f2a","name":"appendAttr","imports":"['\"fmt\"', '\"log\/slog\"', '\"time\"']","structs":"['IndentHandler']","interfaces":"","file_location":"github.com\/finalHFtest\/\/tmp\/repos\/example\/slog-handler-guide\/indenthandler2\/indent_handler.go","code":"func (h *IndentHandler) appendAttr(buf []byte, a slog.Attr, indentLevel int) []byte {\n\t\/\/ Resolve the Attr's value before doing anything else.\n\ta.Value = a.Value.Resolve()\n\t\/\/ Ignore empty Attrs.\n\tif a.Equal(slog.Attr{}) {\n\t\treturn buf\n\t}\n\t\/\/ Indent 4 spaces per level.\n\tbuf = fmt.Appendf(buf, \"%*s\", indentLevel*4, \"\")\n\tswitch a.Value.Kind() {\n\tcase slog.KindString:\n\t\t\/\/ Quote string values, to make them easy to parse.\n\t\tbuf = fmt.Appendf(buf, \"%s: %q\\n\", a.Key, a.Value.String())\n\tcase slog.KindTime:\n\t\t\/\/ Write times in a standard way, without the monotonic time.\n\t\tbuf = fmt.Appendf(buf, \"%s: %s\\n\", a.Key, a.Value.Time().Format(time.RFC3339Nano))\n\tcase slog.KindGroup:\n\t\tattrs := a.Value.Group()\n\t\t\/\/ Ignore empty groups.\n\t\tif len(attrs) == 0 {\n\t\t\treturn buf\n\t\t}\n\t\t\/\/ If the key is non-empty, write it out and indent the rest of the attrs.\n\t\t\/\/ Otherwise, inline the attrs.\n\t\tif a.Key != \"\" {\n\t\t\tbuf = fmt.Appendf(buf, \"%s:\\n\", a.Key)\n\t\t\tindentLevel++\n\t\t}\n\t\tfor _, ga := range attrs {\n\t\t\tbuf = h.appendAttr(buf, ga, indentLevel)\n\t\t}\n\tdefault:\n\t\tbuf = fmt.Appendf(buf, \"%s: %s\\n\", a.Key, a.Value)\n\t}\n\treturn buf\n}","global_vars":"","package":"indenthandler","tags":""} |
|
{"element_type":"file","project_name":"finalHFtest","uuid":"b5ba5e7b-3678-4578-99b1-73dd2e76833b","name":"indent_handler_test.go","imports":"import (\n\t\"bufio\"\n\t\"bytes\"\n\t\"fmt\"\n\t\"reflect\"\n\t\"regexp\"\n\t\"strconv\"\n\t\"strings\"\n\t\"testing\"\n\t\"unicode\"\n\n\t\"log\/slog\"\n\t\"testing\/slogtest\"\n)","structs":"","interfaces":"","file_location":"github.com\/finalHFtest\/\/tmp\/repos\/example\/slog-handler-guide\/indenthandler2\/indent_handler_test.go","code":"\/\/go:build go1.21\n\npackage indenthandler\n\nimport (\n\t\"bufio\"\n\t\"bytes\"\n\t\"fmt\"\n\t\"reflect\"\n\t\"regexp\"\n\t\"strconv\"\n\t\"strings\"\n\t\"testing\"\n\t\"unicode\"\n\n\t\"log\/slog\"\n\t\"testing\/slogtest\"\n)\n\nfunc TestSlogtest(t *testing.T) {\n\tvar buf bytes.Buffer\n\terr := slogtest.TestHandler(New(&buf, nil), func() []map[string]any {\n\t\treturn parseLogEntries(buf.String())\n\t})\n\tif err != nil {\n\t\tt.Error(err)\n\t}\n}\n\nfunc Test(t *testing.T) {\n\tvar buf bytes.Buffer\n\tl := slog.New(New(&buf, nil))\n\tl.Info(\"hello\", \"a\", 1, \"b\", true, \"c\", 3.14, slog.Group(\"g\", \"h\", 1, \"i\", 2), \"d\", \"NO\")\n\tgot := buf.String()\n\twantre := `time: [-0-9T:.]+Z?\nlevel: INFO\nsource: \".*\/indent_handler_test.go:\\d+\"\nmsg: \"hello\"\na: 1\nb: true\nc: 3.14\ng:\n h: 1\n i: 2\nd: \"NO\"\n`\n\tre := regexp.MustCompile(wantre)\n\tif !re.MatchString(got) {\n\t\tt.Errorf(\"\\ngot:\\n%q\\nwant:\\n%q\", got, wantre)\n\t}\n\n\tbuf.Reset()\n\tl.Debug(\"test\")\n\tif got := buf.Len(); got != 0 {\n\t\tt.Errorf(\"got buf.Len() = %d, want 0\", got)\n\t}\n}\n\nfunc parseLogEntries(s string) []map[string]any {\n\tvar ms []map[string]any\n\tscan := bufio.NewScanner(strings.NewReader(s))\n\tfor scan.Scan() {\n\t\tm := parseGroup(scan)\n\t\tms = append(ms, m)\n\t}\n\tif scan.Err() != nil {\n\t\tpanic(scan.Err())\n\t}\n\treturn ms\n}\n\nfunc parseGroup(scan *bufio.Scanner) map[string]any {\n\tm := map[string]any{}\n\tgroupIndent := -1\n\tfor {\n\t\tline := scan.Text()\n\t\tif line == \"---\" { \/\/ end of entry\n\t\t\tbreak\n\t\t}\n\t\tk, v, found := strings.Cut(line, \":\")\n\t\tif !found {\n\t\t\tpanic(fmt.Sprintf(\"no ':' in line %q\", line))\n\t\t}\n\t\tindent := strings.IndexFunc(k, func(r rune) bool {\n\t\t\treturn !unicode.IsSpace(r)\n\t\t})\n\t\tif indent < 0 {\n\t\t\tpanic(\"blank line\")\n\t\t}\n\t\tif groupIndent < 0 {\n\t\t\t\/\/ First line in group; remember the indent.\n\t\t\tgroupIndent = indent\n\t\t} else if indent < groupIndent {\n\t\t\t\/\/ End of group\n\t\t\tbreak\n\t\t} else if indent > groupIndent {\n\t\t\tpanic(fmt.Sprintf(\"indent increased on line %q\", line))\n\t\t}\n\n\t\tkey := strings.TrimSpace(k)\n\t\tif v == \"\" {\n\t\t\t\/\/ Just a key: start of a group.\n\t\t\tif !scan.Scan() {\n\t\t\t\tpanic(\"empty group\")\n\t\t\t}\n\t\t\tm[key] = parseGroup(scan)\n\t\t} else {\n\t\t\tv = strings.TrimSpace(v)\n\t\t\tif len(v) > 0 && v[0] == '\"' {\n\t\t\t\tvar err error\n\t\t\t\tv, err = strconv.Unquote(v)\n\t\t\t\tif err != nil {\n\t\t\t\t\tpanic(err)\n\t\t\t\t}\n\t\t\t}\n\t\t\tm[key] = v\n\t\t\tif !scan.Scan() {\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n\treturn m\n}\n\nfunc TestParseLogEntries(t *testing.T) {\n\tin := `\na: 1\nb: 2\nc: 3\ng:\n h: 4\n i: 5\nd: 6\n---\ne: 7\n---\n`\n\twant := []map[string]any{\n\t\t{\n\t\t\t\"a\": \"1\",\n\t\t\t\"b\": \"2\",\n\t\t\t\"c\": \"3\",\n\t\t\t\"g\": map[string]any{\n\t\t\t\t\"h\": \"4\",\n\t\t\t\t\"i\": \"5\",\n\t\t\t},\n\t\t\t\"d\": \"6\",\n\t\t},\n\t\t{\n\t\t\t\"e\": \"7\",\n\t\t},\n\t}\n\tgot := parseLogEntries(in[1:])\n\tif !reflect.DeepEqual(got, want) {\n\t\tt.Errorf(\"\\ngot:\\n%v\\nwant:\\n%v\", got, want)\n\t}\n}\n","global_vars":"","package":"package indenthandler","tags":""} |
|
{"element_type":"function","project_name":"finalHFtest","uuid":"3e7a7b06-3f10-4bc3-ab92-8842044344de","name":"TestSlogtest","imports":"['\"bytes\"', '\"testing\"', '\"testing\/slogtest\"']","structs":"","interfaces":"","file_location":"github.com\/finalHFtest\/\/tmp\/repos\/example\/slog-handler-guide\/indenthandler2\/indent_handler_test.go","code":"func TestSlogtest(t *testing.T) {\n\tvar buf bytes.Buffer\n\terr := slogtest.TestHandler(New(&buf, nil), func() []map[string]any {\n\t\treturn parseLogEntries(buf.String())\n\t})\n\tif err != nil {\n\t\tt.Error(err)\n\t}\n}","global_vars":"","package":"indenthandler","tags":""} |
|
{"element_type":"function","project_name":"finalHFtest","uuid":"c1813706-3562-417d-916b-c9cba0494c81","name":"Test","imports":"['\"bytes\"', '\"regexp\"', '\"testing\"', '\"log\/slog\"']","structs":"","interfaces":"","file_location":"github.com\/finalHFtest\/\/tmp\/repos\/example\/slog-handler-guide\/indenthandler2\/indent_handler_test.go","code":"func Test(t *testing.T) {\n\tvar buf bytes.Buffer\n\tl := slog.New(New(&buf, nil))\n\tl.Info(\"hello\", \"a\", 1, \"b\", true, \"c\", 3.14, slog.Group(\"g\", \"h\", 1, \"i\", 2), \"d\", \"NO\")\n\tgot := buf.String()\n\twantre := `time: [-0-9T:.]+Z?\nlevel: INFO\nsource: \".*\/indent_handler_test.go:\\d+\"\nmsg: \"hello\"\na: 1\nb: true\nc: 3.14\ng:\n h: 1\n i: 2\nd: \"NO\"\n`\n\tre := regexp.MustCompile(wantre)\n\tif !re.MatchString(got) {\n\t\tt.Errorf(\"\\ngot:\\n%q\\nwant:\\n%q\", got, wantre)\n\t}\n\n\tbuf.Reset()\n\tl.Debug(\"test\")\n\tif got := buf.Len(); got != 0 {\n\t\tt.Errorf(\"got buf.Len() = %d, want 0\", got)\n\t}\n}","global_vars":"","package":"indenthandler","tags":""} |
|
{"element_type":"function","project_name":"finalHFtest","uuid":"ff18dc64-ca8a-4e41-a862-8a087976bcda","name":"parseLogEntries","imports":"['\"bufio\"', '\"strings\"']","structs":"","interfaces":"","file_location":"github.com\/finalHFtest\/\/tmp\/repos\/example\/slog-handler-guide\/indenthandler2\/indent_handler_test.go","code":"func parseLogEntries(s string) []map[string]any {\n\tvar ms []map[string]any\n\tscan := bufio.NewScanner(strings.NewReader(s))\n\tfor scan.Scan() {\n\t\tm := parseGroup(scan)\n\t\tms = append(ms, m)\n\t}\n\tif scan.Err() != nil {\n\t\tpanic(scan.Err())\n\t}\n\treturn ms\n}","global_vars":"","package":"indenthandler","tags":""} |
|
{"element_type":"function","project_name":"finalHFtest","uuid":"712f761e-7186-4f24-a46e-7d0b79895878","name":"parseGroup","imports":"['\"bufio\"', '\"fmt\"', '\"strconv\"', '\"strings\"', '\"unicode\"']","structs":"","interfaces":"","file_location":"github.com\/finalHFtest\/\/tmp\/repos\/example\/slog-handler-guide\/indenthandler2\/indent_handler_test.go","code":"func parseGroup(scan *bufio.Scanner) map[string]any {\n\tm := map[string]any{}\n\tgroupIndent := -1\n\tfor {\n\t\tline := scan.Text()\n\t\tif line == \"---\" { \/\/ end of entry\n\t\t\tbreak\n\t\t}\n\t\tk, v, found := strings.Cut(line, \":\")\n\t\tif !found {\n\t\t\tpanic(fmt.Sprintf(\"no ':' in line %q\", line))\n\t\t}\n\t\tindent := strings.IndexFunc(k, func(r rune) bool {\n\t\t\treturn !unicode.IsSpace(r)\n\t\t})\n\t\tif indent < 0 {\n\t\t\tpanic(\"blank line\")\n\t\t}\n\t\tif groupIndent < 0 {\n\t\t\t\/\/ First line in group; remember the indent.\n\t\t\tgroupIndent = indent\n\t\t} else if indent < groupIndent {\n\t\t\t\/\/ End of group\n\t\t\tbreak\n\t\t} else if indent > groupIndent {\n\t\t\tpanic(fmt.Sprintf(\"indent increased on line %q\", line))\n\t\t}\n\n\t\tkey := strings.TrimSpace(k)\n\t\tif v == \"\" {\n\t\t\t\/\/ Just a key: start of a group.\n\t\t\tif !scan.Scan() {\n\t\t\t\tpanic(\"empty group\")\n\t\t\t}\n\t\t\tm[key] = parseGroup(scan)\n\t\t} else {\n\t\t\tv = strings.TrimSpace(v)\n\t\t\tif len(v) > 0 && v[0] == '\"' {\n\t\t\t\tvar err error\n\t\t\t\tv, err = strconv.Unquote(v)\n\t\t\t\tif err != nil {\n\t\t\t\t\tpanic(err)\n\t\t\t\t}\n\t\t\t}\n\t\t\tm[key] = v\n\t\t\tif !scan.Scan() {\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n\treturn m\n}","global_vars":"","package":"indenthandler","tags":""} |
|
{"element_type":"function","project_name":"finalHFtest","uuid":"a3fa266c-99bc-412f-93b8-e2aa7f3c1c8b","name":"TestParseLogEntries","imports":"['\"reflect\"', '\"testing\"']","structs":"","interfaces":"","file_location":"github.com\/finalHFtest\/\/tmp\/repos\/example\/slog-handler-guide\/indenthandler2\/indent_handler_test.go","code":"func TestParseLogEntries(t *testing.T) {\n\tin := `\na: 1\nb: 2\nc: 3\ng:\n h: 4\n i: 5\nd: 6\n---\ne: 7\n---\n`\n\twant := []map[string]any{\n\t\t{\n\t\t\t\"a\": \"1\",\n\t\t\t\"b\": \"2\",\n\t\t\t\"c\": \"3\",\n\t\t\t\"g\": map[string]any{\n\t\t\t\t\"h\": \"4\",\n\t\t\t\t\"i\": \"5\",\n\t\t\t},\n\t\t\t\"d\": \"6\",\n\t\t},\n\t\t{\n\t\t\t\"e\": \"7\",\n\t\t},\n\t}\n\tgot := parseLogEntries(in[1:])\n\tif !reflect.DeepEqual(got, want) {\n\t\tt.Errorf(\"\\ngot:\\n%v\\nwant:\\n%v\", got, want)\n\t}\n}","global_vars":"","package":"indenthandler","tags":""} |
|
{"element_type":"file","project_name":"finalHFtest","uuid":"38bdb4d2-71b0-4eb4-8d60-de4e3873c718","name":"indent_handler.go","imports":"import (\n\t\"context\"\n\t\"fmt\"\n\t\"io\"\n\t\"log\/slog\"\n\t\"runtime\"\n\t\"slices\"\n\t\"sync\"\n\t\"time\"\n)","structs":"","interfaces":"","file_location":"github.com\/finalHFtest\/\/tmp\/repos\/example\/slog-handler-guide\/indenthandler3\/indent_handler.go","code":"\/\/go:build go1.21\n\npackage indenthandler\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\t\"io\"\n\t\"log\/slog\"\n\t\"runtime\"\n\t\"slices\"\n\t\"sync\"\n\t\"time\"\n)\n\n\/\/ !+IndentHandler\ntype IndentHandler struct {\n\topts Options\n\tpreformatted []byte \/\/ data from WithGroup and WithAttrs\n\tunopenedGroups []string \/\/ groups from WithGroup that haven't been opened\n\tindentLevel int \/\/ same as number of opened groups so far\n\tmu *sync.Mutex\n\tout io.Writer\n}\n\n\/\/!-IndentHandler\n\ntype Options struct {\n\t\/\/ Level reports the minimum level to log.\n\t\/\/ Levels with lower levels are discarded.\n\t\/\/ If nil, the Handler uses [slog.LevelInfo].\n\tLevel slog.Leveler\n}\n\nfunc New(out io.Writer, opts *Options) *IndentHandler {\n\th := &IndentHandler{out: out, mu: &sync.Mutex{}}\n\tif opts != nil {\n\t\th.opts = *opts\n\t}\n\tif h.opts.Level == nil {\n\t\th.opts.Level = slog.LevelInfo\n\t}\n\treturn h\n}\n\nfunc (h *IndentHandler) Enabled(ctx context.Context, level slog.Level) bool {\n\treturn level >= h.opts.Level.Level()\n}\n\n\/\/ !+WithGroup\nfunc (h *IndentHandler) WithGroup(name string) slog.Handler {\n\tif name == \"\" {\n\t\treturn h\n\t}\n\th2 := *h\n\t\/\/ Add an unopened group to h2 without modifying h.\n\th2.unopenedGroups = make([]string, len(h.unopenedGroups)+1)\n\tcopy(h2.unopenedGroups, h.unopenedGroups)\n\th2.unopenedGroups[len(h2.unopenedGroups)-1] = name\n\treturn &h2\n}\n\n\/\/!-WithGroup\n\n\/\/ !+WithAttrs\nfunc (h *IndentHandler) WithAttrs(attrs []slog.Attr) slog.Handler {\n\tif len(attrs) == 0 {\n\t\treturn h\n\t}\n\th2 := *h\n\t\/\/ Force an append to copy the underlying array.\n\tpre := slices.Clip(h.preformatted)\n\t\/\/ Add all groups from WithGroup that haven't already been added.\n\th2.preformatted = h2.appendUnopenedGroups(pre, h2.indentLevel)\n\t\/\/ Each of those groups increased the indent level by 1.\n\th2.indentLevel += len(h2.unopenedGroups)\n\t\/\/ Now all groups have been opened.\n\th2.unopenedGroups = nil\n\t\/\/ Pre-format the attributes.\n\tfor _, a := range attrs {\n\t\th2.preformatted = h2.appendAttr(h2.preformatted, a, h2.indentLevel)\n\t}\n\treturn &h2\n}\n\nfunc (h *IndentHandler) appendUnopenedGroups(buf []byte, indentLevel int) []byte {\n\tfor _, g := range h.unopenedGroups {\n\t\tbuf = fmt.Appendf(buf, \"%*s%s:\\n\", indentLevel*4, \"\", g)\n\t\tindentLevel++\n\t}\n\treturn buf\n}\n\n\/\/!-WithAttrs\n\n\/\/ !+Handle\nfunc (h *IndentHandler) Handle(ctx context.Context, r slog.Record) error {\n\tbuf := make([]byte, 0, 1024)\n\tif !r.Time.IsZero() {\n\t\tbuf = h.appendAttr(buf, slog.Time(slog.TimeKey, r.Time), 0)\n\t}\n\tbuf = h.appendAttr(buf, slog.Any(slog.LevelKey, r.Level), 0)\n\tif r.PC != 0 {\n\t\tfs := runtime.CallersFrames([]uintptr{r.PC})\n\t\tf, _ := fs.Next()\n\t\tbuf = h.appendAttr(buf, slog.String(slog.SourceKey, fmt.Sprintf(\"%s:%d\", f.File, f.Line)), 0)\n\t}\n\tbuf = h.appendAttr(buf, slog.String(slog.MessageKey, r.Message), 0)\n\t\/\/ Insert preformatted attributes just after built-in ones.\n\tbuf = append(buf, h.preformatted...)\n\tif r.NumAttrs() > 0 {\n\t\tbuf = h.appendUnopenedGroups(buf, h.indentLevel)\n\t\tr.Attrs(func(a slog.Attr) bool {\n\t\t\tbuf = h.appendAttr(buf, a, h.indentLevel+len(h.unopenedGroups))\n\t\t\treturn true\n\t\t})\n\t}\n\tbuf = append(buf, \"---\\n\"...)\n\th.mu.Lock()\n\tdefer h.mu.Unlock()\n\t_, err := h.out.Write(buf)\n\treturn err\n}\n\n\/\/!-Handle\n\nfunc (h *IndentHandler) appendAttr(buf []byte, a slog.Attr, indentLevel int) []byte {\n\t\/\/ Resolve the Attr's value before doing anything else.\n\ta.Value = a.Value.Resolve()\n\t\/\/ Ignore empty Attrs.\n\tif a.Equal(slog.Attr{}) {\n\t\treturn buf\n\t}\n\t\/\/ Indent 4 spaces per level.\n\tbuf = fmt.Appendf(buf, \"%*s\", indentLevel*4, \"\")\n\tswitch a.Value.Kind() {\n\tcase slog.KindString:\n\t\t\/\/ Quote string values, to make them easy to parse.\n\t\tbuf = fmt.Appendf(buf, \"%s: %q\\n\", a.Key, a.Value.String())\n\tcase slog.KindTime:\n\t\t\/\/ Write times in a standard way, without the monotonic time.\n\t\tbuf = fmt.Appendf(buf, \"%s: %s\\n\", a.Key, a.Value.Time().Format(time.RFC3339Nano))\n\tcase slog.KindGroup:\n\t\tattrs := a.Value.Group()\n\t\t\/\/ Ignore empty groups.\n\t\tif len(attrs) == 0 {\n\t\t\treturn buf\n\t\t}\n\t\t\/\/ If the key is non-empty, write it out and indent the rest of the attrs.\n\t\t\/\/ Otherwise, inline the attrs.\n\t\tif a.Key != \"\" {\n\t\t\tbuf = fmt.Appendf(buf, \"%s:\\n\", a.Key)\n\t\t\tindentLevel++\n\t\t}\n\t\tfor _, ga := range attrs {\n\t\t\tbuf = h.appendAttr(buf, ga, indentLevel)\n\t\t}\n\tdefault:\n\t\tbuf = fmt.Appendf(buf, \"%s: %s\\n\", a.Key, a.Value)\n\t}\n\treturn buf\n}\n","global_vars":"","package":"package indenthandler","tags":""} |
|
{"element_type":"function","project_name":"finalHFtest","uuid":"e8833591-beae-4a51-bb6b-6ddfbda9e8d5","name":"New","imports":"['\"io\"', '\"log\/slog\"', '\"sync\"']","structs":"['IndentHandler', 'Options']","interfaces":"","file_location":"github.com\/finalHFtest\/\/tmp\/repos\/example\/slog-handler-guide\/indenthandler3\/indent_handler.go","code":"func New(out io.Writer, opts *Options) *IndentHandler {\n\th := &IndentHandler{out: out, mu: &sync.Mutex{}}\n\tif opts != nil {\n\t\th.opts = *opts\n\t}\n\tif h.opts.Level == nil {\n\t\th.opts.Level = slog.LevelInfo\n\t}\n\treturn h\n}","global_vars":"","package":"indenthandler","tags":""} |
|
{"element_type":"function","project_name":"finalHFtest","uuid":"7817c789-6217-4ec9-a898-4fe40b244e78","name":"Enabled","imports":"['\"context\"', '\"log\/slog\"']","structs":"['IndentHandler']","interfaces":"","file_location":"github.com\/finalHFtest\/\/tmp\/repos\/example\/slog-handler-guide\/indenthandler3\/indent_handler.go","code":"func (h *IndentHandler) Enabled(ctx context.Context, level slog.Level) bool {\n\treturn level >= h.opts.Level.Level()\n}","global_vars":"","package":"indenthandler","tags":""} |
|
{"element_type":"function","project_name":"finalHFtest","uuid":"29af9817-670a-4e7f-b0a9-687712e2918e","name":"WithGroup","imports":"['\"log\/slog\"']","structs":"['IndentHandler']","interfaces":"","file_location":"github.com\/finalHFtest\/\/tmp\/repos\/example\/slog-handler-guide\/indenthandler3\/indent_handler.go","code":"func (h *IndentHandler) WithGroup(name string) slog.Handler {\n\tif name == \"\" {\n\t\treturn h\n\t}\n\th2 := *h\n\t\/\/ Add an unopened group to h2 without modifying h.\n\th2.unopenedGroups = make([]string, len(h.unopenedGroups)+1)\n\tcopy(h2.unopenedGroups, h.unopenedGroups)\n\th2.unopenedGroups[len(h2.unopenedGroups)-1] = name\n\treturn &h2\n}","global_vars":"","package":"indenthandler","tags":""} |
|
{"element_type":"function","project_name":"finalHFtest","uuid":"6d045192-a6c8-4af1-92e1-6468d58513a7","name":"WithAttrs","imports":"['\"log\/slog\"', '\"slices\"']","structs":"['IndentHandler']","interfaces":"","file_location":"github.com\/finalHFtest\/\/tmp\/repos\/example\/slog-handler-guide\/indenthandler3\/indent_handler.go","code":"func (h *IndentHandler) WithAttrs(attrs []slog.Attr) slog.Handler {\n\tif len(attrs) == 0 {\n\t\treturn h\n\t}\n\th2 := *h\n\t\/\/ Force an append to copy the underlying array.\n\tpre := slices.Clip(h.preformatted)\n\t\/\/ Add all groups from WithGroup that haven't already been added.\n\th2.preformatted = h2.appendUnopenedGroups(pre, h2.indentLevel)\n\t\/\/ Each of those groups increased the indent level by 1.\n\th2.indentLevel += len(h2.unopenedGroups)\n\t\/\/ Now all groups have been opened.\n\th2.unopenedGroups = nil\n\t\/\/ Pre-format the attributes.\n\tfor _, a := range attrs {\n\t\th2.preformatted = h2.appendAttr(h2.preformatted, a, h2.indentLevel)\n\t}\n\treturn &h2\n}","global_vars":"","package":"indenthandler","tags":""} |
|
{"element_type":"function","project_name":"finalHFtest","uuid":"71e0fc53-b7a1-4abb-8570-d296da0e6717","name":"appendUnopenedGroups","imports":"['\"fmt\"']","structs":"['IndentHandler']","interfaces":"","file_location":"github.com\/finalHFtest\/\/tmp\/repos\/example\/slog-handler-guide\/indenthandler3\/indent_handler.go","code":"func (h *IndentHandler) appendUnopenedGroups(buf []byte, indentLevel int) []byte {\n\tfor _, g := range h.unopenedGroups {\n\t\tbuf = fmt.Appendf(buf, \"%*s%s:\\n\", indentLevel*4, \"\", g)\n\t\tindentLevel++\n\t}\n\treturn buf\n}","global_vars":"","package":"indenthandler","tags":""} |
|
{"element_type":"function","project_name":"finalHFtest","uuid":"b090b87b-c65e-4717-867e-795aaea22ec4","name":"Handle","imports":"['\"context\"', '\"fmt\"', '\"log\/slog\"', '\"runtime\"']","structs":"['IndentHandler']","interfaces":"","file_location":"github.com\/finalHFtest\/\/tmp\/repos\/example\/slog-handler-guide\/indenthandler3\/indent_handler.go","code":"func (h *IndentHandler) Handle(ctx context.Context, r slog.Record) error {\n\tbuf := make([]byte, 0, 1024)\n\tif !r.Time.IsZero() {\n\t\tbuf = h.appendAttr(buf, slog.Time(slog.TimeKey, r.Time), 0)\n\t}\n\tbuf = h.appendAttr(buf, slog.Any(slog.LevelKey, r.Level), 0)\n\tif r.PC != 0 {\n\t\tfs := runtime.CallersFrames([]uintptr{r.PC})\n\t\tf, _ := fs.Next()\n\t\tbuf = h.appendAttr(buf, slog.String(slog.SourceKey, fmt.Sprintf(\"%s:%d\", f.File, f.Line)), 0)\n\t}\n\tbuf = h.appendAttr(buf, slog.String(slog.MessageKey, r.Message), 0)\n\t\/\/ Insert preformatted attributes just after built-in ones.\n\tbuf = append(buf, h.preformatted...)\n\tif r.NumAttrs() > 0 {\n\t\tbuf = h.appendUnopenedGroups(buf, h.indentLevel)\n\t\tr.Attrs(func(a slog.Attr) bool {\n\t\t\tbuf = h.appendAttr(buf, a, h.indentLevel+len(h.unopenedGroups))\n\t\t\treturn true\n\t\t})\n\t}\n\tbuf = append(buf, \"---\\n\"...)\n\th.mu.Lock()\n\tdefer h.mu.Unlock()\n\t_, err := h.out.Write(buf)\n\treturn err\n}","global_vars":"","package":"indenthandler","tags":""} |
|
{"element_type":"function","project_name":"finalHFtest","uuid":"76dd6f45-031f-4245-8964-00a60a6a8619","name":"appendAttr","imports":"['\"fmt\"', '\"log\/slog\"', '\"time\"']","structs":"['IndentHandler']","interfaces":"","file_location":"github.com\/finalHFtest\/\/tmp\/repos\/example\/slog-handler-guide\/indenthandler3\/indent_handler.go","code":"func (h *IndentHandler) appendAttr(buf []byte, a slog.Attr, indentLevel int) []byte {\n\t\/\/ Resolve the Attr's value before doing anything else.\n\ta.Value = a.Value.Resolve()\n\t\/\/ Ignore empty Attrs.\n\tif a.Equal(slog.Attr{}) {\n\t\treturn buf\n\t}\n\t\/\/ Indent 4 spaces per level.\n\tbuf = fmt.Appendf(buf, \"%*s\", indentLevel*4, \"\")\n\tswitch a.Value.Kind() {\n\tcase slog.KindString:\n\t\t\/\/ Quote string values, to make them easy to parse.\n\t\tbuf = fmt.Appendf(buf, \"%s: %q\\n\", a.Key, a.Value.String())\n\tcase slog.KindTime:\n\t\t\/\/ Write times in a standard way, without the monotonic time.\n\t\tbuf = fmt.Appendf(buf, \"%s: %s\\n\", a.Key, a.Value.Time().Format(time.RFC3339Nano))\n\tcase slog.KindGroup:\n\t\tattrs := a.Value.Group()\n\t\t\/\/ Ignore empty groups.\n\t\tif len(attrs) == 0 {\n\t\t\treturn buf\n\t\t}\n\t\t\/\/ If the key is non-empty, write it out and indent the rest of the attrs.\n\t\t\/\/ Otherwise, inline the attrs.\n\t\tif a.Key != \"\" {\n\t\t\tbuf = fmt.Appendf(buf, \"%s:\\n\", a.Key)\n\t\t\tindentLevel++\n\t\t}\n\t\tfor _, ga := range attrs {\n\t\t\tbuf = h.appendAttr(buf, ga, indentLevel)\n\t\t}\n\tdefault:\n\t\tbuf = fmt.Appendf(buf, \"%s: %s\\n\", a.Key, a.Value)\n\t}\n\treturn buf\n}","global_vars":"","package":"indenthandler","tags":""} |
|
{"element_type":"file","project_name":"finalHFtest","uuid":"8e9523e2-e0ba-41c5-9d88-6981ae105c0f","name":"indent_handler_test.go","imports":"import (\n\t\"bytes\"\n\t\"log\/slog\"\n\t\"reflect\"\n\t\"regexp\"\n\t\"testing\"\n\t\"testing\/slogtest\"\n\n\t\"gopkg.in\/yaml.v3\"\n)","structs":"","interfaces":"","file_location":"github.com\/finalHFtest\/\/tmp\/repos\/example\/slog-handler-guide\/indenthandler3\/indent_handler_test.go","code":"\/\/go:build go1.21\n\npackage indenthandler\n\nimport (\n\t\"bytes\"\n\t\"log\/slog\"\n\t\"reflect\"\n\t\"regexp\"\n\t\"testing\"\n\t\"testing\/slogtest\"\n\n\t\"gopkg.in\/yaml.v3\"\n)\n\n\/\/ !+TestSlogtest\nfunc TestSlogtest(t *testing.T) {\n\tvar buf bytes.Buffer\n\terr := slogtest.TestHandler(New(&buf, nil), func() []map[string]any {\n\t\treturn parseLogEntries(t, buf.Bytes())\n\t})\n\tif err != nil {\n\t\tt.Error(err)\n\t}\n}\n\n\/\/ !-TestSlogtest\n\nfunc Test(t *testing.T) {\n\tvar buf bytes.Buffer\n\tl := slog.New(New(&buf, nil))\n\tl.Info(\"hello\", \"a\", 1, \"b\", true, \"c\", 3.14, slog.Group(\"g\", \"h\", 1, \"i\", 2), \"d\", \"NO\")\n\tgot := buf.String()\n\twantre := `time: [-0-9T:.]+Z?\nlevel: INFO\nsource: \".*\/indent_handler_test.go:\\d+\"\nmsg: \"hello\"\na: 1\nb: true\nc: 3.14\ng:\n h: 1\n i: 2\nd: \"NO\"\n`\n\tre := regexp.MustCompile(wantre)\n\tif !re.MatchString(got) {\n\t\tt.Errorf(\"\\ngot:\\n%q\\nwant:\\n%q\", got, wantre)\n\t}\n\n\tbuf.Reset()\n\tl.Debug(\"test\")\n\tif got := buf.Len(); got != 0 {\n\t\tt.Errorf(\"got buf.Len() = %d, want 0\", got)\n\t}\n}\n\n\/\/ !+parseLogEntries\nfunc parseLogEntries(t *testing.T, data []byte) []map[string]any {\n\tentries := bytes.Split(data, []byte(\"---\\n\"))\n\tentries = entries[:len(entries)-1] \/\/ last one is empty\n\tvar ms []map[string]any\n\tfor _, e := range entries {\n\t\tvar m map[string]any\n\t\tif err := yaml.Unmarshal([]byte(e), &m); err != nil {\n\t\t\tt.Fatal(err)\n\t\t}\n\t\tms = append(ms, m)\n\t}\n\treturn ms\n}\n\n\/\/ !-parseLogEntries\n\nfunc TestParseLogEntries(t *testing.T) {\n\tin := `\na: 1\nb: 2\nc: 3\ng:\n h: 4\n i: five\nd: 6\n---\ne: 7\n---\n`\n\twant := []map[string]any{\n\t\t{\n\t\t\t\"a\": 1,\n\t\t\t\"b\": 2,\n\t\t\t\"c\": 3,\n\t\t\t\"g\": map[string]any{\n\t\t\t\t\"h\": 4,\n\t\t\t\t\"i\": \"five\",\n\t\t\t},\n\t\t\t\"d\": 6,\n\t\t},\n\t\t{\n\t\t\t\"e\": 7,\n\t\t},\n\t}\n\tgot := parseLogEntries(t, []byte(in[1:]))\n\tif !reflect.DeepEqual(got, want) {\n\t\tt.Errorf(\"\\ngot:\\n%v\\nwant:\\n%v\", got, want)\n\t}\n}\n","global_vars":"","package":"package indenthandler","tags":""} |
|
{"element_type":"function","project_name":"finalHFtest","uuid":"ae956333-c536-4359-b8b4-8c875128f79b","name":"TestSlogtest","imports":"['\"bytes\"', '\"testing\"', '\"testing\/slogtest\"']","structs":"","interfaces":"","file_location":"github.com\/finalHFtest\/\/tmp\/repos\/example\/slog-handler-guide\/indenthandler3\/indent_handler_test.go","code":"func TestSlogtest(t *testing.T) {\n\tvar buf bytes.Buffer\n\terr := slogtest.TestHandler(New(&buf, nil), func() []map[string]any {\n\t\treturn parseLogEntries(t, buf.Bytes())\n\t})\n\tif err != nil {\n\t\tt.Error(err)\n\t}\n}","global_vars":"","package":"indenthandler","tags":""} |
|
{"element_type":"function","project_name":"finalHFtest","uuid":"4add615d-8839-4a93-8af5-4cd77a84a7d3","name":"Test","imports":"['\"bytes\"', '\"log\/slog\"', '\"regexp\"', '\"testing\"']","structs":"","interfaces":"","file_location":"github.com\/finalHFtest\/\/tmp\/repos\/example\/slog-handler-guide\/indenthandler3\/indent_handler_test.go","code":"func Test(t *testing.T) {\n\tvar buf bytes.Buffer\n\tl := slog.New(New(&buf, nil))\n\tl.Info(\"hello\", \"a\", 1, \"b\", true, \"c\", 3.14, slog.Group(\"g\", \"h\", 1, \"i\", 2), \"d\", \"NO\")\n\tgot := buf.String()\n\twantre := `time: [-0-9T:.]+Z?\nlevel: INFO\nsource: \".*\/indent_handler_test.go:\\d+\"\nmsg: \"hello\"\na: 1\nb: true\nc: 3.14\ng:\n h: 1\n i: 2\nd: \"NO\"\n`\n\tre := regexp.MustCompile(wantre)\n\tif !re.MatchString(got) {\n\t\tt.Errorf(\"\\ngot:\\n%q\\nwant:\\n%q\", got, wantre)\n\t}\n\n\tbuf.Reset()\n\tl.Debug(\"test\")\n\tif got := buf.Len(); got != 0 {\n\t\tt.Errorf(\"got buf.Len() = %d, want 0\", got)\n\t}\n}","global_vars":"","package":"indenthandler","tags":""} |
|
{"element_type":"function","project_name":"finalHFtest","uuid":"3d53d3c0-4b7d-4bf1-9560-b28a7f45d5ed","name":"parseLogEntries","imports":"['\"bytes\"', '\"testing\"']","structs":"","interfaces":"","file_location":"github.com\/finalHFtest\/\/tmp\/repos\/example\/slog-handler-guide\/indenthandler3\/indent_handler_test.go","code":"func parseLogEntries(t *testing.T, data []byte) []map[string]any {\n\tentries := bytes.Split(data, []byte(\"---\\n\"))\n\tentries = entries[:len(entries)-1] \/\/ last one is empty\n\tvar ms []map[string]any\n\tfor _, e := range entries {\n\t\tvar m map[string]any\n\t\tif err := yaml.Unmarshal([]byte(e), &m); err != nil {\n\t\t\tt.Fatal(err)\n\t\t}\n\t\tms = append(ms, m)\n\t}\n\treturn ms\n}","global_vars":"","package":"indenthandler","tags":""} |
|
{"element_type":"function","project_name":"finalHFtest","uuid":"bc201619-f54a-4561-ab8b-8a8eda625bfc","name":"TestParseLogEntries","imports":"['\"reflect\"', '\"testing\"']","structs":"","interfaces":"","file_location":"github.com\/finalHFtest\/\/tmp\/repos\/example\/slog-handler-guide\/indenthandler3\/indent_handler_test.go","code":"func TestParseLogEntries(t *testing.T) {\n\tin := `\na: 1\nb: 2\nc: 3\ng:\n h: 4\n i: five\nd: 6\n---\ne: 7\n---\n`\n\twant := []map[string]any{\n\t\t{\n\t\t\t\"a\": 1,\n\t\t\t\"b\": 2,\n\t\t\t\"c\": 3,\n\t\t\t\"g\": map[string]any{\n\t\t\t\t\"h\": 4,\n\t\t\t\t\"i\": \"five\",\n\t\t\t},\n\t\t\t\"d\": 6,\n\t\t},\n\t\t{\n\t\t\t\"e\": 7,\n\t\t},\n\t}\n\tgot := parseLogEntries(t, []byte(in[1:]))\n\tif !reflect.DeepEqual(got, want) {\n\t\tt.Errorf(\"\\ngot:\\n%v\\nwant:\\n%v\", got, want)\n\t}\n}","global_vars":"","package":"indenthandler","tags":""} |
|
{"element_type":"file","project_name":"finalHFtest","uuid":"5a3a56e7-d80b-413d-9919-8aa5c679cb91","name":"indent_handler.go","imports":"import (\n\t\"context\"\n\t\"fmt\"\n\t\"io\"\n\t\"log\/slog\"\n\t\"runtime\"\n\t\"slices\"\n\t\"strconv\"\n\t\"sync\"\n\t\"time\"\n)","structs":"","interfaces":"","file_location":"github.com\/finalHFtest\/\/tmp\/repos\/example\/slog-handler-guide\/indenthandler4\/indent_handler.go","code":"\/\/go:build go1.21\n\npackage indenthandler\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\t\"io\"\n\t\"log\/slog\"\n\t\"runtime\"\n\t\"slices\"\n\t\"strconv\"\n\t\"sync\"\n\t\"time\"\n)\n\n\/\/ !+IndentHandler\ntype IndentHandler struct {\n\topts Options\n\tpreformatted []byte \/\/ data from WithGroup and WithAttrs\n\tunopenedGroups []string \/\/ groups from WithGroup that haven't been opened\n\tindentLevel int \/\/ same as number of opened groups so far\n\tmu *sync.Mutex\n\tout io.Writer\n}\n\n\/\/!-IndentHandler\n\ntype Options struct {\n\t\/\/ Level reports the minimum level to log.\n\t\/\/ Levels with lower levels are discarded.\n\t\/\/ If nil, the Handler uses [slog.LevelInfo].\n\tLevel slog.Leveler\n}\n\nfunc New(out io.Writer, opts *Options) *IndentHandler {\n\th := &IndentHandler{out: out, mu: &sync.Mutex{}}\n\tif opts != nil {\n\t\th.opts = *opts\n\t}\n\tif h.opts.Level == nil {\n\t\th.opts.Level = slog.LevelInfo\n\t}\n\treturn h\n}\n\nfunc (h *IndentHandler) Enabled(ctx context.Context, level slog.Level) bool {\n\treturn level >= h.opts.Level.Level()\n}\n\n\/\/ !+WithGroup\nfunc (h *IndentHandler) WithGroup(name string) slog.Handler {\n\tif name == \"\" {\n\t\treturn h\n\t}\n\th2 := *h\n\t\/\/ Add an unopened group to h2 without modifying h.\n\th2.unopenedGroups = make([]string, len(h.unopenedGroups)+1)\n\tcopy(h2.unopenedGroups, h.unopenedGroups)\n\th2.unopenedGroups[len(h2.unopenedGroups)-1] = name\n\treturn &h2\n}\n\n\/\/!-WithGroup\n\n\/\/ !+WithAttrs\nfunc (h *IndentHandler) WithAttrs(attrs []slog.Attr) slog.Handler {\n\tif len(attrs) == 0 {\n\t\treturn h\n\t}\n\th2 := *h\n\t\/\/ Force an append to copy the underlying array.\n\tpre := slices.Clip(h.preformatted)\n\t\/\/ Add all groups from WithGroup that haven't already been added.\n\th2.preformatted = h2.appendUnopenedGroups(pre, h2.indentLevel)\n\t\/\/ Each of those groups increased the indent level by 1.\n\th2.indentLevel += len(h2.unopenedGroups)\n\t\/\/ Now all groups have been opened.\n\th2.unopenedGroups = nil\n\t\/\/ Pre-format the attributes.\n\tfor _, a := range attrs {\n\t\th2.preformatted = h2.appendAttr(h2.preformatted, a, h2.indentLevel)\n\t}\n\treturn &h2\n}\n\nfunc (h *IndentHandler) appendUnopenedGroups(buf []byte, indentLevel int) []byte {\n\tfor _, g := range h.unopenedGroups {\n\t\tbuf = fmt.Appendf(buf, \"%*s%s:\\n\", indentLevel*4, \"\", g)\n\t\tindentLevel++\n\t}\n\treturn buf\n}\n\n\/\/!-WithAttrs\n\n\/\/ !+Handle\nfunc (h *IndentHandler) Handle(ctx context.Context, r slog.Record) error {\n\tbufp := allocBuf()\n\tbuf := *bufp\n\tdefer func() {\n\t\t*bufp = buf\n\t\tfreeBuf(bufp)\n\t}()\n\tif !r.Time.IsZero() {\n\t\tbuf = h.appendAttr(buf, slog.Time(slog.TimeKey, r.Time), 0)\n\t}\n\tbuf = h.appendAttr(buf, slog.Any(slog.LevelKey, r.Level), 0)\n\tif r.PC != 0 {\n\t\tfs := runtime.CallersFrames([]uintptr{r.PC})\n\t\tf, _ := fs.Next()\n\t\t\/\/ Optimize to minimize allocation.\n\t\tsrcbufp := allocBuf()\n\t\tdefer freeBuf(srcbufp)\n\t\t*srcbufp = append(*srcbufp, f.File...)\n\t\t*srcbufp = append(*srcbufp, ':')\n\t\t*srcbufp = strconv.AppendInt(*srcbufp, int64(f.Line), 10)\n\t\tbuf = h.appendAttr(buf, slog.String(slog.SourceKey, string(*srcbufp)), 0)\n\t}\n\n\tbuf = h.appendAttr(buf, slog.String(slog.MessageKey, r.Message), 0)\n\t\/\/ Insert preformatted attributes just after built-in ones.\n\tbuf = append(buf, h.preformatted...)\n\tif r.NumAttrs() > 0 {\n\t\tbuf = h.appendUnopenedGroups(buf, h.indentLevel)\n\t\tr.Attrs(func(a slog.Attr) bool {\n\t\t\tbuf = h.appendAttr(buf, a, h.indentLevel+len(h.unopenedGroups))\n\t\t\treturn true\n\t\t})\n\t}\n\tbuf = append(buf, \"---\\n\"...)\n\th.mu.Lock()\n\tdefer h.mu.Unlock()\n\t_, err := h.out.Write(buf)\n\treturn err\n}\n\n\/\/!-Handle\n\nfunc (h *IndentHandler) appendAttr(buf []byte, a slog.Attr, indentLevel int) []byte {\n\t\/\/ Resolve the Attr's value before doing anything else.\n\ta.Value = a.Value.Resolve()\n\t\/\/ Ignore empty Attrs.\n\tif a.Equal(slog.Attr{}) {\n\t\treturn buf\n\t}\n\t\/\/ Indent 4 spaces per level.\n\tbuf = fmt.Appendf(buf, \"%*s\", indentLevel*4, \"\")\n\tswitch a.Value.Kind() {\n\tcase slog.KindString:\n\t\t\/\/ Quote string values, to make them easy to parse.\n\t\tbuf = append(buf, a.Key...)\n\t\tbuf = append(buf, \": \"...)\n\t\tbuf = strconv.AppendQuote(buf, a.Value.String())\n\t\tbuf = append(buf, '\\n')\n\tcase slog.KindTime:\n\t\t\/\/ Write times in a standard way, without the monotonic time.\n\t\tbuf = append(buf, a.Key...)\n\t\tbuf = append(buf, \": \"...)\n\t\tbuf = a.Value.Time().AppendFormat(buf, time.RFC3339Nano)\n\t\tbuf = append(buf, '\\n')\n\tcase slog.KindGroup:\n\t\tattrs := a.Value.Group()\n\t\t\/\/ Ignore empty groups.\n\t\tif len(attrs) == 0 {\n\t\t\treturn buf\n\t\t}\n\t\t\/\/ If the key is non-empty, write it out and indent the rest of the attrs.\n\t\t\/\/ Otherwise, inline the attrs.\n\t\tif a.Key != \"\" {\n\t\t\tbuf = fmt.Appendf(buf, \"%s:\\n\", a.Key)\n\t\t\tindentLevel++\n\t\t}\n\t\tfor _, ga := range attrs {\n\t\t\tbuf = h.appendAttr(buf, ga, indentLevel)\n\t\t}\n\n\tdefault:\n\t\tbuf = append(buf, a.Key...)\n\t\tbuf = append(buf, \": \"...)\n\t\tbuf = append(buf, a.Value.String()...)\n\t\tbuf = append(buf, '\\n')\n\t}\n\treturn buf\n}\n\n\/\/ !+pool\nvar bufPool = sync.Pool{\n\tNew: func() any {\n\t\tb := make([]byte, 0, 1024)\n\t\treturn &b\n\t},\n}\n\nfunc allocBuf() *[]byte {\n\treturn bufPool.Get().(*[]byte)\n}\n\nfunc freeBuf(b *[]byte) {\n\t\/\/ To reduce peak allocation, return only smaller buffers to the pool.\n\tconst maxBufferSize = 16 << 10\n\tif cap(*b) <= maxBufferSize {\n\t\t*b = (*b)[:0]\n\t\tbufPool.Put(b)\n\t}\n}\n\n\/\/!-pool\n","global_vars":"","package":"package indenthandler","tags":""} |
|
{"element_type":"function","project_name":"finalHFtest","uuid":"dcb9157a-5159-4448-a71b-c012a8080e8f","name":"New","imports":"['\"io\"', '\"log\/slog\"', '\"sync\"']","structs":"['IndentHandler', 'Options']","interfaces":"","file_location":"github.com\/finalHFtest\/\/tmp\/repos\/example\/slog-handler-guide\/indenthandler4\/indent_handler.go","code":"func New(out io.Writer, opts *Options) *IndentHandler {\n\th := &IndentHandler{out: out, mu: &sync.Mutex{}}\n\tif opts != nil {\n\t\th.opts = *opts\n\t}\n\tif h.opts.Level == nil {\n\t\th.opts.Level = slog.LevelInfo\n\t}\n\treturn h\n}","global_vars":"","package":"indenthandler","tags":""} |
|
{"element_type":"function","project_name":"finalHFtest","uuid":"8eba66dc-f5a7-4c86-9508-0d3d515ee461","name":"Enabled","imports":"['\"context\"', '\"log\/slog\"']","structs":"['IndentHandler']","interfaces":"","file_location":"github.com\/finalHFtest\/\/tmp\/repos\/example\/slog-handler-guide\/indenthandler4\/indent_handler.go","code":"func (h *IndentHandler) Enabled(ctx context.Context, level slog.Level) bool {\n\treturn level >= h.opts.Level.Level()\n}","global_vars":"","package":"indenthandler","tags":""} |
|
{"element_type":"function","project_name":"finalHFtest","uuid":"b85ffb6a-88ac-46bd-ab5f-96ac060f957d","name":"WithGroup","imports":"['\"log\/slog\"']","structs":"['IndentHandler']","interfaces":"","file_location":"github.com\/finalHFtest\/\/tmp\/repos\/example\/slog-handler-guide\/indenthandler4\/indent_handler.go","code":"func (h *IndentHandler) WithGroup(name string) slog.Handler {\n\tif name == \"\" {\n\t\treturn h\n\t}\n\th2 := *h\n\t\/\/ Add an unopened group to h2 without modifying h.\n\th2.unopenedGroups = make([]string, len(h.unopenedGroups)+1)\n\tcopy(h2.unopenedGroups, h.unopenedGroups)\n\th2.unopenedGroups[len(h2.unopenedGroups)-1] = name\n\treturn &h2\n}","global_vars":"","package":"indenthandler","tags":""} |
|
{"element_type":"function","project_name":"finalHFtest","uuid":"7d485133-1785-4bdb-8341-741d3a41ab4d","name":"WithAttrs","imports":"['\"log\/slog\"', '\"slices\"']","structs":"['IndentHandler']","interfaces":"","file_location":"github.com\/finalHFtest\/\/tmp\/repos\/example\/slog-handler-guide\/indenthandler4\/indent_handler.go","code":"func (h *IndentHandler) WithAttrs(attrs []slog.Attr) slog.Handler {\n\tif len(attrs) == 0 {\n\t\treturn h\n\t}\n\th2 := *h\n\t\/\/ Force an append to copy the underlying array.\n\tpre := slices.Clip(h.preformatted)\n\t\/\/ Add all groups from WithGroup that haven't already been added.\n\th2.preformatted = h2.appendUnopenedGroups(pre, h2.indentLevel)\n\t\/\/ Each of those groups increased the indent level by 1.\n\th2.indentLevel += len(h2.unopenedGroups)\n\t\/\/ Now all groups have been opened.\n\th2.unopenedGroups = nil\n\t\/\/ Pre-format the attributes.\n\tfor _, a := range attrs {\n\t\th2.preformatted = h2.appendAttr(h2.preformatted, a, h2.indentLevel)\n\t}\n\treturn &h2\n}","global_vars":"","package":"indenthandler","tags":""} |
|
{"element_type":"function","project_name":"finalHFtest","uuid":"7c2d2913-4593-43a9-bcee-3a3e0a58bb67","name":"appendUnopenedGroups","imports":"['\"fmt\"']","structs":"['IndentHandler']","interfaces":"","file_location":"github.com\/finalHFtest\/\/tmp\/repos\/example\/slog-handler-guide\/indenthandler4\/indent_handler.go","code":"func (h *IndentHandler) appendUnopenedGroups(buf []byte, indentLevel int) []byte {\n\tfor _, g := range h.unopenedGroups {\n\t\tbuf = fmt.Appendf(buf, \"%*s%s:\\n\", indentLevel*4, \"\", g)\n\t\tindentLevel++\n\t}\n\treturn buf\n}","global_vars":"","package":"indenthandler","tags":""} |
|
{"element_type":"function","project_name":"finalHFtest","uuid":"d0b81607-cc66-48c6-97ed-2aaf8055cf7f","name":"Handle","imports":"['\"context\"', '\"log\/slog\"', '\"runtime\"', '\"strconv\"']","structs":"['IndentHandler']","interfaces":"","file_location":"github.com\/finalHFtest\/\/tmp\/repos\/example\/slog-handler-guide\/indenthandler4\/indent_handler.go","code":"func (h *IndentHandler) Handle(ctx context.Context, r slog.Record) error {\n\tbufp := allocBuf()\n\tbuf := *bufp\n\tdefer func() {\n\t\t*bufp = buf\n\t\tfreeBuf(bufp)\n\t}()\n\tif !r.Time.IsZero() {\n\t\tbuf = h.appendAttr(buf, slog.Time(slog.TimeKey, r.Time), 0)\n\t}\n\tbuf = h.appendAttr(buf, slog.Any(slog.LevelKey, r.Level), 0)\n\tif r.PC != 0 {\n\t\tfs := runtime.CallersFrames([]uintptr{r.PC})\n\t\tf, _ := fs.Next()\n\t\t\/\/ Optimize to minimize allocation.\n\t\tsrcbufp := allocBuf()\n\t\tdefer freeBuf(srcbufp)\n\t\t*srcbufp = append(*srcbufp, f.File...)\n\t\t*srcbufp = append(*srcbufp, ':')\n\t\t*srcbufp = strconv.AppendInt(*srcbufp, int64(f.Line), 10)\n\t\tbuf = h.appendAttr(buf, slog.String(slog.SourceKey, string(*srcbufp)), 0)\n\t}\n\n\tbuf = h.appendAttr(buf, slog.String(slog.MessageKey, r.Message), 0)\n\t\/\/ Insert preformatted attributes just after built-in ones.\n\tbuf = append(buf, h.preformatted...)\n\tif r.NumAttrs() > 0 {\n\t\tbuf = h.appendUnopenedGroups(buf, h.indentLevel)\n\t\tr.Attrs(func(a slog.Attr) bool {\n\t\t\tbuf = h.appendAttr(buf, a, h.indentLevel+len(h.unopenedGroups))\n\t\t\treturn true\n\t\t})\n\t}\n\tbuf = append(buf, \"---\\n\"...)\n\th.mu.Lock()\n\tdefer h.mu.Unlock()\n\t_, err := h.out.Write(buf)\n\treturn err\n}","global_vars":"","package":"indenthandler","tags":""} |
|
{"element_type":"function","project_name":"finalHFtest","uuid":"ee982c7c-d9a9-42e0-baf6-a507678389c3","name":"appendAttr","imports":"['\"fmt\"', '\"log\/slog\"', '\"strconv\"', '\"time\"']","structs":"['IndentHandler']","interfaces":"","file_location":"github.com\/finalHFtest\/\/tmp\/repos\/example\/slog-handler-guide\/indenthandler4\/indent_handler.go","code":"func (h *IndentHandler) appendAttr(buf []byte, a slog.Attr, indentLevel int) []byte {\n\t\/\/ Resolve the Attr's value before doing anything else.\n\ta.Value = a.Value.Resolve()\n\t\/\/ Ignore empty Attrs.\n\tif a.Equal(slog.Attr{}) {\n\t\treturn buf\n\t}\n\t\/\/ Indent 4 spaces per level.\n\tbuf = fmt.Appendf(buf, \"%*s\", indentLevel*4, \"\")\n\tswitch a.Value.Kind() {\n\tcase slog.KindString:\n\t\t\/\/ Quote string values, to make them easy to parse.\n\t\tbuf = append(buf, a.Key...)\n\t\tbuf = append(buf, \": \"...)\n\t\tbuf = strconv.AppendQuote(buf, a.Value.String())\n\t\tbuf = append(buf, '\\n')\n\tcase slog.KindTime:\n\t\t\/\/ Write times in a standard way, without the monotonic time.\n\t\tbuf = append(buf, a.Key...)\n\t\tbuf = append(buf, \": \"...)\n\t\tbuf = a.Value.Time().AppendFormat(buf, time.RFC3339Nano)\n\t\tbuf = append(buf, '\\n')\n\tcase slog.KindGroup:\n\t\tattrs := a.Value.Group()\n\t\t\/\/ Ignore empty groups.\n\t\tif len(attrs) == 0 {\n\t\t\treturn buf\n\t\t}\n\t\t\/\/ If the key is non-empty, write it out and indent the rest of the attrs.\n\t\t\/\/ Otherwise, inline the attrs.\n\t\tif a.Key != \"\" {\n\t\t\tbuf = fmt.Appendf(buf, \"%s:\\n\", a.Key)\n\t\t\tindentLevel++\n\t\t}\n\t\tfor _, ga := range attrs {\n\t\t\tbuf = h.appendAttr(buf, ga, indentLevel)\n\t\t}\n\n\tdefault:\n\t\tbuf = append(buf, a.Key...)\n\t\tbuf = append(buf, \": \"...)\n\t\tbuf = append(buf, a.Value.String()...)\n\t\tbuf = append(buf, '\\n')\n\t}\n\treturn buf\n}","global_vars":"","package":"indenthandler","tags":""} |
|
{"element_type":"function","project_name":"finalHFtest","uuid":"5f5e2d90-cb93-420b-93ed-f48fceb6ab62","name":"allocBuf","imports":"","structs":"","interfaces":"","file_location":"github.com\/finalHFtest\/\/tmp\/repos\/example\/slog-handler-guide\/indenthandler4\/indent_handler.go","code":"func allocBuf() *[]byte {\n\treturn bufPool.Get().(*[]byte)\n}","global_vars":"","package":"indenthandler","tags":""} |
|
{"element_type":"function","project_name":"finalHFtest","uuid":"a91b2b32-9601-446e-bf3e-2cab5afc3216","name":"freeBuf","imports":"","structs":"","interfaces":"","file_location":"github.com\/finalHFtest\/\/tmp\/repos\/example\/slog-handler-guide\/indenthandler4\/indent_handler.go","code":"func freeBuf(b *[]byte) {\n\t\/\/ To reduce peak allocation, return only smaller buffers to the pool.\n\tconst maxBufferSize = 16 << 10\n\tif cap(*b) <= maxBufferSize {\n\t\t*b = (*b)[:0]\n\t\tbufPool.Put(b)\n\t}\n}","global_vars":"","package":"indenthandler","tags":""} |
|
{"element_type":"file","project_name":"finalHFtest","uuid":"5a612c7c-02ad-4438-87d6-360beef1baf6","name":"indent_handler_norace_test.go","imports":"import (\n\t\"fmt\"\n\t\"io\"\n\t\"log\/slog\"\n\t\"strconv\"\n\t\"testing\"\n)","structs":"","interfaces":"","file_location":"github.com\/finalHFtest\/\/tmp\/repos\/example\/slog-handler-guide\/indenthandler4\/indent_handler_norace_test.go","code":"\/\/go:build go1.21 && !race\n\npackage indenthandler\n\nimport (\n\t\"fmt\"\n\t\"io\"\n\t\"log\/slog\"\n\t\"strconv\"\n\t\"testing\"\n)\n\nfunc TestAlloc(t *testing.T) {\n\ta := slog.String(\"key\", \"value\")\n\tt.Run(\"Appendf\", func(t *testing.T) {\n\t\tbuf := make([]byte, 0, 100)\n\t\tg := testing.AllocsPerRun(2, func() {\n\t\t\tbuf = fmt.Appendf(buf, \"%s: %q\\n\", a.Key, a.Value.String())\n\t\t})\n\t\tif g, w := int(g), 2; g != w {\n\t\t\tt.Errorf(\"got %d, want %d\", g, w)\n\t\t}\n\t})\n\tt.Run(\"appends\", func(t *testing.T) {\n\t\tbuf := make([]byte, 0, 100)\n\t\tg := testing.AllocsPerRun(2, func() {\n\t\t\tbuf = append(buf, a.Key...)\n\t\t\tbuf = append(buf, \": \"...)\n\t\t\tbuf = strconv.AppendQuote(buf, a.Value.String())\n\t\t\tbuf = append(buf, '\\n')\n\t\t})\n\t\tif g, w := int(g), 0; g != w {\n\t\t\tt.Errorf(\"got %d, want %d\", g, w)\n\t\t}\n\t})\n\n\tt.Run(\"Handle\", func(t *testing.T) {\n\t\tl := slog.New(New(io.Discard, nil))\n\t\tgot := testing.AllocsPerRun(10, func() {\n\t\t\tl.LogAttrs(nil, slog.LevelInfo, \"hello\", slog.String(\"a\", \"1\"))\n\t\t})\n\t\tif g, w := int(got), 6; g > w {\n\t\t\tt.Errorf(\"got %d, want at most %d\", g, w)\n\t\t}\n\t})\n}\n","global_vars":"","package":"package indenthandler","tags":""} |
|
{"element_type":"function","project_name":"finalHFtest","uuid":"c9af9896-eddb-45b1-856f-30be14823bbe","name":"TestAlloc","imports":"['\"fmt\"', '\"io\"', '\"log\/slog\"', '\"strconv\"', '\"testing\"']","structs":"","interfaces":"","file_location":"github.com\/finalHFtest\/\/tmp\/repos\/example\/slog-handler-guide\/indenthandler4\/indent_handler_norace_test.go","code":"func TestAlloc(t *testing.T) {\n\ta := slog.String(\"key\", \"value\")\n\tt.Run(\"Appendf\", func(t *testing.T) {\n\t\tbuf := make([]byte, 0, 100)\n\t\tg := testing.AllocsPerRun(2, func() {\n\t\t\tbuf = fmt.Appendf(buf, \"%s: %q\\n\", a.Key, a.Value.String())\n\t\t})\n\t\tif g, w := int(g), 2; g != w {\n\t\t\tt.Errorf(\"got %d, want %d\", g, w)\n\t\t}\n\t})\n\tt.Run(\"appends\", func(t *testing.T) {\n\t\tbuf := make([]byte, 0, 100)\n\t\tg := testing.AllocsPerRun(2, func() {\n\t\t\tbuf = append(buf, a.Key...)\n\t\t\tbuf = append(buf, \": \"...)\n\t\t\tbuf = strconv.AppendQuote(buf, a.Value.String())\n\t\t\tbuf = append(buf, '\\n')\n\t\t})\n\t\tif g, w := int(g), 0; g != w {\n\t\t\tt.Errorf(\"got %d, want %d\", g, w)\n\t\t}\n\t})\n\n\tt.Run(\"Handle\", func(t *testing.T) {\n\t\tl := slog.New(New(io.Discard, nil))\n\t\tgot := testing.AllocsPerRun(10, func() {\n\t\t\tl.LogAttrs(nil, slog.LevelInfo, \"hello\", slog.String(\"a\", \"1\"))\n\t\t})\n\t\tif g, w := int(got), 6; g > w {\n\t\t\tt.Errorf(\"got %d, want at most %d\", g, w)\n\t\t}\n\t})\n}","global_vars":"","package":"indenthandler","tags":""} |
|
{"element_type":"file","project_name":"finalHFtest","uuid":"3fe71794-29a6-4ef6-b7cb-822201b87a1c","name":"indent_handler_test.go","imports":"import (\n\t\"bytes\"\n\t\"log\/slog\"\n\t\"reflect\"\n\t\"regexp\"\n\t\"testing\"\n\t\"testing\/slogtest\"\n\n\t\"gopkg.in\/yaml.v3\"\n)","structs":"","interfaces":"","file_location":"github.com\/finalHFtest\/\/tmp\/repos\/example\/slog-handler-guide\/indenthandler4\/indent_handler_test.go","code":"\/\/go:build go1.21\n\npackage indenthandler\n\nimport (\n\t\"bytes\"\n\t\"log\/slog\"\n\t\"reflect\"\n\t\"regexp\"\n\t\"testing\"\n\t\"testing\/slogtest\"\n\n\t\"gopkg.in\/yaml.v3\"\n)\n\n\/\/ !+TestSlogtest\nfunc TestSlogtest(t *testing.T) {\n\tvar buf bytes.Buffer\n\terr := slogtest.TestHandler(New(&buf, nil), func() []map[string]any {\n\t\treturn parseLogEntries(t, buf.Bytes())\n\t})\n\tif err != nil {\n\t\tt.Error(err)\n\t}\n}\n\n\/\/ !-TestSlogtest\n\nfunc Test(t *testing.T) {\n\tvar buf bytes.Buffer\n\tl := slog.New(New(&buf, nil))\n\tl.Info(\"hello\", \"a\", 1, \"b\", true, \"c\", 3.14, slog.Group(\"g\", \"h\", 1, \"i\", 2), \"d\", \"NO\")\n\tgot := buf.String()\n\twantre := `time: [-0-9T:.]+Z?\nlevel: INFO\nsource: \".*\/indent_handler_test.go:\\d+\"\nmsg: \"hello\"\na: 1\nb: true\nc: 3.14\ng:\n h: 1\n i: 2\nd: \"NO\"\n`\n\tre := regexp.MustCompile(wantre)\n\tif !re.MatchString(got) {\n\t\tt.Errorf(\"\\ngot:\\n%q\\nwant:\\n%q\", got, wantre)\n\t}\n\n\tbuf.Reset()\n\tl.Debug(\"test\")\n\tif got := buf.Len(); got != 0 {\n\t\tt.Errorf(\"got buf.Len() = %d, want 0\", got)\n\t}\n}\n\n\/\/ !+parseLogEntries\nfunc parseLogEntries(t *testing.T, data []byte) []map[string]any {\n\tentries := bytes.Split(data, []byte(\"---\\n\"))\n\tentries = entries[:len(entries)-1] \/\/ last one is empty\n\tvar ms []map[string]any\n\tfor _, e := range entries {\n\t\tvar m map[string]any\n\t\tif err := yaml.Unmarshal([]byte(e), &m); err != nil {\n\t\t\tt.Fatal(err)\n\t\t}\n\t\tms = append(ms, m)\n\t}\n\treturn ms\n}\n\n\/\/ !-parseLogEntries\n\nfunc TestParseLogEntries(t *testing.T) {\n\tin := `\na: 1\nb: 2\nc: 3\ng:\n h: 4\n i: five\nd: 6\n---\ne: 7\n---\n`\n\twant := []map[string]any{\n\t\t{\n\t\t\t\"a\": 1,\n\t\t\t\"b\": 2,\n\t\t\t\"c\": 3,\n\t\t\t\"g\": map[string]any{\n\t\t\t\t\"h\": 4,\n\t\t\t\t\"i\": \"five\",\n\t\t\t},\n\t\t\t\"d\": 6,\n\t\t},\n\t\t{\n\t\t\t\"e\": 7,\n\t\t},\n\t}\n\tgot := parseLogEntries(t, []byte(in[1:]))\n\tif !reflect.DeepEqual(got, want) {\n\t\tt.Errorf(\"\\ngot:\\n%v\\nwant:\\n%v\", got, want)\n\t}\n}\n","global_vars":"","package":"package indenthandler","tags":""} |
|
{"element_type":"function","project_name":"finalHFtest","uuid":"7cb1ed23-a431-4453-b0d4-99cdcc4bfc3d","name":"TestSlogtest","imports":"['\"bytes\"', '\"testing\"', '\"testing\/slogtest\"']","structs":"","interfaces":"","file_location":"github.com\/finalHFtest\/\/tmp\/repos\/example\/slog-handler-guide\/indenthandler4\/indent_handler_test.go","code":"func TestSlogtest(t *testing.T) {\n\tvar buf bytes.Buffer\n\terr := slogtest.TestHandler(New(&buf, nil), func() []map[string]any {\n\t\treturn parseLogEntries(t, buf.Bytes())\n\t})\n\tif err != nil {\n\t\tt.Error(err)\n\t}\n}","global_vars":"","package":"indenthandler","tags":""} |
|
{"element_type":"function","project_name":"finalHFtest","uuid":"07641698-ebdc-4af0-9df4-5c9a8872c454","name":"Test","imports":"['\"bytes\"', '\"log\/slog\"', '\"regexp\"', '\"testing\"']","structs":"","interfaces":"","file_location":"github.com\/finalHFtest\/\/tmp\/repos\/example\/slog-handler-guide\/indenthandler4\/indent_handler_test.go","code":"func Test(t *testing.T) {\n\tvar buf bytes.Buffer\n\tl := slog.New(New(&buf, nil))\n\tl.Info(\"hello\", \"a\", 1, \"b\", true, \"c\", 3.14, slog.Group(\"g\", \"h\", 1, \"i\", 2), \"d\", \"NO\")\n\tgot := buf.String()\n\twantre := `time: [-0-9T:.]+Z?\nlevel: INFO\nsource: \".*\/indent_handler_test.go:\\d+\"\nmsg: \"hello\"\na: 1\nb: true\nc: 3.14\ng:\n h: 1\n i: 2\nd: \"NO\"\n`\n\tre := regexp.MustCompile(wantre)\n\tif !re.MatchString(got) {\n\t\tt.Errorf(\"\\ngot:\\n%q\\nwant:\\n%q\", got, wantre)\n\t}\n\n\tbuf.Reset()\n\tl.Debug(\"test\")\n\tif got := buf.Len(); got != 0 {\n\t\tt.Errorf(\"got buf.Len() = %d, want 0\", got)\n\t}\n}","global_vars":"","package":"indenthandler","tags":""} |
|
{"element_type":"function","project_name":"finalHFtest","uuid":"39a9e8c2-209b-4f3b-9399-420b23ad55f4","name":"parseLogEntries","imports":"['\"bytes\"', '\"testing\"']","structs":"","interfaces":"","file_location":"github.com\/finalHFtest\/\/tmp\/repos\/example\/slog-handler-guide\/indenthandler4\/indent_handler_test.go","code":"func parseLogEntries(t *testing.T, data []byte) []map[string]any {\n\tentries := bytes.Split(data, []byte(\"---\\n\"))\n\tentries = entries[:len(entries)-1] \/\/ last one is empty\n\tvar ms []map[string]any\n\tfor _, e := range entries {\n\t\tvar m map[string]any\n\t\tif err := yaml.Unmarshal([]byte(e), &m); err != nil {\n\t\t\tt.Fatal(err)\n\t\t}\n\t\tms = append(ms, m)\n\t}\n\treturn ms\n}","global_vars":"","package":"indenthandler","tags":""} |
|
{"element_type":"function","project_name":"finalHFtest","uuid":"cf406fb3-0d31-4f97-9ff6-d875b7d5d08c","name":"TestParseLogEntries","imports":"['\"reflect\"', '\"testing\"']","structs":"","interfaces":"","file_location":"github.com\/finalHFtest\/\/tmp\/repos\/example\/slog-handler-guide\/indenthandler4\/indent_handler_test.go","code":"func TestParseLogEntries(t *testing.T) {\n\tin := `\na: 1\nb: 2\nc: 3\ng:\n h: 4\n i: five\nd: 6\n---\ne: 7\n---\n`\n\twant := []map[string]any{\n\t\t{\n\t\t\t\"a\": 1,\n\t\t\t\"b\": 2,\n\t\t\t\"c\": 3,\n\t\t\t\"g\": map[string]any{\n\t\t\t\t\"h\": 4,\n\t\t\t\t\"i\": \"five\",\n\t\t\t},\n\t\t\t\"d\": 6,\n\t\t},\n\t\t{\n\t\t\t\"e\": 7,\n\t\t},\n\t}\n\tgot := parseLogEntries(t, []byte(in[1:]))\n\tif !reflect.DeepEqual(got, want) {\n\t\tt.Errorf(\"\\ngot:\\n%v\\nwant:\\n%v\", got, want)\n\t}\n}","global_vars":"","package":"indenthandler","tags":""} |
|
{"element_type":"file","project_name":"finalHFtest","uuid":"905b20f3-4372-42c6-b680-47c278aebd3a","name":"main.go","imports":"import (\n\t\"html\/template\"\n\t\"log\"\n\t\"net\/http\"\n\t\"strings\"\n)","structs":"","interfaces":"","file_location":"github.com\/finalHFtest\/\/tmp\/repos\/example\/template\/main.go","code":"\/\/ Copyright 2023 The Go Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style\n\/\/ license that can be found in the LICENSE file.\n\n\/\/ Template is a trivial web server that uses the text\/template (and\n\/\/ html\/template) package's \"block\" feature to implement a kind of template\n\/\/ inheritance.\n\/\/\n\/\/ It should be executed from the directory in which the source resides,\n\/\/ as it will look for its template files in the current directory.\npackage main\n\nimport (\n\t\"html\/template\"\n\t\"log\"\n\t\"net\/http\"\n\t\"strings\"\n)\n\nfunc main() {\n\thttp.HandleFunc(\"\/\", indexHandler)\n\thttp.HandleFunc(\"\/image\/\", imageHandler)\n\tlog.Fatal(http.ListenAndServe(\"localhost:8080\", nil))\n}\n\n\/\/ indexTemplate is the main site template.\n\/\/ The default template includes two template blocks (\"sidebar\" and \"content\")\n\/\/ that may be replaced in templates derived from this one.\nvar indexTemplate = template.Must(template.ParseFiles(\"index.tmpl\"))\n\n\/\/ Index is a data structure used to populate an indexTemplate.\ntype Index struct {\n\tTitle string\n\tBody string\n\tLinks []Link\n}\n\ntype Link struct {\n\tURL, Title string\n}\n\n\/\/ indexHandler is an HTTP handler that serves the index page.\nfunc indexHandler(w http.ResponseWriter, r *http.Request) {\n\tdata := &Index{\n\t\tTitle: \"Image gallery\",\n\t\tBody: \"Welcome to the image gallery.\",\n\t}\n\tfor name, img := range images {\n\t\tdata.Links = append(data.Links, Link{\n\t\t\tURL: \"\/image\/\" + name,\n\t\t\tTitle: img.Title,\n\t\t})\n\t}\n\tif err := indexTemplate.Execute(w, data); err != nil {\n\t\tlog.Println(err)\n\t}\n}\n\n\/\/ imageTemplate is a clone of indexTemplate that provides\n\/\/ alternate \"sidebar\" and \"content\" templates.\nvar imageTemplate = template.Must(template.Must(indexTemplate.Clone()).ParseFiles(\"image.tmpl\"))\n\n\/\/ Image is a data structure used to populate an imageTemplate.\ntype Image struct {\n\tTitle string\n\tURL string\n}\n\n\/\/ imageHandler is an HTTP handler that serves the image pages.\nfunc imageHandler(w http.ResponseWriter, r *http.Request) {\n\tdata, ok := images[strings.TrimPrefix(r.URL.Path, \"\/image\/\")]\n\tif !ok {\n\t\thttp.NotFound(w, r)\n\t\treturn\n\t}\n\tif err := imageTemplate.Execute(w, data); err != nil {\n\t\tlog.Println(err)\n\t}\n}\n\n\/\/ images specifies the site content: a collection of images.\nvar images = map[string]*Image{\n\t\"go\": {\"The Go Gopher\", \"https:\/\/golang.org\/doc\/gopher\/frontpage.png\"},\n\t\"google\": {\"The Google Logo\", \"https:\/\/www.google.com\/images\/branding\/googlelogo\/1x\/googlelogo_color_272x92dp.png\"},\n}\n","global_vars":"","package":"package main","tags":""} |
|
{"element_type":"function","project_name":"finalHFtest","uuid":"1bf5902e-54c5-4af0-bb79-e4f81a4fa6c6","name":"main","imports":"['\"log\"', '\"net\/http\"']","structs":"","interfaces":"","file_location":"github.com\/finalHFtest\/\/tmp\/repos\/example\/template\/main.go","code":"func main() {\n\thttp.HandleFunc(\"\/\", indexHandler)\n\thttp.HandleFunc(\"\/image\/\", imageHandler)\n\tlog.Fatal(http.ListenAndServe(\"localhost:8080\", nil))\n}","global_vars":"","package":"main","tags":""} |
|
{"element_type":"function","project_name":"finalHFtest","uuid":"8612c721-78dd-4edf-b792-5e9e52cb846a","name":"indexHandler","imports":"['\"log\"', '\"net\/http\"']","structs":"['Index', 'Link', 'Image']","interfaces":"","file_location":"github.com\/finalHFtest\/\/tmp\/repos\/example\/template\/main.go","code":"func indexHandler(w http.ResponseWriter, r *http.Request) {\n\tdata := &Index{\n\t\tTitle: \"Image gallery\",\n\t\tBody: \"Welcome to the image gallery.\",\n\t}\n\tfor name, img := range images {\n\t\tdata.Links = append(data.Links, Link{\n\t\t\tURL: \"\/image\/\" + name,\n\t\t\tTitle: img.Title,\n\t\t})\n\t}\n\tif err := indexTemplate.Execute(w, data); err != nil {\n\t\tlog.Println(err)\n\t}\n}","global_vars":"","package":"main","tags":""} |
|
{"element_type":"function","project_name":"finalHFtest","uuid":"5fc66bd0-fabc-4ea2-8863-5811e8c0cfb9","name":"imageHandler","imports":"['\"log\"', '\"net\/http\"', '\"strings\"']","structs":"","interfaces":"","file_location":"github.com\/finalHFtest\/\/tmp\/repos\/example\/template\/main.go","code":"func imageHandler(w http.ResponseWriter, r *http.Request) {\n\tdata, ok := images[strings.TrimPrefix(r.URL.Path, \"\/image\/\")]\n\tif !ok {\n\t\thttp.NotFound(w, r)\n\t\treturn\n\t}\n\tif err := imageTemplate.Execute(w, data); err != nil {\n\t\tlog.Println(err)\n\t}\n}","global_vars":"","package":"main","tags":""} |
|
|