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
list
docstring
stringlengths
6
2.61k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
85
252
partition
stringclasses
1 value
JamesClonk/vultr
lib/dns.go
DeleteDNSDomain
func (c *Client) DeleteDNSDomain(domain string) error { values := url.Values{ "domain": {domain}, } if err := c.post(`dns/delete_domain`, values, nil); err != nil { return err } return nil }
go
func (c *Client) DeleteDNSDomain(domain string) error { values := url.Values{ "domain": {domain}, } if err := c.post(`dns/delete_domain`, values, nil); err != nil { return err } return nil }
[ "func", "(", "c", "*", "Client", ")", "DeleteDNSDomain", "(", "domain", "string", ")", "error", "{", "values", ":=", "url", ".", "Values", "{", "\"", "\"", ":", "{", "domain", "}", ",", "}", "\n\n", "if", "err", ":=", "c", ".", "post", "(", "`dns...
// DeleteDNSDomain deletes an existing DNS domain name
[ "DeleteDNSDomain", "deletes", "an", "existing", "DNS", "domain", "name" ]
fed59ad207c9bda0a5dfe4d18de53ccbb3d80c91
https://github.com/JamesClonk/vultr/blob/fed59ad207c9bda0a5dfe4d18de53ccbb3d80c91/lib/dns.go#L85-L94
train
JamesClonk/vultr
lib/dns.go
CreateDNSRecord
func (c *Client) CreateDNSRecord(domain, name, rtype, data string, priority, ttl int) error { values := url.Values{ "domain": {domain}, "name": {name}, "type": {rtype}, "data": {data}, "priority": {fmt.Sprintf("%v", priority)}, "ttl": {fmt.Sprintf("%v", ttl)}, } if err := c.post(`dns/create_record`, values, nil); err != nil { return err } return nil }
go
func (c *Client) CreateDNSRecord(domain, name, rtype, data string, priority, ttl int) error { values := url.Values{ "domain": {domain}, "name": {name}, "type": {rtype}, "data": {data}, "priority": {fmt.Sprintf("%v", priority)}, "ttl": {fmt.Sprintf("%v", ttl)}, } if err := c.post(`dns/create_record`, values, nil); err != nil { return err } return nil }
[ "func", "(", "c", "*", "Client", ")", "CreateDNSRecord", "(", "domain", ",", "name", ",", "rtype", ",", "data", "string", ",", "priority", ",", "ttl", "int", ")", "error", "{", "values", ":=", "url", ".", "Values", "{", "\"", "\"", ":", "{", "domai...
// CreateDNSRecord creates a new DNS record
[ "CreateDNSRecord", "creates", "a", "new", "DNS", "record" ]
fed59ad207c9bda0a5dfe4d18de53ccbb3d80c91
https://github.com/JamesClonk/vultr/blob/fed59ad207c9bda0a5dfe4d18de53ccbb3d80c91/lib/dns.go#L97-L111
train
JamesClonk/vultr
lib/dns.go
UpdateDNSRecord
func (c *Client) UpdateDNSRecord(domain string, dnsrecord DNSRecord) error { values := url.Values{ "domain": {domain}, "RECORDID": {fmt.Sprintf("%v", dnsrecord.RecordID)}, } if dnsrecord.Name != "" { values.Add("name", dnsrecord.Name) } if dnsrecord.Data != "" { values.Add("data", dnsrecord.Data) } if dnsrecord.Priority != 0 { values.Add("priority", fmt.Sprintf("%v", dnsrecord.Priority)) } if dnsrecord.TTL != 0 { values.Add("ttl", fmt.Sprintf("%v", dnsrecord.TTL)) } if err := c.post(`dns/update_record`, values, nil); err != nil { return err } return nil }
go
func (c *Client) UpdateDNSRecord(domain string, dnsrecord DNSRecord) error { values := url.Values{ "domain": {domain}, "RECORDID": {fmt.Sprintf("%v", dnsrecord.RecordID)}, } if dnsrecord.Name != "" { values.Add("name", dnsrecord.Name) } if dnsrecord.Data != "" { values.Add("data", dnsrecord.Data) } if dnsrecord.Priority != 0 { values.Add("priority", fmt.Sprintf("%v", dnsrecord.Priority)) } if dnsrecord.TTL != 0 { values.Add("ttl", fmt.Sprintf("%v", dnsrecord.TTL)) } if err := c.post(`dns/update_record`, values, nil); err != nil { return err } return nil }
[ "func", "(", "c", "*", "Client", ")", "UpdateDNSRecord", "(", "domain", "string", ",", "dnsrecord", "DNSRecord", ")", "error", "{", "values", ":=", "url", ".", "Values", "{", "\"", "\"", ":", "{", "domain", "}", ",", "\"", "\"", ":", "{", "fmt", "....
// UpdateDNSRecord updates an existing DNS record
[ "UpdateDNSRecord", "updates", "an", "existing", "DNS", "record" ]
fed59ad207c9bda0a5dfe4d18de53ccbb3d80c91
https://github.com/JamesClonk/vultr/blob/fed59ad207c9bda0a5dfe4d18de53ccbb3d80c91/lib/dns.go#L114-L137
train
JamesClonk/vultr
lib/dns.go
DeleteDNSRecord
func (c *Client) DeleteDNSRecord(domain string, recordID int) error { values := url.Values{ "domain": {domain}, "RECORDID": {fmt.Sprintf("%v", recordID)}, } if err := c.post(`dns/delete_record`, values, nil); err != nil { return err } return nil }
go
func (c *Client) DeleteDNSRecord(domain string, recordID int) error { values := url.Values{ "domain": {domain}, "RECORDID": {fmt.Sprintf("%v", recordID)}, } if err := c.post(`dns/delete_record`, values, nil); err != nil { return err } return nil }
[ "func", "(", "c", "*", "Client", ")", "DeleteDNSRecord", "(", "domain", "string", ",", "recordID", "int", ")", "error", "{", "values", ":=", "url", ".", "Values", "{", "\"", "\"", ":", "{", "domain", "}", ",", "\"", "\"", ":", "{", "fmt", ".", "S...
// DeleteDNSRecord deletes an existing DNS record
[ "DeleteDNSRecord", "deletes", "an", "existing", "DNS", "record" ]
fed59ad207c9bda0a5dfe4d18de53ccbb3d80c91
https://github.com/JamesClonk/vultr/blob/fed59ad207c9bda0a5dfe4d18de53ccbb3d80c91/lib/dns.go#L140-L150
train
JamesClonk/vultr
lib/block_storage.go
UnmarshalJSON
func (b *BlockStorage) UnmarshalJSON(data []byte) (err error) { if b == nil { *b = BlockStorage{} } var fields map[string]interface{} if err := json.Unmarshal(data, &fields); err != nil { return err } value := fmt.Sprintf("%v", fields["SUBID"]) if len(value) == 0 || value == "<nil>" || value == "0" { b.ID = "" } else { id, err := strconv.ParseFloat(value, 64) if err != nil { return err } b.ID = strconv.FormatFloat(id, 'f', -1, 64) } value = fmt.Sprintf("%v", fields["DCID"]) if len(value) == 0 || value == "<nil>" { value = "0" } region, err := strconv.ParseInt(value, 10, 64) if err != nil { return err } b.RegionID = int(region) value = fmt.Sprintf("%v", fields["size_gb"]) if len(value) == 0 || value == "<nil>" { value = "0" } size, err := strconv.ParseInt(value, 10, 64) if err != nil { return err } b.SizeGB = int(size) value = fmt.Sprintf("%v", fields["attached_to_SUBID"]) if len(value) == 0 || value == "<nil>" || value == "0" { b.AttachedTo = "" } else { attached, err := strconv.ParseFloat(value, 64) if err != nil { return err } b.AttachedTo = strconv.FormatFloat(attached, 'f', -1, 64) } b.Name = fmt.Sprintf("%v", fields["label"]) b.Created = fmt.Sprintf("%v", fields["date_created"]) b.Status = fmt.Sprintf("%v", fields["status"]) b.Cost = fmt.Sprintf("%v", fields["cost_per_month"]) return }
go
func (b *BlockStorage) UnmarshalJSON(data []byte) (err error) { if b == nil { *b = BlockStorage{} } var fields map[string]interface{} if err := json.Unmarshal(data, &fields); err != nil { return err } value := fmt.Sprintf("%v", fields["SUBID"]) if len(value) == 0 || value == "<nil>" || value == "0" { b.ID = "" } else { id, err := strconv.ParseFloat(value, 64) if err != nil { return err } b.ID = strconv.FormatFloat(id, 'f', -1, 64) } value = fmt.Sprintf("%v", fields["DCID"]) if len(value) == 0 || value == "<nil>" { value = "0" } region, err := strconv.ParseInt(value, 10, 64) if err != nil { return err } b.RegionID = int(region) value = fmt.Sprintf("%v", fields["size_gb"]) if len(value) == 0 || value == "<nil>" { value = "0" } size, err := strconv.ParseInt(value, 10, 64) if err != nil { return err } b.SizeGB = int(size) value = fmt.Sprintf("%v", fields["attached_to_SUBID"]) if len(value) == 0 || value == "<nil>" || value == "0" { b.AttachedTo = "" } else { attached, err := strconv.ParseFloat(value, 64) if err != nil { return err } b.AttachedTo = strconv.FormatFloat(attached, 'f', -1, 64) } b.Name = fmt.Sprintf("%v", fields["label"]) b.Created = fmt.Sprintf("%v", fields["date_created"]) b.Status = fmt.Sprintf("%v", fields["status"]) b.Cost = fmt.Sprintf("%v", fields["cost_per_month"]) return }
[ "func", "(", "b", "*", "BlockStorage", ")", "UnmarshalJSON", "(", "data", "[", "]", "byte", ")", "(", "err", "error", ")", "{", "if", "b", "==", "nil", "{", "*", "b", "=", "BlockStorage", "{", "}", "\n", "}", "\n\n", "var", "fields", "map", "[", ...
// UnmarshalJSON implements json.Unmarshaller on BlockStorage. // This is needed because the Vultr API is inconsistent in it's JSON responses. // Some fields can change type, from JSON number to JSON string and vice-versa.
[ "UnmarshalJSON", "implements", "json", ".", "Unmarshaller", "on", "BlockStorage", ".", "This", "is", "needed", "because", "the", "Vultr", "API", "is", "inconsistent", "in", "it", "s", "JSON", "responses", ".", "Some", "fields", "can", "change", "type", "from",...
fed59ad207c9bda0a5dfe4d18de53ccbb3d80c91
https://github.com/JamesClonk/vultr/blob/fed59ad207c9bda0a5dfe4d18de53ccbb3d80c91/lib/block_storage.go#L46-L104
train
JamesClonk/vultr
lib/block_storage.go
GetBlockStorages
func (c *Client) GetBlockStorages() (storages []BlockStorage, err error) { if err := c.get(`block/list`, &storages); err != nil { return nil, err } sort.Sort(blockstorages(storages)) return storages, nil }
go
func (c *Client) GetBlockStorages() (storages []BlockStorage, err error) { if err := c.get(`block/list`, &storages); err != nil { return nil, err } sort.Sort(blockstorages(storages)) return storages, nil }
[ "func", "(", "c", "*", "Client", ")", "GetBlockStorages", "(", ")", "(", "storages", "[", "]", "BlockStorage", ",", "err", "error", ")", "{", "if", "err", ":=", "c", ".", "get", "(", "`block/list`", ",", "&", "storages", ")", ";", "err", "!=", "nil...
// GetBlockStorages returns a list of all active block storages on Vultr account
[ "GetBlockStorages", "returns", "a", "list", "of", "all", "active", "block", "storages", "on", "Vultr", "account" ]
fed59ad207c9bda0a5dfe4d18de53ccbb3d80c91
https://github.com/JamesClonk/vultr/blob/fed59ad207c9bda0a5dfe4d18de53ccbb3d80c91/lib/block_storage.go#L107-L113
train
JamesClonk/vultr
lib/block_storage.go
GetBlockStorage
func (c *Client) GetBlockStorage(id string) (BlockStorage, error) { storages, err := c.GetBlockStorages() if err != nil { return BlockStorage{}, err } for _, s := range storages { if s.ID == id { return s, nil } } return BlockStorage{}, fmt.Errorf("BlockStorage with ID %v not found", id) }
go
func (c *Client) GetBlockStorage(id string) (BlockStorage, error) { storages, err := c.GetBlockStorages() if err != nil { return BlockStorage{}, err } for _, s := range storages { if s.ID == id { return s, nil } } return BlockStorage{}, fmt.Errorf("BlockStorage with ID %v not found", id) }
[ "func", "(", "c", "*", "Client", ")", "GetBlockStorage", "(", "id", "string", ")", "(", "BlockStorage", ",", "error", ")", "{", "storages", ",", "err", ":=", "c", ".", "GetBlockStorages", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "Bloc...
// GetBlockStorage returns block storage with given ID
[ "GetBlockStorage", "returns", "block", "storage", "with", "given", "ID" ]
fed59ad207c9bda0a5dfe4d18de53ccbb3d80c91
https://github.com/JamesClonk/vultr/blob/fed59ad207c9bda0a5dfe4d18de53ccbb3d80c91/lib/block_storage.go#L116-L128
train
JamesClonk/vultr
lib/block_storage.go
CreateBlockStorage
func (c *Client) CreateBlockStorage(name string, regionID, size int) (BlockStorage, error) { values := url.Values{ "label": {name}, "DCID": {fmt.Sprintf("%v", regionID)}, "size_gb": {fmt.Sprintf("%v", size)}, } var storage BlockStorage if err := c.post(`block/create`, values, &storage); err != nil { return BlockStorage{}, err } storage.RegionID = regionID storage.Name = name storage.SizeGB = size return storage, nil }
go
func (c *Client) CreateBlockStorage(name string, regionID, size int) (BlockStorage, error) { values := url.Values{ "label": {name}, "DCID": {fmt.Sprintf("%v", regionID)}, "size_gb": {fmt.Sprintf("%v", size)}, } var storage BlockStorage if err := c.post(`block/create`, values, &storage); err != nil { return BlockStorage{}, err } storage.RegionID = regionID storage.Name = name storage.SizeGB = size return storage, nil }
[ "func", "(", "c", "*", "Client", ")", "CreateBlockStorage", "(", "name", "string", ",", "regionID", ",", "size", "int", ")", "(", "BlockStorage", ",", "error", ")", "{", "values", ":=", "url", ".", "Values", "{", "\"", "\"", ":", "{", "name", "}", ...
// CreateBlockStorage creates a new block storage on Vultr account
[ "CreateBlockStorage", "creates", "a", "new", "block", "storage", "on", "Vultr", "account" ]
fed59ad207c9bda0a5dfe4d18de53ccbb3d80c91
https://github.com/JamesClonk/vultr/blob/fed59ad207c9bda0a5dfe4d18de53ccbb3d80c91/lib/block_storage.go#L131-L147
train
JamesClonk/vultr
lib/block_storage.go
ResizeBlockStorage
func (c *Client) ResizeBlockStorage(id string, size int) error { values := url.Values{ "SUBID": {id}, "size_gb": {fmt.Sprintf("%v", size)}, } if err := c.post(`block/resize`, values, nil); err != nil { return err } return nil }
go
func (c *Client) ResizeBlockStorage(id string, size int) error { values := url.Values{ "SUBID": {id}, "size_gb": {fmt.Sprintf("%v", size)}, } if err := c.post(`block/resize`, values, nil); err != nil { return err } return nil }
[ "func", "(", "c", "*", "Client", ")", "ResizeBlockStorage", "(", "id", "string", ",", "size", "int", ")", "error", "{", "values", ":=", "url", ".", "Values", "{", "\"", "\"", ":", "{", "id", "}", ",", "\"", "\"", ":", "{", "fmt", ".", "Sprintf", ...
// ResizeBlockStorage resizes an existing block storage
[ "ResizeBlockStorage", "resizes", "an", "existing", "block", "storage" ]
fed59ad207c9bda0a5dfe4d18de53ccbb3d80c91
https://github.com/JamesClonk/vultr/blob/fed59ad207c9bda0a5dfe4d18de53ccbb3d80c91/lib/block_storage.go#L150-L160
train
JamesClonk/vultr
lib/block_storage.go
AttachBlockStorage
func (c *Client) AttachBlockStorage(id, serverID string) error { values := url.Values{ "SUBID": {id}, "attach_to_SUBID": {serverID}, } if err := c.post(`block/attach`, values, nil); err != nil { return err } return nil }
go
func (c *Client) AttachBlockStorage(id, serverID string) error { values := url.Values{ "SUBID": {id}, "attach_to_SUBID": {serverID}, } if err := c.post(`block/attach`, values, nil); err != nil { return err } return nil }
[ "func", "(", "c", "*", "Client", ")", "AttachBlockStorage", "(", "id", ",", "serverID", "string", ")", "error", "{", "values", ":=", "url", ".", "Values", "{", "\"", "\"", ":", "{", "id", "}", ",", "\"", "\"", ":", "{", "serverID", "}", ",", "}",...
// AttachBlockStorage attaches block storage to an existing virtual machine
[ "AttachBlockStorage", "attaches", "block", "storage", "to", "an", "existing", "virtual", "machine" ]
fed59ad207c9bda0a5dfe4d18de53ccbb3d80c91
https://github.com/JamesClonk/vultr/blob/fed59ad207c9bda0a5dfe4d18de53ccbb3d80c91/lib/block_storage.go#L176-L186
train
JamesClonk/vultr
lib/backup.go
Less
func (bs backups) Less(i, j int) bool { timeLayout := "2006-01-02 15:04:05" // oh my : https://golang.org/src/time/format.go t1, _ := time.Parse(timeLayout, bs[i].Created) t2, _ := time.Parse(timeLayout, bs[j].Created) return t1.After(t2) }
go
func (bs backups) Less(i, j int) bool { timeLayout := "2006-01-02 15:04:05" // oh my : https://golang.org/src/time/format.go t1, _ := time.Parse(timeLayout, bs[i].Created) t2, _ := time.Parse(timeLayout, bs[j].Created) return t1.After(t2) }
[ "func", "(", "bs", "backups", ")", "Less", "(", "i", ",", "j", "int", ")", "bool", "{", "timeLayout", ":=", "\"", "\"", "// oh my : https://golang.org/src/time/format.go", "\n", "t1", ",", "_", ":=", "time", ".", "Parse", "(", "timeLayout", ",", "bs", "[...
// sort by most recent
[ "sort", "by", "most", "recent" ]
fed59ad207c9bda0a5dfe4d18de53ccbb3d80c91
https://github.com/JamesClonk/vultr/blob/fed59ad207c9bda0a5dfe4d18de53ccbb3d80c91/lib/backup.go#L25-L30
train
JamesClonk/vultr
lib/backup.go
GetBackups
func (c *Client) GetBackups(id string, backupid string) ([]Backup, error) { var backupMap map[string]Backup values := url.Values{ "SUBID": {id}, "BACKUPID": {backupid}, } if err := c.post(`backup/list`, values, &backupMap); err != nil { return nil, err } var backup []Backup for _, b := range backupMap { fmt.Println(b) backup = append(backup, b) } sort.Sort(backups(backup)) return backup, nil }
go
func (c *Client) GetBackups(id string, backupid string) ([]Backup, error) { var backupMap map[string]Backup values := url.Values{ "SUBID": {id}, "BACKUPID": {backupid}, } if err := c.post(`backup/list`, values, &backupMap); err != nil { return nil, err } var backup []Backup for _, b := range backupMap { fmt.Println(b) backup = append(backup, b) } sort.Sort(backups(backup)) return backup, nil }
[ "func", "(", "c", "*", "Client", ")", "GetBackups", "(", "id", "string", ",", "backupid", "string", ")", "(", "[", "]", "Backup", ",", "error", ")", "{", "var", "backupMap", "map", "[", "string", "]", "Backup", "\n", "values", ":=", "url", ".", "Va...
// GetBackups retrieves a list of all backups on Vultr account
[ "GetBackups", "retrieves", "a", "list", "of", "all", "backups", "on", "Vultr", "account" ]
fed59ad207c9bda0a5dfe4d18de53ccbb3d80c91
https://github.com/JamesClonk/vultr/blob/fed59ad207c9bda0a5dfe4d18de53ccbb3d80c91/lib/backup.go#L33-L51
train
JamesClonk/vultr
lib/sshkeys.go
GetSSHKeys
func (c *Client) GetSSHKeys() (keys []SSHKey, err error) { var keyMap map[string]SSHKey if err := c.get(`sshkey/list`, &keyMap); err != nil { return nil, err } for _, key := range keyMap { keys = append(keys, key) } sort.Sort(sshkeys(keys)) return keys, nil }
go
func (c *Client) GetSSHKeys() (keys []SSHKey, err error) { var keyMap map[string]SSHKey if err := c.get(`sshkey/list`, &keyMap); err != nil { return nil, err } for _, key := range keyMap { keys = append(keys, key) } sort.Sort(sshkeys(keys)) return keys, nil }
[ "func", "(", "c", "*", "Client", ")", "GetSSHKeys", "(", ")", "(", "keys", "[", "]", "SSHKey", ",", "err", "error", ")", "{", "var", "keyMap", "map", "[", "string", "]", "SSHKey", "\n", "if", "err", ":=", "c", ".", "get", "(", "`sshkey/list`", ",...
// GetSSHKeys returns a list of SSHKeys from Vultr account
[ "GetSSHKeys", "returns", "a", "list", "of", "SSHKeys", "from", "Vultr", "account" ]
fed59ad207c9bda0a5dfe4d18de53ccbb3d80c91
https://github.com/JamesClonk/vultr/blob/fed59ad207c9bda0a5dfe4d18de53ccbb3d80c91/lib/sshkeys.go#L24-L35
train
JamesClonk/vultr
lib/sshkeys.go
CreateSSHKey
func (c *Client) CreateSSHKey(name, key string) (SSHKey, error) { values := url.Values{ "name": {name}, "ssh_key": {key}, } var sshKey SSHKey if err := c.post(`sshkey/create`, values, &sshKey); err != nil { return SSHKey{}, err } sshKey.Name = name sshKey.Key = key return sshKey, nil }
go
func (c *Client) CreateSSHKey(name, key string) (SSHKey, error) { values := url.Values{ "name": {name}, "ssh_key": {key}, } var sshKey SSHKey if err := c.post(`sshkey/create`, values, &sshKey); err != nil { return SSHKey{}, err } sshKey.Name = name sshKey.Key = key return sshKey, nil }
[ "func", "(", "c", "*", "Client", ")", "CreateSSHKey", "(", "name", ",", "key", "string", ")", "(", "SSHKey", ",", "error", ")", "{", "values", ":=", "url", ".", "Values", "{", "\"", "\"", ":", "{", "name", "}", ",", "\"", "\"", ":", "{", "key",...
// CreateSSHKey creates new SSHKey on Vultr
[ "CreateSSHKey", "creates", "new", "SSHKey", "on", "Vultr" ]
fed59ad207c9bda0a5dfe4d18de53ccbb3d80c91
https://github.com/JamesClonk/vultr/blob/fed59ad207c9bda0a5dfe4d18de53ccbb3d80c91/lib/sshkeys.go#L38-L52
train
JamesClonk/vultr
lib/sshkeys.go
UpdateSSHKey
func (c *Client) UpdateSSHKey(key SSHKey) error { values := url.Values{ "SSHKEYID": {key.ID}, } if key.Name != "" { values.Add("name", key.Name) } if key.Key != "" { values.Add("ssh_key", key.Key) } if err := c.post(`sshkey/update`, values, nil); err != nil { return err } return nil }
go
func (c *Client) UpdateSSHKey(key SSHKey) error { values := url.Values{ "SSHKEYID": {key.ID}, } if key.Name != "" { values.Add("name", key.Name) } if key.Key != "" { values.Add("ssh_key", key.Key) } if err := c.post(`sshkey/update`, values, nil); err != nil { return err } return nil }
[ "func", "(", "c", "*", "Client", ")", "UpdateSSHKey", "(", "key", "SSHKey", ")", "error", "{", "values", ":=", "url", ".", "Values", "{", "\"", "\"", ":", "{", "key", ".", "ID", "}", ",", "}", "\n", "if", "key", ".", "Name", "!=", "\"", "\"", ...
// UpdateSSHKey updates an existing SSHKey entry
[ "UpdateSSHKey", "updates", "an", "existing", "SSHKey", "entry" ]
fed59ad207c9bda0a5dfe4d18de53ccbb3d80c91
https://github.com/JamesClonk/vultr/blob/fed59ad207c9bda0a5dfe4d18de53ccbb3d80c91/lib/sshkeys.go#L55-L70
train
peterbourgon/diskv
diskv.go
New
func New(o Options) *Diskv { if o.BasePath == "" { o.BasePath = defaultBasePath } if o.AdvancedTransform == nil { if o.Transform == nil { o.AdvancedTransform = defaultAdvancedTransform } else { o.AdvancedTransform = convertToAdvancedTransform(o.Transform) } if o.InverseTransform == nil { o.InverseTransform = defaultInverseTransform } } else { if o.InverseTransform == nil { panic("You must provide an InverseTransform function in advanced mode") } } if o.PathPerm == 0 { o.PathPerm = defaultPathPerm } if o.FilePerm == 0 { o.FilePerm = defaultFilePerm } d := &Diskv{ Options: o, cache: map[string][]byte{}, cacheSize: 0, } if d.Index != nil && d.IndexLess != nil { d.Index.Initialize(d.IndexLess, d.Keys(nil)) } return d }
go
func New(o Options) *Diskv { if o.BasePath == "" { o.BasePath = defaultBasePath } if o.AdvancedTransform == nil { if o.Transform == nil { o.AdvancedTransform = defaultAdvancedTransform } else { o.AdvancedTransform = convertToAdvancedTransform(o.Transform) } if o.InverseTransform == nil { o.InverseTransform = defaultInverseTransform } } else { if o.InverseTransform == nil { panic("You must provide an InverseTransform function in advanced mode") } } if o.PathPerm == 0 { o.PathPerm = defaultPathPerm } if o.FilePerm == 0 { o.FilePerm = defaultFilePerm } d := &Diskv{ Options: o, cache: map[string][]byte{}, cacheSize: 0, } if d.Index != nil && d.IndexLess != nil { d.Index.Initialize(d.IndexLess, d.Keys(nil)) } return d }
[ "func", "New", "(", "o", "Options", ")", "*", "Diskv", "{", "if", "o", ".", "BasePath", "==", "\"", "\"", "{", "o", ".", "BasePath", "=", "defaultBasePath", "\n", "}", "\n\n", "if", "o", ".", "AdvancedTransform", "==", "nil", "{", "if", "o", ".", ...
// New returns an initialized Diskv structure, ready to use. // If the path identified by baseDir already contains data, // it will be accessible, but not yet cached.
[ "New", "returns", "an", "initialized", "Diskv", "structure", "ready", "to", "use", ".", "If", "the", "path", "identified", "by", "baseDir", "already", "contains", "data", "it", "will", "be", "accessible", "but", "not", "yet", "cached", "." ]
0be1b92a6df0e4f5cb0a5d15fb7f643d0ad93ce6
https://github.com/peterbourgon/diskv/blob/0be1b92a6df0e4f5cb0a5d15fb7f643d0ad93ce6/diskv.go#L104-L142
train
peterbourgon/diskv
diskv.go
convertToAdvancedTransform
func convertToAdvancedTransform(oldFunc func(s string) []string) AdvancedTransformFunction { return func(s string) *PathKey { return &PathKey{Path: oldFunc(s), FileName: s} } }
go
func convertToAdvancedTransform(oldFunc func(s string) []string) AdvancedTransformFunction { return func(s string) *PathKey { return &PathKey{Path: oldFunc(s), FileName: s} } }
[ "func", "convertToAdvancedTransform", "(", "oldFunc", "func", "(", "s", "string", ")", "[", "]", "string", ")", "AdvancedTransformFunction", "{", "return", "func", "(", "s", "string", ")", "*", "PathKey", "{", "return", "&", "PathKey", "{", "Path", ":", "o...
// convertToAdvancedTransform takes a classic Transform function and // converts it to the new AdvancedTransform
[ "convertToAdvancedTransform", "takes", "a", "classic", "Transform", "function", "and", "converts", "it", "to", "the", "new", "AdvancedTransform" ]
0be1b92a6df0e4f5cb0a5d15fb7f643d0ad93ce6
https://github.com/peterbourgon/diskv/blob/0be1b92a6df0e4f5cb0a5d15fb7f643d0ad93ce6/diskv.go#L146-L150
train
peterbourgon/diskv
diskv.go
Write
func (d *Diskv) Write(key string, val []byte) error { return d.WriteStream(key, bytes.NewReader(val), false) }
go
func (d *Diskv) Write(key string, val []byte) error { return d.WriteStream(key, bytes.NewReader(val), false) }
[ "func", "(", "d", "*", "Diskv", ")", "Write", "(", "key", "string", ",", "val", "[", "]", "byte", ")", "error", "{", "return", "d", ".", "WriteStream", "(", "key", ",", "bytes", ".", "NewReader", "(", "val", ")", ",", "false", ")", "\n", "}" ]
// Write synchronously writes the key-value pair to disk, making it immediately // available for reads. Write relies on the filesystem to perform an eventual // sync to physical media. If you need stronger guarantees, see WriteStream.
[ "Write", "synchronously", "writes", "the", "key", "-", "value", "pair", "to", "disk", "making", "it", "immediately", "available", "for", "reads", ".", "Write", "relies", "on", "the", "filesystem", "to", "perform", "an", "eventual", "sync", "to", "physical", ...
0be1b92a6df0e4f5cb0a5d15fb7f643d0ad93ce6
https://github.com/peterbourgon/diskv/blob/0be1b92a6df0e4f5cb0a5d15fb7f643d0ad93ce6/diskv.go#L155-L157
train
peterbourgon/diskv
diskv.go
WriteString
func (d *Diskv) WriteString(key string, val string) error { return d.Write(key, []byte(val)) }
go
func (d *Diskv) WriteString(key string, val string) error { return d.Write(key, []byte(val)) }
[ "func", "(", "d", "*", "Diskv", ")", "WriteString", "(", "key", "string", ",", "val", "string", ")", "error", "{", "return", "d", ".", "Write", "(", "key", ",", "[", "]", "byte", "(", "val", ")", ")", "\n", "}" ]
// WriteString writes a string key-value pair to disk
[ "WriteString", "writes", "a", "string", "key", "-", "value", "pair", "to", "disk" ]
0be1b92a6df0e4f5cb0a5d15fb7f643d0ad93ce6
https://github.com/peterbourgon/diskv/blob/0be1b92a6df0e4f5cb0a5d15fb7f643d0ad93ce6/diskv.go#L160-L162
train
peterbourgon/diskv
diskv.go
WriteStream
func (d *Diskv) WriteStream(key string, r io.Reader, sync bool) error { if len(key) <= 0 { return errEmptyKey } pathKey := d.transform(key) // Ensure keys cannot evaluate to paths that would not exist for _, pathPart := range pathKey.Path { if strings.ContainsRune(pathPart, os.PathSeparator) { return errBadKey } } if strings.ContainsRune(pathKey.FileName, os.PathSeparator) { return errBadKey } d.mu.Lock() defer d.mu.Unlock() return d.writeStreamWithLock(pathKey, r, sync) }
go
func (d *Diskv) WriteStream(key string, r io.Reader, sync bool) error { if len(key) <= 0 { return errEmptyKey } pathKey := d.transform(key) // Ensure keys cannot evaluate to paths that would not exist for _, pathPart := range pathKey.Path { if strings.ContainsRune(pathPart, os.PathSeparator) { return errBadKey } } if strings.ContainsRune(pathKey.FileName, os.PathSeparator) { return errBadKey } d.mu.Lock() defer d.mu.Unlock() return d.writeStreamWithLock(pathKey, r, sync) }
[ "func", "(", "d", "*", "Diskv", ")", "WriteStream", "(", "key", "string", ",", "r", "io", ".", "Reader", ",", "sync", "bool", ")", "error", "{", "if", "len", "(", "key", ")", "<=", "0", "{", "return", "errEmptyKey", "\n", "}", "\n\n", "pathKey", ...
// WriteStream writes the data represented by the io.Reader to the disk, under // the provided key. If sync is true, WriteStream performs an explicit sync on // the file as soon as it's written. // // bytes.Buffer provides io.Reader semantics for basic data types.
[ "WriteStream", "writes", "the", "data", "represented", "by", "the", "io", ".", "Reader", "to", "the", "disk", "under", "the", "provided", "key", ".", "If", "sync", "is", "true", "WriteStream", "performs", "an", "explicit", "sync", "on", "the", "file", "as"...
0be1b92a6df0e4f5cb0a5d15fb7f643d0ad93ce6
https://github.com/peterbourgon/diskv/blob/0be1b92a6df0e4f5cb0a5d15fb7f643d0ad93ce6/diskv.go#L175-L197
train
peterbourgon/diskv
diskv.go
createKeyFileWithLock
func (d *Diskv) createKeyFileWithLock(pathKey *PathKey) (*os.File, error) { if d.TempDir != "" { if err := os.MkdirAll(d.TempDir, d.PathPerm); err != nil { return nil, fmt.Errorf("temp mkdir: %s", err) } f, err := ioutil.TempFile(d.TempDir, "") if err != nil { return nil, fmt.Errorf("temp file: %s", err) } if err := f.Chmod(d.FilePerm); err != nil { f.Close() // error deliberately ignored os.Remove(f.Name()) // error deliberately ignored return nil, fmt.Errorf("chmod: %s", err) } return f, nil } mode := os.O_WRONLY | os.O_CREATE | os.O_TRUNC // overwrite if exists f, err := os.OpenFile(d.completeFilename(pathKey), mode, d.FilePerm) if err != nil { return nil, fmt.Errorf("open file: %s", err) } return f, nil }
go
func (d *Diskv) createKeyFileWithLock(pathKey *PathKey) (*os.File, error) { if d.TempDir != "" { if err := os.MkdirAll(d.TempDir, d.PathPerm); err != nil { return nil, fmt.Errorf("temp mkdir: %s", err) } f, err := ioutil.TempFile(d.TempDir, "") if err != nil { return nil, fmt.Errorf("temp file: %s", err) } if err := f.Chmod(d.FilePerm); err != nil { f.Close() // error deliberately ignored os.Remove(f.Name()) // error deliberately ignored return nil, fmt.Errorf("chmod: %s", err) } return f, nil } mode := os.O_WRONLY | os.O_CREATE | os.O_TRUNC // overwrite if exists f, err := os.OpenFile(d.completeFilename(pathKey), mode, d.FilePerm) if err != nil { return nil, fmt.Errorf("open file: %s", err) } return f, nil }
[ "func", "(", "d", "*", "Diskv", ")", "createKeyFileWithLock", "(", "pathKey", "*", "PathKey", ")", "(", "*", "os", ".", "File", ",", "error", ")", "{", "if", "d", ".", "TempDir", "!=", "\"", "\"", "{", "if", "err", ":=", "os", ".", "MkdirAll", "(...
// createKeyFileWithLock either creates the key file directly, or // creates a temporary file in TempDir if it is set.
[ "createKeyFileWithLock", "either", "creates", "the", "key", "file", "directly", "or", "creates", "a", "temporary", "file", "in", "TempDir", "if", "it", "is", "set", "." ]
0be1b92a6df0e4f5cb0a5d15fb7f643d0ad93ce6
https://github.com/peterbourgon/diskv/blob/0be1b92a6df0e4f5cb0a5d15fb7f643d0ad93ce6/diskv.go#L201-L225
train
peterbourgon/diskv
diskv.go
writeStreamWithLock
func (d *Diskv) writeStreamWithLock(pathKey *PathKey, r io.Reader, sync bool) error { if err := d.ensurePathWithLock(pathKey); err != nil { return fmt.Errorf("ensure path: %s", err) } f, err := d.createKeyFileWithLock(pathKey) if err != nil { return fmt.Errorf("create key file: %s", err) } wc := io.WriteCloser(&nopWriteCloser{f}) if d.Compression != nil { wc, err = d.Compression.Writer(f) if err != nil { f.Close() // error deliberately ignored os.Remove(f.Name()) // error deliberately ignored return fmt.Errorf("compression writer: %s", err) } } if _, err := io.Copy(wc, r); err != nil { f.Close() // error deliberately ignored os.Remove(f.Name()) // error deliberately ignored return fmt.Errorf("i/o copy: %s", err) } if err := wc.Close(); err != nil { f.Close() // error deliberately ignored os.Remove(f.Name()) // error deliberately ignored return fmt.Errorf("compression close: %s", err) } if sync { if err := f.Sync(); err != nil { f.Close() // error deliberately ignored os.Remove(f.Name()) // error deliberately ignored return fmt.Errorf("file sync: %s", err) } } if err := f.Close(); err != nil { return fmt.Errorf("file close: %s", err) } fullPath := d.completeFilename(pathKey) if f.Name() != fullPath { if err := os.Rename(f.Name(), fullPath); err != nil { os.Remove(f.Name()) // error deliberately ignored return fmt.Errorf("rename: %s", err) } } if d.Index != nil { d.Index.Insert(pathKey.originalKey) } d.bustCacheWithLock(pathKey.originalKey) // cache only on read return nil }
go
func (d *Diskv) writeStreamWithLock(pathKey *PathKey, r io.Reader, sync bool) error { if err := d.ensurePathWithLock(pathKey); err != nil { return fmt.Errorf("ensure path: %s", err) } f, err := d.createKeyFileWithLock(pathKey) if err != nil { return fmt.Errorf("create key file: %s", err) } wc := io.WriteCloser(&nopWriteCloser{f}) if d.Compression != nil { wc, err = d.Compression.Writer(f) if err != nil { f.Close() // error deliberately ignored os.Remove(f.Name()) // error deliberately ignored return fmt.Errorf("compression writer: %s", err) } } if _, err := io.Copy(wc, r); err != nil { f.Close() // error deliberately ignored os.Remove(f.Name()) // error deliberately ignored return fmt.Errorf("i/o copy: %s", err) } if err := wc.Close(); err != nil { f.Close() // error deliberately ignored os.Remove(f.Name()) // error deliberately ignored return fmt.Errorf("compression close: %s", err) } if sync { if err := f.Sync(); err != nil { f.Close() // error deliberately ignored os.Remove(f.Name()) // error deliberately ignored return fmt.Errorf("file sync: %s", err) } } if err := f.Close(); err != nil { return fmt.Errorf("file close: %s", err) } fullPath := d.completeFilename(pathKey) if f.Name() != fullPath { if err := os.Rename(f.Name(), fullPath); err != nil { os.Remove(f.Name()) // error deliberately ignored return fmt.Errorf("rename: %s", err) } } if d.Index != nil { d.Index.Insert(pathKey.originalKey) } d.bustCacheWithLock(pathKey.originalKey) // cache only on read return nil }
[ "func", "(", "d", "*", "Diskv", ")", "writeStreamWithLock", "(", "pathKey", "*", "PathKey", ",", "r", "io", ".", "Reader", ",", "sync", "bool", ")", "error", "{", "if", "err", ":=", "d", ".", "ensurePathWithLock", "(", "pathKey", ")", ";", "err", "!=...
// writeStream does no input validation checking.
[ "writeStream", "does", "no", "input", "validation", "checking", "." ]
0be1b92a6df0e4f5cb0a5d15fb7f643d0ad93ce6
https://github.com/peterbourgon/diskv/blob/0be1b92a6df0e4f5cb0a5d15fb7f643d0ad93ce6/diskv.go#L228-L287
train
peterbourgon/diskv
diskv.go
Import
func (d *Diskv) Import(srcFilename, dstKey string, move bool) (err error) { if dstKey == "" { return errEmptyKey } if fi, err := os.Stat(srcFilename); err != nil { return err } else if fi.IsDir() { return errImportDirectory } dstPathKey := d.transform(dstKey) d.mu.Lock() defer d.mu.Unlock() if err := d.ensurePathWithLock(dstPathKey); err != nil { return fmt.Errorf("ensure path: %s", err) } if move { if err := syscall.Rename(srcFilename, d.completeFilename(dstPathKey)); err == nil { d.bustCacheWithLock(dstPathKey.originalKey) return nil } else if err != syscall.EXDEV { // If it failed due to being on a different device, fall back to copying return err } } f, err := os.Open(srcFilename) if err != nil { return err } defer f.Close() err = d.writeStreamWithLock(dstPathKey, f, false) if err == nil && move { err = os.Remove(srcFilename) } return err }
go
func (d *Diskv) Import(srcFilename, dstKey string, move bool) (err error) { if dstKey == "" { return errEmptyKey } if fi, err := os.Stat(srcFilename); err != nil { return err } else if fi.IsDir() { return errImportDirectory } dstPathKey := d.transform(dstKey) d.mu.Lock() defer d.mu.Unlock() if err := d.ensurePathWithLock(dstPathKey); err != nil { return fmt.Errorf("ensure path: %s", err) } if move { if err := syscall.Rename(srcFilename, d.completeFilename(dstPathKey)); err == nil { d.bustCacheWithLock(dstPathKey.originalKey) return nil } else if err != syscall.EXDEV { // If it failed due to being on a different device, fall back to copying return err } } f, err := os.Open(srcFilename) if err != nil { return err } defer f.Close() err = d.writeStreamWithLock(dstPathKey, f, false) if err == nil && move { err = os.Remove(srcFilename) } return err }
[ "func", "(", "d", "*", "Diskv", ")", "Import", "(", "srcFilename", ",", "dstKey", "string", ",", "move", "bool", ")", "(", "err", "error", ")", "{", "if", "dstKey", "==", "\"", "\"", "{", "return", "errEmptyKey", "\n", "}", "\n\n", "if", "fi", ",",...
// Import imports the source file into diskv under the destination key. If the // destination key already exists, it's overwritten. If move is true, the // source file is removed after a successful import.
[ "Import", "imports", "the", "source", "file", "into", "diskv", "under", "the", "destination", "key", ".", "If", "the", "destination", "key", "already", "exists", "it", "s", "overwritten", ".", "If", "move", "is", "true", "the", "source", "file", "is", "rem...
0be1b92a6df0e4f5cb0a5d15fb7f643d0ad93ce6
https://github.com/peterbourgon/diskv/blob/0be1b92a6df0e4f5cb0a5d15fb7f643d0ad93ce6/diskv.go#L292-L332
train
peterbourgon/diskv
diskv.go
Read
func (d *Diskv) Read(key string) ([]byte, error) { rc, err := d.ReadStream(key, false) if err != nil { return []byte{}, err } defer rc.Close() return ioutil.ReadAll(rc) }
go
func (d *Diskv) Read(key string) ([]byte, error) { rc, err := d.ReadStream(key, false) if err != nil { return []byte{}, err } defer rc.Close() return ioutil.ReadAll(rc) }
[ "func", "(", "d", "*", "Diskv", ")", "Read", "(", "key", "string", ")", "(", "[", "]", "byte", ",", "error", ")", "{", "rc", ",", "err", ":=", "d", ".", "ReadStream", "(", "key", ",", "false", ")", "\n", "if", "err", "!=", "nil", "{", "return...
// Read reads the key and returns the value. // If the key is available in the cache, Read won't touch the disk. // If the key is not in the cache, Read will have the side-effect of // lazily caching the value.
[ "Read", "reads", "the", "key", "and", "returns", "the", "value", ".", "If", "the", "key", "is", "available", "in", "the", "cache", "Read", "won", "t", "touch", "the", "disk", ".", "If", "the", "key", "is", "not", "in", "the", "cache", "Read", "will",...
0be1b92a6df0e4f5cb0a5d15fb7f643d0ad93ce6
https://github.com/peterbourgon/diskv/blob/0be1b92a6df0e4f5cb0a5d15fb7f643d0ad93ce6/diskv.go#L338-L345
train
peterbourgon/diskv
diskv.go
ReadString
func (d *Diskv) ReadString(key string) string { value, _ := d.Read(key) return string(value) }
go
func (d *Diskv) ReadString(key string) string { value, _ := d.Read(key) return string(value) }
[ "func", "(", "d", "*", "Diskv", ")", "ReadString", "(", "key", "string", ")", "string", "{", "value", ",", "_", ":=", "d", ".", "Read", "(", "key", ")", "\n", "return", "string", "(", "value", ")", "\n", "}" ]
// ReadString reads the key and returns a string value // In case of error, an empty string is returned
[ "ReadString", "reads", "the", "key", "and", "returns", "a", "string", "value", "In", "case", "of", "error", "an", "empty", "string", "is", "returned" ]
0be1b92a6df0e4f5cb0a5d15fb7f643d0ad93ce6
https://github.com/peterbourgon/diskv/blob/0be1b92a6df0e4f5cb0a5d15fb7f643d0ad93ce6/diskv.go#L349-L352
train
peterbourgon/diskv
diskv.go
readWithRLock
func (d *Diskv) readWithRLock(pathKey *PathKey) (io.ReadCloser, error) { filename := d.completeFilename(pathKey) fi, err := os.Stat(filename) if err != nil { return nil, err } if fi.IsDir() { return nil, os.ErrNotExist } f, err := os.Open(filename) if err != nil { return nil, err } var r io.Reader if d.CacheSizeMax > 0 { r = newSiphon(f, d, pathKey.originalKey) } else { r = &closingReader{f} } var rc = io.ReadCloser(ioutil.NopCloser(r)) if d.Compression != nil { rc, err = d.Compression.Reader(r) if err != nil { return nil, err } } return rc, nil }
go
func (d *Diskv) readWithRLock(pathKey *PathKey) (io.ReadCloser, error) { filename := d.completeFilename(pathKey) fi, err := os.Stat(filename) if err != nil { return nil, err } if fi.IsDir() { return nil, os.ErrNotExist } f, err := os.Open(filename) if err != nil { return nil, err } var r io.Reader if d.CacheSizeMax > 0 { r = newSiphon(f, d, pathKey.originalKey) } else { r = &closingReader{f} } var rc = io.ReadCloser(ioutil.NopCloser(r)) if d.Compression != nil { rc, err = d.Compression.Reader(r) if err != nil { return nil, err } } return rc, nil }
[ "func", "(", "d", "*", "Diskv", ")", "readWithRLock", "(", "pathKey", "*", "PathKey", ")", "(", "io", ".", "ReadCloser", ",", "error", ")", "{", "filename", ":=", "d", ".", "completeFilename", "(", "pathKey", ")", "\n\n", "fi", ",", "err", ":=", "os"...
// read ignores the cache, and returns an io.ReadCloser representing the // decompressed data for the given key, streamed from the disk. Clients should // acquire a read lock on the Diskv and check the cache themselves before // calling read.
[ "read", "ignores", "the", "cache", "and", "returns", "an", "io", ".", "ReadCloser", "representing", "the", "decompressed", "data", "for", "the", "given", "key", "streamed", "from", "the", "disk", ".", "Clients", "should", "acquire", "a", "read", "lock", "on"...
0be1b92a6df0e4f5cb0a5d15fb7f643d0ad93ce6
https://github.com/peterbourgon/diskv/blob/0be1b92a6df0e4f5cb0a5d15fb7f643d0ad93ce6/diskv.go#L393-L425
train
peterbourgon/diskv
diskv.go
newSiphon
func newSiphon(f *os.File, d *Diskv, key string) io.Reader { return &siphon{ f: f, d: d, key: key, buf: &bytes.Buffer{}, } }
go
func newSiphon(f *os.File, d *Diskv, key string) io.Reader { return &siphon{ f: f, d: d, key: key, buf: &bytes.Buffer{}, } }
[ "func", "newSiphon", "(", "f", "*", "os", ".", "File", ",", "d", "*", "Diskv", ",", "key", "string", ")", "io", ".", "Reader", "{", "return", "&", "siphon", "{", "f", ":", "f", ",", "d", ":", "d", ",", "key", ":", "key", ",", "buf", ":", "&...
// newSiphon constructs a siphoning reader that represents the passed file. // When a successful series of reads ends in an EOF, the siphon will write // the buffered data to Diskv's cache under the given key.
[ "newSiphon", "constructs", "a", "siphoning", "reader", "that", "represents", "the", "passed", "file", ".", "When", "a", "successful", "series", "of", "reads", "ends", "in", "an", "EOF", "the", "siphon", "will", "write", "the", "buffered", "data", "to", "Disk...
0be1b92a6df0e4f5cb0a5d15fb7f643d0ad93ce6
https://github.com/peterbourgon/diskv/blob/0be1b92a6df0e4f5cb0a5d15fb7f643d0ad93ce6/diskv.go#L455-L462
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train