element_type
stringclasses 2
values | project_name
stringclasses 2
values | uuid
stringlengths 36
36
| name
stringlengths 3
29
| imports
stringlengths 0
312
| structs
stringclasses 7
values | interfaces
stringclasses 1
value | file_location
stringlengths 58
108
| code
stringlengths 41
7.22k
| global_vars
stringclasses 3
values | package
stringclasses 11
values | tags
stringclasses 1
value |
---|---|---|---|---|---|---|---|---|---|---|---|
function | flightctl/test | 494a4385-31ad-4914-bb79-86d0c775aa44 | WithAttrs | ['"log/slog"'] | ['IndentHandler', 'groupOrAttrs'] | github.com/flightctl/test//tmp/repos/example/slog-handler-guide/indenthandler2/indent_handler.go | func (h *IndentHandler) WithAttrs(attrs []slog.Attr) slog.Handler {
if len(attrs) == 0 {
return h
}
return h.withGroupOrAttrs(groupOrAttrs{attrs: attrs})
} | indenthandler | |||
function | flightctl/test | f7c7ebcb-0e08-4184-be17-260a8cb06f2e | withGroupOrAttrs | ['IndentHandler', 'groupOrAttrs'] | github.com/flightctl/test//tmp/repos/example/slog-handler-guide/indenthandler2/indent_handler.go | func (h *IndentHandler) withGroupOrAttrs(goa groupOrAttrs) *IndentHandler {
h2 := *h
h2.goas = make([]groupOrAttrs, len(h.goas)+1)
copy(h2.goas, h.goas)
h2.goas[len(h2.goas)-1] = goa
return &h2
} | indenthandler | ||||
function | flightctl/test | 49fedc14-9cd8-47cf-b00b-e68b8c43e499 | Handle | ['"context"', '"fmt"', '"log/slog"', '"runtime"'] | ['IndentHandler'] | github.com/flightctl/test//tmp/repos/example/slog-handler-guide/indenthandler2/indent_handler.go | func (h *IndentHandler) Handle(ctx context.Context, r slog.Record) error {
buf := make([]byte, 0, 1024)
if !r.Time.IsZero() {
buf = h.appendAttr(buf, slog.Time(slog.TimeKey, r.Time), 0)
}
buf = h.appendAttr(buf, slog.Any(slog.LevelKey, r.Level), 0)
if r.PC != 0 {
fs := runtime.CallersFrames([]uintptr{r.PC})
f, _ := fs.Next()
buf = h.appendAttr(buf, slog.String(slog.SourceKey, fmt.Sprintf("%s:%d", f.File, f.Line)), 0)
}
buf = h.appendAttr(buf, slog.String(slog.MessageKey, r.Message), 0)
indentLevel := 0
// Handle state from WithGroup and WithAttrs.
goas := h.goas
if r.NumAttrs() == 0 {
// If the record has no Attrs, remove groups at the end of the list; they are empty.
for len(goas) > 0 && goas[len(goas)-1].group != "" {
goas = goas[:len(goas)-1]
}
}
for _, goa := range goas {
if goa.group != "" {
buf = fmt.Appendf(buf, "%*s%s:\n", indentLevel*4, "", goa.group)
indentLevel++
} else {
for _, a := range goa.attrs {
buf = h.appendAttr(buf, a, indentLevel)
}
}
}
r.Attrs(func(a slog.Attr) bool {
buf = h.appendAttr(buf, a, indentLevel)
return true
})
buf = append(buf, "---\n"...)
h.mu.Lock()
defer h.mu.Unlock()
_, err := h.out.Write(buf)
return err
} | indenthandler | |||
function | flightctl/test | b7af3ddd-b2de-4e27-a5ce-d40d18c83e8c | appendAttr | ['"fmt"', '"log/slog"', '"time"'] | ['IndentHandler'] | github.com/flightctl/test//tmp/repos/example/slog-handler-guide/indenthandler2/indent_handler.go | func (h *IndentHandler) appendAttr(buf []byte, a slog.Attr, indentLevel int) []byte {
// Resolve the Attr's value before doing anything else.
a.Value = a.Value.Resolve()
// Ignore empty Attrs.
if a.Equal(slog.Attr{}) {
return buf
}
// Indent 4 spaces per level.
buf = fmt.Appendf(buf, "%*s", indentLevel*4, "")
switch a.Value.Kind() {
case slog.KindString:
// Quote string values, to make them easy to parse.
buf = fmt.Appendf(buf, "%s: %q\n", a.Key, a.Value.String())
case slog.KindTime:
// Write times in a standard way, without the monotonic time.
buf = fmt.Appendf(buf, "%s: %s\n", a.Key, a.Value.Time().Format(time.RFC3339Nano))
case slog.KindGroup:
attrs := a.Value.Group()
// Ignore empty groups.
if len(attrs) == 0 {
return buf
}
// If the key is non-empty, write it out and indent the rest of the attrs.
// Otherwise, inline the attrs.
if a.Key != "" {
buf = fmt.Appendf(buf, "%s:\n", a.Key)
indentLevel++
}
for _, ga := range attrs {
buf = h.appendAttr(buf, ga, indentLevel)
}
default:
buf = fmt.Appendf(buf, "%s: %s\n", a.Key, a.Value)
}
return buf
} | indenthandler | |||
file | flightctl/test | 67b78552-62c3-4562-829e-5d37e6eecf9c | indent_handler_test.go | import (
"bufio"
"bytes"
"fmt"
"reflect"
"regexp"
"strconv"
"strings"
"testing"
"unicode"
"log/slog"
"testing/slogtest"
) | github.com/flightctl/test//tmp/repos/example/slog-handler-guide/indenthandler2/indent_handler_test.go | //go:build go1.21
package indenthandler
import (
"bufio"
"bytes"
"fmt"
"reflect"
"regexp"
"strconv"
"strings"
"testing"
"unicode"
"log/slog"
"testing/slogtest"
)
func TestSlogtest(t *testing.T) {
var buf bytes.Buffer
err := slogtest.TestHandler(New(&buf, nil), func() []map[string]any {
return parseLogEntries(buf.String())
})
if err != nil {
t.Error(err)
}
}
func Test(t *testing.T) {
var buf bytes.Buffer
l := slog.New(New(&buf, nil))
l.Info("hello", "a", 1, "b", true, "c", 3.14, slog.Group("g", "h", 1, "i", 2), "d", "NO")
got := buf.String()
wantre := `time: [-0-9T:.]+Z?
level: INFO
source: ".*/indent_handler_test.go:\d+"
msg: "hello"
a: 1
b: true
c: 3.14
g:
h: 1
i: 2
d: "NO"
`
re := regexp.MustCompile(wantre)
if !re.MatchString(got) {
t.Errorf("\ngot:\n%q\nwant:\n%q", got, wantre)
}
buf.Reset()
l.Debug("test")
if got := buf.Len(); got != 0 {
t.Errorf("got buf.Len() = %d, want 0", got)
}
}
func parseLogEntries(s string) []map[string]any {
var ms []map[string]any
scan := bufio.NewScanner(strings.NewReader(s))
for scan.Scan() {
m := parseGroup(scan)
ms = append(ms, m)
}
if scan.Err() != nil {
panic(scan.Err())
}
return ms
}
func parseGroup(scan *bufio.Scanner) map[string]any {
m := map[string]any{}
groupIndent := -1
for {
line := scan.Text()
if line == "---" { // end of entry
break
}
k, v, found := strings.Cut(line, ":")
if !found {
panic(fmt.Sprintf("no ':' in line %q", line))
}
indent := strings.IndexFunc(k, func(r rune) bool {
return !unicode.IsSpace(r)
})
if indent < 0 {
panic("blank line")
}
if groupIndent < 0 {
// First line in group; remember the indent.
groupIndent = indent
} else if indent < groupIndent {
// End of group
break
} else if indent > groupIndent {
panic(fmt.Sprintf("indent increased on line %q", line))
}
key := strings.TrimSpace(k)
if v == "" {
// Just a key: start of a group.
if !scan.Scan() {
panic("empty group")
}
m[key] = parseGroup(scan)
} else {
v = strings.TrimSpace(v)
if len(v) > 0 && v[0] == '"' {
var err error
v, err = strconv.Unquote(v)
if err != nil {
panic(err)
}
}
m[key] = v
if !scan.Scan() {
break
}
}
}
return m
}
func TestParseLogEntries(t *testing.T) {
in := `
a: 1
b: 2
c: 3
g:
h: 4
i: 5
d: 6
---
e: 7
---
`
want := []map[string]any{
{
"a": "1",
"b": "2",
"c": "3",
"g": map[string]any{
"h": "4",
"i": "5",
},
"d": "6",
},
{
"e": "7",
},
}
got := parseLogEntries(in[1:])
if !reflect.DeepEqual(got, want) {
t.Errorf("\ngot:\n%v\nwant:\n%v", got, want)
}
}
| package indenthandler | ||||
function | flightctl/test | 4c7252e8-d995-4e37-9d02-e8e966fb5ebf | TestSlogtest | ['"bytes"', '"testing"', '"testing/slogtest"'] | github.com/flightctl/test//tmp/repos/example/slog-handler-guide/indenthandler2/indent_handler_test.go | func TestSlogtest(t *testing.T) {
var buf bytes.Buffer
err := slogtest.TestHandler(New(&buf, nil), func() []map[string]any {
return parseLogEntries(buf.String())
})
if err != nil {
t.Error(err)
}
} | indenthandler | ||||
function | flightctl/test | 115f25f5-733c-4925-aa7b-93860e2177fc | Test | ['"bytes"', '"regexp"', '"testing"', '"log/slog"'] | github.com/flightctl/test//tmp/repos/example/slog-handler-guide/indenthandler2/indent_handler_test.go | func Test(t *testing.T) {
var buf bytes.Buffer
l := slog.New(New(&buf, nil))
l.Info("hello", "a", 1, "b", true, "c", 3.14, slog.Group("g", "h", 1, "i", 2), "d", "NO")
got := buf.String()
wantre := `time: [-0-9T:.]+Z?
level: INFO
source: ".*/indent_handler_test.go:\d+"
msg: "hello"
a: 1
b: true
c: 3.14
g:
h: 1
i: 2
d: "NO"
`
re := regexp.MustCompile(wantre)
if !re.MatchString(got) {
t.Errorf("\ngot:\n%q\nwant:\n%q", got, wantre)
}
buf.Reset()
l.Debug("test")
if got := buf.Len(); got != 0 {
t.Errorf("got buf.Len() = %d, want 0", got)
}
} | indenthandler | ||||
function | flightctl/test | f8cb55d6-a766-4e3f-b063-46bab5c0092b | parseLogEntries | ['"bufio"', '"strings"'] | github.com/flightctl/test//tmp/repos/example/slog-handler-guide/indenthandler2/indent_handler_test.go | func parseLogEntries(s string) []map[string]any {
var ms []map[string]any
scan := bufio.NewScanner(strings.NewReader(s))
for scan.Scan() {
m := parseGroup(scan)
ms = append(ms, m)
}
if scan.Err() != nil {
panic(scan.Err())
}
return ms
} | indenthandler | ||||
function | flightctl/test | df4a2a80-df8c-4b16-999b-2d8e37ded9be | parseGroup | ['"bufio"', '"fmt"', '"strconv"', '"strings"', '"unicode"'] | github.com/flightctl/test//tmp/repos/example/slog-handler-guide/indenthandler2/indent_handler_test.go | func parseGroup(scan *bufio.Scanner) map[string]any {
m := map[string]any{}
groupIndent := -1
for {
line := scan.Text()
if line == "---" { // end of entry
break
}
k, v, found := strings.Cut(line, ":")
if !found {
panic(fmt.Sprintf("no ':' in line %q", line))
}
indent := strings.IndexFunc(k, func(r rune) bool {
return !unicode.IsSpace(r)
})
if indent < 0 {
panic("blank line")
}
if groupIndent < 0 {
// First line in group; remember the indent.
groupIndent = indent
} else if indent < groupIndent {
// End of group
break
} else if indent > groupIndent {
panic(fmt.Sprintf("indent increased on line %q", line))
}
key := strings.TrimSpace(k)
if v == "" {
// Just a key: start of a group.
if !scan.Scan() {
panic("empty group")
}
m[key] = parseGroup(scan)
} else {
v = strings.TrimSpace(v)
if len(v) > 0 && v[0] == '"' {
var err error
v, err = strconv.Unquote(v)
if err != nil {
panic(err)
}
}
m[key] = v
if !scan.Scan() {
break
}
}
}
return m
} | indenthandler | ||||
function | flightctl/test | d4180e8e-3486-4543-b6a5-5e3ef55d3e08 | TestParseLogEntries | ['"reflect"', '"testing"'] | github.com/flightctl/test//tmp/repos/example/slog-handler-guide/indenthandler2/indent_handler_test.go | func TestParseLogEntries(t *testing.T) {
in := `
a: 1
b: 2
c: 3
g:
h: 4
i: 5
d: 6
---
e: 7
---
`
want := []map[string]any{
{
"a": "1",
"b": "2",
"c": "3",
"g": map[string]any{
"h": "4",
"i": "5",
},
"d": "6",
},
{
"e": "7",
},
}
got := parseLogEntries(in[1:])
if !reflect.DeepEqual(got, want) {
t.Errorf("\ngot:\n%v\nwant:\n%v", got, want)
}
} | indenthandler | ||||
file | flightctl/test | 6f509e38-39b8-4aa7-99d7-f7f8d66e7787 | indent_handler.go | import (
"context"
"fmt"
"io"
"log/slog"
"runtime"
"slices"
"sync"
"time"
) | github.com/flightctl/test//tmp/repos/example/slog-handler-guide/indenthandler3/indent_handler.go | //go:build go1.21
package indenthandler
import (
"context"
"fmt"
"io"
"log/slog"
"runtime"
"slices"
"sync"
"time"
)
// !+IndentHandler
type IndentHandler struct {
opts Options
preformatted []byte // data from WithGroup and WithAttrs
unopenedGroups []string // groups from WithGroup that haven't been opened
indentLevel int // same as number of opened groups so far
mu *sync.Mutex
out io.Writer
}
//!-IndentHandler
type Options struct {
// Level reports the minimum level to log.
// Levels with lower levels are discarded.
// If nil, the Handler uses [slog.LevelInfo].
Level slog.Leveler
}
func New(out io.Writer, opts *Options) *IndentHandler {
h := &IndentHandler{out: out, mu: &sync.Mutex{}}
if opts != nil {
h.opts = *opts
}
if h.opts.Level == nil {
h.opts.Level = slog.LevelInfo
}
return h
}
func (h *IndentHandler) Enabled(ctx context.Context, level slog.Level) bool {
return level >= h.opts.Level.Level()
}
// !+WithGroup
func (h *IndentHandler) WithGroup(name string) slog.Handler {
if name == "" {
return h
}
h2 := *h
// Add an unopened group to h2 without modifying h.
h2.unopenedGroups = make([]string, len(h.unopenedGroups)+1)
copy(h2.unopenedGroups, h.unopenedGroups)
h2.unopenedGroups[len(h2.unopenedGroups)-1] = name
return &h2
}
//!-WithGroup
// !+WithAttrs
func (h *IndentHandler) WithAttrs(attrs []slog.Attr) slog.Handler {
if len(attrs) == 0 {
return h
}
h2 := *h
// Force an append to copy the underlying array.
pre := slices.Clip(h.preformatted)
// Add all groups from WithGroup that haven't already been added.
h2.preformatted = h2.appendUnopenedGroups(pre, h2.indentLevel)
// Each of those groups increased the indent level by 1.
h2.indentLevel += len(h2.unopenedGroups)
// Now all groups have been opened.
h2.unopenedGroups = nil
// Pre-format the attributes.
for _, a := range attrs {
h2.preformatted = h2.appendAttr(h2.preformatted, a, h2.indentLevel)
}
return &h2
}
func (h *IndentHandler) appendUnopenedGroups(buf []byte, indentLevel int) []byte {
for _, g := range h.unopenedGroups {
buf = fmt.Appendf(buf, "%*s%s:\n", indentLevel*4, "", g)
indentLevel++
}
return buf
}
//!-WithAttrs
// !+Handle
func (h *IndentHandler) Handle(ctx context.Context, r slog.Record) error {
buf := make([]byte, 0, 1024)
if !r.Time.IsZero() {
buf = h.appendAttr(buf, slog.Time(slog.TimeKey, r.Time), 0)
}
buf = h.appendAttr(buf, slog.Any(slog.LevelKey, r.Level), 0)
if r.PC != 0 {
fs := runtime.CallersFrames([]uintptr{r.PC})
f, _ := fs.Next()
buf = h.appendAttr(buf, slog.String(slog.SourceKey, fmt.Sprintf("%s:%d", f.File, f.Line)), 0)
}
buf = h.appendAttr(buf, slog.String(slog.MessageKey, r.Message), 0)
// Insert preformatted attributes just after built-in ones.
buf = append(buf, h.preformatted...)
if r.NumAttrs() > 0 {
buf = h.appendUnopenedGroups(buf, h.indentLevel)
r.Attrs(func(a slog.Attr) bool {
buf = h.appendAttr(buf, a, h.indentLevel+len(h.unopenedGroups))
return true
})
}
buf = append(buf, "---\n"...)
h.mu.Lock()
defer h.mu.Unlock()
_, err := h.out.Write(buf)
return err
}
//!-Handle
func (h *IndentHandler) appendAttr(buf []byte, a slog.Attr, indentLevel int) []byte {
// Resolve the Attr's value before doing anything else.
a.Value = a.Value.Resolve()
// Ignore empty Attrs.
if a.Equal(slog.Attr{}) {
return buf
}
// Indent 4 spaces per level.
buf = fmt.Appendf(buf, "%*s", indentLevel*4, "")
switch a.Value.Kind() {
case slog.KindString:
// Quote string values, to make them easy to parse.
buf = fmt.Appendf(buf, "%s: %q\n", a.Key, a.Value.String())
case slog.KindTime:
// Write times in a standard way, without the monotonic time.
buf = fmt.Appendf(buf, "%s: %s\n", a.Key, a.Value.Time().Format(time.RFC3339Nano))
case slog.KindGroup:
attrs := a.Value.Group()
// Ignore empty groups.
if len(attrs) == 0 {
return buf
}
// If the key is non-empty, write it out and indent the rest of the attrs.
// Otherwise, inline the attrs.
if a.Key != "" {
buf = fmt.Appendf(buf, "%s:\n", a.Key)
indentLevel++
}
for _, ga := range attrs {
buf = h.appendAttr(buf, ga, indentLevel)
}
default:
buf = fmt.Appendf(buf, "%s: %s\n", a.Key, a.Value)
}
return buf
}
| package indenthandler | ||||
function | flightctl/test | 24224776-8b2b-4009-9749-0ebfdc439b5e | New | ['"io"', '"log/slog"', '"sync"'] | ['IndentHandler', 'Options'] | github.com/flightctl/test//tmp/repos/example/slog-handler-guide/indenthandler3/indent_handler.go | func New(out io.Writer, opts *Options) *IndentHandler {
h := &IndentHandler{out: out, mu: &sync.Mutex{}}
if opts != nil {
h.opts = *opts
}
if h.opts.Level == nil {
h.opts.Level = slog.LevelInfo
}
return h
} | indenthandler | |||
function | flightctl/test | dffaaf6d-53bc-42b5-b5e0-5c746ff8819c | Enabled | ['"context"', '"log/slog"'] | ['IndentHandler'] | github.com/flightctl/test//tmp/repos/example/slog-handler-guide/indenthandler3/indent_handler.go | func (h *IndentHandler) Enabled(ctx context.Context, level slog.Level) bool {
return level >= h.opts.Level.Level()
} | indenthandler | |||
function | flightctl/test | 94c4c211-18f9-48ba-afd3-78af2cd0b468 | WithGroup | ['"log/slog"'] | ['IndentHandler'] | github.com/flightctl/test//tmp/repos/example/slog-handler-guide/indenthandler3/indent_handler.go | func (h *IndentHandler) WithGroup(name string) slog.Handler {
if name == "" {
return h
}
h2 := *h
// Add an unopened group to h2 without modifying h.
h2.unopenedGroups = make([]string, len(h.unopenedGroups)+1)
copy(h2.unopenedGroups, h.unopenedGroups)
h2.unopenedGroups[len(h2.unopenedGroups)-1] = name
return &h2
} | indenthandler | |||
function | flightctl/test | 07e4527c-8269-40b7-9a36-8ecb297df7a2 | WithAttrs | ['"log/slog"', '"slices"'] | ['IndentHandler'] | github.com/flightctl/test//tmp/repos/example/slog-handler-guide/indenthandler3/indent_handler.go | func (h *IndentHandler) WithAttrs(attrs []slog.Attr) slog.Handler {
if len(attrs) == 0 {
return h
}
h2 := *h
// Force an append to copy the underlying array.
pre := slices.Clip(h.preformatted)
// Add all groups from WithGroup that haven't already been added.
h2.preformatted = h2.appendUnopenedGroups(pre, h2.indentLevel)
// Each of those groups increased the indent level by 1.
h2.indentLevel += len(h2.unopenedGroups)
// Now all groups have been opened.
h2.unopenedGroups = nil
// Pre-format the attributes.
for _, a := range attrs {
h2.preformatted = h2.appendAttr(h2.preformatted, a, h2.indentLevel)
}
return &h2
} | indenthandler | |||
function | flightctl/test | 15e780a3-46d0-497b-bb7e-abb07bd2158c | appendUnopenedGroups | ['"fmt"'] | ['IndentHandler'] | github.com/flightctl/test//tmp/repos/example/slog-handler-guide/indenthandler3/indent_handler.go | func (h *IndentHandler) appendUnopenedGroups(buf []byte, indentLevel int) []byte {
for _, g := range h.unopenedGroups {
buf = fmt.Appendf(buf, "%*s%s:\n", indentLevel*4, "", g)
indentLevel++
}
return buf
} | indenthandler | |||
function | flightctl/test | 86ce2978-949a-4d93-855f-e257c600f84c | Handle | ['"context"', '"fmt"', '"log/slog"', '"runtime"'] | ['IndentHandler'] | github.com/flightctl/test//tmp/repos/example/slog-handler-guide/indenthandler3/indent_handler.go | func (h *IndentHandler) Handle(ctx context.Context, r slog.Record) error {
buf := make([]byte, 0, 1024)
if !r.Time.IsZero() {
buf = h.appendAttr(buf, slog.Time(slog.TimeKey, r.Time), 0)
}
buf = h.appendAttr(buf, slog.Any(slog.LevelKey, r.Level), 0)
if r.PC != 0 {
fs := runtime.CallersFrames([]uintptr{r.PC})
f, _ := fs.Next()
buf = h.appendAttr(buf, slog.String(slog.SourceKey, fmt.Sprintf("%s:%d", f.File, f.Line)), 0)
}
buf = h.appendAttr(buf, slog.String(slog.MessageKey, r.Message), 0)
// Insert preformatted attributes just after built-in ones.
buf = append(buf, h.preformatted...)
if r.NumAttrs() > 0 {
buf = h.appendUnopenedGroups(buf, h.indentLevel)
r.Attrs(func(a slog.Attr) bool {
buf = h.appendAttr(buf, a, h.indentLevel+len(h.unopenedGroups))
return true
})
}
buf = append(buf, "---\n"...)
h.mu.Lock()
defer h.mu.Unlock()
_, err := h.out.Write(buf)
return err
} | indenthandler | |||
function | flightctl/test | 5a552812-9423-41e2-9bb7-bb97b3d12a4c | appendAttr | ['"fmt"', '"log/slog"', '"time"'] | ['IndentHandler'] | github.com/flightctl/test//tmp/repos/example/slog-handler-guide/indenthandler3/indent_handler.go | func (h *IndentHandler) appendAttr(buf []byte, a slog.Attr, indentLevel int) []byte {
// Resolve the Attr's value before doing anything else.
a.Value = a.Value.Resolve()
// Ignore empty Attrs.
if a.Equal(slog.Attr{}) {
return buf
}
// Indent 4 spaces per level.
buf = fmt.Appendf(buf, "%*s", indentLevel*4, "")
switch a.Value.Kind() {
case slog.KindString:
// Quote string values, to make them easy to parse.
buf = fmt.Appendf(buf, "%s: %q\n", a.Key, a.Value.String())
case slog.KindTime:
// Write times in a standard way, without the monotonic time.
buf = fmt.Appendf(buf, "%s: %s\n", a.Key, a.Value.Time().Format(time.RFC3339Nano))
case slog.KindGroup:
attrs := a.Value.Group()
// Ignore empty groups.
if len(attrs) == 0 {
return buf
}
// If the key is non-empty, write it out and indent the rest of the attrs.
// Otherwise, inline the attrs.
if a.Key != "" {
buf = fmt.Appendf(buf, "%s:\n", a.Key)
indentLevel++
}
for _, ga := range attrs {
buf = h.appendAttr(buf, ga, indentLevel)
}
default:
buf = fmt.Appendf(buf, "%s: %s\n", a.Key, a.Value)
}
return buf
} | indenthandler | |||
file | flightctl/test | 031d1fe3-1d6b-4b69-a68e-da3262937f21 | indent_handler_test.go | import (
"bytes"
"log/slog"
"reflect"
"regexp"
"testing"
"testing/slogtest"
"gopkg.in/yaml.v3"
) | github.com/flightctl/test//tmp/repos/example/slog-handler-guide/indenthandler3/indent_handler_test.go | //go:build go1.21
package indenthandler
import (
"bytes"
"log/slog"
"reflect"
"regexp"
"testing"
"testing/slogtest"
"gopkg.in/yaml.v3"
)
// !+TestSlogtest
func TestSlogtest(t *testing.T) {
var buf bytes.Buffer
err := slogtest.TestHandler(New(&buf, nil), func() []map[string]any {
return parseLogEntries(t, buf.Bytes())
})
if err != nil {
t.Error(err)
}
}
// !-TestSlogtest
func Test(t *testing.T) {
var buf bytes.Buffer
l := slog.New(New(&buf, nil))
l.Info("hello", "a", 1, "b", true, "c", 3.14, slog.Group("g", "h", 1, "i", 2), "d", "NO")
got := buf.String()
wantre := `time: [-0-9T:.]+Z?
level: INFO
source: ".*/indent_handler_test.go:\d+"
msg: "hello"
a: 1
b: true
c: 3.14
g:
h: 1
i: 2
d: "NO"
`
re := regexp.MustCompile(wantre)
if !re.MatchString(got) {
t.Errorf("\ngot:\n%q\nwant:\n%q", got, wantre)
}
buf.Reset()
l.Debug("test")
if got := buf.Len(); got != 0 {
t.Errorf("got buf.Len() = %d, want 0", got)
}
}
// !+parseLogEntries
func parseLogEntries(t *testing.T, data []byte) []map[string]any {
entries := bytes.Split(data, []byte("---\n"))
entries = entries[:len(entries)-1] // last one is empty
var ms []map[string]any
for _, e := range entries {
var m map[string]any
if err := yaml.Unmarshal([]byte(e), &m); err != nil {
t.Fatal(err)
}
ms = append(ms, m)
}
return ms
}
// !-parseLogEntries
func TestParseLogEntries(t *testing.T) {
in := `
a: 1
b: 2
c: 3
g:
h: 4
i: five
d: 6
---
e: 7
---
`
want := []map[string]any{
{
"a": 1,
"b": 2,
"c": 3,
"g": map[string]any{
"h": 4,
"i": "five",
},
"d": 6,
},
{
"e": 7,
},
}
got := parseLogEntries(t, []byte(in[1:]))
if !reflect.DeepEqual(got, want) {
t.Errorf("\ngot:\n%v\nwant:\n%v", got, want)
}
}
| package indenthandler | ||||
function | flightctl/test | f88b8c83-1810-4a42-b7e8-eb18426abcee | TestSlogtest | ['"bytes"', '"testing"', '"testing/slogtest"'] | github.com/flightctl/test//tmp/repos/example/slog-handler-guide/indenthandler3/indent_handler_test.go | func TestSlogtest(t *testing.T) {
var buf bytes.Buffer
err := slogtest.TestHandler(New(&buf, nil), func() []map[string]any {
return parseLogEntries(t, buf.Bytes())
})
if err != nil {
t.Error(err)
}
} | indenthandler | ||||
function | flightctl/test | c03b603f-20d2-44df-83a7-f22676f14c52 | Test | ['"bytes"', '"log/slog"', '"regexp"', '"testing"'] | github.com/flightctl/test//tmp/repos/example/slog-handler-guide/indenthandler3/indent_handler_test.go | func Test(t *testing.T) {
var buf bytes.Buffer
l := slog.New(New(&buf, nil))
l.Info("hello", "a", 1, "b", true, "c", 3.14, slog.Group("g", "h", 1, "i", 2), "d", "NO")
got := buf.String()
wantre := `time: [-0-9T:.]+Z?
level: INFO
source: ".*/indent_handler_test.go:\d+"
msg: "hello"
a: 1
b: true
c: 3.14
g:
h: 1
i: 2
d: "NO"
`
re := regexp.MustCompile(wantre)
if !re.MatchString(got) {
t.Errorf("\ngot:\n%q\nwant:\n%q", got, wantre)
}
buf.Reset()
l.Debug("test")
if got := buf.Len(); got != 0 {
t.Errorf("got buf.Len() = %d, want 0", got)
}
} | indenthandler | ||||
function | flightctl/test | 8cf9961e-6c86-40ed-8ef1-31aec8cbc88c | parseLogEntries | ['"bytes"', '"testing"'] | github.com/flightctl/test//tmp/repos/example/slog-handler-guide/indenthandler3/indent_handler_test.go | func parseLogEntries(t *testing.T, data []byte) []map[string]any {
entries := bytes.Split(data, []byte("---\n"))
entries = entries[:len(entries)-1] // last one is empty
var ms []map[string]any
for _, e := range entries {
var m map[string]any
if err := yaml.Unmarshal([]byte(e), &m); err != nil {
t.Fatal(err)
}
ms = append(ms, m)
}
return ms
} | indenthandler | ||||
function | flightctl/test | 29c0897f-e17f-46ff-869a-d8d360956754 | TestParseLogEntries | ['"reflect"', '"testing"'] | github.com/flightctl/test//tmp/repos/example/slog-handler-guide/indenthandler3/indent_handler_test.go | func TestParseLogEntries(t *testing.T) {
in := `
a: 1
b: 2
c: 3
g:
h: 4
i: five
d: 6
---
e: 7
---
`
want := []map[string]any{
{
"a": 1,
"b": 2,
"c": 3,
"g": map[string]any{
"h": 4,
"i": "five",
},
"d": 6,
},
{
"e": 7,
},
}
got := parseLogEntries(t, []byte(in[1:]))
if !reflect.DeepEqual(got, want) {
t.Errorf("\ngot:\n%v\nwant:\n%v", got, want)
}
} | indenthandler | ||||
file | flightctl/test | 6fc0c7c4-e4e8-4c20-90ee-ab9f67a4377a | indent_handler.go | import (
"context"
"fmt"
"io"
"log/slog"
"runtime"
"slices"
"strconv"
"sync"
"time"
) | github.com/flightctl/test//tmp/repos/example/slog-handler-guide/indenthandler4/indent_handler.go | //go:build go1.21
package indenthandler
import (
"context"
"fmt"
"io"
"log/slog"
"runtime"
"slices"
"strconv"
"sync"
"time"
)
// !+IndentHandler
type IndentHandler struct {
opts Options
preformatted []byte // data from WithGroup and WithAttrs
unopenedGroups []string // groups from WithGroup that haven't been opened
indentLevel int // same as number of opened groups so far
mu *sync.Mutex
out io.Writer
}
//!-IndentHandler
type Options struct {
// Level reports the minimum level to log.
// Levels with lower levels are discarded.
// If nil, the Handler uses [slog.LevelInfo].
Level slog.Leveler
}
func New(out io.Writer, opts *Options) *IndentHandler {
h := &IndentHandler{out: out, mu: &sync.Mutex{}}
if opts != nil {
h.opts = *opts
}
if h.opts.Level == nil {
h.opts.Level = slog.LevelInfo
}
return h
}
func (h *IndentHandler) Enabled(ctx context.Context, level slog.Level) bool {
return level >= h.opts.Level.Level()
}
// !+WithGroup
func (h *IndentHandler) WithGroup(name string) slog.Handler {
if name == "" {
return h
}
h2 := *h
// Add an unopened group to h2 without modifying h.
h2.unopenedGroups = make([]string, len(h.unopenedGroups)+1)
copy(h2.unopenedGroups, h.unopenedGroups)
h2.unopenedGroups[len(h2.unopenedGroups)-1] = name
return &h2
}
//!-WithGroup
// !+WithAttrs
func (h *IndentHandler) WithAttrs(attrs []slog.Attr) slog.Handler {
if len(attrs) == 0 {
return h
}
h2 := *h
// Force an append to copy the underlying array.
pre := slices.Clip(h.preformatted)
// Add all groups from WithGroup that haven't already been added.
h2.preformatted = h2.appendUnopenedGroups(pre, h2.indentLevel)
// Each of those groups increased the indent level by 1.
h2.indentLevel += len(h2.unopenedGroups)
// Now all groups have been opened.
h2.unopenedGroups = nil
// Pre-format the attributes.
for _, a := range attrs {
h2.preformatted = h2.appendAttr(h2.preformatted, a, h2.indentLevel)
}
return &h2
}
func (h *IndentHandler) appendUnopenedGroups(buf []byte, indentLevel int) []byte {
for _, g := range h.unopenedGroups {
buf = fmt.Appendf(buf, "%*s%s:\n", indentLevel*4, "", g)
indentLevel++
}
return buf
}
//!-WithAttrs
// !+Handle
func (h *IndentHandler) Handle(ctx context.Context, r slog.Record) error {
bufp := allocBuf()
buf := *bufp
defer func() {
*bufp = buf
freeBuf(bufp)
}()
if !r.Time.IsZero() {
buf = h.appendAttr(buf, slog.Time(slog.TimeKey, r.Time), 0)
}
buf = h.appendAttr(buf, slog.Any(slog.LevelKey, r.Level), 0)
if r.PC != 0 {
fs := runtime.CallersFrames([]uintptr{r.PC})
f, _ := fs.Next()
// Optimize to minimize allocation.
srcbufp := allocBuf()
defer freeBuf(srcbufp)
*srcbufp = append(*srcbufp, f.File...)
*srcbufp = append(*srcbufp, ':')
*srcbufp = strconv.AppendInt(*srcbufp, int64(f.Line), 10)
buf = h.appendAttr(buf, slog.String(slog.SourceKey, string(*srcbufp)), 0)
}
buf = h.appendAttr(buf, slog.String(slog.MessageKey, r.Message), 0)
// Insert preformatted attributes just after built-in ones.
buf = append(buf, h.preformatted...)
if r.NumAttrs() > 0 {
buf = h.appendUnopenedGroups(buf, h.indentLevel)
r.Attrs(func(a slog.Attr) bool {
buf = h.appendAttr(buf, a, h.indentLevel+len(h.unopenedGroups))
return true
})
}
buf = append(buf, "---\n"...)
h.mu.Lock()
defer h.mu.Unlock()
_, err := h.out.Write(buf)
return err
}
//!-Handle
func (h *IndentHandler) appendAttr(buf []byte, a slog.Attr, indentLevel int) []byte {
// Resolve the Attr's value before doing anything else.
a.Value = a.Value.Resolve()
// Ignore empty Attrs.
if a.Equal(slog.Attr{}) {
return buf
}
// Indent 4 spaces per level.
buf = fmt.Appendf(buf, "%*s", indentLevel*4, "")
switch a.Value.Kind() {
case slog.KindString:
// Quote string values, to make them easy to parse.
buf = append(buf, a.Key...)
buf = append(buf, ": "...)
buf = strconv.AppendQuote(buf, a.Value.String())
buf = append(buf, '\n')
case slog.KindTime:
// Write times in a standard way, without the monotonic time.
buf = append(buf, a.Key...)
buf = append(buf, ": "...)
buf = a.Value.Time().AppendFormat(buf, time.RFC3339Nano)
buf = append(buf, '\n')
case slog.KindGroup:
attrs := a.Value.Group()
// Ignore empty groups.
if len(attrs) == 0 {
return buf
}
// If the key is non-empty, write it out and indent the rest of the attrs.
// Otherwise, inline the attrs.
if a.Key != "" {
buf = fmt.Appendf(buf, "%s:\n", a.Key)
indentLevel++
}
for _, ga := range attrs {
buf = h.appendAttr(buf, ga, indentLevel)
}
default:
buf = append(buf, a.Key...)
buf = append(buf, ": "...)
buf = append(buf, a.Value.String()...)
buf = append(buf, '\n')
}
return buf
}
// !+pool
var bufPool = sync.Pool{
New: func() any {
b := make([]byte, 0, 1024)
return &b
},
}
func allocBuf() *[]byte {
return bufPool.Get().(*[]byte)
}
func freeBuf(b *[]byte) {
// To reduce peak allocation, return only smaller buffers to the pool.
const maxBufferSize = 16 << 10
if cap(*b) <= maxBufferSize {
*b = (*b)[:0]
bufPool.Put(b)
}
}
//!-pool
| package indenthandler | ||||
function | flightctl/test | 2f9270ba-2d0a-4a2f-980f-e6c7fc2c6371 | New | ['"io"', '"log/slog"', '"sync"'] | ['IndentHandler', 'Options'] | github.com/flightctl/test//tmp/repos/example/slog-handler-guide/indenthandler4/indent_handler.go | func New(out io.Writer, opts *Options) *IndentHandler {
h := &IndentHandler{out: out, mu: &sync.Mutex{}}
if opts != nil {
h.opts = *opts
}
if h.opts.Level == nil {
h.opts.Level = slog.LevelInfo
}
return h
} | indenthandler | |||
function | flightctl/test | 7572ff64-3933-4f35-a8b7-49321a09226f | Enabled | ['"context"', '"log/slog"'] | ['IndentHandler'] | github.com/flightctl/test//tmp/repos/example/slog-handler-guide/indenthandler4/indent_handler.go | func (h *IndentHandler) Enabled(ctx context.Context, level slog.Level) bool {
return level >= h.opts.Level.Level()
} | indenthandler | |||
function | flightctl/test | 47f34e42-8a41-4338-9b22-4badb3395f18 | WithGroup | ['"log/slog"'] | ['IndentHandler'] | github.com/flightctl/test//tmp/repos/example/slog-handler-guide/indenthandler4/indent_handler.go | func (h *IndentHandler) WithGroup(name string) slog.Handler {
if name == "" {
return h
}
h2 := *h
// Add an unopened group to h2 without modifying h.
h2.unopenedGroups = make([]string, len(h.unopenedGroups)+1)
copy(h2.unopenedGroups, h.unopenedGroups)
h2.unopenedGroups[len(h2.unopenedGroups)-1] = name
return &h2
} | indenthandler | |||
function | flightctl/test | e4dda0b3-f1f0-489c-a70e-a9c61728e064 | WithAttrs | ['"log/slog"', '"slices"'] | ['IndentHandler'] | github.com/flightctl/test//tmp/repos/example/slog-handler-guide/indenthandler4/indent_handler.go | func (h *IndentHandler) WithAttrs(attrs []slog.Attr) slog.Handler {
if len(attrs) == 0 {
return h
}
h2 := *h
// Force an append to copy the underlying array.
pre := slices.Clip(h.preformatted)
// Add all groups from WithGroup that haven't already been added.
h2.preformatted = h2.appendUnopenedGroups(pre, h2.indentLevel)
// Each of those groups increased the indent level by 1.
h2.indentLevel += len(h2.unopenedGroups)
// Now all groups have been opened.
h2.unopenedGroups = nil
// Pre-format the attributes.
for _, a := range attrs {
h2.preformatted = h2.appendAttr(h2.preformatted, a, h2.indentLevel)
}
return &h2
} | indenthandler | |||
function | flightctl/test | a2a8326d-4000-4e4f-81a7-69486a35e311 | appendUnopenedGroups | ['"fmt"'] | ['IndentHandler'] | github.com/flightctl/test//tmp/repos/example/slog-handler-guide/indenthandler4/indent_handler.go | func (h *IndentHandler) appendUnopenedGroups(buf []byte, indentLevel int) []byte {
for _, g := range h.unopenedGroups {
buf = fmt.Appendf(buf, "%*s%s:\n", indentLevel*4, "", g)
indentLevel++
}
return buf
} | indenthandler | |||
function | flightctl/test | 71bfcca1-c11a-40b5-9d9a-1782643fd7bb | Handle | ['"context"', '"log/slog"', '"runtime"', '"strconv"'] | ['IndentHandler'] | github.com/flightctl/test//tmp/repos/example/slog-handler-guide/indenthandler4/indent_handler.go | func (h *IndentHandler) Handle(ctx context.Context, r slog.Record) error {
bufp := allocBuf()
buf := *bufp
defer func() {
*bufp = buf
freeBuf(bufp)
}()
if !r.Time.IsZero() {
buf = h.appendAttr(buf, slog.Time(slog.TimeKey, r.Time), 0)
}
buf = h.appendAttr(buf, slog.Any(slog.LevelKey, r.Level), 0)
if r.PC != 0 {
fs := runtime.CallersFrames([]uintptr{r.PC})
f, _ := fs.Next()
// Optimize to minimize allocation.
srcbufp := allocBuf()
defer freeBuf(srcbufp)
*srcbufp = append(*srcbufp, f.File...)
*srcbufp = append(*srcbufp, ':')
*srcbufp = strconv.AppendInt(*srcbufp, int64(f.Line), 10)
buf = h.appendAttr(buf, slog.String(slog.SourceKey, string(*srcbufp)), 0)
}
buf = h.appendAttr(buf, slog.String(slog.MessageKey, r.Message), 0)
// Insert preformatted attributes just after built-in ones.
buf = append(buf, h.preformatted...)
if r.NumAttrs() > 0 {
buf = h.appendUnopenedGroups(buf, h.indentLevel)
r.Attrs(func(a slog.Attr) bool {
buf = h.appendAttr(buf, a, h.indentLevel+len(h.unopenedGroups))
return true
})
}
buf = append(buf, "---\n"...)
h.mu.Lock()
defer h.mu.Unlock()
_, err := h.out.Write(buf)
return err
} | indenthandler | |||
function | flightctl/test | 529ce141-6770-4717-a299-4318eada3fe3 | appendAttr | ['"fmt"', '"log/slog"', '"strconv"', '"time"'] | ['IndentHandler'] | github.com/flightctl/test//tmp/repos/example/slog-handler-guide/indenthandler4/indent_handler.go | func (h *IndentHandler) appendAttr(buf []byte, a slog.Attr, indentLevel int) []byte {
// Resolve the Attr's value before doing anything else.
a.Value = a.Value.Resolve()
// Ignore empty Attrs.
if a.Equal(slog.Attr{}) {
return buf
}
// Indent 4 spaces per level.
buf = fmt.Appendf(buf, "%*s", indentLevel*4, "")
switch a.Value.Kind() {
case slog.KindString:
// Quote string values, to make them easy to parse.
buf = append(buf, a.Key...)
buf = append(buf, ": "...)
buf = strconv.AppendQuote(buf, a.Value.String())
buf = append(buf, '\n')
case slog.KindTime:
// Write times in a standard way, without the monotonic time.
buf = append(buf, a.Key...)
buf = append(buf, ": "...)
buf = a.Value.Time().AppendFormat(buf, time.RFC3339Nano)
buf = append(buf, '\n')
case slog.KindGroup:
attrs := a.Value.Group()
// Ignore empty groups.
if len(attrs) == 0 {
return buf
}
// If the key is non-empty, write it out and indent the rest of the attrs.
// Otherwise, inline the attrs.
if a.Key != "" {
buf = fmt.Appendf(buf, "%s:\n", a.Key)
indentLevel++
}
for _, ga := range attrs {
buf = h.appendAttr(buf, ga, indentLevel)
}
default:
buf = append(buf, a.Key...)
buf = append(buf, ": "...)
buf = append(buf, a.Value.String()...)
buf = append(buf, '\n')
}
return buf
} | indenthandler | |||
function | flightctl/test | c65d5564-0038-4420-98e2-c060d2e22a88 | allocBuf | github.com/flightctl/test//tmp/repos/example/slog-handler-guide/indenthandler4/indent_handler.go | func allocBuf() *[]byte {
return bufPool.Get().(*[]byte)
} | indenthandler | |||||
function | flightctl/test | 8bbee994-9664-43a2-a13c-5483b7f955a4 | freeBuf | github.com/flightctl/test//tmp/repos/example/slog-handler-guide/indenthandler4/indent_handler.go | func freeBuf(b *[]byte) {
// To reduce peak allocation, return only smaller buffers to the pool.
const maxBufferSize = 16 << 10
if cap(*b) <= maxBufferSize {
*b = (*b)[:0]
bufPool.Put(b)
}
} | indenthandler | |||||
file | flightctl/test | 24308f3a-724f-4667-8abf-8a25fdef83ae | indent_handler_norace_test.go | import (
"fmt"
"io"
"log/slog"
"strconv"
"testing"
) | github.com/flightctl/test//tmp/repos/example/slog-handler-guide/indenthandler4/indent_handler_norace_test.go | //go:build go1.21 && !race
package indenthandler
import (
"fmt"
"io"
"log/slog"
"strconv"
"testing"
)
func TestAlloc(t *testing.T) {
a := slog.String("key", "value")
t.Run("Appendf", func(t *testing.T) {
buf := make([]byte, 0, 100)
g := testing.AllocsPerRun(2, func() {
buf = fmt.Appendf(buf, "%s: %q\n", a.Key, a.Value.String())
})
if g, w := int(g), 2; g != w {
t.Errorf("got %d, want %d", g, w)
}
})
t.Run("appends", func(t *testing.T) {
buf := make([]byte, 0, 100)
g := testing.AllocsPerRun(2, func() {
buf = append(buf, a.Key...)
buf = append(buf, ": "...)
buf = strconv.AppendQuote(buf, a.Value.String())
buf = append(buf, '\n')
})
if g, w := int(g), 0; g != w {
t.Errorf("got %d, want %d", g, w)
}
})
t.Run("Handle", func(t *testing.T) {
l := slog.New(New(io.Discard, nil))
got := testing.AllocsPerRun(10, func() {
l.LogAttrs(nil, slog.LevelInfo, "hello", slog.String("a", "1"))
})
if g, w := int(got), 6; g > w {
t.Errorf("got %d, want at most %d", g, w)
}
})
}
| package indenthandler | ||||
function | flightctl/test | 9f774cd9-963a-4a5d-9976-350955f79b99 | TestAlloc | ['"fmt"', '"io"', '"log/slog"', '"strconv"', '"testing"'] | github.com/flightctl/test//tmp/repos/example/slog-handler-guide/indenthandler4/indent_handler_norace_test.go | func TestAlloc(t *testing.T) {
a := slog.String("key", "value")
t.Run("Appendf", func(t *testing.T) {
buf := make([]byte, 0, 100)
g := testing.AllocsPerRun(2, func() {
buf = fmt.Appendf(buf, "%s: %q\n", a.Key, a.Value.String())
})
if g, w := int(g), 2; g != w {
t.Errorf("got %d, want %d", g, w)
}
})
t.Run("appends", func(t *testing.T) {
buf := make([]byte, 0, 100)
g := testing.AllocsPerRun(2, func() {
buf = append(buf, a.Key...)
buf = append(buf, ": "...)
buf = strconv.AppendQuote(buf, a.Value.String())
buf = append(buf, '\n')
})
if g, w := int(g), 0; g != w {
t.Errorf("got %d, want %d", g, w)
}
})
t.Run("Handle", func(t *testing.T) {
l := slog.New(New(io.Discard, nil))
got := testing.AllocsPerRun(10, func() {
l.LogAttrs(nil, slog.LevelInfo, "hello", slog.String("a", "1"))
})
if g, w := int(got), 6; g > w {
t.Errorf("got %d, want at most %d", g, w)
}
})
} | indenthandler | ||||
file | flightctl/test | 21acff8a-d8cb-4d14-90d0-27ffe11d1ed0 | indent_handler_test.go | import (
"bytes"
"log/slog"
"reflect"
"regexp"
"testing"
"testing/slogtest"
"gopkg.in/yaml.v3"
) | github.com/flightctl/test//tmp/repos/example/slog-handler-guide/indenthandler4/indent_handler_test.go | //go:build go1.21
package indenthandler
import (
"bytes"
"log/slog"
"reflect"
"regexp"
"testing"
"testing/slogtest"
"gopkg.in/yaml.v3"
)
// !+TestSlogtest
func TestSlogtest(t *testing.T) {
var buf bytes.Buffer
err := slogtest.TestHandler(New(&buf, nil), func() []map[string]any {
return parseLogEntries(t, buf.Bytes())
})
if err != nil {
t.Error(err)
}
}
// !-TestSlogtest
func Test(t *testing.T) {
var buf bytes.Buffer
l := slog.New(New(&buf, nil))
l.Info("hello", "a", 1, "b", true, "c", 3.14, slog.Group("g", "h", 1, "i", 2), "d", "NO")
got := buf.String()
wantre := `time: [-0-9T:.]+Z?
level: INFO
source: ".*/indent_handler_test.go:\d+"
msg: "hello"
a: 1
b: true
c: 3.14
g:
h: 1
i: 2
d: "NO"
`
re := regexp.MustCompile(wantre)
if !re.MatchString(got) {
t.Errorf("\ngot:\n%q\nwant:\n%q", got, wantre)
}
buf.Reset()
l.Debug("test")
if got := buf.Len(); got != 0 {
t.Errorf("got buf.Len() = %d, want 0", got)
}
}
// !+parseLogEntries
func parseLogEntries(t *testing.T, data []byte) []map[string]any {
entries := bytes.Split(data, []byte("---\n"))
entries = entries[:len(entries)-1] // last one is empty
var ms []map[string]any
for _, e := range entries {
var m map[string]any
if err := yaml.Unmarshal([]byte(e), &m); err != nil {
t.Fatal(err)
}
ms = append(ms, m)
}
return ms
}
// !-parseLogEntries
func TestParseLogEntries(t *testing.T) {
in := `
a: 1
b: 2
c: 3
g:
h: 4
i: five
d: 6
---
e: 7
---
`
want := []map[string]any{
{
"a": 1,
"b": 2,
"c": 3,
"g": map[string]any{
"h": 4,
"i": "five",
},
"d": 6,
},
{
"e": 7,
},
}
got := parseLogEntries(t, []byte(in[1:]))
if !reflect.DeepEqual(got, want) {
t.Errorf("\ngot:\n%v\nwant:\n%v", got, want)
}
}
| package indenthandler | ||||
function | flightctl/test | 1d11f5af-cbba-4a5a-b78d-7a9ed58cabf3 | TestSlogtest | ['"bytes"', '"testing"', '"testing/slogtest"'] | github.com/flightctl/test//tmp/repos/example/slog-handler-guide/indenthandler4/indent_handler_test.go | func TestSlogtest(t *testing.T) {
var buf bytes.Buffer
err := slogtest.TestHandler(New(&buf, nil), func() []map[string]any {
return parseLogEntries(t, buf.Bytes())
})
if err != nil {
t.Error(err)
}
} | indenthandler | ||||
function | flightctl/test | 47c618b9-81c5-44c8-ad4b-dd59c7d13d97 | Test | ['"bytes"', '"log/slog"', '"regexp"', '"testing"'] | github.com/flightctl/test//tmp/repos/example/slog-handler-guide/indenthandler4/indent_handler_test.go | func Test(t *testing.T) {
var buf bytes.Buffer
l := slog.New(New(&buf, nil))
l.Info("hello", "a", 1, "b", true, "c", 3.14, slog.Group("g", "h", 1, "i", 2), "d", "NO")
got := buf.String()
wantre := `time: [-0-9T:.]+Z?
level: INFO
source: ".*/indent_handler_test.go:\d+"
msg: "hello"
a: 1
b: true
c: 3.14
g:
h: 1
i: 2
d: "NO"
`
re := regexp.MustCompile(wantre)
if !re.MatchString(got) {
t.Errorf("\ngot:\n%q\nwant:\n%q", got, wantre)
}
buf.Reset()
l.Debug("test")
if got := buf.Len(); got != 0 {
t.Errorf("got buf.Len() = %d, want 0", got)
}
} | indenthandler | ||||
function | flightctl/test | 2ae68f94-8c93-40d9-b8f8-04d1c48488aa | parseLogEntries | ['"bytes"', '"testing"'] | github.com/flightctl/test//tmp/repos/example/slog-handler-guide/indenthandler4/indent_handler_test.go | func parseLogEntries(t *testing.T, data []byte) []map[string]any {
entries := bytes.Split(data, []byte("---\n"))
entries = entries[:len(entries)-1] // last one is empty
var ms []map[string]any
for _, e := range entries {
var m map[string]any
if err := yaml.Unmarshal([]byte(e), &m); err != nil {
t.Fatal(err)
}
ms = append(ms, m)
}
return ms
} | indenthandler | ||||
function | flightctl/test | 3eaebe58-82bf-425b-afaa-ff7c16655758 | TestParseLogEntries | ['"reflect"', '"testing"'] | github.com/flightctl/test//tmp/repos/example/slog-handler-guide/indenthandler4/indent_handler_test.go | func TestParseLogEntries(t *testing.T) {
in := `
a: 1
b: 2
c: 3
g:
h: 4
i: five
d: 6
---
e: 7
---
`
want := []map[string]any{
{
"a": 1,
"b": 2,
"c": 3,
"g": map[string]any{
"h": 4,
"i": "five",
},
"d": 6,
},
{
"e": 7,
},
}
got := parseLogEntries(t, []byte(in[1:]))
if !reflect.DeepEqual(got, want) {
t.Errorf("\ngot:\n%v\nwant:\n%v", got, want)
}
} | indenthandler | ||||
file | flightctl/test | e1c750f5-74bf-4e40-a822-f78770333573 | main.go | import (
"html/template"
"log"
"net/http"
"strings"
) | github.com/flightctl/test//tmp/repos/example/template/main.go | // Copyright 2023 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Template is a trivial web server that uses the text/template (and
// html/template) package's "block" feature to implement a kind of template
// inheritance.
//
// It should be executed from the directory in which the source resides,
// as it will look for its template files in the current directory.
package main
import (
"html/template"
"log"
"net/http"
"strings"
)
func main() {
http.HandleFunc("/", indexHandler)
http.HandleFunc("/image/", imageHandler)
log.Fatal(http.ListenAndServe("localhost:8080", nil))
}
// indexTemplate is the main site template.
// The default template includes two template blocks ("sidebar" and "content")
// that may be replaced in templates derived from this one.
var indexTemplate = template.Must(template.ParseFiles("index.tmpl"))
// Index is a data structure used to populate an indexTemplate.
type Index struct {
Title string
Body string
Links []Link
}
type Link struct {
URL, Title string
}
// indexHandler is an HTTP handler that serves the index page.
func indexHandler(w http.ResponseWriter, r *http.Request) {
data := &Index{
Title: "Image gallery",
Body: "Welcome to the image gallery.",
}
for name, img := range images {
data.Links = append(data.Links, Link{
URL: "/image/" + name,
Title: img.Title,
})
}
if err := indexTemplate.Execute(w, data); err != nil {
log.Println(err)
}
}
// imageTemplate is a clone of indexTemplate that provides
// alternate "sidebar" and "content" templates.
var imageTemplate = template.Must(template.Must(indexTemplate.Clone()).ParseFiles("image.tmpl"))
// Image is a data structure used to populate an imageTemplate.
type Image struct {
Title string
URL string
}
// imageHandler is an HTTP handler that serves the image pages.
func imageHandler(w http.ResponseWriter, r *http.Request) {
data, ok := images[strings.TrimPrefix(r.URL.Path, "/image/")]
if !ok {
http.NotFound(w, r)
return
}
if err := imageTemplate.Execute(w, data); err != nil {
log.Println(err)
}
}
// images specifies the site content: a collection of images.
var images = map[string]*Image{
"go": {"The Go Gopher", "https://golang.org/doc/gopher/frontpage.png"},
"google": {"The Google Logo", "https://www.google.com/images/branding/googlelogo/1x/googlelogo_color_272x92dp.png"},
}
| package main | ||||
function | flightctl/test | 014dc93a-f4d8-4693-b765-15f3bc99d205 | main | ['"log"', '"net/http"'] | github.com/flightctl/test//tmp/repos/example/template/main.go | func main() {
http.HandleFunc("/", indexHandler)
http.HandleFunc("/image/", imageHandler)
log.Fatal(http.ListenAndServe("localhost:8080", nil))
} | main | ||||
function | flightctl/test | 3e7a8ee4-6dc0-4123-928a-007fe559b9f4 | indexHandler | ['"log"', '"net/http"'] | ['Index', 'Link', 'Image'] | github.com/flightctl/test//tmp/repos/example/template/main.go | func indexHandler(w http.ResponseWriter, r *http.Request) {
data := &Index{
Title: "Image gallery",
Body: "Welcome to the image gallery.",
}
for name, img := range images {
data.Links = append(data.Links, Link{
URL: "/image/" + name,
Title: img.Title,
})
}
if err := indexTemplate.Execute(w, data); err != nil {
log.Println(err)
}
} | main | |||
function | flightctl/test | e21b506a-3229-4db4-97ac-0610f374025c | imageHandler | ['"log"', '"net/http"', '"strings"'] | github.com/flightctl/test//tmp/repos/example/template/main.go | func imageHandler(w http.ResponseWriter, r *http.Request) {
data, ok := images[strings.TrimPrefix(r.URL.Path, "/image/")]
if !ok {
http.NotFound(w, r)
return
}
if err := imageTemplate.Execute(w, data); err != nil {
log.Println(err)
}
} | main | ||||
file | final HF test | deccf4d6-b3f8-439d-98fe-cdc848b6d554 | app.go | import (
"fmt"
"net/http"
) | github.com/final HF test//tmp/repos/example/appengine-hello/app.go | // Copyright 2023 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Package hello is a simple App Engine application that replies to requests
// on /hello with a welcoming message.
package hello
import (
"fmt"
"net/http"
)
// init is run before the application starts serving.
func init() {
// Handle all requests with path /hello with the helloHandler function.
http.HandleFunc("/hello", helloHandler)
}
func helloHandler(w http.ResponseWriter, r *http.Request) {
fmt.Fprintln(w, "Hello from the Go app")
}
| package hello | ||||
function | final HF test | 9ef1ff46-e52e-414c-9ce0-3d9fe9091c2e | init | ['"net/http"'] | github.com/final HF test//tmp/repos/example/appengine-hello/app.go | func init() {
// Handle all requests with path /hello with the helloHandler function.
http.HandleFunc("/hello", helloHandler)
} | hello | ||||
function | final HF test | 393f78d9-be3e-4df9-9953-62ba9ab33238 | helloHandler | ['"fmt"', '"net/http"'] | github.com/final HF test//tmp/repos/example/appengine-hello/app.go | func helloHandler(w http.ResponseWriter, r *http.Request) {
fmt.Fprintln(w, "Hello from the Go app")
} | hello | ||||
file | final HF test | 5b5dcecc-c913-4e3a-a987-61d4e3be723a | main.go | import (
"fmt"
"go/ast"
"go/importer"
"go/parser"
"go/token"
"go/types"
"log"
) | github.com/final HF test//tmp/repos/example/gotypes/defsuses/main.go | package main
import (
"fmt"
"go/ast"
"go/importer"
"go/parser"
"go/token"
"go/types"
"log"
)
const hello = `package main
import "fmt"
func main() {
fmt.Println("Hello, world")
}
`
// !+
func PrintDefsUses(fset *token.FileSet, files ...*ast.File) error {
conf := types.Config{Importer: importer.Default()}
info := &types.Info{
Defs: make(map[*ast.Ident]types.Object),
Uses: make(map[*ast.Ident]types.Object),
}
_, err := conf.Check("hello", fset, files, info)
if err != nil {
return err // type error
}
for id, obj := range info.Defs {
fmt.Printf("%s: %q defines %v\n",
fset.Position(id.Pos()), id.Name, obj)
}
for id, obj := range info.Uses {
fmt.Printf("%s: %q uses %v\n",
fset.Position(id.Pos()), id.Name, obj)
}
return nil
}
//!-
func main() {
// Parse one file.
fset := token.NewFileSet()
f, err := parser.ParseFile(fset, "hello.go", hello, 0)
if err != nil {
log.Fatal(err) // parse error
}
if err := PrintDefsUses(fset, f); err != nil {
log.Fatal(err) // type error
}
}
/*
//!+output
$ go build golang.org/x/example/gotypes/defsuses
$ ./defsuses
hello.go:1:9: "main" defines <nil>
hello.go:5:6: "main" defines func hello.main()
hello.go:6:9: "fmt" uses package fmt
hello.go:6:13: "Println" uses func fmt.Println(a ...interface{}) (n int, err error)
//!-output
*/
| package main | ||||
function | final HF test | 45de9330-d5d0-4ee0-a917-d0ef4b4b7cd5 | PrintDefsUses | ['"fmt"', '"go/ast"', '"go/importer"', '"go/token"', '"go/types"'] | github.com/final HF test//tmp/repos/example/gotypes/defsuses/main.go | func PrintDefsUses(fset *token.FileSet, files ...*ast.File) error {
conf := types.Config{Importer: importer.Default()}
info := &types.Info{
Defs: make(map[*ast.Ident]types.Object),
Uses: make(map[*ast.Ident]types.Object),
}
_, err := conf.Check("hello", fset, files, info)
if err != nil {
return err // type error
}
for id, obj := range info.Defs {
fmt.Printf("%s: %q defines %v\n",
fset.Position(id.Pos()), id.Name, obj)
}
for id, obj := range info.Uses {
fmt.Printf("%s: %q uses %v\n",
fset.Position(id.Pos()), id.Name, obj)
}
return nil
} | main | ||||
function | final HF test | 7e017b1d-9f04-422d-a54b-5ec28b77ae6d | main | ['"go/parser"', '"go/token"', '"log"'] | github.com/final HF test//tmp/repos/example/gotypes/defsuses/main.go | func main() {
// Parse one file.
fset := token.NewFileSet()
f, err := parser.ParseFile(fset, "hello.go", hello, 0)
if err != nil {
log.Fatal(err) // parse error
}
if err := PrintDefsUses(fset, f); err != nil {
log.Fatal(err) // type error
}
} | main | ||||
file | final HF test | 5059c46a-967e-4abe-821d-fdd6d5bbe4a1 | main.go | import (
"fmt"
"go/ast"
"log"
"os"
"golang.org/x/tools/go/ast/astutil"
"golang.org/x/tools/go/packages"
"golang.org/x/tools/go/types/typeutil"
) | github.com/final HF test//tmp/repos/example/gotypes/doc/main.go | // The doc command prints the doc comment of a package-level object.
package main
import (
"fmt"
"go/ast"
"log"
"os"
"golang.org/x/tools/go/ast/astutil"
"golang.org/x/tools/go/packages"
"golang.org/x/tools/go/types/typeutil"
)
func main() {
if len(os.Args) != 3 {
log.Fatal("Usage: doc <package> <object>")
}
//!+part1
pkgpath, name := os.Args[1], os.Args[2]
// Load complete type information for the specified packages,
// along with type-annotated syntax.
// Types for dependencies are loaded from export data.
conf := &packages.Config{Mode: packages.LoadSyntax}
pkgs, err := packages.Load(conf, pkgpath)
if err != nil {
log.Fatal(err) // failed to load anything
}
if packages.PrintErrors(pkgs) > 0 {
os.Exit(1) // some packages contained errors
}
// Find the package and package-level object.
pkg := pkgs[0]
obj := pkg.Types.Scope().Lookup(name)
if obj == nil {
log.Fatalf("%s.%s not found", pkg.Types.Path(), name)
}
//!-part1
//!+part2
// Print the object and its methods (incl. location of definition).
fmt.Println(obj)
for _, sel := range typeutil.IntuitiveMethodSet(obj.Type(), nil) {
fmt.Printf("%s: %s\n", pkg.Fset.Position(sel.Obj().Pos()), sel)
}
// Find the path from the root of the AST to the object's position.
// Walk up to the enclosing ast.Decl for the doc comment.
for _, file := range pkg.Syntax {
pos := obj.Pos()
if !(file.FileStart <= pos && pos < file.FileEnd) {
continue // not in this file
}
path, _ := astutil.PathEnclosingInterval(file, pos, pos)
for _, n := range path {
switch n := n.(type) {
case *ast.GenDecl:
fmt.Println("\n", n.Doc.Text())
return
case *ast.FuncDecl:
fmt.Println("\n", n.Doc.Text())
return
}
}
}
//!-part2
}
// (The $GOROOT below is the actual string that appears in file names
// loaded from export data for packages in the standard library.)
/*
//!+output
$ ./doc net/http File
type net/http.File interface{Readdir(count int) ([]os.FileInfo, error); Seek(offset int64, whence int) (int64, error); Stat() (os.FileInfo, error); io.Closer; io.Reader}
$GOROOT/src/io/io.go:92:2: method (net/http.File) Close() error
$GOROOT/src/io/io.go:71:2: method (net/http.File) Read(p []byte) (n int, err error)
/go/src/net/http/fs.go:65:2: method (net/http.File) Readdir(count int) ([]os.FileInfo, error)
$GOROOT/src/net/http/fs.go:66:2: method (net/http.File) Seek(offset int64, whence int) (int64, error)
/go/src/net/http/fs.go:67:2: method (net/http.File) Stat() (os.FileInfo, error)
A File is returned by a FileSystem's Open method and can be
served by the FileServer implementation.
The methods should behave the same as those on an *os.File.
//!-output
*/
| package main | ||||
function | final HF test | e35070f0-ba1f-4001-8835-d98d50ea62a8 | main | ['"fmt"', '"go/ast"', '"log"', '"os"', '"golang.org/x/tools/go/ast/astutil"', '"golang.org/x/tools/go/packages"', '"golang.org/x/tools/go/types/typeutil"'] | github.com/final HF test//tmp/repos/example/gotypes/doc/main.go | func main() {
if len(os.Args) != 3 {
log.Fatal("Usage: doc <package> <object>")
}
//!+part1
pkgpath, name := os.Args[1], os.Args[2]
// Load complete type information for the specified packages,
// along with type-annotated syntax.
// Types for dependencies are loaded from export data.
conf := &packages.Config{Mode: packages.LoadSyntax}
pkgs, err := packages.Load(conf, pkgpath)
if err != nil {
log.Fatal(err) // failed to load anything
}
if packages.PrintErrors(pkgs) > 0 {
os.Exit(1) // some packages contained errors
}
// Find the package and package-level object.
pkg := pkgs[0]
obj := pkg.Types.Scope().Lookup(name)
if obj == nil {
log.Fatalf("%s.%s not found", pkg.Types.Path(), name)
}
//!-part1
//!+part2
// Print the object and its methods (incl. location of definition).
fmt.Println(obj)
for _, sel := range typeutil.IntuitiveMethodSet(obj.Type(), nil) {
fmt.Printf("%s: %s\n", pkg.Fset.Position(sel.Obj().Pos()), sel)
}
// Find the path from the root of the AST to the object's position.
// Walk up to the enclosing ast.Decl for the doc comment.
for _, file := range pkg.Syntax {
pos := obj.Pos()
if !(file.FileStart <= pos && pos < file.FileEnd) {
continue // not in this file
}
path, _ := astutil.PathEnclosingInterval(file, pos, pos)
for _, n := range path {
switch n := n.(type) {
case *ast.GenDecl:
fmt.Println("\n", n.Doc.Text())
return
case *ast.FuncDecl:
fmt.Println("\n", n.Doc.Text())
return
}
}
}
//!-part2
} | main | ||||
file | final HF test | 0b48e7ba-b905-4a7e-91a6-3a39bc4fe8b8 | gen.go | github.com/final HF test//tmp/repos/example/gotypes/gen.go | //go:generate bash -c "go run ../internal/cmd/weave/weave.go ./go-types.md > README.md"
package gotypes
| package gotypes | |||||
file | final HF test | c4dc89b2-3cef-4e4d-ade2-902f11c227c6 | hello.go | import "fmt" | github.com/final HF test//tmp/repos/example/gotypes/hello/hello.go | // !+
package main
import "fmt"
func main() {
fmt.Println("Hello, 世界")
}
//!-
| package main | ||||
function | final HF test | c6f854e0-90ad-4a59-9e10-5a5933bcf866 | main | github.com/final HF test//tmp/repos/example/gotypes/hello/hello.go | func main() {
fmt.Println("Hello, 世界")
} | main | |||||
file | final HF test | c892f0f2-1d6a-42a4-8b2d-42e4e8232a6f | main.go | import (
"flag"
"fmt"
"go/ast"
"go/token"
"go/types"
"log"
"os"
"golang.org/x/tools/go/packages"
) | github.com/final HF test//tmp/repos/example/gotypes/hugeparam/main.go | // The hugeparam command identifies by-value parameters that are larger than n bytes.
//
// Example:
//
// $ ./hugeparams encoding/xml
package main
import (
"flag"
"fmt"
"go/ast"
"go/token"
"go/types"
"log"
"os"
"golang.org/x/tools/go/packages"
)
// !+
var bytesFlag = flag.Int("bytes", 48, "maximum parameter size in bytes")
func PrintHugeParams(fset *token.FileSet, info *types.Info, sizes types.Sizes, files []*ast.File) {
checkTuple := func(descr string, tuple *types.Tuple) {
for i := 0; i < tuple.Len(); i++ {
v := tuple.At(i)
if sz := sizes.Sizeof(v.Type()); sz > int64(*bytesFlag) {
fmt.Printf("%s: %q %s: %s = %d bytes\n",
fset.Position(v.Pos()),
v.Name(), descr, v.Type(), sz)
}
}
}
checkSig := func(sig *types.Signature) {
checkTuple("parameter", sig.Params())
checkTuple("result", sig.Results())
}
for _, file := range files {
ast.Inspect(file, func(n ast.Node) bool {
switch n := n.(type) {
case *ast.FuncDecl:
checkSig(info.Defs[n.Name].Type().(*types.Signature))
case *ast.FuncLit:
checkSig(info.Types[n.Type].Type.(*types.Signature))
}
return true
})
}
}
//!-
func main() {
flag.Parse()
// Load complete type information for the specified packages,
// along with type-annotated syntax and the "sizeof" function.
// Types for dependencies are loaded from export data.
conf := &packages.Config{Mode: packages.LoadSyntax}
pkgs, err := packages.Load(conf, flag.Args()...)
if err != nil {
log.Fatal(err) // failed to load anything
}
if packages.PrintErrors(pkgs) > 0 {
os.Exit(1) // some packages contained errors
}
for _, pkg := range pkgs {
PrintHugeParams(pkg.Fset, pkg.TypesInfo, pkg.TypesSizes, pkg.Syntax)
}
}
/*
//!+output
% ./hugeparam encoding/xml
/go/src/encoding/xml/marshal.go:167:50: "start" parameter: encoding/xml.StartElement = 56 bytes
/go/src/encoding/xml/marshal.go:734:97: "" result: encoding/xml.StartElement = 56 bytes
/go/src/encoding/xml/marshal.go:761:51: "start" parameter: encoding/xml.StartElement = 56 bytes
/go/src/encoding/xml/marshal.go:781:68: "start" parameter: encoding/xml.StartElement = 56 bytes
/go/src/encoding/xml/xml.go:72:30: "" result: encoding/xml.StartElement = 56 bytes
//!-output
*/
| package main | ||||
function | final HF test | b6629a37-ed78-4986-a67f-5d98487438b1 | PrintHugeParams | ['"fmt"', '"go/ast"', '"go/token"', '"go/types"'] | github.com/final HF test//tmp/repos/example/gotypes/hugeparam/main.go | func PrintHugeParams(fset *token.FileSet, info *types.Info, sizes types.Sizes, files []*ast.File) {
checkTuple := func(descr string, tuple *types.Tuple) {
for i := 0; i < tuple.Len(); i++ {
v := tuple.At(i)
if sz := sizes.Sizeof(v.Type()); sz > int64(*bytesFlag) {
fmt.Printf("%s: %q %s: %s = %d bytes\n",
fset.Position(v.Pos()),
v.Name(), descr, v.Type(), sz)
}
}
}
checkSig := func(sig *types.Signature) {
checkTuple("parameter", sig.Params())
checkTuple("result", sig.Results())
}
for _, file := range files {
ast.Inspect(file, func(n ast.Node) bool {
switch n := n.(type) {
case *ast.FuncDecl:
checkSig(info.Defs[n.Name].Type().(*types.Signature))
case *ast.FuncLit:
checkSig(info.Types[n.Type].Type.(*types.Signature))
}
return true
})
}
} | {'bytesFlag': 'flag.Int("bytes", 48, "maximum parameter size in bytes")'} | main | |||
function | final HF test | 529fa1ed-22c4-4dac-b149-0cca792533d6 | main | ['"flag"', '"log"', '"os"', '"golang.org/x/tools/go/packages"'] | github.com/final HF test//tmp/repos/example/gotypes/hugeparam/main.go | func main() {
flag.Parse()
// Load complete type information for the specified packages,
// along with type-annotated syntax and the "sizeof" function.
// Types for dependencies are loaded from export data.
conf := &packages.Config{Mode: packages.LoadSyntax}
pkgs, err := packages.Load(conf, flag.Args()...)
if err != nil {
log.Fatal(err) // failed to load anything
}
if packages.PrintErrors(pkgs) > 0 {
os.Exit(1) // some packages contained errors
}
for _, pkg := range pkgs {
PrintHugeParams(pkg.Fset, pkg.TypesInfo, pkg.TypesSizes, pkg.Syntax)
}
} | main | ||||
file | final HF test | 3b21758c-adf0-4836-a8b1-6f9830fc3c0e | main.go | import (
"fmt"
"go/ast"
"go/importer"
"go/parser"
"go/token"
"go/types"
"log"
) | github.com/final HF test//tmp/repos/example/gotypes/implements/main.go | package main
import (
"fmt"
"go/ast"
"go/importer"
"go/parser"
"go/token"
"go/types"
"log"
)
// !+input
const input = `package main
type A struct{}
func (*A) f()
type B int
func (B) f()
func (*B) g()
type I interface { f() }
type J interface { g() }
`
//!-input
func main() {
// Parse one file.
fset := token.NewFileSet()
f, err := parser.ParseFile(fset, "input.go", input, 0)
if err != nil {
log.Fatal(err) // parse error
}
conf := types.Config{Importer: importer.Default()}
pkg, err := conf.Check("hello", fset, []*ast.File{f}, nil)
if err != nil {
log.Fatal(err) // type error
}
//!+implements
// Find all named types at package level.
var allNamed []*types.Named
for _, name := range pkg.Scope().Names() {
if obj, ok := pkg.Scope().Lookup(name).(*types.TypeName); ok {
allNamed = append(allNamed, obj.Type().(*types.Named))
}
}
// Test assignability of all distinct pairs of
// named types (T, U) where U is an interface.
for _, T := range allNamed {
for _, U := range allNamed {
if T == U || !types.IsInterface(U) {
continue
}
if types.AssignableTo(T, U) {
fmt.Printf("%s satisfies %s\n", T, U)
} else if !types.IsInterface(T) &&
types.AssignableTo(types.NewPointer(T), U) {
fmt.Printf("%s satisfies %s\n", types.NewPointer(T), U)
}
}
}
//!-implements
}
/*
//!+output
$ go build golang.org/x/example/gotypes/implements
$ ./implements
*hello.A satisfies hello.I
hello.B satisfies hello.I
*hello.B satisfies hello.J
//!-output
*/
| package main | ||||
function | final HF test | f4e53958-f7ae-4f14-84c6-1760e059362d | main | ['"fmt"', '"go/ast"', '"go/importer"', '"go/parser"', '"go/token"', '"go/types"', '"log"'] | github.com/final HF test//tmp/repos/example/gotypes/implements/main.go | func main() {
// Parse one file.
fset := token.NewFileSet()
f, err := parser.ParseFile(fset, "input.go", input, 0)
if err != nil {
log.Fatal(err) // parse error
}
conf := types.Config{Importer: importer.Default()}
pkg, err := conf.Check("hello", fset, []*ast.File{f}, nil)
if err != nil {
log.Fatal(err) // type error
}
//!+implements
// Find all named types at package level.
var allNamed []*types.Named
for _, name := range pkg.Scope().Names() {
if obj, ok := pkg.Scope().Lookup(name).(*types.TypeName); ok {
allNamed = append(allNamed, obj.Type().(*types.Named))
}
}
// Test assignability of all distinct pairs of
// named types (T, U) where U is an interface.
for _, T := range allNamed {
for _, U := range allNamed {
if T == U || !types.IsInterface(U) {
continue
}
if types.AssignableTo(T, U) {
fmt.Printf("%s satisfies %s\n", T, U)
} else if !types.IsInterface(T) &&
types.AssignableTo(types.NewPointer(T), U) {
fmt.Printf("%s satisfies %s\n", types.NewPointer(T), U)
}
}
}
//!-implements
} | main | ||||
file | final HF test | 8a639290-a518-48c7-846a-1fc2c2a12968 | lookup.go | import (
"fmt"
"go/ast"
"go/importer"
"go/parser"
"go/token"
"go/types"
"log"
"strings"
) | github.com/final HF test//tmp/repos/example/gotypes/lookup/lookup.go | package main
import (
"fmt"
"go/ast"
"go/importer"
"go/parser"
"go/token"
"go/types"
"log"
"strings"
)
// !+input
const hello = `
package main
import "fmt"
// append
func main() {
// fmt
fmt.Println("Hello, world")
// main
main, x := 1, 2
// main
print(main, x)
// x
}
// x
`
//!-input
// !+main
func main() {
fset := token.NewFileSet()
f, err := parser.ParseFile(fset, "hello.go", hello, parser.ParseComments)
if err != nil {
log.Fatal(err) // parse error
}
conf := types.Config{Importer: importer.Default()}
pkg, err := conf.Check("cmd/hello", fset, []*ast.File{f}, nil)
if err != nil {
log.Fatal(err) // type error
}
// Each comment contains a name.
// Look up that name in the innermost scope enclosing the comment.
for _, comment := range f.Comments {
pos := comment.Pos()
name := strings.TrimSpace(comment.Text())
fmt.Printf("At %s,\t%q = ", fset.Position(pos), name)
inner := pkg.Scope().Innermost(pos)
if _, obj := inner.LookupParent(name, pos); obj != nil {
fmt.Println(obj)
} else {
fmt.Println("not found")
}
}
}
//!-main
/*
//!+output
$ go build golang.org/x/example/gotypes/lookup
$ ./lookup
At hello.go:6:1, "append" = builtin append
At hello.go:8:9, "fmt" = package fmt
At hello.go:10:9, "main" = func cmd/hello.main()
At hello.go:12:9, "main" = var main int
At hello.go:14:9, "x" = var x int
At hello.go:16:1, "x" = not found
//!-output
*/
| package main | ||||
function | final HF test | 7f5890b3-99ca-447e-a584-24539fc74ad5 | main | ['"fmt"', '"go/ast"', '"go/importer"', '"go/parser"', '"go/token"', '"go/types"', '"log"', '"strings"'] | github.com/final HF test//tmp/repos/example/gotypes/lookup/lookup.go | func main() {
fset := token.NewFileSet()
f, err := parser.ParseFile(fset, "hello.go", hello, parser.ParseComments)
if err != nil {
log.Fatal(err) // parse error
}
conf := types.Config{Importer: importer.Default()}
pkg, err := conf.Check("cmd/hello", fset, []*ast.File{f}, nil)
if err != nil {
log.Fatal(err) // type error
}
// Each comment contains a name.
// Look up that name in the innermost scope enclosing the comment.
for _, comment := range f.Comments {
pos := comment.Pos()
name := strings.TrimSpace(comment.Text())
fmt.Printf("At %s,\t%q = ", fset.Position(pos), name)
inner := pkg.Scope().Innermost(pos)
if _, obj := inner.LookupParent(name, pos); obj != nil {
fmt.Println(obj)
} else {
fmt.Println("not found")
}
}
} | main | ||||
file | final HF test | a554e3a0-67fd-4158-bb63-a8fe0d972902 | main.go | import (
"fmt"
"go/ast"
"go/importer"
"go/parser"
"go/token"
"go/types"
"log"
) | github.com/final HF test//tmp/repos/example/gotypes/nilfunc/main.go | package main
import (
"fmt"
"go/ast"
"go/importer"
"go/parser"
"go/token"
"go/types"
"log"
)
// !+input
const input = `package main
import "bytes"
func main() {
var buf bytes.Buffer
if buf.Bytes == nil && bytes.Repeat != nil && main == nil {
// ...
}
}
`
//!-input
var fset = token.NewFileSet()
func main() {
f, err := parser.ParseFile(fset, "input.go", input, 0)
if err != nil {
log.Fatal(err) // parse error
}
conf := types.Config{Importer: importer.Default()}
info := &types.Info{
Defs: make(map[*ast.Ident]types.Object),
Uses: make(map[*ast.Ident]types.Object),
Types: make(map[ast.Expr]types.TypeAndValue),
}
if _, err = conf.Check("cmd/hello", fset, []*ast.File{f}, info); err != nil {
log.Fatal(err) // type error
}
ast.Inspect(f, func(n ast.Node) bool {
if n != nil {
CheckNilFuncComparison(info, n)
}
return true
})
}
// !+
// CheckNilFuncComparison reports unintended comparisons
// of functions against nil, e.g., "if x.Method == nil {".
func CheckNilFuncComparison(info *types.Info, n ast.Node) {
e, ok := n.(*ast.BinaryExpr)
if !ok {
return // not a binary operation
}
if e.Op != token.EQL && e.Op != token.NEQ {
return // not a comparison
}
// If this is a comparison against nil, find the other operand.
var other ast.Expr
if info.Types[e.X].IsNil() {
other = e.Y
} else if info.Types[e.Y].IsNil() {
other = e.X
} else {
return // not a comparison against nil
}
// Find the object.
var obj types.Object
switch v := other.(type) {
case *ast.Ident:
obj = info.Uses[v]
case *ast.SelectorExpr:
obj = info.Uses[v.Sel]
default:
return // not an identifier or selection
}
if _, ok := obj.(*types.Func); !ok {
return // not a function or method
}
fmt.Printf("%s: comparison of function %v %v nil is always %v\n",
fset.Position(e.Pos()), obj.Name(), e.Op, e.Op == token.NEQ)
}
//!-
/*
//!+output
$ go build golang.org/x/example/gotypes/nilfunc
$ ./nilfunc
input.go:7:5: comparison of function Bytes == nil is always false
input.go:7:25: comparison of function Repeat != nil is always true
input.go:7:48: comparison of function main == nil is always false
//!-output
*/
| package main | ||||
function | final HF test | 6cf10a67-f573-41ca-bf5c-21276946f843 | main | ['"go/ast"', '"go/importer"', '"go/parser"', '"go/types"', '"log"'] | github.com/final HF test//tmp/repos/example/gotypes/nilfunc/main.go | func main() {
f, err := parser.ParseFile(fset, "input.go", input, 0)
if err != nil {
log.Fatal(err) // parse error
}
conf := types.Config{Importer: importer.Default()}
info := &types.Info{
Defs: make(map[*ast.Ident]types.Object),
Uses: make(map[*ast.Ident]types.Object),
Types: make(map[ast.Expr]types.TypeAndValue),
}
if _, err = conf.Check("cmd/hello", fset, []*ast.File{f}, info); err != nil {
log.Fatal(err) // type error
}
ast.Inspect(f, func(n ast.Node) bool {
if n != nil {
CheckNilFuncComparison(info, n)
}
return true
})
} | {'fset': 'token.NewFileSet()'} | main | |||
function | final HF test | e4c7ba63-0cf6-4d1c-8573-4c6c77973122 | CheckNilFuncComparison | ['"fmt"', '"go/ast"', '"go/token"', '"go/types"'] | github.com/final HF test//tmp/repos/example/gotypes/nilfunc/main.go | func CheckNilFuncComparison(info *types.Info, n ast.Node) {
e, ok := n.(*ast.BinaryExpr)
if !ok {
return // not a binary operation
}
if e.Op != token.EQL && e.Op != token.NEQ {
return // not a comparison
}
// If this is a comparison against nil, find the other operand.
var other ast.Expr
if info.Types[e.X].IsNil() {
other = e.Y
} else if info.Types[e.Y].IsNil() {
other = e.X
} else {
return // not a comparison against nil
}
// Find the object.
var obj types.Object
switch v := other.(type) {
case *ast.Ident:
obj = info.Uses[v]
case *ast.SelectorExpr:
obj = info.Uses[v.Sel]
default:
return // not an identifier or selection
}
if _, ok := obj.(*types.Func); !ok {
return // not a function or method
}
fmt.Printf("%s: comparison of function %v %v nil is always %v\n",
fset.Position(e.Pos()), obj.Name(), e.Op, e.Op == token.NEQ)
} | {'fset': 'token.NewFileSet()'} | main | |||
file | final HF test | ba70b7c0-b3f2-43e0-837c-87de4ecc8929 | main.go | import (
"fmt"
"go/ast"
"go/importer"
"go/parser"
"go/token"
"go/types"
"log"
) | github.com/final HF test//tmp/repos/example/gotypes/pkginfo/main.go | // !+
package main
import (
"fmt"
"go/ast"
"go/importer"
"go/parser"
"go/token"
"go/types"
"log"
)
const hello = `package main
import "fmt"
func main() {
fmt.Println("Hello, world")
}`
func main() {
fset := token.NewFileSet()
// Parse the input string, []byte, or io.Reader,
// recording position information in fset.
// ParseFile returns an *ast.File, a syntax tree.
f, err := parser.ParseFile(fset, "hello.go", hello, 0)
if err != nil {
log.Fatal(err) // parse error
}
// A Config controls various options of the type checker.
// The defaults work fine except for one setting:
// we must specify how to deal with imports.
conf := types.Config{Importer: importer.Default()}
// Type-check the package containing only file f.
// Check returns a *types.Package.
pkg, err := conf.Check("cmd/hello", fset, []*ast.File{f}, nil)
if err != nil {
log.Fatal(err) // type error
}
fmt.Printf("Package %q\n", pkg.Path())
fmt.Printf("Name: %s\n", pkg.Name())
fmt.Printf("Imports: %s\n", pkg.Imports())
fmt.Printf("Scope: %s\n", pkg.Scope())
}
//!-
/*
//!+output
$ go build golang.org/x/example/gotypes/pkginfo
$ ./pkginfo
Package "cmd/hello"
Name: main
Imports: [package fmt ("fmt")]
Scope: package "cmd/hello" scope 0x820533590 {
. func cmd/hello.main()
}
//!-output
*/
| package main | ||||
function | final HF test | d959cd20-1a2e-4584-9af5-a180d7aa72f8 | main | ['"fmt"', '"go/ast"', '"go/importer"', '"go/parser"', '"go/token"', '"go/types"', '"log"'] | github.com/final HF test//tmp/repos/example/gotypes/pkginfo/main.go | func main() {
fset := token.NewFileSet()
// Parse the input string, []byte, or io.Reader,
// recording position information in fset.
// ParseFile returns an *ast.File, a syntax tree.
f, err := parser.ParseFile(fset, "hello.go", hello, 0)
if err != nil {
log.Fatal(err) // parse error
}
// A Config controls various options of the type checker.
// The defaults work fine except for one setting:
// we must specify how to deal with imports.
conf := types.Config{Importer: importer.Default()}
// Type-check the package containing only file f.
// Check returns a *types.Package.
pkg, err := conf.Check("cmd/hello", fset, []*ast.File{f}, nil)
if err != nil {
log.Fatal(err) // type error
}
fmt.Printf("Package %q\n", pkg.Path())
fmt.Printf("Name: %s\n", pkg.Name())
fmt.Printf("Imports: %s\n", pkg.Imports())
fmt.Printf("Scope: %s\n", pkg.Scope())
} | main | ||||
file | final HF test | 865287ad-3893-44f7-8b6b-6f36b6a4e37c | main.go | import (
"fmt"
"go/types"
"log"
"os"
"strings"
"unicode"
"unicode/utf8"
"golang.org/x/tools/go/packages"
) | github.com/final HF test//tmp/repos/example/gotypes/skeleton/main.go | // The skeleton command prints the boilerplate for a concrete type
// that implements the specified interface type.
//
// Example:
//
// $ ./skeleton io ReadWriteCloser buffer
// // *buffer implements io.ReadWriteCloser.
// type buffer struct{ /* ... */ }
// func (b *buffer) Close() error { panic("unimplemented") }
// func (b *buffer) Read(p []byte) (n int, err error) { panic("unimplemented") }
// func (b *buffer) Write(p []byte) (n int, err error) { panic("unimplemented") }
package main
import (
"fmt"
"go/types"
"log"
"os"
"strings"
"unicode"
"unicode/utf8"
"golang.org/x/tools/go/packages"
)
const usage = "Usage: skeleton <package> <interface> <concrete>"
// !+
func PrintSkeleton(pkg *types.Package, ifacename, concname string) error {
obj := pkg.Scope().Lookup(ifacename)
if obj == nil {
return fmt.Errorf("%s.%s not found", pkg.Path(), ifacename)
}
if _, ok := obj.(*types.TypeName); !ok {
return fmt.Errorf("%v is not a named type", obj)
}
iface, ok := obj.Type().Underlying().(*types.Interface)
if !ok {
return fmt.Errorf("type %v is a %T, not an interface",
obj, obj.Type().Underlying())
}
// Use first letter of type name as receiver parameter.
if !isValidIdentifier(concname) {
return fmt.Errorf("invalid concrete type name: %q", concname)
}
r, _ := utf8.DecodeRuneInString(concname)
fmt.Printf("// *%s implements %s.%s.\n", concname, pkg.Path(), ifacename)
fmt.Printf("type %s struct{}\n", concname)
mset := types.NewMethodSet(iface)
for i := 0; i < mset.Len(); i++ {
meth := mset.At(i).Obj()
sig := types.TypeString(meth.Type(), (*types.Package).Name)
fmt.Printf("func (%c *%s) %s%s {\n\tpanic(\"unimplemented\")\n}\n",
r, concname, meth.Name(),
strings.TrimPrefix(sig, "func"))
}
return nil
}
//!-
func isValidIdentifier(id string) bool {
for i, r := range id {
if !unicode.IsLetter(r) &&
!(i > 0 && unicode.IsDigit(r)) {
return false
}
}
return id != ""
}
func main() {
if len(os.Args) != 4 {
log.Fatal(usage)
}
pkgpath, ifacename, concname := os.Args[1], os.Args[2], os.Args[3]
// Load only exported type information for the specified package.
conf := &packages.Config{Mode: packages.NeedTypes}
pkgs, err := packages.Load(conf, pkgpath)
if err != nil {
log.Fatal(err) // failed to load anything
}
if packages.PrintErrors(pkgs) > 0 {
os.Exit(1) // some packages contained errors
}
if err := PrintSkeleton(pkgs[0].Types, ifacename, concname); err != nil {
log.Fatal(err)
}
}
/*
//!+output1
$ ./skeleton io ReadWriteCloser buffer
// *buffer implements io.ReadWriteCloser.
type buffer struct{}
func (b *buffer) Close() error {
panic("unimplemented")
}
func (b *buffer) Read(p []byte) (n int, err error) {
panic("unimplemented")
}
func (b *buffer) Write(p []byte) (n int, err error) {
panic("unimplemented")
}
//!-output1
//!+output2
$ ./skeleton net/http Handler myHandler
// *myHandler implements net/http.Handler.
type myHandler struct{}
func (m *myHandler) ServeHTTP(http.ResponseWriter, *http.Request) {
panic("unimplemented")
}
//!-output2
*/
| package main | ||||
function | final HF test | ab93b50d-ac2e-412f-88f0-d4ec45469dbc | PrintSkeleton | ['"fmt"', '"go/types"', '"strings"', '"unicode/utf8"'] | github.com/final HF test//tmp/repos/example/gotypes/skeleton/main.go | func PrintSkeleton(pkg *types.Package, ifacename, concname string) error {
obj := pkg.Scope().Lookup(ifacename)
if obj == nil {
return fmt.Errorf("%s.%s not found", pkg.Path(), ifacename)
}
if _, ok := obj.(*types.TypeName); !ok {
return fmt.Errorf("%v is not a named type", obj)
}
iface, ok := obj.Type().Underlying().(*types.Interface)
if !ok {
return fmt.Errorf("type %v is a %T, not an interface",
obj, obj.Type().Underlying())
}
// Use first letter of type name as receiver parameter.
if !isValidIdentifier(concname) {
return fmt.Errorf("invalid concrete type name: %q", concname)
}
r, _ := utf8.DecodeRuneInString(concname)
fmt.Printf("// *%s implements %s.%s.\n", concname, pkg.Path(), ifacename)
fmt.Printf("type %s struct{}\n", concname)
mset := types.NewMethodSet(iface)
for i := 0; i < mset.Len(); i++ {
meth := mset.At(i).Obj()
sig := types.TypeString(meth.Type(), (*types.Package).Name)
fmt.Printf("func (%c *%s) %s%s {\n\tpanic(\"unimplemented\")\n}\n",
r, concname, meth.Name(),
strings.TrimPrefix(sig, "func"))
}
return nil
} | main | ||||
function | final HF test | a8c42c04-a259-4b6b-b1b7-9a077c19ec0b | isValidIdentifier | ['"unicode"'] | github.com/final HF test//tmp/repos/example/gotypes/skeleton/main.go | func isValidIdentifier(id string) bool {
for i, r := range id {
if !unicode.IsLetter(r) &&
!(i > 0 && unicode.IsDigit(r)) {
return false
}
}
return id != ""
} | main | ||||
function | final HF test | 2990b7c1-e804-4c5d-ae12-494765484409 | main | ['"log"', '"os"', '"golang.org/x/tools/go/packages"'] | github.com/final HF test//tmp/repos/example/gotypes/skeleton/main.go | func main() {
if len(os.Args) != 4 {
log.Fatal(usage)
}
pkgpath, ifacename, concname := os.Args[1], os.Args[2], os.Args[3]
// Load only exported type information for the specified package.
conf := &packages.Config{Mode: packages.NeedTypes}
pkgs, err := packages.Load(conf, pkgpath)
if err != nil {
log.Fatal(err) // failed to load anything
}
if packages.PrintErrors(pkgs) > 0 {
os.Exit(1) // some packages contained errors
}
if err := PrintSkeleton(pkgs[0].Types, ifacename, concname); err != nil {
log.Fatal(err)
}
} | main | ||||
file | final HF test | 033a4304-1762-4780-a34c-6e301c172b08 | main.go | import (
"bytes"
"fmt"
"go/ast"
"go/format"
"go/importer"
"go/parser"
"go/token"
"go/types"
"log"
) | github.com/final HF test//tmp/repos/example/gotypes/typeandvalue/main.go | package main
import (
"bytes"
"fmt"
"go/ast"
"go/format"
"go/importer"
"go/parser"
"go/token"
"go/types"
"log"
)
// !+input
const input = `
package main
var m = make(map[string]int)
func main() {
v, ok := m["hello, " + "world"]
print(rune(v), ok)
}
`
//!-input
var fset = token.NewFileSet()
func main() {
f, err := parser.ParseFile(fset, "hello.go", input, 0)
if err != nil {
log.Fatal(err) // parse error
}
conf := types.Config{Importer: importer.Default()}
info := &types.Info{Types: make(map[ast.Expr]types.TypeAndValue)}
if _, err := conf.Check("cmd/hello", fset, []*ast.File{f}, info); err != nil {
log.Fatal(err) // type error
}
//!+inspect
// f is a parsed, type-checked *ast.File.
ast.Inspect(f, func(n ast.Node) bool {
if expr, ok := n.(ast.Expr); ok {
if tv, ok := info.Types[expr]; ok {
fmt.Printf("%-24s\tmode: %s\n", nodeString(expr), mode(tv))
fmt.Printf("\t\t\t\ttype: %v\n", tv.Type)
if tv.Value != nil {
fmt.Printf("\t\t\t\tvalue: %v\n", tv.Value)
}
}
}
return true
})
//!-inspect
}
// nodeString formats a syntax tree in the style of gofmt.
func nodeString(n ast.Node) string {
var buf bytes.Buffer
format.Node(&buf, fset, n)
return buf.String()
}
// mode returns a string describing the mode of an expression.
func mode(tv types.TypeAndValue) string {
s := ""
if tv.IsVoid() {
s += ",void"
}
if tv.IsType() {
s += ",type"
}
if tv.IsBuiltin() {
s += ",builtin"
}
if tv.IsValue() {
s += ",value"
}
if tv.IsNil() {
s += ",nil"
}
if tv.Addressable() {
s += ",addressable"
}
if tv.Assignable() {
s += ",assignable"
}
if tv.HasOk() {
s += ",ok"
}
return s[1:]
}
/*
//!+output
$ go build golang.org/x/example/gotypes/typeandvalue
$ ./typeandvalue
make(map[string]int) mode: value
type: map[string]int
make mode: builtin
type: func(map[string]int) map[string]int
map[string]int mode: type
type: map[string]int
string mode: type
type: string
int mode: type
type: int
m["hello, "+"world"] mode: value,assignable,ok
type: (int, bool)
m mode: value,addressable,assignable
type: map[string]int
"hello, " + "world" mode: value
type: string
value: "hello, world"
"hello, " mode: value
type: untyped string
value: "hello, "
"world" mode: value
type: untyped string
value: "world"
print(rune(v), ok) mode: void
type: ()
print mode: builtin
type: func(rune, bool)
rune(v) mode: value
type: rune
rune mode: type
type: rune
...more not shown...
//!-output
*/
| package main | ||||
function | final HF test | 6d9c1cbb-d6b0-4621-a910-a81839977654 | main | ['"fmt"', '"go/ast"', '"go/importer"', '"go/parser"', '"go/types"', '"log"'] | github.com/final HF test//tmp/repos/example/gotypes/typeandvalue/main.go | func main() {
f, err := parser.ParseFile(fset, "hello.go", input, 0)
if err != nil {
log.Fatal(err) // parse error
}
conf := types.Config{Importer: importer.Default()}
info := &types.Info{Types: make(map[ast.Expr]types.TypeAndValue)}
if _, err := conf.Check("cmd/hello", fset, []*ast.File{f}, info); err != nil {
log.Fatal(err) // type error
}
//!+inspect
// f is a parsed, type-checked *ast.File.
ast.Inspect(f, func(n ast.Node) bool {
if expr, ok := n.(ast.Expr); ok {
if tv, ok := info.Types[expr]; ok {
fmt.Printf("%-24s\tmode: %s\n", nodeString(expr), mode(tv))
fmt.Printf("\t\t\t\ttype: %v\n", tv.Type)
if tv.Value != nil {
fmt.Printf("\t\t\t\tvalue: %v\n", tv.Value)
}
}
}
return true
})
//!-inspect
} | {'fset': 'token.NewFileSet()'} | main | |||
function | final HF test | b3c34be5-bf42-4957-8851-159e9743fb56 | nodeString | ['"bytes"', '"go/ast"', '"go/format"'] | github.com/final HF test//tmp/repos/example/gotypes/typeandvalue/main.go | func nodeString(n ast.Node) string {
var buf bytes.Buffer
format.Node(&buf, fset, n)
return buf.String()
} | {'fset': 'token.NewFileSet()'} | main | |||
function | final HF test | ca1e8308-90fe-4c77-a4fb-bec4d933ab7c | mode | ['"go/types"'] | github.com/final HF test//tmp/repos/example/gotypes/typeandvalue/main.go | func mode(tv types.TypeAndValue) string {
s := ""
if tv.IsVoid() {
s += ",void"
}
if tv.IsType() {
s += ",type"
}
if tv.IsBuiltin() {
s += ",builtin"
}
if tv.IsValue() {
s += ",value"
}
if tv.IsNil() {
s += ",nil"
}
if tv.Addressable() {
s += ",addressable"
}
if tv.Assignable() {
s += ",assignable"
}
if tv.HasOk() {
s += ",ok"
}
return s[1:]
} | main | ||||
file | final HF test | 6f17709a-ce13-41fc-998c-101620f37ee0 | hello.go | import (
"flag"
"fmt"
"log"
"os"
"golang.org/x/example/hello/reverse"
) | github.com/final HF test//tmp/repos/example/hello/hello.go | // Copyright 2023 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Hello is a hello, world program, demonstrating
// how to write a simple command-line program.
//
// Usage:
//
// hello [options] [name]
//
// The options are:
//
// -g greeting
// Greet with the given greeting, instead of "Hello".
//
// -r
// Greet in reverse.
//
// By default, hello greets the world.
// If a name is specified, hello greets that name instead.
package main
import (
"flag"
"fmt"
"log"
"os"
"golang.org/x/example/hello/reverse"
)
func usage() {
fmt.Fprintf(os.Stderr, "usage: hello [options] [name]\n")
flag.PrintDefaults()
os.Exit(2)
}
var (
greeting = flag.String("g", "Hello", "Greet with `greeting`")
reverseFlag = flag.Bool("r", false, "Greet in reverse")
)
func main() {
// Configure logging for a command-line program.
log.SetFlags(0)
log.SetPrefix("hello: ")
// Parse flags.
flag.Usage = usage
flag.Parse()
// Parse and validate arguments.
name := "world"
args := flag.Args()
if len(args) >= 2 {
usage()
}
if len(args) >= 1 {
name = args[0]
}
if name == "" { // hello '' is an error
log.Fatalf("invalid name %q", name)
}
// Run actual logic.
if *reverseFlag {
fmt.Printf("%s, %s!\n", reverse.String(*greeting), reverse.String(name))
return
}
fmt.Printf("%s, %s!\n", *greeting, name)
}
| package main | ||||
function | final HF test | 7bb63290-3d80-4006-908f-16518d4b75e8 | usage | ['"flag"', '"fmt"', '"os"'] | github.com/final HF test//tmp/repos/example/hello/hello.go | func usage() {
fmt.Fprintf(os.Stderr, "usage: hello [options] [name]\n")
flag.PrintDefaults()
os.Exit(2)
} | main | ||||
function | final HF test | 3d6ec9d5-1f42-4ef7-be70-be55ee32af3a | main | ['"flag"', '"fmt"', '"log"', '"golang.org/x/example/hello/reverse"'] | github.com/final HF test//tmp/repos/example/hello/hello.go | func main() {
// Configure logging for a command-line program.
log.SetFlags(0)
log.SetPrefix("hello: ")
// Parse flags.
flag.Usage = usage
flag.Parse()
// Parse and validate arguments.
name := "world"
args := flag.Args()
if len(args) >= 2 {
usage()
}
if len(args) >= 1 {
name = args[0]
}
if name == "" { // hello '' is an error
log.Fatalf("invalid name %q", name)
}
// Run actual logic.
if *reverseFlag {
fmt.Printf("%s, %s!\n", reverse.String(*greeting), reverse.String(name))
return
}
fmt.Printf("%s, %s!\n", *greeting, name)
} | main | ||||
file | final HF test | f7c724f4-4257-4ded-937b-ac9752110d5c | example_test.go | import (
"fmt"
"golang.org/x/example/hello/reverse"
) | github.com/final HF test//tmp/repos/example/hello/reverse/example_test.go | // Copyright 2023 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package reverse_test
import (
"fmt"
"golang.org/x/example/hello/reverse"
)
func ExampleString() {
fmt.Println(reverse.String("hello"))
// Output: olleh
}
| package reverse_test | ||||
function | final HF test | d1d47813-0a33-4b4f-8861-b01b8386bd8f | ExampleString | ['"fmt"', '"golang.org/x/example/hello/reverse"'] | github.com/final HF test//tmp/repos/example/hello/reverse/example_test.go | func ExampleString() {
fmt.Println(reverse.String("hello"))
// Output: olleh
} | reverse_test | ||||
file | final HF test | a81889e1-f777-478b-8c48-95dd98d9fabf | reverse.go | github.com/final HF test//tmp/repos/example/hello/reverse/reverse.go | // Copyright 2023 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Package reverse can reverse things, particularly strings.
package reverse
// String returns its argument string reversed rune-wise left to right.
func String(s string) string {
r := []rune(s)
for i, j := 0, len(r)-1; i < len(r)/2; i, j = i+1, j-1 {
r[i], r[j] = r[j], r[i]
}
return string(r)
}
| package reverse | |||||
function | final HF test | 335a1f50-8b28-4687-975f-d1586958131e | String | github.com/final HF test//tmp/repos/example/hello/reverse/reverse.go | func String(s string) string {
r := []rune(s)
for i, j := 0, len(r)-1; i < len(r)/2; i, j = i+1, j-1 {
r[i], r[j] = r[j], r[i]
}
return string(r)
} | reverse | |||||
file | final HF test | 494292d9-47a9-4401-a54a-c71e0c29be0f | reverse_test.go | import "testing" | github.com/final HF test//tmp/repos/example/hello/reverse/reverse_test.go | // Copyright 2023 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package reverse
import "testing"
func TestString(t *testing.T) {
for _, c := range []struct {
in, want string
}{
{"Hello, world", "dlrow ,olleH"},
{"Hello, 世界", "界世 ,olleH"},
{"", ""},
} {
got := String(c.in)
if got != c.want {
t.Errorf("String(%q) == %q, want %q", c.in, got, c.want)
}
}
}
| package reverse | ||||
function | final HF test | 482a5231-4066-4dff-b360-c52e3b0a36d1 | TestString | github.com/final HF test//tmp/repos/example/hello/reverse/reverse_test.go | func TestString(t *testing.T) {
for _, c := range []struct {
in, want string
}{
{"Hello, world", "dlrow ,olleH"},
{"Hello, 世界", "界世 ,olleH"},
{"", ""},
} {
got := String(c.in)
if got != c.want {
t.Errorf("String(%q) == %q, want %q", c.in, got, c.want)
}
}
} | reverse | |||||
file | final HF test | 6c41d0c3-b7c3-4958-8bc7-16df6b3f0a1d | server.go | import (
"flag"
"fmt"
"html"
"log"
"net/http"
"os"
"runtime/debug"
"strings"
) | github.com/final HF test//tmp/repos/example/helloserver/server.go | // Copyright 2023 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Hello is a simple hello, world demonstration web server.
//
// It serves version information on /version and answers
// any other request like /name by saying "Hello, name!".
//
// See golang.org/x/example/outyet for a more sophisticated server.
package main
import (
"flag"
"fmt"
"html"
"log"
"net/http"
"os"
"runtime/debug"
"strings"
)
func usage() {
fmt.Fprintf(os.Stderr, "usage: helloserver [options]\n")
flag.PrintDefaults()
os.Exit(2)
}
var (
greeting = flag.String("g", "Hello", "Greet with `greeting`")
addr = flag.String("addr", "localhost:8080", "address to serve")
)
func main() {
// Parse flags.
flag.Usage = usage
flag.Parse()
// Parse and validate arguments (none).
args := flag.Args()
if len(args) != 0 {
usage()
}
// Register handlers.
// All requests not otherwise mapped with go to greet.
// /version is mapped specifically to version.
http.HandleFunc("/", greet)
http.HandleFunc("/version", version)
log.Printf("serving http://%s\n", *addr)
log.Fatal(http.ListenAndServe(*addr, nil))
}
func version(w http.ResponseWriter, r *http.Request) {
info, ok := debug.ReadBuildInfo()
if !ok {
http.Error(w, "no build information available", 500)
return
}
fmt.Fprintf(w, "<!DOCTYPE html>\n<pre>\n")
fmt.Fprintf(w, "%s\n", html.EscapeString(info.String()))
}
func greet(w http.ResponseWriter, r *http.Request) {
name := strings.Trim(r.URL.Path, "/")
if name == "" {
name = "Gopher"
}
fmt.Fprintf(w, "<!DOCTYPE html>\n")
fmt.Fprintf(w, "%s, %s!\n", *greeting, html.EscapeString(name))
}
| package main | ||||
function | final HF test | ef3b17e3-8926-41c6-8c23-5f83c7db6aef | usage | ['"flag"', '"fmt"', '"os"'] | github.com/final HF test//tmp/repos/example/helloserver/server.go | func usage() {
fmt.Fprintf(os.Stderr, "usage: helloserver [options]\n")
flag.PrintDefaults()
os.Exit(2)
} | main | ||||
function | final HF test | 35a3ba7d-693a-4907-a918-ef2709ec11ad | main | ['"flag"', '"log"', '"net/http"'] | github.com/final HF test//tmp/repos/example/helloserver/server.go | func main() {
// Parse flags.
flag.Usage = usage
flag.Parse()
// Parse and validate arguments (none).
args := flag.Args()
if len(args) != 0 {
usage()
}
// Register handlers.
// All requests not otherwise mapped with go to greet.
// /version is mapped specifically to version.
http.HandleFunc("/", greet)
http.HandleFunc("/version", version)
log.Printf("serving http://%s\n", *addr)
log.Fatal(http.ListenAndServe(*addr, nil))
} | main | ||||
function | final HF test | 5f18e1fb-d88a-4d2f-b22f-f87d486054f2 | version | ['"fmt"', '"html"', '"net/http"', '"runtime/debug"'] | github.com/final HF test//tmp/repos/example/helloserver/server.go | func version(w http.ResponseWriter, r *http.Request) {
info, ok := debug.ReadBuildInfo()
if !ok {
http.Error(w, "no build information available", 500)
return
}
fmt.Fprintf(w, "<!DOCTYPE html>\n<pre>\n")
fmt.Fprintf(w, "%s\n", html.EscapeString(info.String()))
} | main | ||||
function | final HF test | 95f289e2-1fe4-4677-8c26-efb3bb096a2d | greet | ['"fmt"', '"html"', '"net/http"', '"strings"'] | github.com/final HF test//tmp/repos/example/helloserver/server.go | func greet(w http.ResponseWriter, r *http.Request) {
name := strings.Trim(r.URL.Path, "/")
if name == "" {
name = "Gopher"
}
fmt.Fprintf(w, "<!DOCTYPE html>\n")
fmt.Fprintf(w, "%s, %s!\n", *greeting, html.EscapeString(name))
} | main | ||||
file | final HF test | e0eae9d8-8231-455c-bc03-ec333e5d982e | weave.go | import (
"bufio"
"bytes"
"fmt"
"log"
"os"
"path/filepath"
"regexp"
"strings"
) | github.com/final HF test//tmp/repos/example/internal/cmd/weave/weave.go | // The weave command is a simple preprocessor for markdown files.
// It builds a table of contents and processes %include directives.
//
// Example usage:
//
// $ go run internal/cmd/weave go-types.md > README.md
//
// The weave command copies lines of the input file to standard output, with two
// exceptions:
//
// If a line begins with "%toc", it is replaced with a table of contents
// consisting of links to the top two levels of headers ("#" and "##").
//
// If a line begins with "%include FILENAME TAG", it is replaced with the lines
// of the file between lines containing "!+TAG" and "!-TAG". TAG can be omitted,
// in which case the delimiters are simply "!+" and "!-".
//
// Before the included lines, a line of the form
//
// // go get PACKAGE
//
// is output, where PACKAGE is constructed from the module path, the
// base name of the current directory, and the directory of FILENAME.
// This caption can be suppressed by putting "-" as the final word of the %include line.
package main
import (
"bufio"
"bytes"
"fmt"
"log"
"os"
"path/filepath"
"regexp"
"strings"
)
func main() {
log.SetFlags(0)
log.SetPrefix("weave: ")
if len(os.Args) != 2 {
log.Fatal("usage: weave input.md\n")
}
f, err := os.Open(os.Args[1])
if err != nil {
log.Fatal(err)
}
defer f.Close()
wd, err := os.Getwd()
if err != nil {
log.Fatal(err)
}
curDir := filepath.Base(wd)
fmt.Println("<!-- Autogenerated by weave; DO NOT EDIT -->")
// Pass 1: extract table of contents.
var toc []string
in := bufio.NewScanner(f)
for in.Scan() {
line := in.Text()
if line == "" || (line[0] != '#' && line[0] != '%') {
continue
}
line = strings.TrimSpace(line)
if line == "%toc" {
toc = nil
} else if strings.HasPrefix(line, "# ") || strings.HasPrefix(line, "## ") {
words := strings.Fields(line)
depth := len(words[0])
words = words[1:]
text := strings.Join(words, " ")
for i := range words {
words[i] = strings.ToLower(words[i])
}
line = fmt.Sprintf("%s1. [%s](#%s)",
strings.Repeat("\t", depth-1), text, strings.Join(words, "-"))
toc = append(toc, line)
}
}
if in.Err() != nil {
log.Fatal(in.Err())
}
// Pass 2.
if _, err := f.Seek(0, os.SEEK_SET); err != nil {
log.Fatalf("can't rewind input: %v", err)
}
in = bufio.NewScanner(f)
for in.Scan() {
line := in.Text()
switch {
case strings.HasPrefix(line, "%toc"): // ToC
for _, h := range toc {
fmt.Println(h)
}
case strings.HasPrefix(line, "%include"):
words := strings.Fields(line)
if len(words) < 2 {
log.Fatal(line)
}
filename := words[1]
// Show caption unless '-' follows.
if len(words) < 4 || words[3] != "-" {
fmt.Printf(" // go get golang.org/x/example/%s/%s\n\n",
curDir, filepath.Dir(filename))
}
section := ""
if len(words) > 2 {
section = words[2]
}
s, err := include(filename, section)
if err != nil {
log.Fatal(err)
}
fmt.Println("```")
fmt.Println(cleanListing(s)) // TODO(adonovan): escape /^```/ in s
fmt.Println("```")
default:
fmt.Println(line)
}
}
if in.Err() != nil {
log.Fatal(in.Err())
}
}
// include processes an included file, and returns the included text.
// Only lines between those matching !+tag and !-tag will be returned.
// This is true even if tag=="".
func include(file, tag string) (string, error) {
f, err := os.Open(file)
if err != nil {
return "", err
}
defer f.Close()
startre, err := regexp.Compile("!\\+" + tag + "$")
if err != nil {
return "", err
}
endre, err := regexp.Compile("!\\-" + tag + "$")
if err != nil {
return "", err
}
var text bytes.Buffer
in := bufio.NewScanner(f)
var on bool
for in.Scan() {
line := in.Text()
switch {
case startre.MatchString(line):
on = true
case endre.MatchString(line):
on = false
case on:
text.WriteByte('\t')
text.WriteString(line)
text.WriteByte('\n')
}
}
if in.Err() != nil {
return "", in.Err()
}
if text.Len() == 0 {
return "", fmt.Errorf("no lines of %s matched tag %q", file, tag)
}
return text.String(), nil
}
func isBlank(line string) bool { return strings.TrimSpace(line) == "" }
func indented(line string) bool {
return strings.HasPrefix(line, " ") || strings.HasPrefix(line, "\t")
}
// cleanListing removes entirely blank leading and trailing lines from
// text, and removes n leading tabs.
func cleanListing(text string) string {
lines := strings.Split(text, "\n")
// remove minimum number of leading tabs from all non-blank lines
tabs := 999
for i, line := range lines {
if strings.TrimSpace(line) == "" {
lines[i] = ""
} else {
if n := leadingTabs(line); n < tabs {
tabs = n
}
}
}
for i, line := range lines {
if line != "" {
line := line[tabs:]
lines[i] = line // remove leading tabs
}
}
// remove leading blank lines
for len(lines) > 0 && lines[0] == "" {
lines = lines[1:]
}
// remove trailing blank lines
for len(lines) > 0 && lines[len(lines)-1] == "" {
lines = lines[:len(lines)-1]
}
return strings.Join(lines, "\n")
}
func leadingTabs(s string) int {
var i int
for i = 0; i < len(s); i++ {
if s[i] != '\t' {
break
}
}
return i
}
| package main | ||||
function | final HF test | b674e6ce-1331-422d-9507-3cfec1dfcdf6 | main | ['"bufio"', '"fmt"', '"log"', '"os"', '"path/filepath"', '"strings"'] | github.com/final HF test//tmp/repos/example/internal/cmd/weave/weave.go | func main() {
log.SetFlags(0)
log.SetPrefix("weave: ")
if len(os.Args) != 2 {
log.Fatal("usage: weave input.md\n")
}
f, err := os.Open(os.Args[1])
if err != nil {
log.Fatal(err)
}
defer f.Close()
wd, err := os.Getwd()
if err != nil {
log.Fatal(err)
}
curDir := filepath.Base(wd)
fmt.Println("<!-- Autogenerated by weave; DO NOT EDIT -->")
// Pass 1: extract table of contents.
var toc []string
in := bufio.NewScanner(f)
for in.Scan() {
line := in.Text()
if line == "" || (line[0] != '#' && line[0] != '%') {
continue
}
line = strings.TrimSpace(line)
if line == "%toc" {
toc = nil
} else if strings.HasPrefix(line, "# ") || strings.HasPrefix(line, "## ") {
words := strings.Fields(line)
depth := len(words[0])
words = words[1:]
text := strings.Join(words, " ")
for i := range words {
words[i] = strings.ToLower(words[i])
}
line = fmt.Sprintf("%s1. [%s](#%s)",
strings.Repeat("\t", depth-1), text, strings.Join(words, "-"))
toc = append(toc, line)
}
}
if in.Err() != nil {
log.Fatal(in.Err())
}
// Pass 2.
if _, err := f.Seek(0, os.SEEK_SET); err != nil {
log.Fatalf("can't rewind input: %v", err)
}
in = bufio.NewScanner(f)
for in.Scan() {
line := in.Text()
switch {
case strings.HasPrefix(line, "%toc"): // ToC
for _, h := range toc {
fmt.Println(h)
}
case strings.HasPrefix(line, "%include"):
words := strings.Fields(line)
if len(words) < 2 {
log.Fatal(line)
}
filename := words[1]
// Show caption unless '-' follows.
if len(words) < 4 || words[3] != "-" {
fmt.Printf(" // go get golang.org/x/example/%s/%s\n\n",
curDir, filepath.Dir(filename))
}
section := ""
if len(words) > 2 {
section = words[2]
}
s, err := include(filename, section)
if err != nil {
log.Fatal(err)
}
fmt.Println("```")
fmt.Println(cleanListing(s)) // TODO(adonovan): escape /^```/ in s
fmt.Println("```")
default:
fmt.Println(line)
}
}
if in.Err() != nil {
log.Fatal(in.Err())
}
} | main | ||||
function | final HF test | 84424c55-9a1c-4fcc-bd45-57943dbf1501 | include | ['"bufio"', '"bytes"', '"fmt"', '"os"', '"regexp"'] | github.com/final HF test//tmp/repos/example/internal/cmd/weave/weave.go | func include(file, tag string) (string, error) {
f, err := os.Open(file)
if err != nil {
return "", err
}
defer f.Close()
startre, err := regexp.Compile("!\\+" + tag + "$")
if err != nil {
return "", err
}
endre, err := regexp.Compile("!\\-" + tag + "$")
if err != nil {
return "", err
}
var text bytes.Buffer
in := bufio.NewScanner(f)
var on bool
for in.Scan() {
line := in.Text()
switch {
case startre.MatchString(line):
on = true
case endre.MatchString(line):
on = false
case on:
text.WriteByte('\t')
text.WriteString(line)
text.WriteByte('\n')
}
}
if in.Err() != nil {
return "", in.Err()
}
if text.Len() == 0 {
return "", fmt.Errorf("no lines of %s matched tag %q", file, tag)
}
return text.String(), nil
} | main | ||||
function | final HF test | d4d178f8-0391-4180-a4cc-1019508475ff | isBlank | ['"strings"'] | github.com/final HF test//tmp/repos/example/internal/cmd/weave/weave.go | func isBlank(line string) bool { return strings.TrimSpace(line) == "" } | main | ||||
function | final HF test | b650ad36-8b71-40ef-a6e4-281b3257d827 | indented | ['"strings"'] | github.com/final HF test//tmp/repos/example/internal/cmd/weave/weave.go | func indented(line string) bool {
return strings.HasPrefix(line, " ") || strings.HasPrefix(line, "\t")
} | main | ||||
function | final HF test | 032a4361-99be-48a7-8ae1-0e1152cdee00 | cleanListing | ['"strings"'] | github.com/final HF test//tmp/repos/example/internal/cmd/weave/weave.go | func cleanListing(text string) string {
lines := strings.Split(text, "\n")
// remove minimum number of leading tabs from all non-blank lines
tabs := 999
for i, line := range lines {
if strings.TrimSpace(line) == "" {
lines[i] = ""
} else {
if n := leadingTabs(line); n < tabs {
tabs = n
}
}
}
for i, line := range lines {
if line != "" {
line := line[tabs:]
lines[i] = line // remove leading tabs
}
}
// remove leading blank lines
for len(lines) > 0 && lines[0] == "" {
lines = lines[1:]
}
// remove trailing blank lines
for len(lines) > 0 && lines[len(lines)-1] == "" {
lines = lines[:len(lines)-1]
}
return strings.Join(lines, "\n")
} | main | ||||
function | final HF test | 2113f572-fa4b-4434-a0f4-94bc9ef3bc5a | leadingTabs | github.com/final HF test//tmp/repos/example/internal/cmd/weave/weave.go | func leadingTabs(s string) int {
var i int
for i = 0; i < len(s); i++ {
if s[i] != '\t' {
break
}
}
return i
} | main | |||||
file | final HF test | 4cd839a9-fda2-4632-974c-d485f31cf8f3 | main.go | import (
"expvar"
"flag"
"fmt"
"html/template"
"log"
"net/http"
"sync"
"time"
) | github.com/final HF test//tmp/repos/example/outyet/main.go | // Copyright 2023 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Outyet is a web server that announces whether or not a particular Go version
// has been tagged.
package main
import (
"expvar"
"flag"
"fmt"
"html/template"
"log"
"net/http"
"sync"
"time"
)
// Command-line flags.
var (
httpAddr = flag.String("http", "localhost:8080", "Listen address")
pollPeriod = flag.Duration("poll", 5*time.Second, "Poll period")
version = flag.String("version", "1.4", "Go version")
)
const baseChangeURL = "https://go.googlesource.com/go/+/"
func main() {
flag.Parse()
changeURL := fmt.Sprintf("%sgo%s", baseChangeURL, *version)
http.Handle("/", NewServer(*version, changeURL, *pollPeriod))
log.Printf("serving http://%s", *httpAddr)
log.Fatal(http.ListenAndServe(*httpAddr, nil))
}
// Exported variables for monitoring the server.
// These are exported via HTTP as a JSON object at /debug/vars.
var (
hitCount = expvar.NewInt("hitCount")
pollCount = expvar.NewInt("pollCount")
pollError = expvar.NewString("pollError")
pollErrorCount = expvar.NewInt("pollErrorCount")
)
// Server implements the outyet server.
// It serves the user interface (it's an http.Handler)
// and polls the remote repository for changes.
type Server struct {
version string
url string
period time.Duration
mu sync.RWMutex // protects the yes variable
yes bool
}
// NewServer returns an initialized outyet server.
func NewServer(version, url string, period time.Duration) *Server {
s := &Server{version: version, url: url, period: period}
go s.poll()
return s
}
// poll polls the change URL for the specified period until the tag exists.
// Then it sets the Server's yes field true and exits.
func (s *Server) poll() {
for !isTagged(s.url) {
pollSleep(s.period)
}
s.mu.Lock()
s.yes = true
s.mu.Unlock()
pollDone()
}
// Hooks that may be overridden for integration tests.
var (
pollSleep = time.Sleep
pollDone = func() {}
)
// isTagged makes an HTTP HEAD request to the given URL and reports whether it
// returned a 200 OK response.
func isTagged(url string) bool {
pollCount.Add(1)
r, err := http.Head(url)
if err != nil {
log.Print(err)
pollError.Set(err.Error())
pollErrorCount.Add(1)
return false
}
return r.StatusCode == http.StatusOK
}
// ServeHTTP implements the HTTP user interface.
func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
hitCount.Add(1)
s.mu.RLock()
data := struct {
URL string
Version string
Yes bool
}{
s.url,
s.version,
s.yes,
}
s.mu.RUnlock()
err := tmpl.Execute(w, data)
if err != nil {
log.Print(err)
}
}
// tmpl is the HTML template that drives the user interface.
var tmpl = template.Must(template.New("tmpl").Parse(`
<!DOCTYPE html><html><body><center>
<h2>Is Go {{.Version}} out yet?</h2>
<h1>
{{if .Yes}}
<a href="{{.URL}}">YES!</a>
{{else}}
No. :-(
{{end}}
</h1>
</center></body></html>
`))
| package main | ||||
function | final HF test | cfff8da5-6393-4955-b8b8-6e93f1f0c7c3 | main | ['"flag"', '"fmt"', '"log"', '"net/http"'] | github.com/final HF test//tmp/repos/example/outyet/main.go | func main() {
flag.Parse()
changeURL := fmt.Sprintf("%sgo%s", baseChangeURL, *version)
http.Handle("/", NewServer(*version, changeURL, *pollPeriod))
log.Printf("serving http://%s", *httpAddr)
log.Fatal(http.ListenAndServe(*httpAddr, nil))
} | main | ||||
function | final HF test | 44b471bb-30ee-4f77-b65c-df36eaa1e8ff | NewServer | ['"time"'] | ['Server'] | github.com/final HF test//tmp/repos/example/outyet/main.go | func NewServer(version, url string, period time.Duration) *Server {
s := &Server{version: version, url: url, period: period}
go s.poll()
return s
} | main | |||
function | final HF test | 30b17d1b-6fbc-461e-b8c7-8051358ab5b4 | poll | ['Server'] | github.com/final HF test//tmp/repos/example/outyet/main.go | func (s *Server) poll() {
for !isTagged(s.url) {
pollSleep(s.period)
}
s.mu.Lock()
s.yes = true
s.mu.Unlock()
pollDone()
} | main |
Subsets and Splits