id
int32
0
167k
repo
stringlengths
5
54
path
stringlengths
4
155
func_name
stringlengths
1
118
original_string
stringlengths
52
85.5k
language
stringclasses
1 value
code
stringlengths
52
85.5k
code_tokens
listlengths
21
1.41k
docstring
stringlengths
6
2.61k
docstring_tokens
listlengths
3
215
sha
stringlengths
40
40
url
stringlengths
85
252
152,900
peterbourgon/diskv
diskv.go
Read
func (s *siphon) Read(p []byte) (int, error) { n, err := s.f.Read(p) if err == nil { return s.buf.Write(p[0:n]) // Write must succeed for Read to succeed } if err == io.EOF { s.d.cacheWithoutLock(s.key, s.buf.Bytes()) // cache may fail if closeErr := s.f.Close(); closeErr != nil { return n, closeErr // close must succeed for Read to succeed } return n, err } return n, err }
go
func (s *siphon) Read(p []byte) (int, error) { n, err := s.f.Read(p) if err == nil { return s.buf.Write(p[0:n]) // Write must succeed for Read to succeed } if err == io.EOF { s.d.cacheWithoutLock(s.key, s.buf.Bytes()) // cache may fail if closeErr := s.f.Close(); closeErr != nil { return n, closeErr // close must succeed for Read to succeed } return n, err } return n, err }
[ "func", "(", "s", "*", "siphon", ")", "Read", "(", "p", "[", "]", "byte", ")", "(", "int", ",", "error", ")", "{", "n", ",", "err", ":=", "s", ".", "f", ".", "Read", "(", "p", ")", "\n\n", "if", "err", "==", "nil", "{", "return", "s", "."...
// Read implements the io.Reader interface for siphon.
[ "Read", "implements", "the", "io", ".", "Reader", "interface", "for", "siphon", "." ]
0be1b92a6df0e4f5cb0a5d15fb7f643d0ad93ce6
https://github.com/peterbourgon/diskv/blob/0be1b92a6df0e4f5cb0a5d15fb7f643d0ad93ce6/diskv.go#L465-L481
152,901
peterbourgon/diskv
diskv.go
Erase
func (d *Diskv) Erase(key string) error { pathKey := d.transform(key) d.mu.Lock() defer d.mu.Unlock() d.bustCacheWithLock(key) // erase from index if d.Index != nil { d.Index.Delete(key) } // erase from disk filename := d.completeFilename(pathKey) if s, err := os.Stat(filename); err == nil { if s.IsDir() { return errBadKey } if err = os.Remove(filename); err != nil { return err } } else { // Return err as-is so caller can do os.IsNotExist(err). return err } // clean up and return d.pruneDirsWithLock(key) return nil }
go
func (d *Diskv) Erase(key string) error { pathKey := d.transform(key) d.mu.Lock() defer d.mu.Unlock() d.bustCacheWithLock(key) // erase from index if d.Index != nil { d.Index.Delete(key) } // erase from disk filename := d.completeFilename(pathKey) if s, err := os.Stat(filename); err == nil { if s.IsDir() { return errBadKey } if err = os.Remove(filename); err != nil { return err } } else { // Return err as-is so caller can do os.IsNotExist(err). return err } // clean up and return d.pruneDirsWithLock(key) return nil }
[ "func", "(", "d", "*", "Diskv", ")", "Erase", "(", "key", "string", ")", "error", "{", "pathKey", ":=", "d", ".", "transform", "(", "key", ")", "\n", "d", ".", "mu", ".", "Lock", "(", ")", "\n", "defer", "d", ".", "mu", ".", "Unlock", "(", ")...
// Erase synchronously erases the given key from the disk and the cache.
[ "Erase", "synchronously", "erases", "the", "given", "key", "from", "the", "disk", "and", "the", "cache", "." ]
0be1b92a6df0e4f5cb0a5d15fb7f643d0ad93ce6
https://github.com/peterbourgon/diskv/blob/0be1b92a6df0e4f5cb0a5d15fb7f643d0ad93ce6/diskv.go#L484-L513
152,902
peterbourgon/diskv
diskv.go
EraseAll
func (d *Diskv) EraseAll() error { d.mu.Lock() defer d.mu.Unlock() d.cache = make(map[string][]byte) d.cacheSize = 0 if d.TempDir != "" { os.RemoveAll(d.TempDir) // errors ignored } return os.RemoveAll(d.BasePath) }
go
func (d *Diskv) EraseAll() error { d.mu.Lock() defer d.mu.Unlock() d.cache = make(map[string][]byte) d.cacheSize = 0 if d.TempDir != "" { os.RemoveAll(d.TempDir) // errors ignored } return os.RemoveAll(d.BasePath) }
[ "func", "(", "d", "*", "Diskv", ")", "EraseAll", "(", ")", "error", "{", "d", ".", "mu", ".", "Lock", "(", ")", "\n", "defer", "d", ".", "mu", ".", "Unlock", "(", ")", "\n", "d", ".", "cache", "=", "make", "(", "map", "[", "string", "]", "[...
// EraseAll will delete all of the data from the store, both in the cache and on // the disk. Note that EraseAll doesn't distinguish diskv-related data from non- // diskv-related data. Care should be taken to always specify a diskv base // directory that is exclusively for diskv data.
[ "EraseAll", "will", "delete", "all", "of", "the", "data", "from", "the", "store", "both", "in", "the", "cache", "and", "on", "the", "disk", ".", "Note", "that", "EraseAll", "doesn", "t", "distinguish", "diskv", "-", "related", "data", "from", "non", "-",...
0be1b92a6df0e4f5cb0a5d15fb7f643d0ad93ce6
https://github.com/peterbourgon/diskv/blob/0be1b92a6df0e4f5cb0a5d15fb7f643d0ad93ce6/diskv.go#L519-L528
152,903
peterbourgon/diskv
diskv.go
Has
func (d *Diskv) Has(key string) bool { pathKey := d.transform(key) d.mu.Lock() defer d.mu.Unlock() if _, ok := d.cache[key]; ok { return true } filename := d.completeFilename(pathKey) s, err := os.Stat(filename) if err != nil { return false } if s.IsDir() { return false } return true }
go
func (d *Diskv) Has(key string) bool { pathKey := d.transform(key) d.mu.Lock() defer d.mu.Unlock() if _, ok := d.cache[key]; ok { return true } filename := d.completeFilename(pathKey) s, err := os.Stat(filename) if err != nil { return false } if s.IsDir() { return false } return true }
[ "func", "(", "d", "*", "Diskv", ")", "Has", "(", "key", "string", ")", "bool", "{", "pathKey", ":=", "d", ".", "transform", "(", "key", ")", "\n", "d", ".", "mu", ".", "Lock", "(", ")", "\n", "defer", "d", ".", "mu", ".", "Unlock", "(", ")", ...
// Has returns true if the given key exists.
[ "Has", "returns", "true", "if", "the", "given", "key", "exists", "." ]
0be1b92a6df0e4f5cb0a5d15fb7f643d0ad93ce6
https://github.com/peterbourgon/diskv/blob/0be1b92a6df0e4f5cb0a5d15fb7f643d0ad93ce6/diskv.go#L531-L550
152,904
peterbourgon/diskv
diskv.go
KeysPrefix
func (d *Diskv) KeysPrefix(prefix string, cancel <-chan struct{}) <-chan string { var prepath string if prefix == "" { prepath = d.BasePath } else { prefixKey := d.transform(prefix) prepath = d.pathFor(prefixKey) } c := make(chan string) go func() { filepath.Walk(prepath, d.walker(c, prefix, cancel)) close(c) }() return c }
go
func (d *Diskv) KeysPrefix(prefix string, cancel <-chan struct{}) <-chan string { var prepath string if prefix == "" { prepath = d.BasePath } else { prefixKey := d.transform(prefix) prepath = d.pathFor(prefixKey) } c := make(chan string) go func() { filepath.Walk(prepath, d.walker(c, prefix, cancel)) close(c) }() return c }
[ "func", "(", "d", "*", "Diskv", ")", "KeysPrefix", "(", "prefix", "string", ",", "cancel", "<-", "chan", "struct", "{", "}", ")", "<-", "chan", "string", "{", "var", "prepath", "string", "\n", "if", "prefix", "==", "\"", "\"", "{", "prepath", "=", ...
// KeysPrefix returns a channel that will yield every key accessible by the // store with the given prefix, in undefined order. If a cancel channel is // provided, closing it will terminate and close the keys channel. If the // provided prefix is the empty string, all keys will be yielded.
[ "KeysPrefix", "returns", "a", "channel", "that", "will", "yield", "every", "key", "accessible", "by", "the", "store", "with", "the", "given", "prefix", "in", "undefined", "order", ".", "If", "a", "cancel", "channel", "is", "provided", "closing", "it", "will"...
0be1b92a6df0e4f5cb0a5d15fb7f643d0ad93ce6
https://github.com/peterbourgon/diskv/blob/0be1b92a6df0e4f5cb0a5d15fb7f643d0ad93ce6/diskv.go#L563-L577
152,905
peterbourgon/diskv
diskv.go
walker
func (d *Diskv) walker(c chan<- string, prefix string, cancel <-chan struct{}) filepath.WalkFunc { return func(path string, info os.FileInfo, err error) error { if err != nil { return err } relPath, _ := filepath.Rel(d.BasePath, path) dir, file := filepath.Split(relPath) pathSplit := strings.Split(dir, string(filepath.Separator)) pathSplit = pathSplit[:len(pathSplit)-1] pathKey := &PathKey{ Path: pathSplit, FileName: file, } key := d.InverseTransform(pathKey) if info.IsDir() || !strings.HasPrefix(key, prefix) { return nil // "pass" } select { case c <- key: case <-cancel: return errCanceled } return nil } }
go
func (d *Diskv) walker(c chan<- string, prefix string, cancel <-chan struct{}) filepath.WalkFunc { return func(path string, info os.FileInfo, err error) error { if err != nil { return err } relPath, _ := filepath.Rel(d.BasePath, path) dir, file := filepath.Split(relPath) pathSplit := strings.Split(dir, string(filepath.Separator)) pathSplit = pathSplit[:len(pathSplit)-1] pathKey := &PathKey{ Path: pathSplit, FileName: file, } key := d.InverseTransform(pathKey) if info.IsDir() || !strings.HasPrefix(key, prefix) { return nil // "pass" } select { case c <- key: case <-cancel: return errCanceled } return nil } }
[ "func", "(", "d", "*", "Diskv", ")", "walker", "(", "c", "chan", "<-", "string", ",", "prefix", "string", ",", "cancel", "<-", "chan", "struct", "{", "}", ")", "filepath", ".", "WalkFunc", "{", "return", "func", "(", "path", "string", ",", "info", ...
// walker returns a function which satisfies the filepath.WalkFunc interface. // It sends every non-directory file entry down the channel c.
[ "walker", "returns", "a", "function", "which", "satisfies", "the", "filepath", ".", "WalkFunc", "interface", ".", "It", "sends", "every", "non", "-", "directory", "file", "entry", "down", "the", "channel", "c", "." ]
0be1b92a6df0e4f5cb0a5d15fb7f643d0ad93ce6
https://github.com/peterbourgon/diskv/blob/0be1b92a6df0e4f5cb0a5d15fb7f643d0ad93ce6/diskv.go#L581-L611
152,906
peterbourgon/diskv
diskv.go
pathFor
func (d *Diskv) pathFor(pathKey *PathKey) string { return filepath.Join(d.BasePath, filepath.Join(pathKey.Path...)) }
go
func (d *Diskv) pathFor(pathKey *PathKey) string { return filepath.Join(d.BasePath, filepath.Join(pathKey.Path...)) }
[ "func", "(", "d", "*", "Diskv", ")", "pathFor", "(", "pathKey", "*", "PathKey", ")", "string", "{", "return", "filepath", ".", "Join", "(", "d", ".", "BasePath", ",", "filepath", ".", "Join", "(", "pathKey", ".", "Path", "...", ")", ")", "\n", "}" ...
// pathFor returns the absolute path for location on the filesystem where the // data for the given key will be stored.
[ "pathFor", "returns", "the", "absolute", "path", "for", "location", "on", "the", "filesystem", "where", "the", "data", "for", "the", "given", "key", "will", "be", "stored", "." ]
0be1b92a6df0e4f5cb0a5d15fb7f643d0ad93ce6
https://github.com/peterbourgon/diskv/blob/0be1b92a6df0e4f5cb0a5d15fb7f643d0ad93ce6/diskv.go#L615-L617
152,907
peterbourgon/diskv
diskv.go
ensurePathWithLock
func (d *Diskv) ensurePathWithLock(pathKey *PathKey) error { return os.MkdirAll(d.pathFor(pathKey), d.PathPerm) }
go
func (d *Diskv) ensurePathWithLock(pathKey *PathKey) error { return os.MkdirAll(d.pathFor(pathKey), d.PathPerm) }
[ "func", "(", "d", "*", "Diskv", ")", "ensurePathWithLock", "(", "pathKey", "*", "PathKey", ")", "error", "{", "return", "os", ".", "MkdirAll", "(", "d", ".", "pathFor", "(", "pathKey", ")", ",", "d", ".", "PathPerm", ")", "\n", "}" ]
// ensurePathWithLock is a helper function that generates all necessary // directories on the filesystem for the given key.
[ "ensurePathWithLock", "is", "a", "helper", "function", "that", "generates", "all", "necessary", "directories", "on", "the", "filesystem", "for", "the", "given", "key", "." ]
0be1b92a6df0e4f5cb0a5d15fb7f643d0ad93ce6
https://github.com/peterbourgon/diskv/blob/0be1b92a6df0e4f5cb0a5d15fb7f643d0ad93ce6/diskv.go#L621-L623
152,908
peterbourgon/diskv
diskv.go
completeFilename
func (d *Diskv) completeFilename(pathKey *PathKey) string { return filepath.Join(d.pathFor(pathKey), pathKey.FileName) }
go
func (d *Diskv) completeFilename(pathKey *PathKey) string { return filepath.Join(d.pathFor(pathKey), pathKey.FileName) }
[ "func", "(", "d", "*", "Diskv", ")", "completeFilename", "(", "pathKey", "*", "PathKey", ")", "string", "{", "return", "filepath", ".", "Join", "(", "d", ".", "pathFor", "(", "pathKey", ")", ",", "pathKey", ".", "FileName", ")", "\n", "}" ]
// completeFilename returns the absolute path to the file for the given key.
[ "completeFilename", "returns", "the", "absolute", "path", "to", "the", "file", "for", "the", "given", "key", "." ]
0be1b92a6df0e4f5cb0a5d15fb7f643d0ad93ce6
https://github.com/peterbourgon/diskv/blob/0be1b92a6df0e4f5cb0a5d15fb7f643d0ad93ce6/diskv.go#L626-L628
152,909
peterbourgon/diskv
diskv.go
cacheWithLock
func (d *Diskv) cacheWithLock(key string, val []byte) error { valueSize := uint64(len(val)) if err := d.ensureCacheSpaceWithLock(valueSize); err != nil { return fmt.Errorf("%s; not caching", err) } // be very strict about memory guarantees if (d.cacheSize + valueSize) > d.CacheSizeMax { panic(fmt.Sprintf("failed to make room for value (%d/%d)", valueSize, d.CacheSizeMax)) } d.cache[key] = val d.cacheSize += valueSize return nil }
go
func (d *Diskv) cacheWithLock(key string, val []byte) error { valueSize := uint64(len(val)) if err := d.ensureCacheSpaceWithLock(valueSize); err != nil { return fmt.Errorf("%s; not caching", err) } // be very strict about memory guarantees if (d.cacheSize + valueSize) > d.CacheSizeMax { panic(fmt.Sprintf("failed to make room for value (%d/%d)", valueSize, d.CacheSizeMax)) } d.cache[key] = val d.cacheSize += valueSize return nil }
[ "func", "(", "d", "*", "Diskv", ")", "cacheWithLock", "(", "key", "string", ",", "val", "[", "]", "byte", ")", "error", "{", "valueSize", ":=", "uint64", "(", "len", "(", "val", ")", ")", "\n", "if", "err", ":=", "d", ".", "ensureCacheSpaceWithLock",...
// cacheWithLock attempts to cache the given key-value pair in the store's // cache. It can fail if the value is larger than the cache's maximum size.
[ "cacheWithLock", "attempts", "to", "cache", "the", "given", "key", "-", "value", "pair", "in", "the", "store", "s", "cache", ".", "It", "can", "fail", "if", "the", "value", "is", "larger", "than", "the", "cache", "s", "maximum", "size", "." ]
0be1b92a6df0e4f5cb0a5d15fb7f643d0ad93ce6
https://github.com/peterbourgon/diskv/blob/0be1b92a6df0e4f5cb0a5d15fb7f643d0ad93ce6/diskv.go#L632-L646
152,910
peterbourgon/diskv
diskv.go
pruneDirsWithLock
func (d *Diskv) pruneDirsWithLock(key string) error { pathlist := d.transform(key).Path for i := range pathlist { dir := filepath.Join(d.BasePath, filepath.Join(pathlist[:len(pathlist)-i]...)) // thanks to Steven Blenkinsop for this snippet switch fi, err := os.Stat(dir); true { case err != nil: return err case !fi.IsDir(): panic(fmt.Sprintf("corrupt dirstate at %s", dir)) } nlinks, err := filepath.Glob(filepath.Join(dir, "*")) if err != nil { return err } else if len(nlinks) > 0 { return nil // has subdirs -- do not prune } if err = os.Remove(dir); err != nil { return err } } return nil }
go
func (d *Diskv) pruneDirsWithLock(key string) error { pathlist := d.transform(key).Path for i := range pathlist { dir := filepath.Join(d.BasePath, filepath.Join(pathlist[:len(pathlist)-i]...)) // thanks to Steven Blenkinsop for this snippet switch fi, err := os.Stat(dir); true { case err != nil: return err case !fi.IsDir(): panic(fmt.Sprintf("corrupt dirstate at %s", dir)) } nlinks, err := filepath.Glob(filepath.Join(dir, "*")) if err != nil { return err } else if len(nlinks) > 0 { return nil // has subdirs -- do not prune } if err = os.Remove(dir); err != nil { return err } } return nil }
[ "func", "(", "d", "*", "Diskv", ")", "pruneDirsWithLock", "(", "key", "string", ")", "error", "{", "pathlist", ":=", "d", ".", "transform", "(", "key", ")", ".", "Path", "\n", "for", "i", ":=", "range", "pathlist", "{", "dir", ":=", "filepath", ".", ...
// pruneDirsWithLock deletes empty directories in the path walk leading to the // key k. Typically this function is called after an Erase is made.
[ "pruneDirsWithLock", "deletes", "empty", "directories", "in", "the", "path", "walk", "leading", "to", "the", "key", "k", ".", "Typically", "this", "function", "is", "called", "after", "an", "Erase", "is", "made", "." ]
0be1b92a6df0e4f5cb0a5d15fb7f643d0ad93ce6
https://github.com/peterbourgon/diskv/blob/0be1b92a6df0e4f5cb0a5d15fb7f643d0ad93ce6/diskv.go#L668-L693
152,911
peterbourgon/diskv
diskv.go
ensureCacheSpaceWithLock
func (d *Diskv) ensureCacheSpaceWithLock(valueSize uint64) error { if valueSize > d.CacheSizeMax { return fmt.Errorf("value size (%d bytes) too large for cache (%d bytes)", valueSize, d.CacheSizeMax) } safe := func() bool { return (d.cacheSize + valueSize) <= d.CacheSizeMax } for key, val := range d.cache { if safe() { break } d.uncacheWithLock(key, uint64(len(val))) } if !safe() { panic(fmt.Sprintf("%d bytes still won't fit in the cache! (max %d bytes)", valueSize, d.CacheSizeMax)) } return nil }
go
func (d *Diskv) ensureCacheSpaceWithLock(valueSize uint64) error { if valueSize > d.CacheSizeMax { return fmt.Errorf("value size (%d bytes) too large for cache (%d bytes)", valueSize, d.CacheSizeMax) } safe := func() bool { return (d.cacheSize + valueSize) <= d.CacheSizeMax } for key, val := range d.cache { if safe() { break } d.uncacheWithLock(key, uint64(len(val))) } if !safe() { panic(fmt.Sprintf("%d bytes still won't fit in the cache! (max %d bytes)", valueSize, d.CacheSizeMax)) } return nil }
[ "func", "(", "d", "*", "Diskv", ")", "ensureCacheSpaceWithLock", "(", "valueSize", "uint64", ")", "error", "{", "if", "valueSize", ">", "d", ".", "CacheSizeMax", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "valueSize", ",", "d", ".", "Ca...
// ensureCacheSpaceWithLock deletes entries from the cache in arbitrary order // until the cache has at least valueSize bytes available.
[ "ensureCacheSpaceWithLock", "deletes", "entries", "from", "the", "cache", "in", "arbitrary", "order", "until", "the", "cache", "has", "at", "least", "valueSize", "bytes", "available", "." ]
0be1b92a6df0e4f5cb0a5d15fb7f643d0ad93ce6
https://github.com/peterbourgon/diskv/blob/0be1b92a6df0e4f5cb0a5d15fb7f643d0ad93ce6/diskv.go#L697-L717
152,912
peterbourgon/diskv
compression.go
NewGzipCompressionLevel
func NewGzipCompressionLevel(level int) Compression { return &genericCompression{ wf: func(w io.Writer) (io.WriteCloser, error) { return gzip.NewWriterLevel(w, level) }, rf: func(r io.Reader) (io.ReadCloser, error) { return gzip.NewReader(r) }, } }
go
func NewGzipCompressionLevel(level int) Compression { return &genericCompression{ wf: func(w io.Writer) (io.WriteCloser, error) { return gzip.NewWriterLevel(w, level) }, rf: func(r io.Reader) (io.ReadCloser, error) { return gzip.NewReader(r) }, } }
[ "func", "NewGzipCompressionLevel", "(", "level", "int", ")", "Compression", "{", "return", "&", "genericCompression", "{", "wf", ":", "func", "(", "w", "io", ".", "Writer", ")", "(", "io", ".", "WriteCloser", ",", "error", ")", "{", "return", "gzip", "."...
// NewGzipCompressionLevel returns a Gzip-based Compression with the given level.
[ "NewGzipCompressionLevel", "returns", "a", "Gzip", "-", "based", "Compression", "with", "the", "given", "level", "." ]
0be1b92a6df0e4f5cb0a5d15fb7f643d0ad93ce6
https://github.com/peterbourgon/diskv/blob/0be1b92a6df0e4f5cb0a5d15fb7f643d0ad93ce6/compression.go#L27-L32
152,913
peterbourgon/diskv
compression.go
NewZlibCompressionLevelDict
func NewZlibCompressionLevelDict(level int, dict []byte) Compression { return &genericCompression{ func(w io.Writer) (io.WriteCloser, error) { return zlib.NewWriterLevelDict(w, level, dict) }, func(r io.Reader) (io.ReadCloser, error) { return zlib.NewReaderDict(r, dict) }, } }
go
func NewZlibCompressionLevelDict(level int, dict []byte) Compression { return &genericCompression{ func(w io.Writer) (io.WriteCloser, error) { return zlib.NewWriterLevelDict(w, level, dict) }, func(r io.Reader) (io.ReadCloser, error) { return zlib.NewReaderDict(r, dict) }, } }
[ "func", "NewZlibCompressionLevelDict", "(", "level", "int", ",", "dict", "[", "]", "byte", ")", "Compression", "{", "return", "&", "genericCompression", "{", "func", "(", "w", "io", ".", "Writer", ")", "(", "io", ".", "WriteCloser", ",", "error", ")", "{...
// NewZlibCompressionLevelDict returns a Zlib-based Compression with the given // level, based on the given dictionary.
[ "NewZlibCompressionLevelDict", "returns", "a", "Zlib", "-", "based", "Compression", "with", "the", "given", "level", "based", "on", "the", "given", "dictionary", "." ]
0be1b92a6df0e4f5cb0a5d15fb7f643d0ad93ce6
https://github.com/peterbourgon/diskv/blob/0be1b92a6df0e4f5cb0a5d15fb7f643d0ad93ce6/compression.go#L46-L51
152,914
peterbourgon/diskv
index.go
Less
func (s btreeString) Less(i btree.Item) bool { return s.l(s.s, i.(btreeString).s) }
go
func (s btreeString) Less(i btree.Item) bool { return s.l(s.s, i.(btreeString).s) }
[ "func", "(", "s", "btreeString", ")", "Less", "(", "i", "btree", ".", "Item", ")", "bool", "{", "return", "s", ".", "l", "(", "s", ".", "s", ",", "i", ".", "(", "btreeString", ")", ".", "s", ")", "\n", "}" ]
// Less satisfies the BTree.Less interface using the btreeString's LessFunction.
[ "Less", "satisfies", "the", "BTree", ".", "Less", "interface", "using", "the", "btreeString", "s", "LessFunction", "." ]
0be1b92a6df0e4f5cb0a5d15fb7f643d0ad93ce6
https://github.com/peterbourgon/diskv/blob/0be1b92a6df0e4f5cb0a5d15fb7f643d0ad93ce6/index.go#L29-L31
152,915
peterbourgon/diskv
index.go
Initialize
func (i *BTreeIndex) Initialize(less LessFunction, keys <-chan string) { i.Lock() defer i.Unlock() i.LessFunction = less i.BTree = rebuild(less, keys) }
go
func (i *BTreeIndex) Initialize(less LessFunction, keys <-chan string) { i.Lock() defer i.Unlock() i.LessFunction = less i.BTree = rebuild(less, keys) }
[ "func", "(", "i", "*", "BTreeIndex", ")", "Initialize", "(", "less", "LessFunction", ",", "keys", "<-", "chan", "string", ")", "{", "i", ".", "Lock", "(", ")", "\n", "defer", "i", ".", "Unlock", "(", ")", "\n", "i", ".", "LessFunction", "=", "less"...
// Initialize populates the BTree tree with data from the keys channel, // according to the passed less function. It's destructive to the BTreeIndex.
[ "Initialize", "populates", "the", "BTree", "tree", "with", "data", "from", "the", "keys", "channel", "according", "to", "the", "passed", "less", "function", ".", "It", "s", "destructive", "to", "the", "BTreeIndex", "." ]
0be1b92a6df0e4f5cb0a5d15fb7f643d0ad93ce6
https://github.com/peterbourgon/diskv/blob/0be1b92a6df0e4f5cb0a5d15fb7f643d0ad93ce6/index.go#L42-L47
152,916
peterbourgon/diskv
index.go
Keys
func (i *BTreeIndex) Keys(from string, n int) []string { i.RLock() defer i.RUnlock() if i.BTree == nil || i.LessFunction == nil { panic("uninitialized index") } if i.BTree.Len() <= 0 { return []string{} } btreeFrom := btreeString{s: from, l: i.LessFunction} skipFirst := true if len(from) <= 0 || !i.BTree.Has(btreeFrom) { // no such key, so fabricate an always-smallest item btreeFrom = btreeString{s: "", l: func(string, string) bool { return true }} skipFirst = false } keys := []string{} iterator := func(i btree.Item) bool { keys = append(keys, i.(btreeString).s) return len(keys) < n } i.BTree.AscendGreaterOrEqual(btreeFrom, iterator) if skipFirst && len(keys) > 0 { keys = keys[1:] } return keys }
go
func (i *BTreeIndex) Keys(from string, n int) []string { i.RLock() defer i.RUnlock() if i.BTree == nil || i.LessFunction == nil { panic("uninitialized index") } if i.BTree.Len() <= 0 { return []string{} } btreeFrom := btreeString{s: from, l: i.LessFunction} skipFirst := true if len(from) <= 0 || !i.BTree.Has(btreeFrom) { // no such key, so fabricate an always-smallest item btreeFrom = btreeString{s: "", l: func(string, string) bool { return true }} skipFirst = false } keys := []string{} iterator := func(i btree.Item) bool { keys = append(keys, i.(btreeString).s) return len(keys) < n } i.BTree.AscendGreaterOrEqual(btreeFrom, iterator) if skipFirst && len(keys) > 0 { keys = keys[1:] } return keys }
[ "func", "(", "i", "*", "BTreeIndex", ")", "Keys", "(", "from", "string", ",", "n", "int", ")", "[", "]", "string", "{", "i", ".", "RLock", "(", ")", "\n", "defer", "i", ".", "RUnlock", "(", ")", "\n\n", "if", "i", ".", "BTree", "==", "nil", "...
// Keys yields a maximum of n keys in order. If the passed 'from' key is empty, // Keys will return the first n keys. If the passed 'from' key is non-empty, the // first key in the returned slice will be the key that immediately follows the // passed key, in key order.
[ "Keys", "yields", "a", "maximum", "of", "n", "keys", "in", "order", ".", "If", "the", "passed", "from", "key", "is", "empty", "Keys", "will", "return", "the", "first", "n", "keys", ".", "If", "the", "passed", "from", "key", "is", "non", "-", "empty",...
0be1b92a6df0e4f5cb0a5d15fb7f643d0ad93ce6
https://github.com/peterbourgon/diskv/blob/0be1b92a6df0e4f5cb0a5d15fb7f643d0ad93ce6/index.go#L73-L105
152,917
peterbourgon/diskv
index.go
rebuild
func rebuild(less LessFunction, keys <-chan string) *btree.BTree { tree := btree.New(2) for key := range keys { tree.ReplaceOrInsert(btreeString{s: key, l: less}) } return tree }
go
func rebuild(less LessFunction, keys <-chan string) *btree.BTree { tree := btree.New(2) for key := range keys { tree.ReplaceOrInsert(btreeString{s: key, l: less}) } return tree }
[ "func", "rebuild", "(", "less", "LessFunction", ",", "keys", "<-", "chan", "string", ")", "*", "btree", ".", "BTree", "{", "tree", ":=", "btree", ".", "New", "(", "2", ")", "\n", "for", "key", ":=", "range", "keys", "{", "tree", ".", "ReplaceOrInsert...
// rebuildIndex does the work of regenerating the index // with the given keys.
[ "rebuildIndex", "does", "the", "work", "of", "regenerating", "the", "index", "with", "the", "given", "keys", "." ]
0be1b92a6df0e4f5cb0a5d15fb7f643d0ad93ce6
https://github.com/peterbourgon/diskv/blob/0be1b92a6df0e4f5cb0a5d15fb7f643d0ad93ce6/index.go#L109-L115
152,918
kubernetes/gengo
examples/deepcopy-gen/generators/deepcopy.go
deepCopyMethodOrDie
func deepCopyMethodOrDie(t *types.Type) *types.Signature { ret, err := deepCopyMethod(t) if err != nil { klog.Fatal(err) } return ret }
go
func deepCopyMethodOrDie(t *types.Type) *types.Signature { ret, err := deepCopyMethod(t) if err != nil { klog.Fatal(err) } return ret }
[ "func", "deepCopyMethodOrDie", "(", "t", "*", "types", ".", "Type", ")", "*", "types", ".", "Signature", "{", "ret", ",", "err", ":=", "deepCopyMethod", "(", "t", ")", "\n", "if", "err", "!=", "nil", "{", "klog", ".", "Fatal", "(", "err", ")", "\n"...
// deepCopyMethodOrDie returns the signatrue of a DeepCopy method, nil or calls klog.Fatalf // if the type does not match.
[ "deepCopyMethodOrDie", "returns", "the", "signatrue", "of", "a", "DeepCopy", "method", "nil", "or", "calls", "klog", ".", "Fatalf", "if", "the", "type", "does", "not", "match", "." ]
e17681d19d3ac4837a019ece36c2a0ec31ffe985
https://github.com/kubernetes/gengo/blob/e17681d19d3ac4837a019ece36c2a0ec31ffe985/examples/deepcopy-gen/generators/deepcopy.go#L331-L337
152,919
kubernetes/gengo
examples/deepcopy-gen/generators/deepcopy.go
deepCopyableInterfaces
func (g *genDeepCopy) deepCopyableInterfaces(c *generator.Context, t *types.Type) ([]*types.Type, bool, error) { ts, err := g.deepCopyableInterfacesInner(c, t) if err != nil { return nil, false, err } set := map[string]*types.Type{} for _, t := range ts { set[t.String()] = t } result := []*types.Type{} for _, t := range set { result = append(result, t) } TypeSlice(result).Sort() // we need a stable sorting because it determines the order in generation nonPointerReceiver, err := extractNonPointerInterfaces(t) if err != nil { return nil, false, err } return result, nonPointerReceiver, nil }
go
func (g *genDeepCopy) deepCopyableInterfaces(c *generator.Context, t *types.Type) ([]*types.Type, bool, error) { ts, err := g.deepCopyableInterfacesInner(c, t) if err != nil { return nil, false, err } set := map[string]*types.Type{} for _, t := range ts { set[t.String()] = t } result := []*types.Type{} for _, t := range set { result = append(result, t) } TypeSlice(result).Sort() // we need a stable sorting because it determines the order in generation nonPointerReceiver, err := extractNonPointerInterfaces(t) if err != nil { return nil, false, err } return result, nonPointerReceiver, nil }
[ "func", "(", "g", "*", "genDeepCopy", ")", "deepCopyableInterfaces", "(", "c", "*", "generator", ".", "Context", ",", "t", "*", "types", ".", "Type", ")", "(", "[", "]", "*", "types", ".", "Type", ",", "bool", ",", "error", ")", "{", "ts", ",", "...
// deepCopyableInterfaces returns the interface types to implement and whether they apply to a non-pointer receiver.
[ "deepCopyableInterfaces", "returns", "the", "interface", "types", "to", "implement", "and", "whether", "they", "apply", "to", "a", "non", "-", "pointer", "receiver", "." ]
e17681d19d3ac4837a019ece36c2a0ec31ffe985
https://github.com/kubernetes/gengo/blob/e17681d19d3ac4837a019ece36c2a0ec31ffe985/examples/deepcopy-gen/generators/deepcopy.go#L549-L573
152,920
kubernetes/gengo
examples/deepcopy-gen/generators/deepcopy.go
isReference
func isReference(t *types.Type) bool { if t.Kind == types.Pointer || t.Kind == types.Map || t.Kind == types.Slice { return true } return t.Kind == types.Alias && isReference(underlyingType(t)) }
go
func isReference(t *types.Type) bool { if t.Kind == types.Pointer || t.Kind == types.Map || t.Kind == types.Slice { return true } return t.Kind == types.Alias && isReference(underlyingType(t)) }
[ "func", "isReference", "(", "t", "*", "types", ".", "Type", ")", "bool", "{", "if", "t", ".", "Kind", "==", "types", ".", "Pointer", "||", "t", ".", "Kind", "==", "types", ".", "Map", "||", "t", ".", "Kind", "==", "types", ".", "Slice", "{", "r...
// isReference return true for pointer, maps, slices and aliases of those.
[ "isReference", "return", "true", "for", "pointer", "maps", "slices", "and", "aliases", "of", "those", "." ]
e17681d19d3ac4837a019ece36c2a0ec31ffe985
https://github.com/kubernetes/gengo/blob/e17681d19d3ac4837a019ece36c2a0ec31ffe985/examples/deepcopy-gen/generators/deepcopy.go#L659-L664
152,921
kubernetes/gengo
examples/deepcopy-gen/generators/deepcopy.go
doBuiltin
func (g *genDeepCopy) doBuiltin(t *types.Type, sw *generator.SnippetWriter) { if deepCopyMethodOrDie(t) != nil || deepCopyIntoMethodOrDie(t) != nil { sw.Do("*out = in.DeepCopy()\n", nil) return } sw.Do("*out = *in\n", nil) }
go
func (g *genDeepCopy) doBuiltin(t *types.Type, sw *generator.SnippetWriter) { if deepCopyMethodOrDie(t) != nil || deepCopyIntoMethodOrDie(t) != nil { sw.Do("*out = in.DeepCopy()\n", nil) return } sw.Do("*out = *in\n", nil) }
[ "func", "(", "g", "*", "genDeepCopy", ")", "doBuiltin", "(", "t", "*", "types", ".", "Type", ",", "sw", "*", "generator", ".", "SnippetWriter", ")", "{", "if", "deepCopyMethodOrDie", "(", "t", ")", "!=", "nil", "||", "deepCopyIntoMethodOrDie", "(", "t", ...
// doBuiltin generates code for a builtin or an alias to a builtin. The generated code is // is the same for both cases, i.e. it's the code for the underlying type.
[ "doBuiltin", "generates", "code", "for", "a", "builtin", "or", "an", "alias", "to", "a", "builtin", ".", "The", "generated", "code", "is", "is", "the", "same", "for", "both", "cases", "i", ".", "e", ".", "it", "s", "the", "code", "for", "the", "under...
e17681d19d3ac4837a019ece36c2a0ec31ffe985
https://github.com/kubernetes/gengo/blob/e17681d19d3ac4837a019ece36c2a0ec31ffe985/examples/deepcopy-gen/generators/deepcopy.go#L700-L707
152,922
kubernetes/gengo
examples/deepcopy-gen/generators/deepcopy.go
doMap
func (g *genDeepCopy) doMap(t *types.Type, sw *generator.SnippetWriter) { ut := underlyingType(t) uet := underlyingType(ut.Elem) if deepCopyMethodOrDie(t) != nil || deepCopyIntoMethodOrDie(t) != nil { sw.Do("*out = in.DeepCopy()\n", nil) return } if !ut.Key.IsAssignable() { klog.Fatalf("Hit an unsupported type %v for: %v", uet, t) } sw.Do("*out = make($.|raw$, len(*in))\n", t) sw.Do("for key, val := range *in {\n", nil) dc, dci := deepCopyMethodOrDie(ut.Elem), deepCopyIntoMethodOrDie(ut.Elem) switch { case dc != nil || dci != nil: // Note: a DeepCopy exists because it is added if DeepCopyInto is manually defined leftPointer := ut.Elem.Kind == types.Pointer rightPointer := !isReference(ut.Elem) if dc != nil { rightPointer = dc.Results[0].Kind == types.Pointer } if leftPointer == rightPointer { sw.Do("(*out)[key] = val.DeepCopy()\n", nil) } else if leftPointer { sw.Do("x := val.DeepCopy()\n", nil) sw.Do("(*out)[key] = &x\n", nil) } else { sw.Do("(*out)[key] = *val.DeepCopy()\n", nil) } case ut.Elem.IsAnonymousStruct(): // not uet here because it needs type cast sw.Do("(*out)[key] = val\n", nil) case uet.IsAssignable(): sw.Do("(*out)[key] = val\n", nil) case uet.Kind == types.Interface: // Note: do not generate code that won't compile as `DeepCopyinterface{}()` is not a valid function if uet.Name.Name == "interface{}" { klog.Fatalf("DeepCopy of %q is unsupported. Instead, use named interfaces with DeepCopy<named-interface> as one of the methods.", uet.Name.Name) } sw.Do("if val == nil {(*out)[key]=nil} else {\n", nil) // Note: if t.Elem has been an alias "J" of an interface "I" in Go, we will see it // as kind Interface of name "J" here, i.e. generate val.DeepCopyJ(). The golang // parser does not give us the underlying interface name. So we cannot do any better. sw.Do(fmt.Sprintf("(*out)[key] = val.DeepCopy%s()\n", uet.Name.Name), nil) sw.Do("}\n", nil) case uet.Kind == types.Slice || uet.Kind == types.Map || uet.Kind == types.Pointer: sw.Do("var outVal $.|raw$\n", uet) sw.Do("if val == nil { (*out)[key] = nil } else {\n", nil) sw.Do("in, out := &val, &outVal\n", uet) g.generateFor(ut.Elem, sw) sw.Do("}\n", nil) sw.Do("(*out)[key] = outVal\n", nil) case uet.Kind == types.Struct: sw.Do("(*out)[key] = *val.DeepCopy()\n", uet) default: klog.Fatalf("Hit an unsupported type %v for %v", uet, t) } sw.Do("}\n", nil) }
go
func (g *genDeepCopy) doMap(t *types.Type, sw *generator.SnippetWriter) { ut := underlyingType(t) uet := underlyingType(ut.Elem) if deepCopyMethodOrDie(t) != nil || deepCopyIntoMethodOrDie(t) != nil { sw.Do("*out = in.DeepCopy()\n", nil) return } if !ut.Key.IsAssignable() { klog.Fatalf("Hit an unsupported type %v for: %v", uet, t) } sw.Do("*out = make($.|raw$, len(*in))\n", t) sw.Do("for key, val := range *in {\n", nil) dc, dci := deepCopyMethodOrDie(ut.Elem), deepCopyIntoMethodOrDie(ut.Elem) switch { case dc != nil || dci != nil: // Note: a DeepCopy exists because it is added if DeepCopyInto is manually defined leftPointer := ut.Elem.Kind == types.Pointer rightPointer := !isReference(ut.Elem) if dc != nil { rightPointer = dc.Results[0].Kind == types.Pointer } if leftPointer == rightPointer { sw.Do("(*out)[key] = val.DeepCopy()\n", nil) } else if leftPointer { sw.Do("x := val.DeepCopy()\n", nil) sw.Do("(*out)[key] = &x\n", nil) } else { sw.Do("(*out)[key] = *val.DeepCopy()\n", nil) } case ut.Elem.IsAnonymousStruct(): // not uet here because it needs type cast sw.Do("(*out)[key] = val\n", nil) case uet.IsAssignable(): sw.Do("(*out)[key] = val\n", nil) case uet.Kind == types.Interface: // Note: do not generate code that won't compile as `DeepCopyinterface{}()` is not a valid function if uet.Name.Name == "interface{}" { klog.Fatalf("DeepCopy of %q is unsupported. Instead, use named interfaces with DeepCopy<named-interface> as one of the methods.", uet.Name.Name) } sw.Do("if val == nil {(*out)[key]=nil} else {\n", nil) // Note: if t.Elem has been an alias "J" of an interface "I" in Go, we will see it // as kind Interface of name "J" here, i.e. generate val.DeepCopyJ(). The golang // parser does not give us the underlying interface name. So we cannot do any better. sw.Do(fmt.Sprintf("(*out)[key] = val.DeepCopy%s()\n", uet.Name.Name), nil) sw.Do("}\n", nil) case uet.Kind == types.Slice || uet.Kind == types.Map || uet.Kind == types.Pointer: sw.Do("var outVal $.|raw$\n", uet) sw.Do("if val == nil { (*out)[key] = nil } else {\n", nil) sw.Do("in, out := &val, &outVal\n", uet) g.generateFor(ut.Elem, sw) sw.Do("}\n", nil) sw.Do("(*out)[key] = outVal\n", nil) case uet.Kind == types.Struct: sw.Do("(*out)[key] = *val.DeepCopy()\n", uet) default: klog.Fatalf("Hit an unsupported type %v for %v", uet, t) } sw.Do("}\n", nil) }
[ "func", "(", "g", "*", "genDeepCopy", ")", "doMap", "(", "t", "*", "types", ".", "Type", ",", "sw", "*", "generator", ".", "SnippetWriter", ")", "{", "ut", ":=", "underlyingType", "(", "t", ")", "\n", "uet", ":=", "underlyingType", "(", "ut", ".", ...
// doMap generates code for a map or an alias to a map. The generated code is // is the same for both cases, i.e. it's the code for the underlying type.
[ "doMap", "generates", "code", "for", "a", "map", "or", "an", "alias", "to", "a", "map", ".", "The", "generated", "code", "is", "is", "the", "same", "for", "both", "cases", "i", ".", "e", ".", "it", "s", "the", "code", "for", "the", "underlying", "t...
e17681d19d3ac4837a019ece36c2a0ec31ffe985
https://github.com/kubernetes/gengo/blob/e17681d19d3ac4837a019ece36c2a0ec31ffe985/examples/deepcopy-gen/generators/deepcopy.go#L711-L771
152,923
kubernetes/gengo
examples/deepcopy-gen/generators/deepcopy.go
doSlice
func (g *genDeepCopy) doSlice(t *types.Type, sw *generator.SnippetWriter) { ut := underlyingType(t) uet := underlyingType(ut.Elem) if deepCopyMethodOrDie(t) != nil || deepCopyIntoMethodOrDie(t) != nil { sw.Do("*out = in.DeepCopy()\n", nil) return } sw.Do("*out = make($.|raw$, len(*in))\n", t) if deepCopyMethodOrDie(ut.Elem) != nil || deepCopyIntoMethodOrDie(ut.Elem) != nil { sw.Do("for i := range *in {\n", nil) // Note: a DeepCopyInto exists because it is added if DeepCopy is manually defined sw.Do("(*in)[i].DeepCopyInto(&(*out)[i])\n", nil) sw.Do("}\n", nil) } else if uet.Kind == types.Builtin || uet.IsAssignable() { sw.Do("copy(*out, *in)\n", nil) } else { sw.Do("for i := range *in {\n", nil) if uet.Kind == types.Slice || uet.Kind == types.Map || uet.Kind == types.Pointer || deepCopyMethodOrDie(ut.Elem) != nil || deepCopyIntoMethodOrDie(ut.Elem) != nil { sw.Do("if (*in)[i] != nil {\n", nil) sw.Do("in, out := &(*in)[i], &(*out)[i]\n", nil) g.generateFor(ut.Elem, sw) sw.Do("}\n", nil) } else if uet.Kind == types.Interface { // Note: do not generate code that won't compile as `DeepCopyinterface{}()` is not a valid function if uet.Name.Name == "interface{}" { klog.Fatalf("DeepCopy of %q is unsupported. Instead, use named interfaces with DeepCopy<named-interface> as one of the methods.", uet.Name.Name) } sw.Do("if (*in)[i] != nil {\n", nil) // Note: if t.Elem has been an alias "J" of an interface "I" in Go, we will see it // as kind Interface of name "J" here, i.e. generate val.DeepCopyJ(). The golang // parser does not give us the underlying interface name. So we cannot do any better. sw.Do(fmt.Sprintf("(*out)[i] = (*in)[i].DeepCopy%s()\n", uet.Name.Name), nil) sw.Do("}\n", nil) } else if uet.Kind == types.Struct { sw.Do("(*in)[i].DeepCopyInto(&(*out)[i])\n", nil) } else { klog.Fatalf("Hit an unsupported type %v for %v", uet, t) } sw.Do("}\n", nil) } }
go
func (g *genDeepCopy) doSlice(t *types.Type, sw *generator.SnippetWriter) { ut := underlyingType(t) uet := underlyingType(ut.Elem) if deepCopyMethodOrDie(t) != nil || deepCopyIntoMethodOrDie(t) != nil { sw.Do("*out = in.DeepCopy()\n", nil) return } sw.Do("*out = make($.|raw$, len(*in))\n", t) if deepCopyMethodOrDie(ut.Elem) != nil || deepCopyIntoMethodOrDie(ut.Elem) != nil { sw.Do("for i := range *in {\n", nil) // Note: a DeepCopyInto exists because it is added if DeepCopy is manually defined sw.Do("(*in)[i].DeepCopyInto(&(*out)[i])\n", nil) sw.Do("}\n", nil) } else if uet.Kind == types.Builtin || uet.IsAssignable() { sw.Do("copy(*out, *in)\n", nil) } else { sw.Do("for i := range *in {\n", nil) if uet.Kind == types.Slice || uet.Kind == types.Map || uet.Kind == types.Pointer || deepCopyMethodOrDie(ut.Elem) != nil || deepCopyIntoMethodOrDie(ut.Elem) != nil { sw.Do("if (*in)[i] != nil {\n", nil) sw.Do("in, out := &(*in)[i], &(*out)[i]\n", nil) g.generateFor(ut.Elem, sw) sw.Do("}\n", nil) } else if uet.Kind == types.Interface { // Note: do not generate code that won't compile as `DeepCopyinterface{}()` is not a valid function if uet.Name.Name == "interface{}" { klog.Fatalf("DeepCopy of %q is unsupported. Instead, use named interfaces with DeepCopy<named-interface> as one of the methods.", uet.Name.Name) } sw.Do("if (*in)[i] != nil {\n", nil) // Note: if t.Elem has been an alias "J" of an interface "I" in Go, we will see it // as kind Interface of name "J" here, i.e. generate val.DeepCopyJ(). The golang // parser does not give us the underlying interface name. So we cannot do any better. sw.Do(fmt.Sprintf("(*out)[i] = (*in)[i].DeepCopy%s()\n", uet.Name.Name), nil) sw.Do("}\n", nil) } else if uet.Kind == types.Struct { sw.Do("(*in)[i].DeepCopyInto(&(*out)[i])\n", nil) } else { klog.Fatalf("Hit an unsupported type %v for %v", uet, t) } sw.Do("}\n", nil) } }
[ "func", "(", "g", "*", "genDeepCopy", ")", "doSlice", "(", "t", "*", "types", ".", "Type", ",", "sw", "*", "generator", ".", "SnippetWriter", ")", "{", "ut", ":=", "underlyingType", "(", "t", ")", "\n", "uet", ":=", "underlyingType", "(", "ut", ".", ...
// doSlice generates code for a slice or an alias to a slice. The generated code is // is the same for both cases, i.e. it's the code for the underlying type.
[ "doSlice", "generates", "code", "for", "a", "slice", "or", "an", "alias", "to", "a", "slice", ".", "The", "generated", "code", "is", "is", "the", "same", "for", "both", "cases", "i", ".", "e", ".", "it", "s", "the", "code", "for", "the", "underlying"...
e17681d19d3ac4837a019ece36c2a0ec31ffe985
https://github.com/kubernetes/gengo/blob/e17681d19d3ac4837a019ece36c2a0ec31ffe985/examples/deepcopy-gen/generators/deepcopy.go#L775-L817
152,924
kubernetes/gengo
examples/deepcopy-gen/generators/deepcopy.go
doStruct
func (g *genDeepCopy) doStruct(t *types.Type, sw *generator.SnippetWriter) { ut := underlyingType(t) if deepCopyMethodOrDie(t) != nil || deepCopyIntoMethodOrDie(t) != nil { sw.Do("*out = in.DeepCopy()\n", nil) return } // Simple copy covers a lot of cases. sw.Do("*out = *in\n", nil) // Now fix-up fields as needed. for _, m := range ut.Members { ft := m.Type uft := underlyingType(ft) args := generator.Args{ "type": ft, "kind": ft.Kind, "name": m.Name, } dc, dci := deepCopyMethodOrDie(ft), deepCopyIntoMethodOrDie(ft) switch { case dc != nil || dci != nil: // Note: a DeepCopyInto exists because it is added if DeepCopy is manually defined leftPointer := ft.Kind == types.Pointer rightPointer := !isReference(ft) if dc != nil { rightPointer = dc.Results[0].Kind == types.Pointer } if leftPointer == rightPointer { sw.Do("out.$.name$ = in.$.name$.DeepCopy()\n", args) } else if leftPointer { sw.Do("x := in.$.name$.DeepCopy()\n", args) sw.Do("out.$.name$ = = &x\n", args) } else { sw.Do("in.$.name$.DeepCopyInto(&out.$.name$)\n", args) } case uft.Kind == types.Builtin: // the initial *out = *in was enough case uft.Kind == types.Map, uft.Kind == types.Slice, uft.Kind == types.Pointer: // Fixup non-nil reference-semantic types. sw.Do("if in.$.name$ != nil {\n", args) sw.Do("in, out := &in.$.name$, &out.$.name$\n", args) g.generateFor(ft, sw) sw.Do("}\n", nil) case uft.Kind == types.Struct: if ft.IsAssignable() { sw.Do("out.$.name$ = in.$.name$\n", args) } else { sw.Do("in.$.name$.DeepCopyInto(&out.$.name$)\n", args) } case uft.Kind == types.Interface: // Note: do not generate code that won't compile as `DeepCopyinterface{}()` is not a valid function if uft.Name.Name == "interface{}" { klog.Fatalf("DeepCopy of %q is unsupported. Instead, use named interfaces with DeepCopy<named-interface> as one of the methods.", uft.Name.Name) } sw.Do("if in.$.name$ != nil {\n", args) // Note: if t.Elem has been an alias "J" of an interface "I" in Go, we will see it // as kind Interface of name "J" here, i.e. generate val.DeepCopyJ(). The golang // parser does not give us the underlying interface name. So we cannot do any better. sw.Do(fmt.Sprintf("out.$.name$ = in.$.name$.DeepCopy%s()\n", uft.Name.Name), args) sw.Do("}\n", nil) default: klog.Fatalf("Hit an unsupported type %v for %v, from %v", uft, ft, t) } } }
go
func (g *genDeepCopy) doStruct(t *types.Type, sw *generator.SnippetWriter) { ut := underlyingType(t) if deepCopyMethodOrDie(t) != nil || deepCopyIntoMethodOrDie(t) != nil { sw.Do("*out = in.DeepCopy()\n", nil) return } // Simple copy covers a lot of cases. sw.Do("*out = *in\n", nil) // Now fix-up fields as needed. for _, m := range ut.Members { ft := m.Type uft := underlyingType(ft) args := generator.Args{ "type": ft, "kind": ft.Kind, "name": m.Name, } dc, dci := deepCopyMethodOrDie(ft), deepCopyIntoMethodOrDie(ft) switch { case dc != nil || dci != nil: // Note: a DeepCopyInto exists because it is added if DeepCopy is manually defined leftPointer := ft.Kind == types.Pointer rightPointer := !isReference(ft) if dc != nil { rightPointer = dc.Results[0].Kind == types.Pointer } if leftPointer == rightPointer { sw.Do("out.$.name$ = in.$.name$.DeepCopy()\n", args) } else if leftPointer { sw.Do("x := in.$.name$.DeepCopy()\n", args) sw.Do("out.$.name$ = = &x\n", args) } else { sw.Do("in.$.name$.DeepCopyInto(&out.$.name$)\n", args) } case uft.Kind == types.Builtin: // the initial *out = *in was enough case uft.Kind == types.Map, uft.Kind == types.Slice, uft.Kind == types.Pointer: // Fixup non-nil reference-semantic types. sw.Do("if in.$.name$ != nil {\n", args) sw.Do("in, out := &in.$.name$, &out.$.name$\n", args) g.generateFor(ft, sw) sw.Do("}\n", nil) case uft.Kind == types.Struct: if ft.IsAssignable() { sw.Do("out.$.name$ = in.$.name$\n", args) } else { sw.Do("in.$.name$.DeepCopyInto(&out.$.name$)\n", args) } case uft.Kind == types.Interface: // Note: do not generate code that won't compile as `DeepCopyinterface{}()` is not a valid function if uft.Name.Name == "interface{}" { klog.Fatalf("DeepCopy of %q is unsupported. Instead, use named interfaces with DeepCopy<named-interface> as one of the methods.", uft.Name.Name) } sw.Do("if in.$.name$ != nil {\n", args) // Note: if t.Elem has been an alias "J" of an interface "I" in Go, we will see it // as kind Interface of name "J" here, i.e. generate val.DeepCopyJ(). The golang // parser does not give us the underlying interface name. So we cannot do any better. sw.Do(fmt.Sprintf("out.$.name$ = in.$.name$.DeepCopy%s()\n", uft.Name.Name), args) sw.Do("}\n", nil) default: klog.Fatalf("Hit an unsupported type %v for %v, from %v", uft, ft, t) } } }
[ "func", "(", "g", "*", "genDeepCopy", ")", "doStruct", "(", "t", "*", "types", ".", "Type", ",", "sw", "*", "generator", ".", "SnippetWriter", ")", "{", "ut", ":=", "underlyingType", "(", "t", ")", "\n\n", "if", "deepCopyMethodOrDie", "(", "t", ")", ...
// doStruct generates code for a struct or an alias to a struct. The generated code is // is the same for both cases, i.e. it's the code for the underlying type.
[ "doStruct", "generates", "code", "for", "a", "struct", "or", "an", "alias", "to", "a", "struct", ".", "The", "generated", "code", "is", "is", "the", "same", "for", "both", "cases", "i", ".", "e", ".", "it", "s", "the", "code", "for", "the", "underlyi...
e17681d19d3ac4837a019ece36c2a0ec31ffe985
https://github.com/kubernetes/gengo/blob/e17681d19d3ac4837a019ece36c2a0ec31ffe985/examples/deepcopy-gen/generators/deepcopy.go#L821-L888
152,925
kubernetes/gengo
examples/deepcopy-gen/generators/deepcopy.go
doPointer
func (g *genDeepCopy) doPointer(t *types.Type, sw *generator.SnippetWriter) { ut := underlyingType(t) uet := underlyingType(ut.Elem) dc, dci := deepCopyMethodOrDie(ut.Elem), deepCopyIntoMethodOrDie(ut.Elem) switch { case dc != nil || dci != nil: rightPointer := !isReference(ut.Elem) if dc != nil { rightPointer = dc.Results[0].Kind == types.Pointer } if rightPointer { sw.Do("*out = (*in).DeepCopy()\n", nil) } else { sw.Do("x := (*in).DeepCopy()\n", nil) sw.Do("*out = &x\n", nil) } case uet.IsAssignable(): sw.Do("*out = new($.Elem|raw$)\n", ut) sw.Do("**out = **in", nil) case uet.Kind == types.Map, uet.Kind == types.Slice, uet.Kind == types.Pointer: sw.Do("*out = new($.Elem|raw$)\n", ut) sw.Do("if **in != nil {\n", nil) sw.Do("in, out := *in, *out\n", nil) g.generateFor(uet, sw) sw.Do("}\n", nil) case uet.Kind == types.Struct: sw.Do("*out = new($.Elem|raw$)\n", ut) sw.Do("(*in).DeepCopyInto(*out)\n", nil) default: klog.Fatalf("Hit an unsupported type %v for %v", uet, t) } }
go
func (g *genDeepCopy) doPointer(t *types.Type, sw *generator.SnippetWriter) { ut := underlyingType(t) uet := underlyingType(ut.Elem) dc, dci := deepCopyMethodOrDie(ut.Elem), deepCopyIntoMethodOrDie(ut.Elem) switch { case dc != nil || dci != nil: rightPointer := !isReference(ut.Elem) if dc != nil { rightPointer = dc.Results[0].Kind == types.Pointer } if rightPointer { sw.Do("*out = (*in).DeepCopy()\n", nil) } else { sw.Do("x := (*in).DeepCopy()\n", nil) sw.Do("*out = &x\n", nil) } case uet.IsAssignable(): sw.Do("*out = new($.Elem|raw$)\n", ut) sw.Do("**out = **in", nil) case uet.Kind == types.Map, uet.Kind == types.Slice, uet.Kind == types.Pointer: sw.Do("*out = new($.Elem|raw$)\n", ut) sw.Do("if **in != nil {\n", nil) sw.Do("in, out := *in, *out\n", nil) g.generateFor(uet, sw) sw.Do("}\n", nil) case uet.Kind == types.Struct: sw.Do("*out = new($.Elem|raw$)\n", ut) sw.Do("(*in).DeepCopyInto(*out)\n", nil) default: klog.Fatalf("Hit an unsupported type %v for %v", uet, t) } }
[ "func", "(", "g", "*", "genDeepCopy", ")", "doPointer", "(", "t", "*", "types", ".", "Type", ",", "sw", "*", "generator", ".", "SnippetWriter", ")", "{", "ut", ":=", "underlyingType", "(", "t", ")", "\n", "uet", ":=", "underlyingType", "(", "ut", "."...
// doPointer generates code for a pointer or an alias to a pointer. The generated code is // is the same for both cases, i.e. it's the code for the underlying type.
[ "doPointer", "generates", "code", "for", "a", "pointer", "or", "an", "alias", "to", "a", "pointer", ".", "The", "generated", "code", "is", "is", "the", "same", "for", "both", "cases", "i", ".", "e", ".", "it", "s", "the", "code", "for", "the", "under...
e17681d19d3ac4837a019ece36c2a0ec31ffe985
https://github.com/kubernetes/gengo/blob/e17681d19d3ac4837a019ece36c2a0ec31ffe985/examples/deepcopy-gen/generators/deepcopy.go#L892-L924
152,926
kubernetes/gengo
parser/parse.go
New
func New() *Builder { c := build.Default if c.GOROOT == "" { if p, err := exec.Command("which", "go").CombinedOutput(); err == nil { // The returned string will have some/path/bin/go, so remove the last two elements. c.GOROOT = filepath.Dir(filepath.Dir(strings.Trim(string(p), "\n"))) } else { klog.Warningf("Warning: $GOROOT not set, and unable to run `which go` to find it: %v\n", err) } } // Force this to off, since we don't properly parse CGo. All symbols must // have non-CGo equivalents. c.CgoEnabled = false return &Builder{ context: &c, buildPackages: map[string]*build.Package{}, typeCheckedPackages: map[importPathString]*tc.Package{}, fset: token.NewFileSet(), parsed: map[importPathString][]parsedFile{}, absPaths: map[importPathString]string{}, userRequested: map[importPathString]bool{}, endLineToCommentGroup: map[fileLine]*ast.CommentGroup{}, importGraph: map[importPathString]map[string]struct{}{}, } }
go
func New() *Builder { c := build.Default if c.GOROOT == "" { if p, err := exec.Command("which", "go").CombinedOutput(); err == nil { // The returned string will have some/path/bin/go, so remove the last two elements. c.GOROOT = filepath.Dir(filepath.Dir(strings.Trim(string(p), "\n"))) } else { klog.Warningf("Warning: $GOROOT not set, and unable to run `which go` to find it: %v\n", err) } } // Force this to off, since we don't properly parse CGo. All symbols must // have non-CGo equivalents. c.CgoEnabled = false return &Builder{ context: &c, buildPackages: map[string]*build.Package{}, typeCheckedPackages: map[importPathString]*tc.Package{}, fset: token.NewFileSet(), parsed: map[importPathString][]parsedFile{}, absPaths: map[importPathString]string{}, userRequested: map[importPathString]bool{}, endLineToCommentGroup: map[fileLine]*ast.CommentGroup{}, importGraph: map[importPathString]map[string]struct{}{}, } }
[ "func", "New", "(", ")", "*", "Builder", "{", "c", ":=", "build", ".", "Default", "\n", "if", "c", ".", "GOROOT", "==", "\"", "\"", "{", "if", "p", ",", "err", ":=", "exec", ".", "Command", "(", "\"", "\"", ",", "\"", "\"", ")", ".", "Combine...
// New constructs a new builder.
[ "New", "constructs", "a", "new", "builder", "." ]
e17681d19d3ac4837a019ece36c2a0ec31ffe985
https://github.com/kubernetes/gengo/blob/e17681d19d3ac4837a019ece36c2a0ec31ffe985/parser/parse.go#L85-L109
152,927
kubernetes/gengo
parser/parse.go
AddBuildTags
func (b *Builder) AddBuildTags(tags ...string) { b.context.BuildTags = append(b.context.BuildTags, tags...) }
go
func (b *Builder) AddBuildTags(tags ...string) { b.context.BuildTags = append(b.context.BuildTags, tags...) }
[ "func", "(", "b", "*", "Builder", ")", "AddBuildTags", "(", "tags", "...", "string", ")", "{", "b", ".", "context", ".", "BuildTags", "=", "append", "(", "b", ".", "context", ".", "BuildTags", ",", "tags", "...", ")", "\n", "}" ]
// AddBuildTags adds the specified build tags to the parse context.
[ "AddBuildTags", "adds", "the", "specified", "build", "tags", "to", "the", "parse", "context", "." ]
e17681d19d3ac4837a019ece36c2a0ec31ffe985
https://github.com/kubernetes/gengo/blob/e17681d19d3ac4837a019ece36c2a0ec31ffe985/parser/parse.go#L112-L114
152,928
kubernetes/gengo
parser/parse.go
AddDirRecursive
func (b *Builder) AddDirRecursive(dir string) error { // Add the root. if _, err := b.importPackage(dir, true); err != nil { klog.Warningf("Ignoring directory %v: %v", dir, err) } // filepath.Walk includes the root dir, but we already did that, so we'll // remove that prefix and rebuild a package import path. prefix := b.buildPackages[dir].Dir fn := func(filePath string, info os.FileInfo, err error) error { if info != nil && info.IsDir() { rel := filepath.ToSlash(strings.TrimPrefix(filePath, prefix)) if rel != "" { // Make a pkg path. pkg := path.Join(string(canonicalizeImportPath(b.buildPackages[dir].ImportPath)), rel) // Add it. if _, err := b.importPackage(pkg, true); err != nil { klog.Warningf("Ignoring child directory %v: %v", pkg, err) } } } return nil } if err := filepath.Walk(b.buildPackages[dir].Dir, fn); err != nil { return err } return nil }
go
func (b *Builder) AddDirRecursive(dir string) error { // Add the root. if _, err := b.importPackage(dir, true); err != nil { klog.Warningf("Ignoring directory %v: %v", dir, err) } // filepath.Walk includes the root dir, but we already did that, so we'll // remove that prefix and rebuild a package import path. prefix := b.buildPackages[dir].Dir fn := func(filePath string, info os.FileInfo, err error) error { if info != nil && info.IsDir() { rel := filepath.ToSlash(strings.TrimPrefix(filePath, prefix)) if rel != "" { // Make a pkg path. pkg := path.Join(string(canonicalizeImportPath(b.buildPackages[dir].ImportPath)), rel) // Add it. if _, err := b.importPackage(pkg, true); err != nil { klog.Warningf("Ignoring child directory %v: %v", pkg, err) } } } return nil } if err := filepath.Walk(b.buildPackages[dir].Dir, fn); err != nil { return err } return nil }
[ "func", "(", "b", "*", "Builder", ")", "AddDirRecursive", "(", "dir", "string", ")", "error", "{", "// Add the root.", "if", "_", ",", "err", ":=", "b", ".", "importPackage", "(", "dir", ",", "true", ")", ";", "err", "!=", "nil", "{", "klog", ".", ...
// AddDirRecursive is just like AddDir, but it also recursively adds // subdirectories; it returns an error only if the path couldn't be resolved; // any directories recursed into without go source are ignored.
[ "AddDirRecursive", "is", "just", "like", "AddDir", "but", "it", "also", "recursively", "adds", "subdirectories", ";", "it", "returns", "an", "error", "only", "if", "the", "path", "couldn", "t", "be", "resolved", ";", "any", "directories", "recursed", "into", ...
e17681d19d3ac4837a019ece36c2a0ec31ffe985
https://github.com/kubernetes/gengo/blob/e17681d19d3ac4837a019ece36c2a0ec31ffe985/parser/parse.go#L221-L249
152,929
kubernetes/gengo
parser/parse.go
addDir
func (b *Builder) addDir(dir string, userRequested bool) error { klog.V(5).Infof("addDir %s", dir) buildPkg, err := b.importBuildPackage(dir) if err != nil { return err } canonicalPackage := canonicalizeImportPath(buildPkg.ImportPath) pkgPath := canonicalPackage if dir != string(canonicalPackage) { klog.V(5).Infof("addDir %s, canonical path is %s", dir, pkgPath) } // Sanity check the pkg dir has not changed. if prev, found := b.absPaths[pkgPath]; found { if buildPkg.Dir != prev { return fmt.Errorf("package %q (%s) previously resolved to %s", pkgPath, buildPkg.Dir, prev) } } else { b.absPaths[pkgPath] = buildPkg.Dir } for _, n := range buildPkg.GoFiles { if !strings.HasSuffix(n, ".go") { continue } absPath := filepath.Join(buildPkg.Dir, n) data, err := ioutil.ReadFile(absPath) if err != nil { return fmt.Errorf("while loading %q: %v", absPath, err) } err = b.addFile(pkgPath, absPath, data, userRequested) if err != nil { return fmt.Errorf("while parsing %q: %v", absPath, err) } } return nil }
go
func (b *Builder) addDir(dir string, userRequested bool) error { klog.V(5).Infof("addDir %s", dir) buildPkg, err := b.importBuildPackage(dir) if err != nil { return err } canonicalPackage := canonicalizeImportPath(buildPkg.ImportPath) pkgPath := canonicalPackage if dir != string(canonicalPackage) { klog.V(5).Infof("addDir %s, canonical path is %s", dir, pkgPath) } // Sanity check the pkg dir has not changed. if prev, found := b.absPaths[pkgPath]; found { if buildPkg.Dir != prev { return fmt.Errorf("package %q (%s) previously resolved to %s", pkgPath, buildPkg.Dir, prev) } } else { b.absPaths[pkgPath] = buildPkg.Dir } for _, n := range buildPkg.GoFiles { if !strings.HasSuffix(n, ".go") { continue } absPath := filepath.Join(buildPkg.Dir, n) data, err := ioutil.ReadFile(absPath) if err != nil { return fmt.Errorf("while loading %q: %v", absPath, err) } err = b.addFile(pkgPath, absPath, data, userRequested) if err != nil { return fmt.Errorf("while parsing %q: %v", absPath, err) } } return nil }
[ "func", "(", "b", "*", "Builder", ")", "addDir", "(", "dir", "string", ",", "userRequested", "bool", ")", "error", "{", "klog", ".", "V", "(", "5", ")", ".", "Infof", "(", "\"", "\"", ",", "dir", ")", "\n", "buildPkg", ",", "err", ":=", "b", "....
// The implementation of AddDir. A flag indicates whether this directory was // user-requested or just from following the import graph.
[ "The", "implementation", "of", "AddDir", ".", "A", "flag", "indicates", "whether", "this", "directory", "was", "user", "-", "requested", "or", "just", "from", "following", "the", "import", "graph", "." ]
e17681d19d3ac4837a019ece36c2a0ec31ffe985
https://github.com/kubernetes/gengo/blob/e17681d19d3ac4837a019ece36c2a0ec31ffe985/parser/parse.go#L286-L322
152,930
kubernetes/gengo
parser/parse.go
importPackage
func (b *Builder) importPackage(dir string, userRequested bool) (*tc.Package, error) { klog.V(5).Infof("importPackage %s", dir) var pkgPath = importPathString(dir) // Get the canonical path if we can. if buildPkg := b.buildPackages[dir]; buildPkg != nil { canonicalPackage := canonicalizeImportPath(buildPkg.ImportPath) klog.V(5).Infof("importPackage %s, canonical path is %s", dir, canonicalPackage) pkgPath = canonicalPackage } // If we have not seen this before, process it now. ignoreError := false if _, found := b.parsed[pkgPath]; !found { // Ignore errors in paths that we're importing solely because // they're referenced by other packages. ignoreError = true // Add it. if err := b.addDir(dir, userRequested); err != nil { return nil, err } // Get the canonical path now that it has been added. if buildPkg := b.buildPackages[dir]; buildPkg != nil { canonicalPackage := canonicalizeImportPath(buildPkg.ImportPath) klog.V(5).Infof("importPackage %s, canonical path is %s", dir, canonicalPackage) pkgPath = canonicalPackage } } // If it was previously known, just check that the user-requestedness hasn't // changed. b.userRequested[pkgPath] = userRequested || b.userRequested[pkgPath] // Run the type checker. We may end up doing this to pkgs that are already // done, or are in the queue to be done later, but it will short-circuit, // and we can't miss pkgs that are only depended on. pkg, err := b.typeCheckPackage(pkgPath) if err != nil { switch { case ignoreError && pkg != nil: klog.V(2).Infof("type checking encountered some issues in %q, but ignoring.\n", pkgPath) case !ignoreError && pkg != nil: klog.V(2).Infof("type checking encountered some errors in %q\n", pkgPath) return nil, err default: return nil, err } } return pkg, nil }
go
func (b *Builder) importPackage(dir string, userRequested bool) (*tc.Package, error) { klog.V(5).Infof("importPackage %s", dir) var pkgPath = importPathString(dir) // Get the canonical path if we can. if buildPkg := b.buildPackages[dir]; buildPkg != nil { canonicalPackage := canonicalizeImportPath(buildPkg.ImportPath) klog.V(5).Infof("importPackage %s, canonical path is %s", dir, canonicalPackage) pkgPath = canonicalPackage } // If we have not seen this before, process it now. ignoreError := false if _, found := b.parsed[pkgPath]; !found { // Ignore errors in paths that we're importing solely because // they're referenced by other packages. ignoreError = true // Add it. if err := b.addDir(dir, userRequested); err != nil { return nil, err } // Get the canonical path now that it has been added. if buildPkg := b.buildPackages[dir]; buildPkg != nil { canonicalPackage := canonicalizeImportPath(buildPkg.ImportPath) klog.V(5).Infof("importPackage %s, canonical path is %s", dir, canonicalPackage) pkgPath = canonicalPackage } } // If it was previously known, just check that the user-requestedness hasn't // changed. b.userRequested[pkgPath] = userRequested || b.userRequested[pkgPath] // Run the type checker. We may end up doing this to pkgs that are already // done, or are in the queue to be done later, but it will short-circuit, // and we can't miss pkgs that are only depended on. pkg, err := b.typeCheckPackage(pkgPath) if err != nil { switch { case ignoreError && pkg != nil: klog.V(2).Infof("type checking encountered some issues in %q, but ignoring.\n", pkgPath) case !ignoreError && pkg != nil: klog.V(2).Infof("type checking encountered some errors in %q\n", pkgPath) return nil, err default: return nil, err } } return pkg, nil }
[ "func", "(", "b", "*", "Builder", ")", "importPackage", "(", "dir", "string", ",", "userRequested", "bool", ")", "(", "*", "tc", ".", "Package", ",", "error", ")", "{", "klog", ".", "V", "(", "5", ")", ".", "Infof", "(", "\"", "\"", ",", "dir", ...
// importPackage is a function that will be called by the type check package when it // needs to import a go package. 'path' is the import path.
[ "importPackage", "is", "a", "function", "that", "will", "be", "called", "by", "the", "type", "check", "package", "when", "it", "needs", "to", "import", "a", "go", "package", ".", "path", "is", "the", "import", "path", "." ]
e17681d19d3ac4837a019ece36c2a0ec31ffe985
https://github.com/kubernetes/gengo/blob/e17681d19d3ac4837a019ece36c2a0ec31ffe985/parser/parse.go#L326-L378
152,931
kubernetes/gengo
parser/parse.go
typeCheckPackage
func (b *Builder) typeCheckPackage(pkgPath importPathString) (*tc.Package, error) { klog.V(5).Infof("typeCheckPackage %s", pkgPath) if pkg, ok := b.typeCheckedPackages[pkgPath]; ok { if pkg != nil { klog.V(6).Infof("typeCheckPackage %s already done", pkgPath) return pkg, nil } // We store a nil right before starting work on a package. So // if we get here and it's present and nil, that means there's // another invocation of this function on the call stack // already processing this package. return nil, fmt.Errorf("circular dependency for %q", pkgPath) } parsedFiles, ok := b.parsed[pkgPath] if !ok { return nil, fmt.Errorf("No files for pkg %q", pkgPath) } files := make([]*ast.File, len(parsedFiles)) for i := range parsedFiles { files[i] = parsedFiles[i].file } b.typeCheckedPackages[pkgPath] = nil c := tc.Config{ IgnoreFuncBodies: true, // Note that importAdapter can call b.importPackage which calls this // method. So there can't be cycles in the import graph. Importer: importAdapter{b}, Error: func(err error) { klog.V(2).Infof("type checker: %v\n", err) }, } pkg, err := c.Check(string(pkgPath), b.fset, files, nil) b.typeCheckedPackages[pkgPath] = pkg // record the result whether or not there was an error return pkg, err }
go
func (b *Builder) typeCheckPackage(pkgPath importPathString) (*tc.Package, error) { klog.V(5).Infof("typeCheckPackage %s", pkgPath) if pkg, ok := b.typeCheckedPackages[pkgPath]; ok { if pkg != nil { klog.V(6).Infof("typeCheckPackage %s already done", pkgPath) return pkg, nil } // We store a nil right before starting work on a package. So // if we get here and it's present and nil, that means there's // another invocation of this function on the call stack // already processing this package. return nil, fmt.Errorf("circular dependency for %q", pkgPath) } parsedFiles, ok := b.parsed[pkgPath] if !ok { return nil, fmt.Errorf("No files for pkg %q", pkgPath) } files := make([]*ast.File, len(parsedFiles)) for i := range parsedFiles { files[i] = parsedFiles[i].file } b.typeCheckedPackages[pkgPath] = nil c := tc.Config{ IgnoreFuncBodies: true, // Note that importAdapter can call b.importPackage which calls this // method. So there can't be cycles in the import graph. Importer: importAdapter{b}, Error: func(err error) { klog.V(2).Infof("type checker: %v\n", err) }, } pkg, err := c.Check(string(pkgPath), b.fset, files, nil) b.typeCheckedPackages[pkgPath] = pkg // record the result whether or not there was an error return pkg, err }
[ "func", "(", "b", "*", "Builder", ")", "typeCheckPackage", "(", "pkgPath", "importPathString", ")", "(", "*", "tc", ".", "Package", ",", "error", ")", "{", "klog", ".", "V", "(", "5", ")", ".", "Infof", "(", "\"", "\"", ",", "pkgPath", ")", "\n", ...
// typeCheckPackage will attempt to return the package even if there are some // errors, so you may check whether the package is nil or not even if you get // an error.
[ "typeCheckPackage", "will", "attempt", "to", "return", "the", "package", "even", "if", "there", "are", "some", "errors", "so", "you", "may", "check", "whether", "the", "package", "is", "nil", "or", "not", "even", "if", "you", "get", "an", "error", "." ]
e17681d19d3ac4837a019ece36c2a0ec31ffe985
https://github.com/kubernetes/gengo/blob/e17681d19d3ac4837a019ece36c2a0ec31ffe985/parser/parse.go#L391-L425
152,932
kubernetes/gengo
parser/parse.go
FindTypes
func (b *Builder) FindTypes() (types.Universe, error) { // Take a snapshot of pkgs to iterate, since this will recursively mutate // b.parsed. Iterate in a predictable order. pkgPaths := []string{} for pkgPath := range b.parsed { pkgPaths = append(pkgPaths, string(pkgPath)) } sort.Strings(pkgPaths) u := types.Universe{} for _, pkgPath := range pkgPaths { if err := b.findTypesIn(importPathString(pkgPath), &u); err != nil { return nil, err } } return u, nil }
go
func (b *Builder) FindTypes() (types.Universe, error) { // Take a snapshot of pkgs to iterate, since this will recursively mutate // b.parsed. Iterate in a predictable order. pkgPaths := []string{} for pkgPath := range b.parsed { pkgPaths = append(pkgPaths, string(pkgPath)) } sort.Strings(pkgPaths) u := types.Universe{} for _, pkgPath := range pkgPaths { if err := b.findTypesIn(importPathString(pkgPath), &u); err != nil { return nil, err } } return u, nil }
[ "func", "(", "b", "*", "Builder", ")", "FindTypes", "(", ")", "(", "types", ".", "Universe", ",", "error", ")", "{", "// Take a snapshot of pkgs to iterate, since this will recursively mutate", "// b.parsed. Iterate in a predictable order.", "pkgPaths", ":=", "[", "]", ...
// FindTypes finalizes the package imports, and searches through all the // packages for types.
[ "FindTypes", "finalizes", "the", "package", "imports", "and", "searches", "through", "all", "the", "packages", "for", "types", "." ]
e17681d19d3ac4837a019ece36c2a0ec31ffe985
https://github.com/kubernetes/gengo/blob/e17681d19d3ac4837a019ece36c2a0ec31ffe985/parser/parse.go#L451-L467
152,933
kubernetes/gengo
parser/parse.go
priorCommentLines
func (b *Builder) priorCommentLines(pos token.Pos, lines int) *ast.CommentGroup { position := b.fset.Position(pos) key := fileLine{position.Filename, position.Line - lines} return b.endLineToCommentGroup[key] }
go
func (b *Builder) priorCommentLines(pos token.Pos, lines int) *ast.CommentGroup { position := b.fset.Position(pos) key := fileLine{position.Filename, position.Line - lines} return b.endLineToCommentGroup[key] }
[ "func", "(", "b", "*", "Builder", ")", "priorCommentLines", "(", "pos", "token", ".", "Pos", ",", "lines", "int", ")", "*", "ast", ".", "CommentGroup", "{", "position", ":=", "b", ".", "fset", ".", "Position", "(", "pos", ")", "\n", "key", ":=", "f...
// if there's a comment on the line `lines` before pos, return its text, otherwise "".
[ "if", "there", "s", "a", "comment", "on", "the", "line", "lines", "before", "pos", "return", "its", "text", "otherwise", "." ]
e17681d19d3ac4837a019ece36c2a0ec31ffe985
https://github.com/kubernetes/gengo/blob/e17681d19d3ac4837a019ece36c2a0ec31ffe985/parser/parse.go#L571-L575
152,934
kubernetes/gengo
parser/parse.go
canonicalizeImportPath
func canonicalizeImportPath(importPath string) importPathString { if !strings.Contains(importPath, "/vendor/") { return importPathString(importPath) } return importPathString(importPath[strings.Index(importPath, "/vendor/")+len("/vendor/"):]) }
go
func canonicalizeImportPath(importPath string) importPathString { if !strings.Contains(importPath, "/vendor/") { return importPathString(importPath) } return importPathString(importPath[strings.Index(importPath, "/vendor/")+len("/vendor/"):]) }
[ "func", "canonicalizeImportPath", "(", "importPath", "string", ")", "importPathString", "{", "if", "!", "strings", ".", "Contains", "(", "importPath", ",", "\"", "\"", ")", "{", "return", "importPathString", "(", "importPath", ")", "\n", "}", "\n\n", "return",...
// canonicalizeImportPath takes an import path and returns the actual package. // It doesn't support nested vendoring.
[ "canonicalizeImportPath", "takes", "an", "import", "path", "and", "returns", "the", "actual", "package", ".", "It", "doesn", "t", "support", "nested", "vendoring", "." ]
e17681d19d3ac4837a019ece36c2a0ec31ffe985
https://github.com/kubernetes/gengo/blob/e17681d19d3ac4837a019ece36c2a0ec31ffe985/parser/parse.go#L807-L813
152,935
kubernetes/gengo
namer/namer.go
IsPrivateGoName
func IsPrivateGoName(name string) bool { return len(name) == 0 || strings.ToLower(name[:1]) == name[:1] }
go
func IsPrivateGoName(name string) bool { return len(name) == 0 || strings.ToLower(name[:1]) == name[:1] }
[ "func", "IsPrivateGoName", "(", "name", "string", ")", "bool", "{", "return", "len", "(", "name", ")", "==", "0", "||", "strings", ".", "ToLower", "(", "name", "[", ":", "1", "]", ")", "==", "name", "[", ":", "1", "]", "\n", "}" ]
// Returns whether a name is a private Go name.
[ "Returns", "whether", "a", "name", "is", "a", "private", "Go", "name", "." ]
e17681d19d3ac4837a019ece36c2a0ec31ffe985
https://github.com/kubernetes/gengo/blob/e17681d19d3ac4837a019ece36c2a0ec31ffe985/namer/namer.go#L38-L40
152,936
kubernetes/gengo
namer/namer.go
NewPublicNamer
func NewPublicNamer(prependPackageNames int, ignoreWords ...string) *NameStrategy { n := &NameStrategy{ Join: Joiner(IC, IC), IgnoreWords: map[string]bool{}, PrependPackageNames: prependPackageNames, } for _, w := range ignoreWords { n.IgnoreWords[w] = true } return n }
go
func NewPublicNamer(prependPackageNames int, ignoreWords ...string) *NameStrategy { n := &NameStrategy{ Join: Joiner(IC, IC), IgnoreWords: map[string]bool{}, PrependPackageNames: prependPackageNames, } for _, w := range ignoreWords { n.IgnoreWords[w] = true } return n }
[ "func", "NewPublicNamer", "(", "prependPackageNames", "int", ",", "ignoreWords", "...", "string", ")", "*", "NameStrategy", "{", "n", ":=", "&", "NameStrategy", "{", "Join", ":", "Joiner", "(", "IC", ",", "IC", ")", ",", "IgnoreWords", ":", "map", "[", "...
// NewPublicNamer is a helper function that returns a namer that makes // CamelCase names. See the NameStrategy struct for an explanation of the // arguments to this constructor.
[ "NewPublicNamer", "is", "a", "helper", "function", "that", "returns", "a", "namer", "that", "makes", "CamelCase", "names", ".", "See", "the", "NameStrategy", "struct", "for", "an", "explanation", "of", "the", "arguments", "to", "this", "constructor", "." ]
e17681d19d3ac4837a019ece36c2a0ec31ffe985
https://github.com/kubernetes/gengo/blob/e17681d19d3ac4837a019ece36c2a0ec31ffe985/namer/namer.go#L45-L55
152,937
kubernetes/gengo
namer/namer.go
IC
func IC(in string) string { if in == "" { return in } return strings.ToUpper(in[:1]) + in[1:] }
go
func IC(in string) string { if in == "" { return in } return strings.ToUpper(in[:1]) + in[1:] }
[ "func", "IC", "(", "in", "string", ")", "string", "{", "if", "in", "==", "\"", "\"", "{", "return", "in", "\n", "}", "\n", "return", "strings", ".", "ToUpper", "(", "in", "[", ":", "1", "]", ")", "+", "in", "[", "1", ":", "]", "\n", "}" ]
// IC ensures the first character is uppercase.
[ "IC", "ensures", "the", "first", "character", "is", "uppercase", "." ]
e17681d19d3ac4837a019ece36c2a0ec31ffe985
https://github.com/kubernetes/gengo/blob/e17681d19d3ac4837a019ece36c2a0ec31ffe985/namer/namer.go#L151-L156
152,938
kubernetes/gengo
namer/namer.go
IL
func IL(in string) string { if in == "" { return in } return strings.ToLower(in[:1]) + in[1:] }
go
func IL(in string) string { if in == "" { return in } return strings.ToLower(in[:1]) + in[1:] }
[ "func", "IL", "(", "in", "string", ")", "string", "{", "if", "in", "==", "\"", "\"", "{", "return", "in", "\n", "}", "\n", "return", "strings", ".", "ToLower", "(", "in", "[", ":", "1", "]", ")", "+", "in", "[", "1", ":", "]", "\n", "}" ]
// IL ensures the first character is lowercase.
[ "IL", "ensures", "the", "first", "character", "is", "lowercase", "." ]
e17681d19d3ac4837a019ece36c2a0ec31ffe985
https://github.com/kubernetes/gengo/blob/e17681d19d3ac4837a019ece36c2a0ec31ffe985/namer/namer.go#L159-L164
152,939
kubernetes/gengo
namer/namer.go
filterDirs
func (ns *NameStrategy) filterDirs(path string) []string { allDirs := strings.Split(path, GoSeperator) dirs := make([]string, 0, len(allDirs)) for _, p := range allDirs { if ns.IgnoreWords == nil || !ns.IgnoreWords[p] { dirs = append(dirs, importPathNameSanitizer.Replace(p)) } } return dirs }
go
func (ns *NameStrategy) filterDirs(path string) []string { allDirs := strings.Split(path, GoSeperator) dirs := make([]string, 0, len(allDirs)) for _, p := range allDirs { if ns.IgnoreWords == nil || !ns.IgnoreWords[p] { dirs = append(dirs, importPathNameSanitizer.Replace(p)) } } return dirs }
[ "func", "(", "ns", "*", "NameStrategy", ")", "filterDirs", "(", "path", "string", ")", "[", "]", "string", "{", "allDirs", ":=", "strings", ".", "Split", "(", "path", ",", "GoSeperator", ")", "\n", "dirs", ":=", "make", "(", "[", "]", "string", ",", ...
// filters out unwanted directory names and sanitizes remaining names.
[ "filters", "out", "unwanted", "directory", "names", "and", "sanitizes", "remaining", "names", "." ]
e17681d19d3ac4837a019ece36c2a0ec31ffe985
https://github.com/kubernetes/gengo/blob/e17681d19d3ac4837a019ece36c2a0ec31ffe985/namer/namer.go#L200-L209
152,940
kubernetes/gengo
generator/snippet_writer.go
NewSnippetWriter
func NewSnippetWriter(w io.Writer, c *Context, left, right string) *SnippetWriter { sw := &SnippetWriter{ w: w, context: c, left: left, right: right, funcMap: template.FuncMap{}, } for name, namer := range c.Namers { sw.funcMap[name] = namer.Name } return sw }
go
func NewSnippetWriter(w io.Writer, c *Context, left, right string) *SnippetWriter { sw := &SnippetWriter{ w: w, context: c, left: left, right: right, funcMap: template.FuncMap{}, } for name, namer := range c.Namers { sw.funcMap[name] = namer.Name } return sw }
[ "func", "NewSnippetWriter", "(", "w", "io", ".", "Writer", ",", "c", "*", "Context", ",", "left", ",", "right", "string", ")", "*", "SnippetWriter", "{", "sw", ":=", "&", "SnippetWriter", "{", "w", ":", "w", ",", "context", ":", "c", ",", "left", "...
// w is the destination; left and right are the delimiters; @ and $ are both // reasonable choices. // // c is used to make a function for every naming system, to which you can pass // a type and get the corresponding name.
[ "w", "is", "the", "destination", ";", "left", "and", "right", "are", "the", "delimiters", ";" ]
e17681d19d3ac4837a019ece36c2a0ec31ffe985
https://github.com/kubernetes/gengo/blob/e17681d19d3ac4837a019ece36c2a0ec31ffe985/generator/snippet_writer.go#L44-L56
152,941
kubernetes/gengo
generator/snippet_writer.go
With
func (a Args) With(key, value interface{}) Args { a2 := Args{key: value} for k, v := range a { a2[k] = v } return a2 }
go
func (a Args) With(key, value interface{}) Args { a2 := Args{key: value} for k, v := range a { a2[k] = v } return a2 }
[ "func", "(", "a", "Args", ")", "With", "(", "key", ",", "value", "interface", "{", "}", ")", "Args", "{", "a2", ":=", "Args", "{", "key", ":", "value", "}", "\n", "for", "k", ",", "v", ":=", "range", "a", "{", "a2", "[", "k", "]", "=", "v",...
// With makes a copy of a and adds the given key, value pair.
[ "With", "makes", "a", "copy", "of", "a", "and", "adds", "the", "given", "key", "value", "pair", "." ]
e17681d19d3ac4837a019ece36c2a0ec31ffe985
https://github.com/kubernetes/gengo/blob/e17681d19d3ac4837a019ece36c2a0ec31ffe985/generator/snippet_writer.go#L127-L133
152,942
kubernetes/gengo
generator/snippet_writer.go
WithArgs
func (a Args) WithArgs(rhs Args) Args { a2 := Args{} for k, v := range rhs { a2[k] = v } for k, v := range a { a2[k] = v } return a2 }
go
func (a Args) WithArgs(rhs Args) Args { a2 := Args{} for k, v := range rhs { a2[k] = v } for k, v := range a { a2[k] = v } return a2 }
[ "func", "(", "a", "Args", ")", "WithArgs", "(", "rhs", "Args", ")", "Args", "{", "a2", ":=", "Args", "{", "}", "\n", "for", "k", ",", "v", ":=", "range", "rhs", "{", "a2", "[", "k", "]", "=", "v", "\n", "}", "\n", "for", "k", ",", "v", ":...
// WithArgs makes a copy of a and adds the given arguments.
[ "WithArgs", "makes", "a", "copy", "of", "a", "and", "adds", "the", "given", "arguments", "." ]
e17681d19d3ac4837a019ece36c2a0ec31ffe985
https://github.com/kubernetes/gengo/blob/e17681d19d3ac4837a019ece36c2a0ec31ffe985/generator/snippet_writer.go#L136-L145
152,943
kubernetes/gengo
namer/order.go
OrderUniverse
func (o *Orderer) OrderUniverse(u types.Universe) []*types.Type { list := tList{ namer: o.Namer, } for _, p := range u { for _, t := range p.Types { list.types = append(list.types, t) } for _, f := range p.Functions { list.types = append(list.types, f) } for _, v := range p.Variables { list.types = append(list.types, v) } } sort.Sort(list) return list.types }
go
func (o *Orderer) OrderUniverse(u types.Universe) []*types.Type { list := tList{ namer: o.Namer, } for _, p := range u { for _, t := range p.Types { list.types = append(list.types, t) } for _, f := range p.Functions { list.types = append(list.types, f) } for _, v := range p.Variables { list.types = append(list.types, v) } } sort.Sort(list) return list.types }
[ "func", "(", "o", "*", "Orderer", ")", "OrderUniverse", "(", "u", "types", ".", "Universe", ")", "[", "]", "*", "types", ".", "Type", "{", "list", ":=", "tList", "{", "namer", ":", "o", ".", "Namer", ",", "}", "\n", "for", "_", ",", "p", ":=", ...
// OrderUniverse assigns a name to every type in the Universe, including Types, // Functions and Variables, and returns a list sorted by those names.
[ "OrderUniverse", "assigns", "a", "name", "to", "every", "type", "in", "the", "Universe", "including", "Types", "Functions", "and", "Variables", "and", "returns", "a", "list", "sorted", "by", "those", "names", "." ]
e17681d19d3ac4837a019ece36c2a0ec31ffe985
https://github.com/kubernetes/gengo/blob/e17681d19d3ac4837a019ece36c2a0ec31ffe985/namer/order.go#L32-L49
152,944
kubernetes/gengo
namer/order.go
OrderTypes
func (o *Orderer) OrderTypes(typeList []*types.Type) []*types.Type { list := tList{ namer: o.Namer, types: typeList, } sort.Sort(list) return list.types }
go
func (o *Orderer) OrderTypes(typeList []*types.Type) []*types.Type { list := tList{ namer: o.Namer, types: typeList, } sort.Sort(list) return list.types }
[ "func", "(", "o", "*", "Orderer", ")", "OrderTypes", "(", "typeList", "[", "]", "*", "types", ".", "Type", ")", "[", "]", "*", "types", ".", "Type", "{", "list", ":=", "tList", "{", "namer", ":", "o", ".", "Namer", ",", "types", ":", "typeList", ...
// OrderTypes assigns a name to every type, and returns a list sorted by those // names.
[ "OrderTypes", "assigns", "a", "name", "to", "every", "type", "and", "returns", "a", "list", "sorted", "by", "those", "names", "." ]
e17681d19d3ac4837a019ece36c2a0ec31ffe985
https://github.com/kubernetes/gengo/blob/e17681d19d3ac4837a019ece36c2a0ec31ffe985/namer/order.go#L53-L60
152,945
kubernetes/gengo
generator/execute.go
addIndentHeaderComment
func addIndentHeaderComment(b *bytes.Buffer, format string, args ...interface{}) { if b.Len() > 0 { fmt.Fprintf(b, "\n// "+format+"\n", args...) } else { fmt.Fprintf(b, "// "+format+"\n", args...) } }
go
func addIndentHeaderComment(b *bytes.Buffer, format string, args ...interface{}) { if b.Len() > 0 { fmt.Fprintf(b, "\n// "+format+"\n", args...) } else { fmt.Fprintf(b, "// "+format+"\n", args...) } }
[ "func", "addIndentHeaderComment", "(", "b", "*", "bytes", ".", "Buffer", ",", "format", "string", ",", "args", "...", "interface", "{", "}", ")", "{", "if", "b", ".", "Len", "(", ")", ">", "0", "{", "fmt", ".", "Fprintf", "(", "b", ",", "\"", "\\...
// format should be one line only, and not end with \n.
[ "format", "should", "be", "one", "line", "only", "and", "not", "end", "with", "\\", "n", "." ]
e17681d19d3ac4837a019ece36c2a0ec31ffe985
https://github.com/kubernetes/gengo/blob/e17681d19d3ac4837a019ece36c2a0ec31ffe985/generator/execute.go#L173-L179
152,946
kubernetes/gengo
generator/execute.go
addNameSystems
func (c *Context) addNameSystems(namers namer.NameSystems) *Context { if namers == nil { return c } c2 := *c // Copy the existing name systems so we don't corrupt a parent context c2.Namers = namer.NameSystems{} for k, v := range c.Namers { c2.Namers[k] = v } for name, namer := range namers { c2.Namers[name] = namer } return &c2 }
go
func (c *Context) addNameSystems(namers namer.NameSystems) *Context { if namers == nil { return c } c2 := *c // Copy the existing name systems so we don't corrupt a parent context c2.Namers = namer.NameSystems{} for k, v := range c.Namers { c2.Namers[k] = v } for name, namer := range namers { c2.Namers[name] = namer } return &c2 }
[ "func", "(", "c", "*", "Context", ")", "addNameSystems", "(", "namers", "namer", ".", "NameSystems", ")", "*", "Context", "{", "if", "namers", "==", "nil", "{", "return", "c", "\n", "}", "\n", "c2", ":=", "*", "c", "\n", "// Copy the existing name system...
// make a new context; inheret c.Namers, but add on 'namers'. In case of a name // collision, the namer in 'namers' wins.
[ "make", "a", "new", "context", ";", "inheret", "c", ".", "Namers", "but", "add", "on", "namers", ".", "In", "case", "of", "a", "name", "collision", "the", "namer", "in", "namers", "wins", "." ]
e17681d19d3ac4837a019ece36c2a0ec31ffe985
https://github.com/kubernetes/gengo/blob/e17681d19d3ac4837a019ece36c2a0ec31ffe985/generator/execute.go#L194-L209
152,947
kubernetes/gengo
namer/import_tracker.go
PathOf
func (tracker *DefaultImportTracker) PathOf(localName string) (string, bool) { name, ok := tracker.nameToPath[localName] return name, ok }
go
func (tracker *DefaultImportTracker) PathOf(localName string) (string, bool) { name, ok := tracker.nameToPath[localName] return name, ok }
[ "func", "(", "tracker", "*", "DefaultImportTracker", ")", "PathOf", "(", "localName", "string", ")", "(", "string", ",", "bool", ")", "{", "name", ",", "ok", ":=", "tracker", ".", "nameToPath", "[", "localName", "]", "\n", "return", "name", ",", "ok", ...
// PathOf returns the path that a given localName is referring to within the // body of a file.
[ "PathOf", "returns", "the", "path", "that", "a", "given", "localName", "is", "referring", "to", "within", "the", "body", "of", "a", "file", "." ]
e17681d19d3ac4837a019ece36c2a0ec31ffe985
https://github.com/kubernetes/gengo/blob/e17681d19d3ac4837a019ece36c2a0ec31ffe985/namer/import_tracker.go#L109-L112
152,948
kubernetes/gengo
generator/generator.go
NewContext
func NewContext(b *parser.Builder, nameSystems namer.NameSystems, canonicalOrderName string) (*Context, error) { universe, err := b.FindTypes() if err != nil { return nil, err } c := &Context{ Namers: namer.NameSystems{}, Universe: universe, Inputs: b.FindPackages(), FileTypes: map[string]FileType{ GolangFileType: NewGolangFile(), }, builder: b, } for name, systemNamer := range nameSystems { c.Namers[name] = systemNamer if name == canonicalOrderName { orderer := namer.Orderer{Namer: systemNamer} c.Order = orderer.OrderUniverse(universe) } } return c, nil }
go
func NewContext(b *parser.Builder, nameSystems namer.NameSystems, canonicalOrderName string) (*Context, error) { universe, err := b.FindTypes() if err != nil { return nil, err } c := &Context{ Namers: namer.NameSystems{}, Universe: universe, Inputs: b.FindPackages(), FileTypes: map[string]FileType{ GolangFileType: NewGolangFile(), }, builder: b, } for name, systemNamer := range nameSystems { c.Namers[name] = systemNamer if name == canonicalOrderName { orderer := namer.Orderer{Namer: systemNamer} c.Order = orderer.OrderUniverse(universe) } } return c, nil }
[ "func", "NewContext", "(", "b", "*", "parser", ".", "Builder", ",", "nameSystems", "namer", ".", "NameSystems", ",", "canonicalOrderName", "string", ")", "(", "*", "Context", ",", "error", ")", "{", "universe", ",", "err", ":=", "b", ".", "FindTypes", "(...
// NewContext generates a context from the given builder, naming systems, and // the naming system you wish to construct the canonical ordering from.
[ "NewContext", "generates", "a", "context", "from", "the", "given", "builder", "naming", "systems", "and", "the", "naming", "system", "you", "wish", "to", "construct", "the", "canonical", "ordering", "from", "." ]
e17681d19d3ac4837a019ece36c2a0ec31ffe985
https://github.com/kubernetes/gengo/blob/e17681d19d3ac4837a019ece36c2a0ec31ffe985/generator/generator.go#L180-L204
152,949
kubernetes/gengo
generator/error_tracker.go
Write
func (et *ErrorTracker) Write(p []byte) (n int, err error) { if et.err != nil { return 0, et.err } n, err = et.Writer.Write(p) if err != nil { et.err = err } return n, err }
go
func (et *ErrorTracker) Write(p []byte) (n int, err error) { if et.err != nil { return 0, et.err } n, err = et.Writer.Write(p) if err != nil { et.err = err } return n, err }
[ "func", "(", "et", "*", "ErrorTracker", ")", "Write", "(", "p", "[", "]", "byte", ")", "(", "n", "int", ",", "err", "error", ")", "{", "if", "et", ".", "err", "!=", "nil", "{", "return", "0", ",", "et", ".", "err", "\n", "}", "\n", "n", ","...
// Write intercepts calls to Write.
[ "Write", "intercepts", "calls", "to", "Write", "." ]
e17681d19d3ac4837a019ece36c2a0ec31ffe985
https://github.com/kubernetes/gengo/blob/e17681d19d3ac4837a019ece36c2a0ec31ffe985/generator/error_tracker.go#L36-L45
152,950
kubernetes/gengo
types/types.go
String
func (n Name) String() string { if n.Package == "" { return n.Name } return n.Package + "." + n.Name }
go
func (n Name) String() string { if n.Package == "" { return n.Name } return n.Package + "." + n.Name }
[ "func", "(", "n", "Name", ")", "String", "(", ")", "string", "{", "if", "n", ".", "Package", "==", "\"", "\"", "{", "return", "n", ".", "Name", "\n", "}", "\n", "return", "n", ".", "Package", "+", "\"", "\"", "+", "n", ".", "Name", "\n", "}" ...
// String returns the name formatted as a string.
[ "String", "returns", "the", "name", "formatted", "as", "a", "string", "." ]
e17681d19d3ac4837a019ece36c2a0ec31ffe985
https://github.com/kubernetes/gengo/blob/e17681d19d3ac4837a019ece36c2a0ec31ffe985/types/types.go#L42-L47
152,951
kubernetes/gengo
types/types.go
Has
func (p *Package) Has(name string) bool { _, has := p.Types[name] return has }
go
func (p *Package) Has(name string) bool { _, has := p.Types[name] return has }
[ "func", "(", "p", "*", "Package", ")", "Has", "(", "name", "string", ")", "bool", "{", "_", ",", "has", ":=", "p", ".", "Types", "[", "name", "]", "\n", "return", "has", "\n", "}" ]
// Has returns true if the given name references a type known to this package.
[ "Has", "returns", "true", "if", "the", "given", "name", "references", "a", "type", "known", "to", "this", "package", "." ]
e17681d19d3ac4837a019ece36c2a0ec31ffe985
https://github.com/kubernetes/gengo/blob/e17681d19d3ac4837a019ece36c2a0ec31ffe985/types/types.go#L144-L147
152,952
kubernetes/gengo
types/types.go
Type
func (p *Package) Type(typeName string) *Type { if t, ok := p.Types[typeName]; ok { return t } if p.Path == "" { // Import the standard builtin types! if t, ok := builtins.Types[typeName]; ok { p.Types[typeName] = t return t } } t := &Type{Name: Name{Package: p.Path, Name: typeName}} p.Types[typeName] = t return t }
go
func (p *Package) Type(typeName string) *Type { if t, ok := p.Types[typeName]; ok { return t } if p.Path == "" { // Import the standard builtin types! if t, ok := builtins.Types[typeName]; ok { p.Types[typeName] = t return t } } t := &Type{Name: Name{Package: p.Path, Name: typeName}} p.Types[typeName] = t return t }
[ "func", "(", "p", "*", "Package", ")", "Type", "(", "typeName", "string", ")", "*", "Type", "{", "if", "t", ",", "ok", ":=", "p", ".", "Types", "[", "typeName", "]", ";", "ok", "{", "return", "t", "\n", "}", "\n", "if", "p", ".", "Path", "=="...
// Type gets the given Type in this Package. If the Type is not already // defined, this will add it and return the new Type value. The caller is // expected to finish initialization.
[ "Type", "gets", "the", "given", "Type", "in", "this", "Package", ".", "If", "the", "Type", "is", "not", "already", "defined", "this", "will", "add", "it", "and", "return", "the", "new", "Type", "value", ".", "The", "caller", "is", "expected", "to", "fi...
e17681d19d3ac4837a019ece36c2a0ec31ffe985
https://github.com/kubernetes/gengo/blob/e17681d19d3ac4837a019ece36c2a0ec31ffe985/types/types.go#L152-L166
152,953
kubernetes/gengo
types/types.go
Function
func (p *Package) Function(funcName string) *Type { if t, ok := p.Functions[funcName]; ok { return t } t := &Type{Name: Name{Package: p.Path, Name: funcName}} t.Kind = DeclarationOf p.Functions[funcName] = t return t }
go
func (p *Package) Function(funcName string) *Type { if t, ok := p.Functions[funcName]; ok { return t } t := &Type{Name: Name{Package: p.Path, Name: funcName}} t.Kind = DeclarationOf p.Functions[funcName] = t return t }
[ "func", "(", "p", "*", "Package", ")", "Function", "(", "funcName", "string", ")", "*", "Type", "{", "if", "t", ",", "ok", ":=", "p", ".", "Functions", "[", "funcName", "]", ";", "ok", "{", "return", "t", "\n", "}", "\n", "t", ":=", "&", "Type"...
// Function gets the given function Type in this Package. If the function is // not already defined, this will add it. If a function is added, it's the // caller's responsibility to finish construction of the function by setting // Underlying to the correct type.
[ "Function", "gets", "the", "given", "function", "Type", "in", "this", "Package", ".", "If", "the", "function", "is", "not", "already", "defined", "this", "will", "add", "it", ".", "If", "a", "function", "is", "added", "it", "s", "the", "caller", "s", "...
e17681d19d3ac4837a019ece36c2a0ec31ffe985
https://github.com/kubernetes/gengo/blob/e17681d19d3ac4837a019ece36c2a0ec31ffe985/types/types.go#L172-L180
152,954
kubernetes/gengo
types/types.go
Variable
func (p *Package) Variable(varName string) *Type { if t, ok := p.Variables[varName]; ok { return t } t := &Type{Name: Name{Package: p.Path, Name: varName}} t.Kind = DeclarationOf p.Variables[varName] = t return t }
go
func (p *Package) Variable(varName string) *Type { if t, ok := p.Variables[varName]; ok { return t } t := &Type{Name: Name{Package: p.Path, Name: varName}} t.Kind = DeclarationOf p.Variables[varName] = t return t }
[ "func", "(", "p", "*", "Package", ")", "Variable", "(", "varName", "string", ")", "*", "Type", "{", "if", "t", ",", "ok", ":=", "p", ".", "Variables", "[", "varName", "]", ";", "ok", "{", "return", "t", "\n", "}", "\n", "t", ":=", "&", "Type", ...
// Variable gets the given variable Type in this Package. If the variable is // not already defined, this will add it. If a variable is added, it's the caller's // responsibility to finish construction of the variable by setting Underlying // to the correct type.
[ "Variable", "gets", "the", "given", "variable", "Type", "in", "this", "Package", ".", "If", "the", "variable", "is", "not", "already", "defined", "this", "will", "add", "it", ".", "If", "a", "variable", "is", "added", "it", "s", "the", "caller", "s", "...
e17681d19d3ac4837a019ece36c2a0ec31ffe985
https://github.com/kubernetes/gengo/blob/e17681d19d3ac4837a019ece36c2a0ec31ffe985/types/types.go#L186-L194
152,955
kubernetes/gengo
types/types.go
HasImport
func (p *Package) HasImport(packageName string) bool { _, has := p.Imports[packageName] return has }
go
func (p *Package) HasImport(packageName string) bool { _, has := p.Imports[packageName] return has }
[ "func", "(", "p", "*", "Package", ")", "HasImport", "(", "packageName", "string", ")", "bool", "{", "_", ",", "has", ":=", "p", ".", "Imports", "[", "packageName", "]", "\n", "return", "has", "\n", "}" ]
// HasImport returns true if p imports packageName. Package names include the // package directory.
[ "HasImport", "returns", "true", "if", "p", "imports", "packageName", ".", "Package", "names", "include", "the", "package", "directory", "." ]
e17681d19d3ac4837a019ece36c2a0ec31ffe985
https://github.com/kubernetes/gengo/blob/e17681d19d3ac4837a019ece36c2a0ec31ffe985/types/types.go#L198-L201
152,956
kubernetes/gengo
types/types.go
AddImports
func (u Universe) AddImports(packagePath string, importPaths ...string) { p := u.Package(packagePath) for _, i := range importPaths { p.Imports[i] = u.Package(i) } }
go
func (u Universe) AddImports(packagePath string, importPaths ...string) { p := u.Package(packagePath) for _, i := range importPaths { p.Imports[i] = u.Package(i) } }
[ "func", "(", "u", "Universe", ")", "AddImports", "(", "packagePath", "string", ",", "importPaths", "...", "string", ")", "{", "p", ":=", "u", ".", "Package", "(", "packagePath", ")", "\n", "for", "_", ",", "i", ":=", "range", "importPaths", "{", "p", ...
// AddImports registers import lines for packageName. May be called multiple times. // You are responsible for canonicalizing all package paths.
[ "AddImports", "registers", "import", "lines", "for", "packageName", ".", "May", "be", "called", "multiple", "times", ".", "You", "are", "responsible", "for", "canonicalizing", "all", "package", "paths", "." ]
e17681d19d3ac4837a019ece36c2a0ec31ffe985
https://github.com/kubernetes/gengo/blob/e17681d19d3ac4837a019ece36c2a0ec31ffe985/types/types.go#L234-L239
152,957
kubernetes/gengo
types/types.go
IsAssignable
func (t *Type) IsAssignable() bool { if t.IsPrimitive() { return true } if t.Kind == Struct { for _, m := range t.Members { if !m.Type.IsAssignable() { return false } } return true } return false }
go
func (t *Type) IsAssignable() bool { if t.IsPrimitive() { return true } if t.Kind == Struct { for _, m := range t.Members { if !m.Type.IsAssignable() { return false } } return true } return false }
[ "func", "(", "t", "*", "Type", ")", "IsAssignable", "(", ")", "bool", "{", "if", "t", ".", "IsPrimitive", "(", ")", "{", "return", "true", "\n", "}", "\n", "if", "t", ".", "Kind", "==", "Struct", "{", "for", "_", ",", "m", ":=", "range", "t", ...
// IsAssignable returns whether the type is deep-assignable. For example, // slices and maps and pointers are shallow copies, but ints and strings are // complete.
[ "IsAssignable", "returns", "whether", "the", "type", "is", "deep", "-", "assignable", ".", "For", "example", "slices", "and", "maps", "and", "pointers", "are", "shallow", "copies", "but", "ints", "and", "strings", "are", "complete", "." ]
e17681d19d3ac4837a019ece36c2a0ec31ffe985
https://github.com/kubernetes/gengo/blob/e17681d19d3ac4837a019ece36c2a0ec31ffe985/types/types.go#L340-L353
152,958
kubernetes/gengo
types/types.go
IsAnonymousStruct
func (t *Type) IsAnonymousStruct() bool { return (t.Kind == Struct && t.Name.Name == "struct{}") || (t.Kind == Alias && t.Underlying.IsAnonymousStruct()) }
go
func (t *Type) IsAnonymousStruct() bool { return (t.Kind == Struct && t.Name.Name == "struct{}") || (t.Kind == Alias && t.Underlying.IsAnonymousStruct()) }
[ "func", "(", "t", "*", "Type", ")", "IsAnonymousStruct", "(", ")", "bool", "{", "return", "(", "t", ".", "Kind", "==", "Struct", "&&", "t", ".", "Name", ".", "Name", "==", "\"", "\"", ")", "||", "(", "t", ".", "Kind", "==", "Alias", "&&", "t", ...
// IsAnonymousStruct returns true if the type is an anonymous struct or an alias // to an anonymous struct.
[ "IsAnonymousStruct", "returns", "true", "if", "the", "type", "is", "an", "anonymous", "struct", "or", "an", "alias", "to", "an", "anonymous", "struct", "." ]
e17681d19d3ac4837a019ece36c2a0ec31ffe985
https://github.com/kubernetes/gengo/blob/e17681d19d3ac4837a019ece36c2a0ec31ffe985/types/types.go#L357-L359
152,959
kubernetes/gengo
examples/import-boss/generators/import_restrict.go
Packages
func Packages(c *generator.Context, arguments *args.GeneratorArgs) generator.Packages { pkgs := generator.Packages{} c.FileTypes = map[string]generator.FileType{ importBossFileType: importRuleFile{}, } for _, p := range c.Universe { if !arguments.InputIncludes(p) { // Don't run on e.g. third party dependencies. continue } savedPackage := p pkgs = append(pkgs, &generator.DefaultPackage{ PackageName: p.Name, PackagePath: p.Path, // GeneratorFunc returns a list of generators. Each generator makes a // single file. GeneratorFunc: func(c *generator.Context) (generators []generator.Generator) { return []generator.Generator{&importRules{ myPackage: savedPackage, }} }, FilterFunc: func(c *generator.Context, t *types.Type) bool { return false }, }) } return pkgs }
go
func Packages(c *generator.Context, arguments *args.GeneratorArgs) generator.Packages { pkgs := generator.Packages{} c.FileTypes = map[string]generator.FileType{ importBossFileType: importRuleFile{}, } for _, p := range c.Universe { if !arguments.InputIncludes(p) { // Don't run on e.g. third party dependencies. continue } savedPackage := p pkgs = append(pkgs, &generator.DefaultPackage{ PackageName: p.Name, PackagePath: p.Path, // GeneratorFunc returns a list of generators. Each generator makes a // single file. GeneratorFunc: func(c *generator.Context) (generators []generator.Generator) { return []generator.Generator{&importRules{ myPackage: savedPackage, }} }, FilterFunc: func(c *generator.Context, t *types.Type) bool { return false }, }) } return pkgs }
[ "func", "Packages", "(", "c", "*", "generator", ".", "Context", ",", "arguments", "*", "args", ".", "GeneratorArgs", ")", "generator", ".", "Packages", "{", "pkgs", ":=", "generator", ".", "Packages", "{", "}", "\n", "c", ".", "FileTypes", "=", "map", ...
// Packages makes the import-boss package definition.
[ "Packages", "makes", "the", "import", "-", "boss", "package", "definition", "." ]
e17681d19d3ac4837a019ece36c2a0ec31ffe985
https://github.com/kubernetes/gengo/blob/e17681d19d3ac4837a019ece36c2a0ec31ffe985/examples/import-boss/generators/import_restrict.go#L58-L87
152,960
kubernetes/gengo
examples/import-boss/generators/import_restrict.go
recursiveRead
func recursiveRead(path string) (*fileFormat, string, error) { for { if _, err := os.Stat(path); err == nil { ff, err := readFile(path) return ff, path, err } nextPath, removedDir := removeLastDir(path) if nextPath == path || removedDir == "src" { break } path = nextPath } return nil, "", nil }
go
func recursiveRead(path string) (*fileFormat, string, error) { for { if _, err := os.Stat(path); err == nil { ff, err := readFile(path) return ff, path, err } nextPath, removedDir := removeLastDir(path) if nextPath == path || removedDir == "src" { break } path = nextPath } return nil, "", nil }
[ "func", "recursiveRead", "(", "path", "string", ")", "(", "*", "fileFormat", ",", "string", ",", "error", ")", "{", "for", "{", "if", "_", ",", "err", ":=", "os", ".", "Stat", "(", "path", ")", ";", "err", "==", "nil", "{", "ff", ",", "err", ":...
// Keep going up a directory until we find an .import-restrictions file.
[ "Keep", "going", "up", "a", "directory", "until", "we", "find", "an", ".", "import", "-", "restrictions", "file", "." ]
e17681d19d3ac4837a019ece36c2a0ec31ffe985
https://github.com/kubernetes/gengo/blob/e17681d19d3ac4837a019ece36c2a0ec31ffe985/examples/import-boss/generators/import_restrict.go#L173-L187
152,961
kubernetes/gengo
examples/defaulter-gen/generators/defaulter.go
varsForDepth
func varsForDepth(depth int) (index, local string) { if depth > len(indexVariables) { index = fmt.Sprintf("i%d", depth) } else { index = indexVariables[depth : depth+1] } if depth > len(localVariables) { local = fmt.Sprintf("local%d", depth) } else { local = localVariables[depth : depth+1] } return }
go
func varsForDepth(depth int) (index, local string) { if depth > len(indexVariables) { index = fmt.Sprintf("i%d", depth) } else { index = indexVariables[depth : depth+1] } if depth > len(localVariables) { local = fmt.Sprintf("local%d", depth) } else { local = localVariables[depth : depth+1] } return }
[ "func", "varsForDepth", "(", "depth", "int", ")", "(", "index", ",", "local", "string", ")", "{", "if", "depth", ">", "len", "(", "indexVariables", ")", "{", "index", "=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "depth", ")", "\n", "}", "else"...
// varsForDepth creates temporary variables guaranteed to be unique within lexical Go scopes // of this depth in a function. It uses canonical Go loop variables for the first 7 levels // and then resorts to uglier prefixes.
[ "varsForDepth", "creates", "temporary", "variables", "guaranteed", "to", "be", "unique", "within", "lexical", "Go", "scopes", "of", "this", "depth", "in", "a", "function", ".", "It", "uses", "canonical", "Go", "loop", "variables", "for", "the", "first", "7", ...
e17681d19d3ac4837a019ece36c2a0ec31ffe985
https://github.com/kubernetes/gengo/blob/e17681d19d3ac4837a019ece36c2a0ec31ffe985/examples/defaulter-gen/generators/defaulter.go#L701-L713
152,962
kubernetes/gengo
examples/defaulter-gen/generators/defaulter.go
writeCalls
func (n *callNode) writeCalls(varName string, isVarPointer bool, sw *generator.SnippetWriter) { accessor := varName if !isVarPointer { accessor = "&" + accessor } for _, fn := range n.call { sw.Do("$.fn|raw$($.var$)\n", generator.Args{ "fn": fn, "var": accessor, }) } }
go
func (n *callNode) writeCalls(varName string, isVarPointer bool, sw *generator.SnippetWriter) { accessor := varName if !isVarPointer { accessor = "&" + accessor } for _, fn := range n.call { sw.Do("$.fn|raw$($.var$)\n", generator.Args{ "fn": fn, "var": accessor, }) } }
[ "func", "(", "n", "*", "callNode", ")", "writeCalls", "(", "varName", "string", ",", "isVarPointer", "bool", ",", "sw", "*", "generator", ".", "SnippetWriter", ")", "{", "accessor", ":=", "varName", "\n", "if", "!", "isVarPointer", "{", "accessor", "=", ...
// writeCalls generates a list of function calls based on the calls field for the provided variable // name and pointer.
[ "writeCalls", "generates", "a", "list", "of", "function", "calls", "based", "on", "the", "calls", "field", "for", "the", "provided", "variable", "name", "and", "pointer", "." ]
e17681d19d3ac4837a019ece36c2a0ec31ffe985
https://github.com/kubernetes/gengo/blob/e17681d19d3ac4837a019ece36c2a0ec31ffe985/examples/defaulter-gen/generators/defaulter.go#L717-L728
152,963
kubernetes/gengo
examples/defaulter-gen/generators/defaulter.go
WriteMethod
func (n *callNode) WriteMethod(varName string, depth int, ancestors []*callNode, sw *generator.SnippetWriter) { // if len(n.call) > 0 { // sw.Do(fmt.Sprintf("// %s\n", callPath(append(ancestors, n)).String()), nil) // } if len(n.field) > 0 { varName = varName + "." + n.field } index, local := varsForDepth(depth) vars := generator.Args{ "index": index, "local": local, "var": varName, } isPointer := n.elem && !n.index if isPointer && len(ancestors) > 0 { sw.Do("if $.var$ != nil {\n", vars) } switch { case n.index: sw.Do("for $.index$ := range $.var$ {\n", vars) if n.elem { sw.Do("$.local$ := $.var$[$.index$]\n", vars) } else { sw.Do("$.local$ := &$.var$[$.index$]\n", vars) } n.writeCalls(local, true, sw) for i := range n.children { n.children[i].WriteMethod(local, depth+1, append(ancestors, n), sw) } sw.Do("}\n", nil) case n.key: default: n.writeCalls(varName, isPointer, sw) for i := range n.children { n.children[i].WriteMethod(varName, depth, append(ancestors, n), sw) } } if isPointer && len(ancestors) > 0 { sw.Do("}\n", nil) } }
go
func (n *callNode) WriteMethod(varName string, depth int, ancestors []*callNode, sw *generator.SnippetWriter) { // if len(n.call) > 0 { // sw.Do(fmt.Sprintf("// %s\n", callPath(append(ancestors, n)).String()), nil) // } if len(n.field) > 0 { varName = varName + "." + n.field } index, local := varsForDepth(depth) vars := generator.Args{ "index": index, "local": local, "var": varName, } isPointer := n.elem && !n.index if isPointer && len(ancestors) > 0 { sw.Do("if $.var$ != nil {\n", vars) } switch { case n.index: sw.Do("for $.index$ := range $.var$ {\n", vars) if n.elem { sw.Do("$.local$ := $.var$[$.index$]\n", vars) } else { sw.Do("$.local$ := &$.var$[$.index$]\n", vars) } n.writeCalls(local, true, sw) for i := range n.children { n.children[i].WriteMethod(local, depth+1, append(ancestors, n), sw) } sw.Do("}\n", nil) case n.key: default: n.writeCalls(varName, isPointer, sw) for i := range n.children { n.children[i].WriteMethod(varName, depth, append(ancestors, n), sw) } } if isPointer && len(ancestors) > 0 { sw.Do("}\n", nil) } }
[ "func", "(", "n", "*", "callNode", ")", "WriteMethod", "(", "varName", "string", ",", "depth", "int", ",", "ancestors", "[", "]", "*", "callNode", ",", "sw", "*", "generator", ".", "SnippetWriter", ")", "{", "// if len(n.call) > 0 {", "// \tsw.Do(fmt.Sprintf(\...
// WriteMethod performs an in-order traversal of the calltree, generating loops and if blocks as necessary // to correctly turn the call tree into a method body that invokes all calls on all child nodes of the call tree. // Depth is used to generate local variables at the proper depth.
[ "WriteMethod", "performs", "an", "in", "-", "order", "traversal", "of", "the", "calltree", "generating", "loops", "and", "if", "blocks", "as", "necessary", "to", "correctly", "turn", "the", "call", "tree", "into", "a", "method", "body", "that", "invokes", "a...
e17681d19d3ac4837a019ece36c2a0ec31ffe985
https://github.com/kubernetes/gengo/blob/e17681d19d3ac4837a019ece36c2a0ec31ffe985/examples/defaulter-gen/generators/defaulter.go#L733-L779
152,964
kubernetes/gengo
examples/defaulter-gen/generators/defaulter.go
String
func (path callPath) String() string { if len(path) == 0 { return "<none>" } var parts []string for _, p := range path { last := len(parts) - 1 switch { case p.elem: if len(parts) > 0 { parts[last] = "*" + parts[last] } else { parts = append(parts, "*") } case p.index: if len(parts) > 0 { parts[last] = parts[last] + "[i]" } else { parts = append(parts, "[i]") } case p.key: if len(parts) > 0 { parts[last] = parts[last] + "[key]" } else { parts = append(parts, "[key]") } default: if len(p.field) > 0 { parts = append(parts, p.field) } else { parts = append(parts, "<root>") } } } var calls []string for _, fn := range path[len(path)-1].call { calls = append(calls, fn.Name.String()) } if len(calls) == 0 { calls = append(calls, "<none>") } return strings.Join(parts, ".") + " calls " + strings.Join(calls, ", ") }
go
func (path callPath) String() string { if len(path) == 0 { return "<none>" } var parts []string for _, p := range path { last := len(parts) - 1 switch { case p.elem: if len(parts) > 0 { parts[last] = "*" + parts[last] } else { parts = append(parts, "*") } case p.index: if len(parts) > 0 { parts[last] = parts[last] + "[i]" } else { parts = append(parts, "[i]") } case p.key: if len(parts) > 0 { parts[last] = parts[last] + "[key]" } else { parts = append(parts, "[key]") } default: if len(p.field) > 0 { parts = append(parts, p.field) } else { parts = append(parts, "<root>") } } } var calls []string for _, fn := range path[len(path)-1].call { calls = append(calls, fn.Name.String()) } if len(calls) == 0 { calls = append(calls, "<none>") } return strings.Join(parts, ".") + " calls " + strings.Join(calls, ", ") }
[ "func", "(", "path", "callPath", ")", "String", "(", ")", "string", "{", "if", "len", "(", "path", ")", "==", "0", "{", "return", "\"", "\"", "\n", "}", "\n", "var", "parts", "[", "]", "string", "\n", "for", "_", ",", "p", ":=", "range", "path"...
// String prints a representation of a callPath that roughly approximates what a Go accessor // would look like. Used for debugging only.
[ "String", "prints", "a", "representation", "of", "a", "callPath", "that", "roughly", "approximates", "what", "a", "Go", "accessor", "would", "look", "like", ".", "Used", "for", "debugging", "only", "." ]
e17681d19d3ac4837a019ece36c2a0ec31ffe985
https://github.com/kubernetes/gengo/blob/e17681d19d3ac4837a019ece36c2a0ec31ffe985/examples/defaulter-gen/generators/defaulter.go#L785-L828
152,965
kubernetes/gengo
namer/plural_namer.go
Name
func (r *pluralNamer) Name(t *types.Type) string { singular := t.Name.Name var plural string var ok bool if plural, ok = r.exceptions[singular]; ok { return r.finalize(plural) } if len(singular) < 2 { return r.finalize(singular) } switch rune(singular[len(singular)-1]) { case 's', 'x', 'z': plural = esPlural(singular) case 'y': sl := rune(singular[len(singular)-2]) if isConsonant(sl) { plural = iesPlural(singular) } else { plural = sPlural(singular) } case 'h': sl := rune(singular[len(singular)-2]) if sl == 'c' || sl == 's' { plural = esPlural(singular) } else { plural = sPlural(singular) } case 'e': sl := rune(singular[len(singular)-2]) if sl == 'f' { plural = vesPlural(singular[:len(singular)-1]) } else { plural = sPlural(singular) } case 'f': plural = vesPlural(singular) default: plural = sPlural(singular) } return r.finalize(plural) }
go
func (r *pluralNamer) Name(t *types.Type) string { singular := t.Name.Name var plural string var ok bool if plural, ok = r.exceptions[singular]; ok { return r.finalize(plural) } if len(singular) < 2 { return r.finalize(singular) } switch rune(singular[len(singular)-1]) { case 's', 'x', 'z': plural = esPlural(singular) case 'y': sl := rune(singular[len(singular)-2]) if isConsonant(sl) { plural = iesPlural(singular) } else { plural = sPlural(singular) } case 'h': sl := rune(singular[len(singular)-2]) if sl == 'c' || sl == 's' { plural = esPlural(singular) } else { plural = sPlural(singular) } case 'e': sl := rune(singular[len(singular)-2]) if sl == 'f' { plural = vesPlural(singular[:len(singular)-1]) } else { plural = sPlural(singular) } case 'f': plural = vesPlural(singular) default: plural = sPlural(singular) } return r.finalize(plural) }
[ "func", "(", "r", "*", "pluralNamer", ")", "Name", "(", "t", "*", "types", ".", "Type", ")", "string", "{", "singular", ":=", "t", ".", "Name", ".", "Name", "\n", "var", "plural", "string", "\n", "var", "ok", "bool", "\n", "if", "plural", ",", "o...
// Name returns the plural form of the type's name. If the type's name is found // in the exceptions map, the map value is returned.
[ "Name", "returns", "the", "plural", "form", "of", "the", "type", "s", "name", ".", "If", "the", "type", "s", "name", "is", "found", "in", "the", "exceptions", "map", "the", "map", "value", "is", "returned", "." ]
e17681d19d3ac4837a019ece36c2a0ec31ffe985
https://github.com/kubernetes/gengo/blob/e17681d19d3ac4837a019ece36c2a0ec31ffe985/namer/plural_namer.go#L54-L95
152,966
kubernetes/gengo
examples/set-gen/generators/sets.go
Packages
func Packages(_ *generator.Context, arguments *args.GeneratorArgs) generator.Packages { boilerplate, err := arguments.LoadGoBoilerplate() if err != nil { klog.Fatalf("Failed loading boilerplate: %v", err) } return generator.Packages{&generator.DefaultPackage{ PackageName: "sets", PackagePath: arguments.OutputPackagePath, HeaderText: boilerplate, PackageDocumentation: []byte( `// Package sets has auto-generated set types. `), // GeneratorFunc returns a list of generators. Each generator makes a // single file. GeneratorFunc: func(c *generator.Context) (generators []generator.Generator) { generators = []generator.Generator{ // Always generate a "doc.go" file. generator.DefaultGen{OptionalName: "doc"}, // Make a separate file for the Empty type, since it's shared by every type. generator.DefaultGen{ OptionalName: "empty", OptionalBody: []byte(emptyTypeDecl), }, } // Since we want a file per type that we generate a set for, we // have to provide a function for this. for _, t := range c.Order { generators = append(generators, &genSet{ DefaultGen: generator.DefaultGen{ // Use the privatized version of the // type name as the file name. // // TODO: make a namer that converts // camelCase to '-' separation for file // names? OptionalName: c.Namers["private"].Name(t), }, outputPackage: arguments.OutputPackagePath, typeToMatch: t, imports: generator.NewImportTracker(), }) } return generators }, FilterFunc: func(c *generator.Context, t *types.Type) bool { // It would be reasonable to filter by the type's package here. // It might be necessary if your input directory has a big // import graph. switch t.Kind { case types.Map, types.Slice, types.Pointer: // These types can't be keys in a map. return false case types.Builtin: return true case types.Struct: // Only some structs can be keys in a map. This is triggered by the line // // +genset // or // // +genset=true return extractBoolTagOrDie("genset", t.CommentLines) == true } return false }, }} }
go
func Packages(_ *generator.Context, arguments *args.GeneratorArgs) generator.Packages { boilerplate, err := arguments.LoadGoBoilerplate() if err != nil { klog.Fatalf("Failed loading boilerplate: %v", err) } return generator.Packages{&generator.DefaultPackage{ PackageName: "sets", PackagePath: arguments.OutputPackagePath, HeaderText: boilerplate, PackageDocumentation: []byte( `// Package sets has auto-generated set types. `), // GeneratorFunc returns a list of generators. Each generator makes a // single file. GeneratorFunc: func(c *generator.Context) (generators []generator.Generator) { generators = []generator.Generator{ // Always generate a "doc.go" file. generator.DefaultGen{OptionalName: "doc"}, // Make a separate file for the Empty type, since it's shared by every type. generator.DefaultGen{ OptionalName: "empty", OptionalBody: []byte(emptyTypeDecl), }, } // Since we want a file per type that we generate a set for, we // have to provide a function for this. for _, t := range c.Order { generators = append(generators, &genSet{ DefaultGen: generator.DefaultGen{ // Use the privatized version of the // type name as the file name. // // TODO: make a namer that converts // camelCase to '-' separation for file // names? OptionalName: c.Namers["private"].Name(t), }, outputPackage: arguments.OutputPackagePath, typeToMatch: t, imports: generator.NewImportTracker(), }) } return generators }, FilterFunc: func(c *generator.Context, t *types.Type) bool { // It would be reasonable to filter by the type's package here. // It might be necessary if your input directory has a big // import graph. switch t.Kind { case types.Map, types.Slice, types.Pointer: // These types can't be keys in a map. return false case types.Builtin: return true case types.Struct: // Only some structs can be keys in a map. This is triggered by the line // // +genset // or // // +genset=true return extractBoolTagOrDie("genset", t.CommentLines) == true } return false }, }} }
[ "func", "Packages", "(", "_", "*", "generator", ".", "Context", ",", "arguments", "*", "args", ".", "GeneratorArgs", ")", "generator", ".", "Packages", "{", "boilerplate", ",", "err", ":=", "arguments", ".", "LoadGoBoilerplate", "(", ")", "\n", "if", "err"...
// Packages makes the sets package definition.
[ "Packages", "makes", "the", "sets", "package", "definition", "." ]
e17681d19d3ac4837a019ece36c2a0ec31ffe985
https://github.com/kubernetes/gengo/blob/e17681d19d3ac4837a019ece36c2a0ec31ffe985/examples/set-gen/generators/sets.go#L47-L112
152,967
kubernetes/gengo
args/args.go
Default
func Default() *GeneratorArgs { return &GeneratorArgs{ OutputBase: DefaultSourceTree(), GoHeaderFilePath: filepath.Join(DefaultSourceTree(), "k8s.io/gengo/boilerplate/boilerplate.go.txt"), GeneratedBuildTag: "ignore_autogenerated", GeneratedByCommentTemplate: "// Code generated by GENERATOR_NAME. DO NOT EDIT.", defaultCommandLineFlags: true, } }
go
func Default() *GeneratorArgs { return &GeneratorArgs{ OutputBase: DefaultSourceTree(), GoHeaderFilePath: filepath.Join(DefaultSourceTree(), "k8s.io/gengo/boilerplate/boilerplate.go.txt"), GeneratedBuildTag: "ignore_autogenerated", GeneratedByCommentTemplate: "// Code generated by GENERATOR_NAME. DO NOT EDIT.", defaultCommandLineFlags: true, } }
[ "func", "Default", "(", ")", "*", "GeneratorArgs", "{", "return", "&", "GeneratorArgs", "{", "OutputBase", ":", "DefaultSourceTree", "(", ")", ",", "GoHeaderFilePath", ":", "filepath", ".", "Join", "(", "DefaultSourceTree", "(", ")", ",", "\"", "\"", ")", ...
// Default returns a defaulted GeneratorArgs. You may change the defaults // before calling AddFlags.
[ "Default", "returns", "a", "defaulted", "GeneratorArgs", ".", "You", "may", "change", "the", "defaults", "before", "calling", "AddFlags", "." ]
e17681d19d3ac4837a019ece36c2a0ec31ffe985
https://github.com/kubernetes/gengo/blob/e17681d19d3ac4837a019ece36c2a0ec31ffe985/args/args.go#L42-L50
152,968
kubernetes/gengo
args/args.go
NewBuilder
func (g *GeneratorArgs) NewBuilder() (*parser.Builder, error) { b := parser.New() // Ignore all auto-generated files. b.AddBuildTags(g.GeneratedBuildTag) for _, d := range g.InputDirs { var err error if strings.HasSuffix(d, "/...") { err = b.AddDirRecursive(strings.TrimSuffix(d, "/...")) } else { err = b.AddDir(d) } if err != nil { return nil, fmt.Errorf("unable to add directory %q: %v", d, err) } } return b, nil }
go
func (g *GeneratorArgs) NewBuilder() (*parser.Builder, error) { b := parser.New() // Ignore all auto-generated files. b.AddBuildTags(g.GeneratedBuildTag) for _, d := range g.InputDirs { var err error if strings.HasSuffix(d, "/...") { err = b.AddDirRecursive(strings.TrimSuffix(d, "/...")) } else { err = b.AddDir(d) } if err != nil { return nil, fmt.Errorf("unable to add directory %q: %v", d, err) } } return b, nil }
[ "func", "(", "g", "*", "GeneratorArgs", ")", "NewBuilder", "(", ")", "(", "*", "parser", ".", "Builder", ",", "error", ")", "{", "b", ":=", "parser", ".", "New", "(", ")", "\n", "// Ignore all auto-generated files.", "b", ".", "AddBuildTags", "(", "g", ...
// NewBuilder makes a new parser.Builder and populates it with the input // directories.
[ "NewBuilder", "makes", "a", "new", "parser", ".", "Builder", "and", "populates", "it", "with", "the", "input", "directories", "." ]
e17681d19d3ac4837a019ece36c2a0ec31ffe985
https://github.com/kubernetes/gengo/blob/e17681d19d3ac4837a019ece36c2a0ec31ffe985/args/args.go#L128-L145
152,969
vektra/mockery
mockery/generator.go
NewGenerator
func NewGenerator(iface *Interface, pkg string, inPackage bool) *Generator { var roots []string for _, root := range filepath.SplitList(build.Default.GOPATH) { roots = append(roots, filepath.Join(root, "src")) } g := &Generator{ iface: iface, pkg: pkg, ip: inPackage, localizationCache: make(map[string]string), packagePathToName: make(map[string]string), nameToPackagePath: make(map[string]string), packageRoots: roots, } g.addPackageImportWithName("github.com/stretchr/testify/mock", "mock") return g }
go
func NewGenerator(iface *Interface, pkg string, inPackage bool) *Generator { var roots []string for _, root := range filepath.SplitList(build.Default.GOPATH) { roots = append(roots, filepath.Join(root, "src")) } g := &Generator{ iface: iface, pkg: pkg, ip: inPackage, localizationCache: make(map[string]string), packagePathToName: make(map[string]string), nameToPackagePath: make(map[string]string), packageRoots: roots, } g.addPackageImportWithName("github.com/stretchr/testify/mock", "mock") return g }
[ "func", "NewGenerator", "(", "iface", "*", "Interface", ",", "pkg", "string", ",", "inPackage", "bool", ")", "*", "Generator", "{", "var", "roots", "[", "]", "string", "\n\n", "for", "_", ",", "root", ":=", "range", "filepath", ".", "SplitList", "(", "...
// NewGenerator builds a Generator.
[ "NewGenerator", "builds", "a", "Generator", "." ]
e78b021dcbb558a8e7ac1fc5bc757ad7c277bb81
https://github.com/vektra/mockery/blob/e78b021dcbb558a8e7ac1fc5bc757ad7c277bb81/mockery/generator.go#L56-L76
152,970
vektra/mockery
mockery/generator.go
GeneratePrologue
func (g *Generator) GeneratePrologue(pkg string) { g.populateImports() if g.ip { g.printf("package %s\n\n", g.iface.Pkg.Name()) } else { g.printf("package %v\n\n", pkg) } g.generateImports() g.printf("\n") }
go
func (g *Generator) GeneratePrologue(pkg string) { g.populateImports() if g.ip { g.printf("package %s\n\n", g.iface.Pkg.Name()) } else { g.printf("package %v\n\n", pkg) } g.generateImports() g.printf("\n") }
[ "func", "(", "g", "*", "Generator", ")", "GeneratePrologue", "(", "pkg", "string", ")", "{", "g", ".", "populateImports", "(", ")", "\n", "if", "g", ".", "ip", "{", "g", ".", "printf", "(", "\"", "\\n", "\\n", "\"", ",", "g", ".", "iface", ".", ...
// GeneratePrologue generates the prologue of the mock.
[ "GeneratePrologue", "generates", "the", "prologue", "of", "the", "mock", "." ]
e78b021dcbb558a8e7ac1fc5bc757ad7c277bb81
https://github.com/vektra/mockery/blob/e78b021dcbb558a8e7ac1fc5bc757ad7c277bb81/mockery/generator.go#L256-L266
152,971
vektra/mockery
mockery/generator.go
GeneratePrologueNote
func (g *Generator) GeneratePrologueNote(note string) { g.printf("// Code generated by mockery v%s. DO NOT EDIT.\n", SemVer) if note != "" { g.printf("\n") for _, n := range strings.Split(note, "\\n") { g.printf("// %s\n", n) } } g.printf("\n") }
go
func (g *Generator) GeneratePrologueNote(note string) { g.printf("// Code generated by mockery v%s. DO NOT EDIT.\n", SemVer) if note != "" { g.printf("\n") for _, n := range strings.Split(note, "\\n") { g.printf("// %s\n", n) } } g.printf("\n") }
[ "func", "(", "g", "*", "Generator", ")", "GeneratePrologueNote", "(", "note", "string", ")", "{", "g", ".", "printf", "(", "\"", "\\n", "\"", ",", "SemVer", ")", "\n", "if", "note", "!=", "\"", "\"", "{", "g", ".", "printf", "(", "\"", "\\n", "\"...
// GeneratePrologueNote adds a note after the prologue to the output // string.
[ "GeneratePrologueNote", "adds", "a", "note", "after", "the", "prologue", "to", "the", "output", "string", "." ]
e78b021dcbb558a8e7ac1fc5bc757ad7c277bb81
https://github.com/vektra/mockery/blob/e78b021dcbb558a8e7ac1fc5bc757ad7c277bb81/mockery/generator.go#L270-L279
152,972
vektra/mockery
mockery/generator.go
Generate
func (g *Generator) Generate() error { g.populateImports() if g.iface == nil { return ErrNotSetup } g.printf( "// %s is an autogenerated mock type for the %s type\n", g.mockName(), g.iface.Name, ) g.printf( "type %s struct {\n\tmock.Mock\n}\n\n", g.mockName(), ) for i := 0; i < g.iface.Type.NumMethods(); i++ { fn := g.iface.Type.Method(i) ftype := fn.Type().(*types.Signature) fname := fn.Name() params := g.genList(ftype.Params(), ftype.Variadic()) returns := g.genList(ftype.Results(), false) if len(params.Names) == 0 { g.printf("// %s provides a mock function with given fields:\n", fname) } else { g.printf( "// %s provides a mock function with given fields: %s\n", fname, strings.Join(params.Names, ", "), ) } g.printf( "func (_m *%s) %s(%s) ", g.mockName(), fname, strings.Join(params.Params, ", "), ) switch len(returns.Types) { case 0: g.printf("{\n") case 1: g.printf("%s {\n", returns.Types[0]) default: g.printf("(%s) {\n", strings.Join(returns.Types, ", ")) } var formattedParamNames string for i, name := range params.Names { if i > 0 { formattedParamNames += ", " } paramType := params.Types[i] // for variable args, move the ... to the end. if strings.Index(paramType, "...") == 0 { name += "..." } formattedParamNames += name } called := g.generateCalled(params, formattedParamNames) // _m.Called invocation string if len(returns.Types) > 0 { g.printf("\tret := %s\n\n", called) var ( ret []string ) for idx, typ := range returns.Types { g.printf("\tvar r%d %s\n", idx, typ) g.printf("\tif rf, ok := ret.Get(%d).(func(%s) %s); ok {\n", idx, strings.Join(params.Types, ", "), typ) g.printf("\t\tr%d = rf(%s)\n", idx, formattedParamNames) g.printf("\t} else {\n") if typ == "error" { g.printf("\t\tr%d = ret.Error(%d)\n", idx, idx) } else if returns.Nilable[idx] { g.printf("\t\tif ret.Get(%d) != nil {\n", idx) g.printf("\t\t\tr%d = ret.Get(%d).(%s)\n", idx, idx, typ) g.printf("\t\t}\n") } else { g.printf("\t\tr%d = ret.Get(%d).(%s)\n", idx, idx, typ) } g.printf("\t}\n\n") ret = append(ret, fmt.Sprintf("r%d", idx)) } g.printf("\treturn %s\n", strings.Join(ret, ", ")) } else { g.printf("\t%s\n", called) } g.printf("}\n") } return nil }
go
func (g *Generator) Generate() error { g.populateImports() if g.iface == nil { return ErrNotSetup } g.printf( "// %s is an autogenerated mock type for the %s type\n", g.mockName(), g.iface.Name, ) g.printf( "type %s struct {\n\tmock.Mock\n}\n\n", g.mockName(), ) for i := 0; i < g.iface.Type.NumMethods(); i++ { fn := g.iface.Type.Method(i) ftype := fn.Type().(*types.Signature) fname := fn.Name() params := g.genList(ftype.Params(), ftype.Variadic()) returns := g.genList(ftype.Results(), false) if len(params.Names) == 0 { g.printf("// %s provides a mock function with given fields:\n", fname) } else { g.printf( "// %s provides a mock function with given fields: %s\n", fname, strings.Join(params.Names, ", "), ) } g.printf( "func (_m *%s) %s(%s) ", g.mockName(), fname, strings.Join(params.Params, ", "), ) switch len(returns.Types) { case 0: g.printf("{\n") case 1: g.printf("%s {\n", returns.Types[0]) default: g.printf("(%s) {\n", strings.Join(returns.Types, ", ")) } var formattedParamNames string for i, name := range params.Names { if i > 0 { formattedParamNames += ", " } paramType := params.Types[i] // for variable args, move the ... to the end. if strings.Index(paramType, "...") == 0 { name += "..." } formattedParamNames += name } called := g.generateCalled(params, formattedParamNames) // _m.Called invocation string if len(returns.Types) > 0 { g.printf("\tret := %s\n\n", called) var ( ret []string ) for idx, typ := range returns.Types { g.printf("\tvar r%d %s\n", idx, typ) g.printf("\tif rf, ok := ret.Get(%d).(func(%s) %s); ok {\n", idx, strings.Join(params.Types, ", "), typ) g.printf("\t\tr%d = rf(%s)\n", idx, formattedParamNames) g.printf("\t} else {\n") if typ == "error" { g.printf("\t\tr%d = ret.Error(%d)\n", idx, idx) } else if returns.Nilable[idx] { g.printf("\t\tif ret.Get(%d) != nil {\n", idx) g.printf("\t\t\tr%d = ret.Get(%d).(%s)\n", idx, idx, typ) g.printf("\t\t}\n") } else { g.printf("\t\tr%d = ret.Get(%d).(%s)\n", idx, idx, typ) } g.printf("\t}\n\n") ret = append(ret, fmt.Sprintf("r%d", idx)) } g.printf("\treturn %s\n", strings.Join(ret, ", ")) } else { g.printf("\t%s\n", called) } g.printf("}\n") } return nil }
[ "func", "(", "g", "*", "Generator", ")", "Generate", "(", ")", "error", "{", "g", ".", "populateImports", "(", ")", "\n", "if", "g", ".", "iface", "==", "nil", "{", "return", "ErrNotSetup", "\n", "}", "\n\n", "g", ".", "printf", "(", "\"", "\\n", ...
// Generate builds a string that constitutes a valid go source file // containing the mock of the relevant interface.
[ "Generate", "builds", "a", "string", "that", "constitutes", "a", "valid", "go", "source", "file", "containing", "the", "mock", "of", "the", "relevant", "interface", "." ]
e78b021dcbb558a8e7ac1fc5bc757ad7c277bb81
https://github.com/vektra/mockery/blob/e78b021dcbb558a8e7ac1fc5bc757ad7c277bb81/mockery/generator.go#L479-L577
152,973
vektra/mockery
mockery/generator.go
generateCalled
func (g *Generator) generateCalled(list *paramList, formattedParamNames string) string { namesLen := len(list.Names) if namesLen == 0 { return "_m.Called()" } if !list.Variadic { return "_m.Called(" + formattedParamNames + ")" } var variadicArgsName string variadicName := list.Names[namesLen-1] variadicIface := strings.Contains(list.Types[namesLen-1], "interface{}") if variadicIface { // Variadic is already of the interface{} type, so we don't need special handling. variadicArgsName = variadicName } else { // Define _va to avoid "cannot use t (type T) as type []interface {} in append" error // whenever the variadic type is non-interface{}. g.printf("\t_va := make([]interface{}, len(%s))\n", variadicName) g.printf("\tfor _i := range %s {\n\t\t_va[_i] = %s[_i]\n\t}\n", variadicName, variadicName) variadicArgsName = "_va" } // _ca will hold all arguments we'll mirror into Called, one argument per distinct value // passed to the method. // // For example, if the second argument is variadic and consists of three values, // a total of 4 arguments will be passed to Called. The alternative is to // pass a total of 2 arguments where the second is a slice with those 3 values from // the variadic argument. But the alternative is less accessible because it requires // building a []interface{} before calling Mock methods like On and AssertCalled for // the variadic argument, and creates incompatibility issues with the diff algorithm // in github.com/stretchr/testify/mock. // // This mirroring will allow argument lists for methods like On and AssertCalled to // always resemble the expected calls they describe and retain compatibility. // // It's okay for us to use the interface{} type, regardless of the actual types, because // Called receives only interface{} anyway. g.printf("\tvar _ca []interface{}\n") if namesLen > 1 { nonVariadicParamNames := formattedParamNames[0:strings.LastIndex(formattedParamNames, ",")] g.printf("\t_ca = append(_ca, %s)\n", nonVariadicParamNames) } g.printf("\t_ca = append(_ca, %s...)\n", variadicArgsName) return "_m.Called(_ca...)" }
go
func (g *Generator) generateCalled(list *paramList, formattedParamNames string) string { namesLen := len(list.Names) if namesLen == 0 { return "_m.Called()" } if !list.Variadic { return "_m.Called(" + formattedParamNames + ")" } var variadicArgsName string variadicName := list.Names[namesLen-1] variadicIface := strings.Contains(list.Types[namesLen-1], "interface{}") if variadicIface { // Variadic is already of the interface{} type, so we don't need special handling. variadicArgsName = variadicName } else { // Define _va to avoid "cannot use t (type T) as type []interface {} in append" error // whenever the variadic type is non-interface{}. g.printf("\t_va := make([]interface{}, len(%s))\n", variadicName) g.printf("\tfor _i := range %s {\n\t\t_va[_i] = %s[_i]\n\t}\n", variadicName, variadicName) variadicArgsName = "_va" } // _ca will hold all arguments we'll mirror into Called, one argument per distinct value // passed to the method. // // For example, if the second argument is variadic and consists of three values, // a total of 4 arguments will be passed to Called. The alternative is to // pass a total of 2 arguments where the second is a slice with those 3 values from // the variadic argument. But the alternative is less accessible because it requires // building a []interface{} before calling Mock methods like On and AssertCalled for // the variadic argument, and creates incompatibility issues with the diff algorithm // in github.com/stretchr/testify/mock. // // This mirroring will allow argument lists for methods like On and AssertCalled to // always resemble the expected calls they describe and retain compatibility. // // It's okay for us to use the interface{} type, regardless of the actual types, because // Called receives only interface{} anyway. g.printf("\tvar _ca []interface{}\n") if namesLen > 1 { nonVariadicParamNames := formattedParamNames[0:strings.LastIndex(formattedParamNames, ",")] g.printf("\t_ca = append(_ca, %s)\n", nonVariadicParamNames) } g.printf("\t_ca = append(_ca, %s...)\n", variadicArgsName) return "_m.Called(_ca...)" }
[ "func", "(", "g", "*", "Generator", ")", "generateCalled", "(", "list", "*", "paramList", ",", "formattedParamNames", "string", ")", "string", "{", "namesLen", ":=", "len", "(", "list", ".", "Names", ")", "\n", "if", "namesLen", "==", "0", "{", "return",...
// generateCalled returns the Mock.Called invocation string and, if necessary, prints the // steps to prepare its argument list. // // It is separate from Generate to avoid cyclomatic complexity through early return statements.
[ "generateCalled", "returns", "the", "Mock", ".", "Called", "invocation", "string", "and", "if", "necessary", "prints", "the", "steps", "to", "prepare", "its", "argument", "list", ".", "It", "is", "separate", "from", "Generate", "to", "avoid", "cyclomatic", "co...
e78b021dcbb558a8e7ac1fc5bc757ad7c277bb81
https://github.com/vektra/mockery/blob/e78b021dcbb558a8e7ac1fc5bc757ad7c277bb81/mockery/generator.go#L583-L633
152,974
evanphx/json-patch
cmd/json-patch/file_flag.go
UnmarshalFlag
func (f *FileFlag) UnmarshalFlag(value string) error { stat, err := os.Stat(value) if err != nil { return err } if stat.IsDir() { return fmt.Errorf("path '%s' is a directory, not a file", value) } abs, err := filepath.Abs(value) if err != nil { return err } *f = FileFlag(abs) return nil }
go
func (f *FileFlag) UnmarshalFlag(value string) error { stat, err := os.Stat(value) if err != nil { return err } if stat.IsDir() { return fmt.Errorf("path '%s' is a directory, not a file", value) } abs, err := filepath.Abs(value) if err != nil { return err } *f = FileFlag(abs) return nil }
[ "func", "(", "f", "*", "FileFlag", ")", "UnmarshalFlag", "(", "value", "string", ")", "error", "{", "stat", ",", "err", ":=", "os", ".", "Stat", "(", "value", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "if", "st...
// UnmarshalFlag implements go-flag's Unmarshaler interface
[ "UnmarshalFlag", "implements", "go", "-", "flag", "s", "Unmarshaler", "interface" ]
5858425f75500d40c52783dce87d085a483ce135
https://github.com/evanphx/json-patch/blob/5858425f75500d40c52783dce87d085a483ce135/cmd/json-patch/file_flag.go#L16-L34
152,975
evanphx/json-patch
patch.go
set
func (d *partialArray) set(key string, val *lazyNode) error { idx, err := strconv.Atoi(key) if err != nil { return err } (*d)[idx] = val return nil }
go
func (d *partialArray) set(key string, val *lazyNode) error { idx, err := strconv.Atoi(key) if err != nil { return err } (*d)[idx] = val return nil }
[ "func", "(", "d", "*", "partialArray", ")", "set", "(", "key", "string", ",", "val", "*", "lazyNode", ")", "error", "{", "idx", ",", "err", ":=", "strconv", ".", "Atoi", "(", "key", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n",...
// set should only be used to implement the "replace" operation, so "key" must // be an already existing index in "d".
[ "set", "should", "only", "be", "used", "to", "implement", "the", "replace", "operation", "so", "key", "must", "be", "an", "already", "existing", "index", "in", "d", "." ]
5858425f75500d40c52783dce87d085a483ce135
https://github.com/evanphx/json-patch/blob/5858425f75500d40c52783dce87d085a483ce135/patch.go#L371-L378
152,976
evanphx/json-patch
patch.go
Equal
func Equal(a, b []byte) bool { ra := make(json.RawMessage, len(a)) copy(ra, a) la := newLazyNode(&ra) rb := make(json.RawMessage, len(b)) copy(rb, b) lb := newLazyNode(&rb) return la.equal(lb) }
go
func Equal(a, b []byte) bool { ra := make(json.RawMessage, len(a)) copy(ra, a) la := newLazyNode(&ra) rb := make(json.RawMessage, len(b)) copy(rb, b) lb := newLazyNode(&rb) return la.equal(lb) }
[ "func", "Equal", "(", "a", ",", "b", "[", "]", "byte", ")", "bool", "{", "ra", ":=", "make", "(", "json", ".", "RawMessage", ",", "len", "(", "a", ")", ")", "\n", "copy", "(", "ra", ",", "a", ")", "\n", "la", ":=", "newLazyNode", "(", "&", ...
// Equal indicates if 2 JSON documents have the same structural equality.
[ "Equal", "indicates", "if", "2", "JSON", "documents", "have", "the", "same", "structural", "equality", "." ]
5858425f75500d40c52783dce87d085a483ce135
https://github.com/evanphx/json-patch/blob/5858425f75500d40c52783dce87d085a483ce135/patch.go#L602-L612
152,977
evanphx/json-patch
patch.go
DecodePatch
func DecodePatch(buf []byte) (Patch, error) { var p Patch err := json.Unmarshal(buf, &p) if err != nil { return nil, err } return p, nil }
go
func DecodePatch(buf []byte) (Patch, error) { var p Patch err := json.Unmarshal(buf, &p) if err != nil { return nil, err } return p, nil }
[ "func", "DecodePatch", "(", "buf", "[", "]", "byte", ")", "(", "Patch", ",", "error", ")", "{", "var", "p", "Patch", "\n\n", "err", ":=", "json", ".", "Unmarshal", "(", "buf", ",", "&", "p", ")", "\n\n", "if", "err", "!=", "nil", "{", "return", ...
// DecodePatch decodes the passed JSON document as an RFC 6902 patch.
[ "DecodePatch", "decodes", "the", "passed", "JSON", "document", "as", "an", "RFC", "6902", "patch", "." ]
5858425f75500d40c52783dce87d085a483ce135
https://github.com/evanphx/json-patch/blob/5858425f75500d40c52783dce87d085a483ce135/patch.go#L615-L625
152,978
evanphx/json-patch
patch.go
Apply
func (p Patch) Apply(doc []byte) ([]byte, error) { return p.ApplyIndent(doc, "") }
go
func (p Patch) Apply(doc []byte) ([]byte, error) { return p.ApplyIndent(doc, "") }
[ "func", "(", "p", "Patch", ")", "Apply", "(", "doc", "[", "]", "byte", ")", "(", "[", "]", "byte", ",", "error", ")", "{", "return", "p", ".", "ApplyIndent", "(", "doc", ",", "\"", "\"", ")", "\n", "}" ]
// Apply mutates a JSON document according to the patch, and returns the new // document.
[ "Apply", "mutates", "a", "JSON", "document", "according", "to", "the", "patch", "and", "returns", "the", "new", "document", "." ]
5858425f75500d40c52783dce87d085a483ce135
https://github.com/evanphx/json-patch/blob/5858425f75500d40c52783dce87d085a483ce135/patch.go#L629-L631
152,979
evanphx/json-patch
patch.go
ApplyIndent
func (p Patch) ApplyIndent(doc []byte, indent string) ([]byte, error) { var pd container if doc[0] == '[' { pd = &partialArray{} } else { pd = &partialDoc{} } err := json.Unmarshal(doc, pd) if err != nil { return nil, err } err = nil var accumulatedCopySize int64 for _, op := range p { switch op.kind() { case "add": err = p.add(&pd, op) case "remove": err = p.remove(&pd, op) case "replace": err = p.replace(&pd, op) case "move": err = p.move(&pd, op) case "test": err = p.test(&pd, op) case "copy": err = p.copy(&pd, op, &accumulatedCopySize) default: err = fmt.Errorf("Unexpected kind: %s", op.kind()) } if err != nil { return nil, err } } if indent != "" { return json.MarshalIndent(pd, "", indent) } return json.Marshal(pd) }
go
func (p Patch) ApplyIndent(doc []byte, indent string) ([]byte, error) { var pd container if doc[0] == '[' { pd = &partialArray{} } else { pd = &partialDoc{} } err := json.Unmarshal(doc, pd) if err != nil { return nil, err } err = nil var accumulatedCopySize int64 for _, op := range p { switch op.kind() { case "add": err = p.add(&pd, op) case "remove": err = p.remove(&pd, op) case "replace": err = p.replace(&pd, op) case "move": err = p.move(&pd, op) case "test": err = p.test(&pd, op) case "copy": err = p.copy(&pd, op, &accumulatedCopySize) default: err = fmt.Errorf("Unexpected kind: %s", op.kind()) } if err != nil { return nil, err } } if indent != "" { return json.MarshalIndent(pd, "", indent) } return json.Marshal(pd) }
[ "func", "(", "p", "Patch", ")", "ApplyIndent", "(", "doc", "[", "]", "byte", ",", "indent", "string", ")", "(", "[", "]", "byte", ",", "error", ")", "{", "var", "pd", "container", "\n", "if", "doc", "[", "0", "]", "==", "'['", "{", "pd", "=", ...
// ApplyIndent mutates a JSON document according to the patch, and returns the new // document indented.
[ "ApplyIndent", "mutates", "a", "JSON", "document", "according", "to", "the", "patch", "and", "returns", "the", "new", "document", "indented", "." ]
5858425f75500d40c52783dce87d085a483ce135
https://github.com/evanphx/json-patch/blob/5858425f75500d40c52783dce87d085a483ce135/patch.go#L635-L681
152,980
evanphx/json-patch
errors.go
NewAccumulatedCopySizeError
func NewAccumulatedCopySizeError(l, a int64) *AccumulatedCopySizeError { return &AccumulatedCopySizeError{limit: l, accumulated: a} }
go
func NewAccumulatedCopySizeError(l, a int64) *AccumulatedCopySizeError { return &AccumulatedCopySizeError{limit: l, accumulated: a} }
[ "func", "NewAccumulatedCopySizeError", "(", "l", ",", "a", "int64", ")", "*", "AccumulatedCopySizeError", "{", "return", "&", "AccumulatedCopySizeError", "{", "limit", ":", "l", ",", "accumulated", ":", "a", "}", "\n", "}" ]
// NewAccumulatedCopySizeError returns an AccumulatedCopySizeError.
[ "NewAccumulatedCopySizeError", "returns", "an", "AccumulatedCopySizeError", "." ]
5858425f75500d40c52783dce87d085a483ce135
https://github.com/evanphx/json-patch/blob/5858425f75500d40c52783dce87d085a483ce135/errors.go#L14-L16
152,981
evanphx/json-patch
errors.go
NewArraySizeError
func NewArraySizeError(l, s int) *ArraySizeError { return &ArraySizeError{limit: l, size: s} }
go
func NewArraySizeError(l, s int) *ArraySizeError { return &ArraySizeError{limit: l, size: s} }
[ "func", "NewArraySizeError", "(", "l", ",", "s", "int", ")", "*", "ArraySizeError", "{", "return", "&", "ArraySizeError", "{", "limit", ":", "l", ",", "size", ":", "s", "}", "\n", "}" ]
// NewArraySizeError returns an ArraySizeError.
[ "NewArraySizeError", "returns", "an", "ArraySizeError", "." ]
5858425f75500d40c52783dce87d085a483ce135
https://github.com/evanphx/json-patch/blob/5858425f75500d40c52783dce87d085a483ce135/errors.go#L31-L33
152,982
evanphx/json-patch
merge.go
MergeMergePatches
func MergeMergePatches(patch1Data, patch2Data []byte) ([]byte, error) { return doMergePatch(patch1Data, patch2Data, true) }
go
func MergeMergePatches(patch1Data, patch2Data []byte) ([]byte, error) { return doMergePatch(patch1Data, patch2Data, true) }
[ "func", "MergeMergePatches", "(", "patch1Data", ",", "patch2Data", "[", "]", "byte", ")", "(", "[", "]", "byte", ",", "error", ")", "{", "return", "doMergePatch", "(", "patch1Data", ",", "patch2Data", ",", "true", ")", "\n", "}" ]
// MergeMergePatches merges two merge patches together, such that // applying this resulting merged merge patch to a document yields the same // as merging each merge patch to the document in succession.
[ "MergeMergePatches", "merges", "two", "merge", "patches", "together", "such", "that", "applying", "this", "resulting", "merged", "merge", "patch", "to", "a", "document", "yields", "the", "same", "as", "merging", "each", "merge", "patch", "to", "the", "document",...
5858425f75500d40c52783dce87d085a483ce135
https://github.com/evanphx/json-patch/blob/5858425f75500d40c52783dce87d085a483ce135/merge.go#L98-L100
152,983
evanphx/json-patch
merge.go
MergePatch
func MergePatch(docData, patchData []byte) ([]byte, error) { return doMergePatch(docData, patchData, false) }
go
func MergePatch(docData, patchData []byte) ([]byte, error) { return doMergePatch(docData, patchData, false) }
[ "func", "MergePatch", "(", "docData", ",", "patchData", "[", "]", "byte", ")", "(", "[", "]", "byte", ",", "error", ")", "{", "return", "doMergePatch", "(", "docData", ",", "patchData", ",", "false", ")", "\n", "}" ]
// MergePatch merges the patchData into the docData.
[ "MergePatch", "merges", "the", "patchData", "into", "the", "docData", "." ]
5858425f75500d40c52783dce87d085a483ce135
https://github.com/evanphx/json-patch/blob/5858425f75500d40c52783dce87d085a483ce135/merge.go#L103-L105
152,984
evanphx/json-patch
merge.go
resemblesJSONArray
func resemblesJSONArray(input []byte) bool { input = bytes.TrimSpace(input) hasPrefix := bytes.HasPrefix(input, []byte("[")) hasSuffix := bytes.HasSuffix(input, []byte("]")) return hasPrefix && hasSuffix }
go
func resemblesJSONArray(input []byte) bool { input = bytes.TrimSpace(input) hasPrefix := bytes.HasPrefix(input, []byte("[")) hasSuffix := bytes.HasSuffix(input, []byte("]")) return hasPrefix && hasSuffix }
[ "func", "resemblesJSONArray", "(", "input", "[", "]", "byte", ")", "bool", "{", "input", "=", "bytes", ".", "TrimSpace", "(", "input", ")", "\n\n", "hasPrefix", ":=", "bytes", ".", "HasPrefix", "(", "input", ",", "[", "]", "byte", "(", "\"", "\"", ")...
// resemblesJSONArray indicates whether the byte-slice "appears" to be // a JSON array or not. // False-positives are possible, as this function does not check the internal // structure of the array. It only checks that the outer syntax is present and // correct.
[ "resemblesJSONArray", "indicates", "whether", "the", "byte", "-", "slice", "appears", "to", "be", "a", "JSON", "array", "or", "not", ".", "False", "-", "positives", "are", "possible", "as", "this", "function", "does", "not", "check", "the", "internal", "stru...
5858425f75500d40c52783dce87d085a483ce135
https://github.com/evanphx/json-patch/blob/5858425f75500d40c52783dce87d085a483ce135/merge.go#L170-L177
152,985
evanphx/json-patch
merge.go
createObjectMergePatch
func createObjectMergePatch(originalJSON, modifiedJSON []byte) ([]byte, error) { originalDoc := map[string]interface{}{} modifiedDoc := map[string]interface{}{} err := json.Unmarshal(originalJSON, &originalDoc) if err != nil { return nil, errBadJSONDoc } err = json.Unmarshal(modifiedJSON, &modifiedDoc) if err != nil { return nil, errBadJSONDoc } dest, err := getDiff(originalDoc, modifiedDoc) if err != nil { return nil, err } return json.Marshal(dest) }
go
func createObjectMergePatch(originalJSON, modifiedJSON []byte) ([]byte, error) { originalDoc := map[string]interface{}{} modifiedDoc := map[string]interface{}{} err := json.Unmarshal(originalJSON, &originalDoc) if err != nil { return nil, errBadJSONDoc } err = json.Unmarshal(modifiedJSON, &modifiedDoc) if err != nil { return nil, errBadJSONDoc } dest, err := getDiff(originalDoc, modifiedDoc) if err != nil { return nil, err } return json.Marshal(dest) }
[ "func", "createObjectMergePatch", "(", "originalJSON", ",", "modifiedJSON", "[", "]", "byte", ")", "(", "[", "]", "byte", ",", "error", ")", "{", "originalDoc", ":=", "map", "[", "string", "]", "interface", "{", "}", "{", "}", "\n", "modifiedDoc", ":=", ...
// createObjectMergePatch will return a merge-patch document capable of // converting the original document to the modified document.
[ "createObjectMergePatch", "will", "return", "a", "merge", "-", "patch", "document", "capable", "of", "converting", "the", "original", "document", "to", "the", "modified", "document", "." ]
5858425f75500d40c52783dce87d085a483ce135
https://github.com/evanphx/json-patch/blob/5858425f75500d40c52783dce87d085a483ce135/merge.go#L204-L224
152,986
evanphx/json-patch
merge.go
createArrayMergePatch
func createArrayMergePatch(originalJSON, modifiedJSON []byte) ([]byte, error) { originalDocs := []json.RawMessage{} modifiedDocs := []json.RawMessage{} err := json.Unmarshal(originalJSON, &originalDocs) if err != nil { return nil, errBadJSONDoc } err = json.Unmarshal(modifiedJSON, &modifiedDocs) if err != nil { return nil, errBadJSONDoc } total := len(originalDocs) if len(modifiedDocs) != total { return nil, errBadJSONDoc } result := []json.RawMessage{} for i := 0; i < len(originalDocs); i++ { original := originalDocs[i] modified := modifiedDocs[i] patch, err := createObjectMergePatch(original, modified) if err != nil { return nil, err } result = append(result, json.RawMessage(patch)) } return json.Marshal(result) }
go
func createArrayMergePatch(originalJSON, modifiedJSON []byte) ([]byte, error) { originalDocs := []json.RawMessage{} modifiedDocs := []json.RawMessage{} err := json.Unmarshal(originalJSON, &originalDocs) if err != nil { return nil, errBadJSONDoc } err = json.Unmarshal(modifiedJSON, &modifiedDocs) if err != nil { return nil, errBadJSONDoc } total := len(originalDocs) if len(modifiedDocs) != total { return nil, errBadJSONDoc } result := []json.RawMessage{} for i := 0; i < len(originalDocs); i++ { original := originalDocs[i] modified := modifiedDocs[i] patch, err := createObjectMergePatch(original, modified) if err != nil { return nil, err } result = append(result, json.RawMessage(patch)) } return json.Marshal(result) }
[ "func", "createArrayMergePatch", "(", "originalJSON", ",", "modifiedJSON", "[", "]", "byte", ")", "(", "[", "]", "byte", ",", "error", ")", "{", "originalDocs", ":=", "[", "]", "json", ".", "RawMessage", "{", "}", "\n", "modifiedDocs", ":=", "[", "]", ...
// createArrayMergePatch will return an array of merge-patch documents capable // of converting the original document to the modified document for each // pair of JSON documents provided in the arrays. // Arrays of mismatched sizes will result in an error.
[ "createArrayMergePatch", "will", "return", "an", "array", "of", "merge", "-", "patch", "documents", "capable", "of", "converting", "the", "original", "document", "to", "the", "modified", "document", "for", "each", "pair", "of", "JSON", "documents", "provided", "...
5858425f75500d40c52783dce87d085a483ce135
https://github.com/evanphx/json-patch/blob/5858425f75500d40c52783dce87d085a483ce135/merge.go#L230-L263
152,987
mssola/user_agent
operating_systems.go
normalizeOS
func normalizeOS(name string) string { sp := strings.SplitN(name, " ", 3) if len(sp) != 3 || sp[1] != "NT" { return name } switch sp[2] { case "5.0": return "Windows 2000" case "5.01": return "Windows 2000, Service Pack 1 (SP1)" case "5.1": return "Windows XP" case "5.2": return "Windows XP x64 Edition" case "6.0": return "Windows Vista" case "6.1": return "Windows 7" case "6.2": return "Windows 8" case "6.3": return "Windows 8.1" case "10.0": return "Windows 10" } return name }
go
func normalizeOS(name string) string { sp := strings.SplitN(name, " ", 3) if len(sp) != 3 || sp[1] != "NT" { return name } switch sp[2] { case "5.0": return "Windows 2000" case "5.01": return "Windows 2000, Service Pack 1 (SP1)" case "5.1": return "Windows XP" case "5.2": return "Windows XP x64 Edition" case "6.0": return "Windows Vista" case "6.1": return "Windows 7" case "6.2": return "Windows 8" case "6.3": return "Windows 8.1" case "10.0": return "Windows 10" } return name }
[ "func", "normalizeOS", "(", "name", "string", ")", "string", "{", "sp", ":=", "strings", ".", "SplitN", "(", "name", ",", "\"", "\"", ",", "3", ")", "\n", "if", "len", "(", "sp", ")", "!=", "3", "||", "sp", "[", "1", "]", "!=", "\"", "\"", "{...
// Normalize the name of the operating system. By now, this just // affects to Windows NT. // // Returns a string containing the normalized name for the Operating System.
[ "Normalize", "the", "name", "of", "the", "operating", "system", ".", "By", "now", "this", "just", "affects", "to", "Windows", "NT", ".", "Returns", "a", "string", "containing", "the", "normalized", "name", "for", "the", "Operating", "System", "." ]
74451004a1beb37221bccd8a3931c6acf4a2e80e
https://github.com/mssola/user_agent/blob/74451004a1beb37221bccd8a3931c6acf4a2e80e/operating_systems.go#L26-L53
152,988
mssola/user_agent
operating_systems.go
webkit
func webkit(p *UserAgent, comment []string) { if p.platform == "webOS" { p.browser.Name = p.platform p.os = "Palm" if len(comment) > 2 { p.localization = comment[2] } p.mobile = true } else if p.platform == "Symbian" { p.mobile = true p.browser.Name = p.platform p.os = comment[0] } else if p.platform == "Linux" { p.mobile = true if p.browser.Name == "Safari" { p.browser.Name = "Android" } if len(comment) > 1 { if comment[1] == "U" { if len(comment) > 2 { p.os = comment[2] } else { p.mobile = false p.os = comment[0] } } else { p.os = comment[1] } } if len(comment) > 3 { p.localization = comment[3] } else if len(comment) == 3 { _ = p.googleBot() } } else if len(comment) > 0 { if len(comment) > 3 { p.localization = comment[3] } if strings.HasPrefix(comment[0], "Windows NT") { p.os = normalizeOS(comment[0]) } else if len(comment) < 2 { p.localization = comment[0] } else if len(comment) < 3 { if !p.googleBot() { p.os = normalizeOS(comment[1]) } } else { p.os = normalizeOS(comment[2]) } if p.platform == "BlackBerry" { p.browser.Name = p.platform if p.os == "Touch" { p.os = p.platform } } } }
go
func webkit(p *UserAgent, comment []string) { if p.platform == "webOS" { p.browser.Name = p.platform p.os = "Palm" if len(comment) > 2 { p.localization = comment[2] } p.mobile = true } else if p.platform == "Symbian" { p.mobile = true p.browser.Name = p.platform p.os = comment[0] } else if p.platform == "Linux" { p.mobile = true if p.browser.Name == "Safari" { p.browser.Name = "Android" } if len(comment) > 1 { if comment[1] == "U" { if len(comment) > 2 { p.os = comment[2] } else { p.mobile = false p.os = comment[0] } } else { p.os = comment[1] } } if len(comment) > 3 { p.localization = comment[3] } else if len(comment) == 3 { _ = p.googleBot() } } else if len(comment) > 0 { if len(comment) > 3 { p.localization = comment[3] } if strings.HasPrefix(comment[0], "Windows NT") { p.os = normalizeOS(comment[0]) } else if len(comment) < 2 { p.localization = comment[0] } else if len(comment) < 3 { if !p.googleBot() { p.os = normalizeOS(comment[1]) } } else { p.os = normalizeOS(comment[2]) } if p.platform == "BlackBerry" { p.browser.Name = p.platform if p.os == "Touch" { p.os = p.platform } } } }
[ "func", "webkit", "(", "p", "*", "UserAgent", ",", "comment", "[", "]", "string", ")", "{", "if", "p", ".", "platform", "==", "\"", "\"", "{", "p", ".", "browser", ".", "Name", "=", "p", ".", "platform", "\n", "p", ".", "os", "=", "\"", "\"", ...
// Guess the OS, the localization and if this is a mobile device for a // Webkit-powered browser. // // The first argument p is a reference to the current UserAgent and the second // argument is a slice of strings containing the comment.
[ "Guess", "the", "OS", "the", "localization", "and", "if", "this", "is", "a", "mobile", "device", "for", "a", "Webkit", "-", "powered", "browser", ".", "The", "first", "argument", "p", "is", "a", "reference", "to", "the", "current", "UserAgent", "and", "t...
74451004a1beb37221bccd8a3931c6acf4a2e80e
https://github.com/mssola/user_agent/blob/74451004a1beb37221bccd8a3931c6acf4a2e80e/operating_systems.go#L60-L116
152,989
mssola/user_agent
operating_systems.go
gecko
func gecko(p *UserAgent, comment []string) { if len(comment) > 1 { if comment[1] == "U" { if len(comment) > 2 { p.os = normalizeOS(comment[2]) } else { p.os = normalizeOS(comment[1]) } } else { if strings.Contains(p.platform, "Android") { p.mobile = true p.platform, p.os = normalizeOS(comment[1]), p.platform } else if comment[0] == "Mobile" || comment[0] == "Tablet" { p.mobile = true p.os = "FirefoxOS" } else { if p.os == "" { p.os = normalizeOS(comment[1]) } } } // Only parse 4th comment as localization if it doesn't start with rv:. // For example Firefox on Ubuntu contains "rv:XX.X" in this field. if len(comment) > 3 && !strings.HasPrefix(comment[3], "rv:") { p.localization = comment[3] } } }
go
func gecko(p *UserAgent, comment []string) { if len(comment) > 1 { if comment[1] == "U" { if len(comment) > 2 { p.os = normalizeOS(comment[2]) } else { p.os = normalizeOS(comment[1]) } } else { if strings.Contains(p.platform, "Android") { p.mobile = true p.platform, p.os = normalizeOS(comment[1]), p.platform } else if comment[0] == "Mobile" || comment[0] == "Tablet" { p.mobile = true p.os = "FirefoxOS" } else { if p.os == "" { p.os = normalizeOS(comment[1]) } } } // Only parse 4th comment as localization if it doesn't start with rv:. // For example Firefox on Ubuntu contains "rv:XX.X" in this field. if len(comment) > 3 && !strings.HasPrefix(comment[3], "rv:") { p.localization = comment[3] } } }
[ "func", "gecko", "(", "p", "*", "UserAgent", ",", "comment", "[", "]", "string", ")", "{", "if", "len", "(", "comment", ")", ">", "1", "{", "if", "comment", "[", "1", "]", "==", "\"", "\"", "{", "if", "len", "(", "comment", ")", ">", "2", "{"...
// Guess the OS, the localization and if this is a mobile device // for a Gecko-powered browser. // // The first argument p is a reference to the current UserAgent and the second // argument is a slice of strings containing the comment.
[ "Guess", "the", "OS", "the", "localization", "and", "if", "this", "is", "a", "mobile", "device", "for", "a", "Gecko", "-", "powered", "browser", ".", "The", "first", "argument", "p", "is", "a", "reference", "to", "the", "current", "UserAgent", "and", "th...
74451004a1beb37221bccd8a3931c6acf4a2e80e
https://github.com/mssola/user_agent/blob/74451004a1beb37221bccd8a3931c6acf4a2e80e/operating_systems.go#L123-L150
152,990
mssola/user_agent
operating_systems.go
trident
func trident(p *UserAgent, comment []string) { // Internet Explorer only runs on Windows. p.platform = "Windows" // The OS can be set before to handle a new case in IE11. if p.os == "" { if len(comment) > 2 { p.os = normalizeOS(comment[2]) } else { p.os = "Windows NT 4.0" } } // Last but not least, let's detect if it comes from a mobile device. for _, v := range comment { if strings.HasPrefix(v, "IEMobile") { p.mobile = true return } } }
go
func trident(p *UserAgent, comment []string) { // Internet Explorer only runs on Windows. p.platform = "Windows" // The OS can be set before to handle a new case in IE11. if p.os == "" { if len(comment) > 2 { p.os = normalizeOS(comment[2]) } else { p.os = "Windows NT 4.0" } } // Last but not least, let's detect if it comes from a mobile device. for _, v := range comment { if strings.HasPrefix(v, "IEMobile") { p.mobile = true return } } }
[ "func", "trident", "(", "p", "*", "UserAgent", ",", "comment", "[", "]", "string", ")", "{", "// Internet Explorer only runs on Windows.", "p", ".", "platform", "=", "\"", "\"", "\n\n", "// The OS can be set before to handle a new case in IE11.", "if", "p", ".", "os...
// Guess the OS, the localization and if this is a mobile device // for Internet Explorer. // // The first argument p is a reference to the current UserAgent and the second // argument is a slice of strings containing the comment.
[ "Guess", "the", "OS", "the", "localization", "and", "if", "this", "is", "a", "mobile", "device", "for", "Internet", "Explorer", ".", "The", "first", "argument", "p", "is", "a", "reference", "to", "the", "current", "UserAgent", "and", "the", "second", "argu...
74451004a1beb37221bccd8a3931c6acf4a2e80e
https://github.com/mssola/user_agent/blob/74451004a1beb37221bccd8a3931c6acf4a2e80e/operating_systems.go#L157-L177
152,991
mssola/user_agent
operating_systems.go
opera
func opera(p *UserAgent, comment []string) { slen := len(comment) if strings.HasPrefix(comment[0], "Windows") { p.platform = "Windows" p.os = normalizeOS(comment[0]) if slen > 2 { if slen > 3 && strings.HasPrefix(comment[2], "MRA") { p.localization = comment[3] } else { p.localization = comment[2] } } } else { if strings.HasPrefix(comment[0], "Android") { p.mobile = true } p.platform = comment[0] if slen > 1 { p.os = comment[1] if slen > 3 { p.localization = comment[3] } } else { p.os = comment[0] } } }
go
func opera(p *UserAgent, comment []string) { slen := len(comment) if strings.HasPrefix(comment[0], "Windows") { p.platform = "Windows" p.os = normalizeOS(comment[0]) if slen > 2 { if slen > 3 && strings.HasPrefix(comment[2], "MRA") { p.localization = comment[3] } else { p.localization = comment[2] } } } else { if strings.HasPrefix(comment[0], "Android") { p.mobile = true } p.platform = comment[0] if slen > 1 { p.os = comment[1] if slen > 3 { p.localization = comment[3] } } else { p.os = comment[0] } } }
[ "func", "opera", "(", "p", "*", "UserAgent", ",", "comment", "[", "]", "string", ")", "{", "slen", ":=", "len", "(", "comment", ")", "\n\n", "if", "strings", ".", "HasPrefix", "(", "comment", "[", "0", "]", ",", "\"", "\"", ")", "{", "p", ".", ...
// Guess the OS, the localization and if this is a mobile device // for Opera. // // The first argument p is a reference to the current UserAgent and the second // argument is a slice of strings containing the comment.
[ "Guess", "the", "OS", "the", "localization", "and", "if", "this", "is", "a", "mobile", "device", "for", "Opera", ".", "The", "first", "argument", "p", "is", "a", "reference", "to", "the", "current", "UserAgent", "and", "the", "second", "argument", "is", ...
74451004a1beb37221bccd8a3931c6acf4a2e80e
https://github.com/mssola/user_agent/blob/74451004a1beb37221bccd8a3931c6acf4a2e80e/operating_systems.go#L184-L211
152,992
mssola/user_agent
operating_systems.go
dalvik
func dalvik(p *UserAgent, comment []string) { slen := len(comment) if strings.HasPrefix(comment[0], "Linux") { p.platform = comment[0] if slen > 2 { p.os = comment[2] } p.mobile = true } }
go
func dalvik(p *UserAgent, comment []string) { slen := len(comment) if strings.HasPrefix(comment[0], "Linux") { p.platform = comment[0] if slen > 2 { p.os = comment[2] } p.mobile = true } }
[ "func", "dalvik", "(", "p", "*", "UserAgent", ",", "comment", "[", "]", "string", ")", "{", "slen", ":=", "len", "(", "comment", ")", "\n\n", "if", "strings", ".", "HasPrefix", "(", "comment", "[", "0", "]", ",", "\"", "\"", ")", "{", "p", ".", ...
// Guess the OS. Android browsers send Dalvik as the user agent in the // request header. // // The first argument p is a reference to the current UserAgent and the second // argument is a slice of strings containing the comment.
[ "Guess", "the", "OS", ".", "Android", "browsers", "send", "Dalvik", "as", "the", "user", "agent", "in", "the", "request", "header", ".", "The", "first", "argument", "p", "is", "a", "reference", "to", "the", "current", "UserAgent", "and", "the", "second", ...
74451004a1beb37221bccd8a3931c6acf4a2e80e
https://github.com/mssola/user_agent/blob/74451004a1beb37221bccd8a3931c6acf4a2e80e/operating_systems.go#L218-L228
152,993
mssola/user_agent
operating_systems.go
getPlatform
func getPlatform(comment []string) string { if len(comment) > 0 { if comment[0] != "compatible" { if strings.HasPrefix(comment[0], "Windows") { return "Windows" } else if strings.HasPrefix(comment[0], "Symbian") { return "Symbian" } else if strings.HasPrefix(comment[0], "webOS") { return "webOS" } else if comment[0] == "BB10" { return "BlackBerry" } return comment[0] } } return "" }
go
func getPlatform(comment []string) string { if len(comment) > 0 { if comment[0] != "compatible" { if strings.HasPrefix(comment[0], "Windows") { return "Windows" } else if strings.HasPrefix(comment[0], "Symbian") { return "Symbian" } else if strings.HasPrefix(comment[0], "webOS") { return "webOS" } else if comment[0] == "BB10" { return "BlackBerry" } return comment[0] } } return "" }
[ "func", "getPlatform", "(", "comment", "[", "]", "string", ")", "string", "{", "if", "len", "(", "comment", ")", ">", "0", "{", "if", "comment", "[", "0", "]", "!=", "\"", "\"", "{", "if", "strings", ".", "HasPrefix", "(", "comment", "[", "0", "]...
// Given the comment of the first section of the UserAgent string, // get the platform.
[ "Given", "the", "comment", "of", "the", "first", "section", "of", "the", "UserAgent", "string", "get", "the", "platform", "." ]
74451004a1beb37221bccd8a3931c6acf4a2e80e
https://github.com/mssola/user_agent/blob/74451004a1beb37221bccd8a3931c6acf4a2e80e/operating_systems.go#L232-L248
152,994
mssola/user_agent
operating_systems.go
detectOS
func (p *UserAgent) detectOS(s section) { if s.name == "Mozilla" { // Get the platform here. Be aware that IE11 provides a new format // that is not backwards-compatible with previous versions of IE. p.platform = getPlatform(s.comment) if p.platform == "Windows" && len(s.comment) > 0 { p.os = normalizeOS(s.comment[0]) } // And finally get the OS depending on the engine. switch p.browser.Engine { case "": p.undecided = true case "Gecko": gecko(p, s.comment) case "AppleWebKit": webkit(p, s.comment) case "Trident": trident(p, s.comment) } } else if s.name == "Opera" { if len(s.comment) > 0 { opera(p, s.comment) } } else if s.name == "Dalvik" { if len(s.comment) > 0 { dalvik(p, s.comment) } } else { // Check whether this is a bot or just a weird browser. p.undecided = true } }
go
func (p *UserAgent) detectOS(s section) { if s.name == "Mozilla" { // Get the platform here. Be aware that IE11 provides a new format // that is not backwards-compatible with previous versions of IE. p.platform = getPlatform(s.comment) if p.platform == "Windows" && len(s.comment) > 0 { p.os = normalizeOS(s.comment[0]) } // And finally get the OS depending on the engine. switch p.browser.Engine { case "": p.undecided = true case "Gecko": gecko(p, s.comment) case "AppleWebKit": webkit(p, s.comment) case "Trident": trident(p, s.comment) } } else if s.name == "Opera" { if len(s.comment) > 0 { opera(p, s.comment) } } else if s.name == "Dalvik" { if len(s.comment) > 0 { dalvik(p, s.comment) } } else { // Check whether this is a bot or just a weird browser. p.undecided = true } }
[ "func", "(", "p", "*", "UserAgent", ")", "detectOS", "(", "s", "section", ")", "{", "if", "s", ".", "name", "==", "\"", "\"", "{", "// Get the platform here. Be aware that IE11 provides a new format", "// that is not backwards-compatible with previous versions of IE.", "p...
// Detect some properties of the OS from the given section.
[ "Detect", "some", "properties", "of", "the", "OS", "from", "the", "given", "section", "." ]
74451004a1beb37221bccd8a3931c6acf4a2e80e
https://github.com/mssola/user_agent/blob/74451004a1beb37221bccd8a3931c6acf4a2e80e/operating_systems.go#L251-L283
152,995
mssola/user_agent
operating_systems.go
osName
func osName(osSplit []string) (name, version string) { if len(osSplit) == 1 { name = osSplit[0] version = "" } else { // Assume version is stored in the last part of the array. nameSplit := osSplit[:len(osSplit)-1] version = osSplit[len(osSplit)-1] // Nicer looking Mac OS X if len(nameSplit) >= 2 && nameSplit[0] == "Intel" && nameSplit[1] == "Mac" { nameSplit = nameSplit[1:] } name = strings.Join(nameSplit, " ") if strings.Contains(version, "x86") || strings.Contains(version, "i686") { // x86_64 and i868 are not Linux versions but architectures version = "" } else if version == "X" && name == "Mac OS" { // X is not a version for Mac OS. name = name + " " + version version = "" } } return name, version }
go
func osName(osSplit []string) (name, version string) { if len(osSplit) == 1 { name = osSplit[0] version = "" } else { // Assume version is stored in the last part of the array. nameSplit := osSplit[:len(osSplit)-1] version = osSplit[len(osSplit)-1] // Nicer looking Mac OS X if len(nameSplit) >= 2 && nameSplit[0] == "Intel" && nameSplit[1] == "Mac" { nameSplit = nameSplit[1:] } name = strings.Join(nameSplit, " ") if strings.Contains(version, "x86") || strings.Contains(version, "i686") { // x86_64 and i868 are not Linux versions but architectures version = "" } else if version == "X" && name == "Mac OS" { // X is not a version for Mac OS. name = name + " " + version version = "" } } return name, version }
[ "func", "osName", "(", "osSplit", "[", "]", "string", ")", "(", "name", ",", "version", "string", ")", "{", "if", "len", "(", "osSplit", ")", "==", "1", "{", "name", "=", "osSplit", "[", "0", "]", "\n", "version", "=", "\"", "\"", "\n", "}", "e...
// Return OS name and version from a slice of strings created from the full name of the OS.
[ "Return", "OS", "name", "and", "version", "from", "a", "slice", "of", "strings", "created", "from", "the", "full", "name", "of", "the", "OS", "." ]
74451004a1beb37221bccd8a3931c6acf4a2e80e
https://github.com/mssola/user_agent/blob/74451004a1beb37221bccd8a3931c6acf4a2e80e/operating_systems.go#L301-L326
152,996
mssola/user_agent
operating_systems.go
OSInfo
func (p *UserAgent) OSInfo() OSInfo { // Special case for iPhone weirdness os := strings.Replace(p.os, "like Mac OS X", "", 1) os = strings.Replace(os, "CPU", "", 1) os = strings.Trim(os, " ") osSplit := strings.Split(os, " ") // Special case for x64 edition of Windows if os == "Windows XP x64 Edition" { osSplit = osSplit[:len(osSplit)-2] } name, version := osName(osSplit) // Special case for names that contain a forward slash version separator. if strings.Contains(name, "/") { s := strings.Split(name, "/") name = s[0] version = s[1] } // Special case for versions that use underscores version = strings.Replace(version, "_", ".", -1) return OSInfo{ FullName: p.os, Name: name, Version: version, } }
go
func (p *UserAgent) OSInfo() OSInfo { // Special case for iPhone weirdness os := strings.Replace(p.os, "like Mac OS X", "", 1) os = strings.Replace(os, "CPU", "", 1) os = strings.Trim(os, " ") osSplit := strings.Split(os, " ") // Special case for x64 edition of Windows if os == "Windows XP x64 Edition" { osSplit = osSplit[:len(osSplit)-2] } name, version := osName(osSplit) // Special case for names that contain a forward slash version separator. if strings.Contains(name, "/") { s := strings.Split(name, "/") name = s[0] version = s[1] } // Special case for versions that use underscores version = strings.Replace(version, "_", ".", -1) return OSInfo{ FullName: p.os, Name: name, Version: version, } }
[ "func", "(", "p", "*", "UserAgent", ")", "OSInfo", "(", ")", "OSInfo", "{", "// Special case for iPhone weirdness", "os", ":=", "strings", ".", "Replace", "(", "p", ".", "os", ",", "\"", "\"", ",", "\"", "\"", ",", "1", ")", "\n", "os", "=", "strings...
// OSInfo returns combined information for the operating system.
[ "OSInfo", "returns", "combined", "information", "for", "the", "operating", "system", "." ]
74451004a1beb37221bccd8a3931c6acf4a2e80e
https://github.com/mssola/user_agent/blob/74451004a1beb37221bccd8a3931c6acf4a2e80e/operating_systems.go#L329-L359
152,997
mssola/user_agent
browser.go
Engine
func (p *UserAgent) Engine() (string, string) { return p.browser.Engine, p.browser.EngineVersion }
go
func (p *UserAgent) Engine() (string, string) { return p.browser.Engine, p.browser.EngineVersion }
[ "func", "(", "p", "*", "UserAgent", ")", "Engine", "(", ")", "(", "string", ",", "string", ")", "{", "return", "p", ".", "browser", ".", "Engine", ",", "p", ".", "browser", ".", "EngineVersion", "\n", "}" ]
// Engine returns two strings. The first string is the name of the engine and the // second one is the version of the engine.
[ "Engine", "returns", "two", "strings", ".", "The", "first", "string", "is", "the", "name", "of", "the", "engine", "and", "the", "second", "one", "is", "the", "version", "of", "the", "engine", "." ]
74451004a1beb37221bccd8a3931c6acf4a2e80e
https://github.com/mssola/user_agent/blob/74451004a1beb37221bccd8a3931c6acf4a2e80e/browser.go#L146-L148
152,998
mssola/user_agent
browser.go
Browser
func (p *UserAgent) Browser() (string, string) { return p.browser.Name, p.browser.Version }
go
func (p *UserAgent) Browser() (string, string) { return p.browser.Name, p.browser.Version }
[ "func", "(", "p", "*", "UserAgent", ")", "Browser", "(", ")", "(", "string", ",", "string", ")", "{", "return", "p", ".", "browser", ".", "Name", ",", "p", ".", "browser", ".", "Version", "\n", "}" ]
// Browser returns two strings. The first string is the name of the browser and the // second one is the version of the browser.
[ "Browser", "returns", "two", "strings", ".", "The", "first", "string", "is", "the", "name", "of", "the", "browser", "and", "the", "second", "one", "is", "the", "version", "of", "the", "browser", "." ]
74451004a1beb37221bccd8a3931c6acf4a2e80e
https://github.com/mssola/user_agent/blob/74451004a1beb37221bccd8a3931c6acf4a2e80e/browser.go#L152-L154
152,999
mssola/user_agent
user_agent.go
readUntil
func readUntil(ua string, index *int, delimiter byte, cat bool) []byte { var buffer []byte i := *index catalan := 0 for ; i < len(ua); i = i + 1 { if ua[i] == delimiter { if catalan == 0 { *index = i + 1 return buffer } catalan-- } else if cat && ua[i] == '(' { catalan++ } buffer = append(buffer, ua[i]) } *index = i + 1 return buffer }
go
func readUntil(ua string, index *int, delimiter byte, cat bool) []byte { var buffer []byte i := *index catalan := 0 for ; i < len(ua); i = i + 1 { if ua[i] == delimiter { if catalan == 0 { *index = i + 1 return buffer } catalan-- } else if cat && ua[i] == '(' { catalan++ } buffer = append(buffer, ua[i]) } *index = i + 1 return buffer }
[ "func", "readUntil", "(", "ua", "string", ",", "index", "*", "int", ",", "delimiter", "byte", ",", "cat", "bool", ")", "[", "]", "byte", "{", "var", "buffer", "[", "]", "byte", "\n\n", "i", ":=", "*", "index", "\n", "catalan", ":=", "0", "\n", "f...
// Read from the given string until the given delimiter or the // end of the string have been reached. // // The first argument is the user agent string being parsed. The second // argument is a reference pointing to the current index of the user agent // string. The delimiter argument specifies which character is the delimiter // and the cat argument determines whether nested '(' should be ignored or not. // // Returns an array of bytes containing what has been read.
[ "Read", "from", "the", "given", "string", "until", "the", "given", "delimiter", "or", "the", "end", "of", "the", "string", "have", "been", "reached", ".", "The", "first", "argument", "is", "the", "user", "agent", "string", "being", "parsed", ".", "The", ...
74451004a1beb37221bccd8a3931c6acf4a2e80e
https://github.com/mssola/user_agent/blob/74451004a1beb37221bccd8a3931c6acf4a2e80e/user_agent.go#L44-L63