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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
alexedwards/scs | postgresstore/postgresstore.go | Delete | func (p *PostgresStore) Delete(token string) error {
_, err := p.db.Exec("DELETE FROM sessions WHERE token = $1", token)
return err
} | go | func (p *PostgresStore) Delete(token string) error {
_, err := p.db.Exec("DELETE FROM sessions WHERE token = $1", token)
return err
} | [
"func",
"(",
"p",
"*",
"PostgresStore",
")",
"Delete",
"(",
"token",
"string",
")",
"error",
"{",
"_",
",",
"err",
":=",
"p",
".",
"db",
".",
"Exec",
"(",
"\"",
"\"",
",",
"token",
")",
"\n",
"return",
"err",
"\n",
"}"
] | // Delete removes a session token and corresponding data from the PostgresStore
// instance. | [
"Delete",
"removes",
"a",
"session",
"token",
"and",
"corresponding",
"data",
"from",
"the",
"PostgresStore",
"instance",
"."
] | 7591275b1edfd53a361e4bdbe42148cbd1b00ac1 | https://github.com/alexedwards/scs/blob/7591275b1edfd53a361e4bdbe42148cbd1b00ac1/postgresstore/postgresstore.go#L60-L63 | train |
alexedwards/scs | memstore/memstore.go | Find | func (m *MemStore) Find(token string) ([]byte, bool, error) {
m.mu.RLock()
defer m.mu.RUnlock()
item, found := m.items[token]
if !found {
return nil, false, nil
}
if time.Now().UnixNano() > item.expiration {
return nil, false, nil
}
b, ok := item.object.([]byte)
if !ok {
return nil, true, errTypeAssertionFailed
}
return b, true, nil
} | go | func (m *MemStore) Find(token string) ([]byte, bool, error) {
m.mu.RLock()
defer m.mu.RUnlock()
item, found := m.items[token]
if !found {
return nil, false, nil
}
if time.Now().UnixNano() > item.expiration {
return nil, false, nil
}
b, ok := item.object.([]byte)
if !ok {
return nil, true, errTypeAssertionFailed
}
return b, true, nil
} | [
"func",
"(",
"m",
"*",
"MemStore",
")",
"Find",
"(",
"token",
"string",
")",
"(",
"[",
"]",
"byte",
",",
"bool",
",",
"error",
")",
"{",
"m",
".",
"mu",
".",
"RLock",
"(",
")",
"\n",
"defer",
"m",
".",
"mu",
".",
"RUnlock",
"(",
")",
"\n\n",
... | // Find returns the data for a given session token from the MemStore instance.
// If the session token is not found or is expired, the returned exists flag will
// be set to false. | [
"Find",
"returns",
"the",
"data",
"for",
"a",
"given",
"session",
"token",
"from",
"the",
"MemStore",
"instance",
".",
"If",
"the",
"session",
"token",
"is",
"not",
"found",
"or",
"is",
"expired",
"the",
"returned",
"exists",
"flag",
"will",
"be",
"set",
... | 7591275b1edfd53a361e4bdbe42148cbd1b00ac1 | https://github.com/alexedwards/scs/blob/7591275b1edfd53a361e4bdbe42148cbd1b00ac1/memstore/memstore.go#L48-L66 | train |
alexedwards/scs | memstore/memstore.go | Commit | func (m *MemStore) Commit(token string, b []byte, expiry time.Time) error {
m.mu.Lock()
m.items[token] = item{
object: b,
expiration: expiry.UnixNano(),
}
m.mu.Unlock()
return nil
} | go | func (m *MemStore) Commit(token string, b []byte, expiry time.Time) error {
m.mu.Lock()
m.items[token] = item{
object: b,
expiration: expiry.UnixNano(),
}
m.mu.Unlock()
return nil
} | [
"func",
"(",
"m",
"*",
"MemStore",
")",
"Commit",
"(",
"token",
"string",
",",
"b",
"[",
"]",
"byte",
",",
"expiry",
"time",
".",
"Time",
")",
"error",
"{",
"m",
".",
"mu",
".",
"Lock",
"(",
")",
"\n",
"m",
".",
"items",
"[",
"token",
"]",
"=... | // Commit adds a session token and data to the MemStore instance with the given
// expiry time. If the session token already exists, then the data and expiry
// time are updated. | [
"Commit",
"adds",
"a",
"session",
"token",
"and",
"data",
"to",
"the",
"MemStore",
"instance",
"with",
"the",
"given",
"expiry",
"time",
".",
"If",
"the",
"session",
"token",
"already",
"exists",
"then",
"the",
"data",
"and",
"expiry",
"time",
"are",
"upda... | 7591275b1edfd53a361e4bdbe42148cbd1b00ac1 | https://github.com/alexedwards/scs/blob/7591275b1edfd53a361e4bdbe42148cbd1b00ac1/memstore/memstore.go#L71-L80 | train |
alexedwards/scs | memstore/memstore.go | Delete | func (m *MemStore) Delete(token string) error {
m.mu.Lock()
delete(m.items, token)
m.mu.Unlock()
return nil
} | go | func (m *MemStore) Delete(token string) error {
m.mu.Lock()
delete(m.items, token)
m.mu.Unlock()
return nil
} | [
"func",
"(",
"m",
"*",
"MemStore",
")",
"Delete",
"(",
"token",
"string",
")",
"error",
"{",
"m",
".",
"mu",
".",
"Lock",
"(",
")",
"\n",
"delete",
"(",
"m",
".",
"items",
",",
"token",
")",
"\n",
"m",
".",
"mu",
".",
"Unlock",
"(",
")",
"\n\... | // Delete removes a session token and corresponding data from the MemStore
// instance. | [
"Delete",
"removes",
"a",
"session",
"token",
"and",
"corresponding",
"data",
"from",
"the",
"MemStore",
"instance",
"."
] | 7591275b1edfd53a361e4bdbe42148cbd1b00ac1 | https://github.com/alexedwards/scs/blob/7591275b1edfd53a361e4bdbe42148cbd1b00ac1/memstore/memstore.go#L84-L90 | train |
alexedwards/scs | redisstore/redisstore.go | NewWithPrefix | func NewWithPrefix(pool *redis.Pool, prefix string) *RedisStore {
return &RedisStore{
pool: pool,
prefix: prefix,
}
} | go | func NewWithPrefix(pool *redis.Pool, prefix string) *RedisStore {
return &RedisStore{
pool: pool,
prefix: prefix,
}
} | [
"func",
"NewWithPrefix",
"(",
"pool",
"*",
"redis",
".",
"Pool",
",",
"prefix",
"string",
")",
"*",
"RedisStore",
"{",
"return",
"&",
"RedisStore",
"{",
"pool",
":",
"pool",
",",
"prefix",
":",
"prefix",
",",
"}",
"\n",
"}"
] | // New returns a new RedisStore instance. The pool parameter should be a pointer
// to a redigo connection pool. The prefix parameter controls the Redis key
// prefix, which can be used to avoid naming clashes if necessary. | [
"New",
"returns",
"a",
"new",
"RedisStore",
"instance",
".",
"The",
"pool",
"parameter",
"should",
"be",
"a",
"pointer",
"to",
"a",
"redigo",
"connection",
"pool",
".",
"The",
"prefix",
"parameter",
"controls",
"the",
"Redis",
"key",
"prefix",
"which",
"can"... | 7591275b1edfd53a361e4bdbe42148cbd1b00ac1 | https://github.com/alexedwards/scs/blob/7591275b1edfd53a361e4bdbe42148cbd1b00ac1/redisstore/redisstore.go#L24-L29 | train |
alexedwards/scs | redisstore/redisstore.go | Find | func (r *RedisStore) Find(token string) (b []byte, exists bool, err error) {
conn := r.pool.Get()
defer conn.Close()
b, err = redis.Bytes(conn.Do("GET", r.prefix+token))
if err == redis.ErrNil {
return nil, false, nil
} else if err != nil {
return nil, false, err
}
return b, true, nil
} | go | func (r *RedisStore) Find(token string) (b []byte, exists bool, err error) {
conn := r.pool.Get()
defer conn.Close()
b, err = redis.Bytes(conn.Do("GET", r.prefix+token))
if err == redis.ErrNil {
return nil, false, nil
} else if err != nil {
return nil, false, err
}
return b, true, nil
} | [
"func",
"(",
"r",
"*",
"RedisStore",
")",
"Find",
"(",
"token",
"string",
")",
"(",
"b",
"[",
"]",
"byte",
",",
"exists",
"bool",
",",
"err",
"error",
")",
"{",
"conn",
":=",
"r",
".",
"pool",
".",
"Get",
"(",
")",
"\n",
"defer",
"conn",
".",
... | // Find returns the data for a given session token from the RedisStore instance.
// If the session token is not found or is expired, the returned exists flag
// will be set to false. | [
"Find",
"returns",
"the",
"data",
"for",
"a",
"given",
"session",
"token",
"from",
"the",
"RedisStore",
"instance",
".",
"If",
"the",
"session",
"token",
"is",
"not",
"found",
"or",
"is",
"expired",
"the",
"returned",
"exists",
"flag",
"will",
"be",
"set",... | 7591275b1edfd53a361e4bdbe42148cbd1b00ac1 | https://github.com/alexedwards/scs/blob/7591275b1edfd53a361e4bdbe42148cbd1b00ac1/redisstore/redisstore.go#L34-L45 | train |
alexedwards/scs | redisstore/redisstore.go | Commit | func (r *RedisStore) Commit(token string, b []byte, expiry time.Time) error {
conn := r.pool.Get()
defer conn.Close()
err := conn.Send("MULTI")
if err != nil {
return err
}
err = conn.Send("SET", r.prefix+token, b)
if err != nil {
return err
}
err = conn.Send("PEXPIREAT", r.prefix+token, makeMillisecondTimestamp(expiry))
if err != nil {
return err
}
_, err = conn.Do("EXEC")
return err
} | go | func (r *RedisStore) Commit(token string, b []byte, expiry time.Time) error {
conn := r.pool.Get()
defer conn.Close()
err := conn.Send("MULTI")
if err != nil {
return err
}
err = conn.Send("SET", r.prefix+token, b)
if err != nil {
return err
}
err = conn.Send("PEXPIREAT", r.prefix+token, makeMillisecondTimestamp(expiry))
if err != nil {
return err
}
_, err = conn.Do("EXEC")
return err
} | [
"func",
"(",
"r",
"*",
"RedisStore",
")",
"Commit",
"(",
"token",
"string",
",",
"b",
"[",
"]",
"byte",
",",
"expiry",
"time",
".",
"Time",
")",
"error",
"{",
"conn",
":=",
"r",
".",
"pool",
".",
"Get",
"(",
")",
"\n",
"defer",
"conn",
".",
"Cl... | // Commit adds a session token and data to the RedisStore instance with the
// given expiry time. If the session token already exists then the data and
// expiry time are updated. | [
"Commit",
"adds",
"a",
"session",
"token",
"and",
"data",
"to",
"the",
"RedisStore",
"instance",
"with",
"the",
"given",
"expiry",
"time",
".",
"If",
"the",
"session",
"token",
"already",
"exists",
"then",
"the",
"data",
"and",
"expiry",
"time",
"are",
"up... | 7591275b1edfd53a361e4bdbe42148cbd1b00ac1 | https://github.com/alexedwards/scs/blob/7591275b1edfd53a361e4bdbe42148cbd1b00ac1/redisstore/redisstore.go#L50-L68 | train |
alexedwards/scs | redisstore/redisstore.go | Delete | func (r *RedisStore) Delete(token string) error {
conn := r.pool.Get()
defer conn.Close()
_, err := conn.Do("DEL", r.prefix+token)
return err
} | go | func (r *RedisStore) Delete(token string) error {
conn := r.pool.Get()
defer conn.Close()
_, err := conn.Do("DEL", r.prefix+token)
return err
} | [
"func",
"(",
"r",
"*",
"RedisStore",
")",
"Delete",
"(",
"token",
"string",
")",
"error",
"{",
"conn",
":=",
"r",
".",
"pool",
".",
"Get",
"(",
")",
"\n",
"defer",
"conn",
".",
"Close",
"(",
")",
"\n\n",
"_",
",",
"err",
":=",
"conn",
".",
"Do"... | // Delete removes a session token and corresponding data from the RedisStore
// instance. | [
"Delete",
"removes",
"a",
"session",
"token",
"and",
"corresponding",
"data",
"from",
"the",
"RedisStore",
"instance",
"."
] | 7591275b1edfd53a361e4bdbe42148cbd1b00ac1 | https://github.com/alexedwards/scs/blob/7591275b1edfd53a361e4bdbe42148cbd1b00ac1/redisstore/redisstore.go#L72-L78 | train |
alexedwards/scs | mysqlstore/mysqlstore.go | Find | func (m *MySQLStore) Find(token string) ([]byte, bool, error) {
var b []byte
var stmt string
if compareVersion("5.6.4", m.version) >= 0 {
stmt = "SELECT data FROM sessions WHERE token = ? AND UTC_TIMESTAMP(6) < expiry"
} else {
stmt = "SELECT data FROM sessions WHERE token = ? AND UTC_TIMESTAMP < expiry"
}
row := m.DB.QueryRow(stmt, token)
err := row.Scan(&b)
if err == sql.ErrNoRows {
return nil, false, nil
} else if err != nil {
return nil, false, err
}
return b, true, nil
} | go | func (m *MySQLStore) Find(token string) ([]byte, bool, error) {
var b []byte
var stmt string
if compareVersion("5.6.4", m.version) >= 0 {
stmt = "SELECT data FROM sessions WHERE token = ? AND UTC_TIMESTAMP(6) < expiry"
} else {
stmt = "SELECT data FROM sessions WHERE token = ? AND UTC_TIMESTAMP < expiry"
}
row := m.DB.QueryRow(stmt, token)
err := row.Scan(&b)
if err == sql.ErrNoRows {
return nil, false, nil
} else if err != nil {
return nil, false, err
}
return b, true, nil
} | [
"func",
"(",
"m",
"*",
"MySQLStore",
")",
"Find",
"(",
"token",
"string",
")",
"(",
"[",
"]",
"byte",
",",
"bool",
",",
"error",
")",
"{",
"var",
"b",
"[",
"]",
"byte",
"\n",
"var",
"stmt",
"string",
"\n\n",
"if",
"compareVersion",
"(",
"\"",
"\"... | // Find returns the data for a given session token from the MySQLStore instance.
// If the session token is not found or is expired, the returned exists flag will
// be set to false. | [
"Find",
"returns",
"the",
"data",
"for",
"a",
"given",
"session",
"token",
"from",
"the",
"MySQLStore",
"instance",
".",
"If",
"the",
"session",
"token",
"is",
"not",
"found",
"or",
"is",
"expired",
"the",
"returned",
"exists",
"flag",
"will",
"be",
"set",... | 7591275b1edfd53a361e4bdbe42148cbd1b00ac1 | https://github.com/alexedwards/scs/blob/7591275b1edfd53a361e4bdbe42148cbd1b00ac1/mysqlstore/mysqlstore.go#L44-L62 | train |
alexedwards/scs | mysqlstore/mysqlstore.go | Commit | func (m *MySQLStore) Commit(token string, b []byte, expiry time.Time) error {
_, err := m.DB.Exec("INSERT INTO sessions (token, data, expiry) VALUES (?, ?, ?) ON DUPLICATE KEY UPDATE data = VALUES(data), expiry = VALUES(expiry)", token, b, expiry.UTC())
if err != nil {
return err
}
return nil
} | go | func (m *MySQLStore) Commit(token string, b []byte, expiry time.Time) error {
_, err := m.DB.Exec("INSERT INTO sessions (token, data, expiry) VALUES (?, ?, ?) ON DUPLICATE KEY UPDATE data = VALUES(data), expiry = VALUES(expiry)", token, b, expiry.UTC())
if err != nil {
return err
}
return nil
} | [
"func",
"(",
"m",
"*",
"MySQLStore",
")",
"Commit",
"(",
"token",
"string",
",",
"b",
"[",
"]",
"byte",
",",
"expiry",
"time",
".",
"Time",
")",
"error",
"{",
"_",
",",
"err",
":=",
"m",
".",
"DB",
".",
"Exec",
"(",
"\"",
"\"",
",",
"token",
... | // Commit adds a session token and data to the MySQLStore instance with the given
// expiry time. If the session token already exists, then the data and expiry
// time are updated. | [
"Commit",
"adds",
"a",
"session",
"token",
"and",
"data",
"to",
"the",
"MySQLStore",
"instance",
"with",
"the",
"given",
"expiry",
"time",
".",
"If",
"the",
"session",
"token",
"already",
"exists",
"then",
"the",
"data",
"and",
"expiry",
"time",
"are",
"up... | 7591275b1edfd53a361e4bdbe42148cbd1b00ac1 | https://github.com/alexedwards/scs/blob/7591275b1edfd53a361e4bdbe42148cbd1b00ac1/mysqlstore/mysqlstore.go#L67-L73 | train |
alexedwards/scs | mysqlstore/mysqlstore.go | Delete | func (m *MySQLStore) Delete(token string) error {
_, err := m.DB.Exec("DELETE FROM sessions WHERE token = ?", token)
return err
} | go | func (m *MySQLStore) Delete(token string) error {
_, err := m.DB.Exec("DELETE FROM sessions WHERE token = ?", token)
return err
} | [
"func",
"(",
"m",
"*",
"MySQLStore",
")",
"Delete",
"(",
"token",
"string",
")",
"error",
"{",
"_",
",",
"err",
":=",
"m",
".",
"DB",
".",
"Exec",
"(",
"\"",
"\"",
",",
"token",
")",
"\n",
"return",
"err",
"\n",
"}"
] | // Delete removes a session token and corresponding data from the MySQLStore
// instance. | [
"Delete",
"removes",
"a",
"session",
"token",
"and",
"corresponding",
"data",
"from",
"the",
"MySQLStore",
"instance",
"."
] | 7591275b1edfd53a361e4bdbe42148cbd1b00ac1 | https://github.com/alexedwards/scs/blob/7591275b1edfd53a361e4bdbe42148cbd1b00ac1/mysqlstore/mysqlstore.go#L77-L80 | train |
alexedwards/scs | data.go | Destroy | func (s *Session) Destroy(ctx context.Context) error {
sd := s.getSessionDataFromContext(ctx)
sd.mu.Lock()
defer sd.mu.Unlock()
err := s.Store.Delete(sd.token)
if err != nil {
return err
}
sd.status = Destroyed
// Reset everything else to defaults.
sd.token = ""
sd.Deadline = time.Now().Add(s.Lifetime).UTC()
for key := range sd.Values {
delete(sd.Values, key)
}
return nil
} | go | func (s *Session) Destroy(ctx context.Context) error {
sd := s.getSessionDataFromContext(ctx)
sd.mu.Lock()
defer sd.mu.Unlock()
err := s.Store.Delete(sd.token)
if err != nil {
return err
}
sd.status = Destroyed
// Reset everything else to defaults.
sd.token = ""
sd.Deadline = time.Now().Add(s.Lifetime).UTC()
for key := range sd.Values {
delete(sd.Values, key)
}
return nil
} | [
"func",
"(",
"s",
"*",
"Session",
")",
"Destroy",
"(",
"ctx",
"context",
".",
"Context",
")",
"error",
"{",
"sd",
":=",
"s",
".",
"getSessionDataFromContext",
"(",
"ctx",
")",
"\n\n",
"sd",
".",
"mu",
".",
"Lock",
"(",
")",
"\n",
"defer",
"sd",
"."... | // Destroy deletes the session data from the session store and sets the session
// status to Destroyed. Any futher operations in the same request cycle will
// result in a new session being created. | [
"Destroy",
"deletes",
"the",
"session",
"data",
"from",
"the",
"session",
"store",
"and",
"sets",
"the",
"session",
"status",
"to",
"Destroyed",
".",
"Any",
"futher",
"operations",
"in",
"the",
"same",
"request",
"cycle",
"will",
"result",
"in",
"a",
"new",
... | 7591275b1edfd53a361e4bdbe42148cbd1b00ac1 | https://github.com/alexedwards/scs/blob/7591275b1edfd53a361e4bdbe42148cbd1b00ac1/data.go#L131-L152 | train |
alexedwards/scs | data.go | Put | func (s *Session) Put(ctx context.Context, key string, val interface{}) {
sd := s.getSessionDataFromContext(ctx)
sd.mu.Lock()
sd.Values[key] = val
sd.status = Modified
sd.mu.Unlock()
} | go | func (s *Session) Put(ctx context.Context, key string, val interface{}) {
sd := s.getSessionDataFromContext(ctx)
sd.mu.Lock()
sd.Values[key] = val
sd.status = Modified
sd.mu.Unlock()
} | [
"func",
"(",
"s",
"*",
"Session",
")",
"Put",
"(",
"ctx",
"context",
".",
"Context",
",",
"key",
"string",
",",
"val",
"interface",
"{",
"}",
")",
"{",
"sd",
":=",
"s",
".",
"getSessionDataFromContext",
"(",
"ctx",
")",
"\n\n",
"sd",
".",
"mu",
"."... | // Put adds a key and corresponding value to the session data. Any existing
// value for the key will be replaced. The session data status will be set to
// Modified. | [
"Put",
"adds",
"a",
"key",
"and",
"corresponding",
"value",
"to",
"the",
"session",
"data",
".",
"Any",
"existing",
"value",
"for",
"the",
"key",
"will",
"be",
"replaced",
".",
"The",
"session",
"data",
"status",
"will",
"be",
"set",
"to",
"Modified",
".... | 7591275b1edfd53a361e4bdbe42148cbd1b00ac1 | https://github.com/alexedwards/scs/blob/7591275b1edfd53a361e4bdbe42148cbd1b00ac1/data.go#L157-L164 | train |
alexedwards/scs | data.go | Remove | func (s *Session) Remove(ctx context.Context, key string) {
sd := s.getSessionDataFromContext(ctx)
sd.mu.Lock()
defer sd.mu.Unlock()
_, exists := sd.Values[key]
if !exists {
return
}
delete(sd.Values, key)
sd.status = Modified
} | go | func (s *Session) Remove(ctx context.Context, key string) {
sd := s.getSessionDataFromContext(ctx)
sd.mu.Lock()
defer sd.mu.Unlock()
_, exists := sd.Values[key]
if !exists {
return
}
delete(sd.Values, key)
sd.status = Modified
} | [
"func",
"(",
"s",
"*",
"Session",
")",
"Remove",
"(",
"ctx",
"context",
".",
"Context",
",",
"key",
"string",
")",
"{",
"sd",
":=",
"s",
".",
"getSessionDataFromContext",
"(",
"ctx",
")",
"\n\n",
"sd",
".",
"mu",
".",
"Lock",
"(",
")",
"\n",
"defer... | // Remove deletes the given key and corresponding value from the session data.
// The session data status will be set to Modified. If the key is not present
// this operation is a no-op. | [
"Remove",
"deletes",
"the",
"given",
"key",
"and",
"corresponding",
"value",
"from",
"the",
"session",
"data",
".",
"The",
"session",
"data",
"status",
"will",
"be",
"set",
"to",
"Modified",
".",
"If",
"the",
"key",
"is",
"not",
"present",
"this",
"operati... | 7591275b1edfd53a361e4bdbe42148cbd1b00ac1 | https://github.com/alexedwards/scs/blob/7591275b1edfd53a361e4bdbe42148cbd1b00ac1/data.go#L209-L222 | train |
alexedwards/scs | data.go | Exists | func (s *Session) Exists(ctx context.Context, key string) bool {
sd := s.getSessionDataFromContext(ctx)
sd.mu.Lock()
_, exists := sd.Values[key]
sd.mu.Unlock()
return exists
} | go | func (s *Session) Exists(ctx context.Context, key string) bool {
sd := s.getSessionDataFromContext(ctx)
sd.mu.Lock()
_, exists := sd.Values[key]
sd.mu.Unlock()
return exists
} | [
"func",
"(",
"s",
"*",
"Session",
")",
"Exists",
"(",
"ctx",
"context",
".",
"Context",
",",
"key",
"string",
")",
"bool",
"{",
"sd",
":=",
"s",
".",
"getSessionDataFromContext",
"(",
"ctx",
")",
"\n\n",
"sd",
".",
"mu",
".",
"Lock",
"(",
")",
"\n"... | // Exists returns true if the given key is present in the session data. | [
"Exists",
"returns",
"true",
"if",
"the",
"given",
"key",
"is",
"present",
"in",
"the",
"session",
"data",
"."
] | 7591275b1edfd53a361e4bdbe42148cbd1b00ac1 | https://github.com/alexedwards/scs/blob/7591275b1edfd53a361e4bdbe42148cbd1b00ac1/data.go#L225-L233 | train |
alexedwards/scs | data.go | Keys | func (s *Session) Keys(ctx context.Context) []string {
sd := s.getSessionDataFromContext(ctx)
sd.mu.Lock()
keys := make([]string, len(sd.Values))
i := 0
for key := range sd.Values {
keys[i] = key
i++
}
sd.mu.Unlock()
sort.Strings(keys)
return keys
} | go | func (s *Session) Keys(ctx context.Context) []string {
sd := s.getSessionDataFromContext(ctx)
sd.mu.Lock()
keys := make([]string, len(sd.Values))
i := 0
for key := range sd.Values {
keys[i] = key
i++
}
sd.mu.Unlock()
sort.Strings(keys)
return keys
} | [
"func",
"(",
"s",
"*",
"Session",
")",
"Keys",
"(",
"ctx",
"context",
".",
"Context",
")",
"[",
"]",
"string",
"{",
"sd",
":=",
"s",
".",
"getSessionDataFromContext",
"(",
"ctx",
")",
"\n\n",
"sd",
".",
"mu",
".",
"Lock",
"(",
")",
"\n",
"keys",
... | // Keys returns a slice of all key names present in the session data, sorted
// alphabetically. If the data contains no data then an empty slice will be
// returned. | [
"Keys",
"returns",
"a",
"slice",
"of",
"all",
"key",
"names",
"present",
"in",
"the",
"session",
"data",
"sorted",
"alphabetically",
".",
"If",
"the",
"data",
"contains",
"no",
"data",
"then",
"an",
"empty",
"slice",
"will",
"be",
"returned",
"."
] | 7591275b1edfd53a361e4bdbe42148cbd1b00ac1 | https://github.com/alexedwards/scs/blob/7591275b1edfd53a361e4bdbe42148cbd1b00ac1/data.go#L238-L252 | train |
alexedwards/scs | data.go | Status | func (s *Session) Status(ctx context.Context) Status {
sd := s.getSessionDataFromContext(ctx)
sd.mu.Lock()
defer sd.mu.Unlock()
return sd.status
} | go | func (s *Session) Status(ctx context.Context) Status {
sd := s.getSessionDataFromContext(ctx)
sd.mu.Lock()
defer sd.mu.Unlock()
return sd.status
} | [
"func",
"(",
"s",
"*",
"Session",
")",
"Status",
"(",
"ctx",
"context",
".",
"Context",
")",
"Status",
"{",
"sd",
":=",
"s",
".",
"getSessionDataFromContext",
"(",
"ctx",
")",
"\n\n",
"sd",
".",
"mu",
".",
"Lock",
"(",
")",
"\n",
"defer",
"sd",
"."... | // Status returns the current status of the session data. | [
"Status",
"returns",
"the",
"current",
"status",
"of",
"the",
"session",
"data",
"."
] | 7591275b1edfd53a361e4bdbe42148cbd1b00ac1 | https://github.com/alexedwards/scs/blob/7591275b1edfd53a361e4bdbe42148cbd1b00ac1/data.go#L288-L295 | train |
alexedwards/scs | data.go | PopTime | func (s *Session) PopTime(ctx context.Context, key string) time.Time {
val := s.Pop(ctx, key)
t, ok := val.(time.Time)
if !ok {
return time.Time{}
}
return t
} | go | func (s *Session) PopTime(ctx context.Context, key string) time.Time {
val := s.Pop(ctx, key)
t, ok := val.(time.Time)
if !ok {
return time.Time{}
}
return t
} | [
"func",
"(",
"s",
"*",
"Session",
")",
"PopTime",
"(",
"ctx",
"context",
".",
"Context",
",",
"key",
"string",
")",
"time",
".",
"Time",
"{",
"val",
":=",
"s",
".",
"Pop",
"(",
"ctx",
",",
"key",
")",
"\n",
"t",
",",
"ok",
":=",
"val",
".",
"... | // PopTime returns the time.Time value for a given key and then deletes it from
// the session data. The session data status will be set to Modified. The zero
// value for a time.Time object is returned if the key does not exist or the
// value could not be type asserted to a time.Time. | [
"PopTime",
"returns",
"the",
"time",
".",
"Time",
"value",
"for",
"a",
"given",
"key",
"and",
"then",
"deletes",
"it",
"from",
"the",
"session",
"data",
".",
"The",
"session",
"data",
"status",
"will",
"be",
"set",
"to",
"Modified",
".",
"The",
"zero",
... | 7591275b1edfd53a361e4bdbe42148cbd1b00ac1 | https://github.com/alexedwards/scs/blob/7591275b1edfd53a361e4bdbe42148cbd1b00ac1/data.go#L439-L446 | train |
alexedwards/scs | session.go | NewSession | func NewSession() *Session {
s := &Session{
IdleTimeout: 0,
Lifetime: 24 * time.Hour,
Store: memstore.New(),
contextKey: generateContextKey(),
Cookie: SessionCookie{
Name: "session",
Domain: "",
HttpOnly: true,
Path: "/",
Persist: true,
Secure: false,
SameSite: http.SameSiteLaxMode,
},
}
return s
} | go | func NewSession() *Session {
s := &Session{
IdleTimeout: 0,
Lifetime: 24 * time.Hour,
Store: memstore.New(),
contextKey: generateContextKey(),
Cookie: SessionCookie{
Name: "session",
Domain: "",
HttpOnly: true,
Path: "/",
Persist: true,
Secure: false,
SameSite: http.SameSiteLaxMode,
},
}
return s
} | [
"func",
"NewSession",
"(",
")",
"*",
"Session",
"{",
"s",
":=",
"&",
"Session",
"{",
"IdleTimeout",
":",
"0",
",",
"Lifetime",
":",
"24",
"*",
"time",
".",
"Hour",
",",
"Store",
":",
"memstore",
".",
"New",
"(",
")",
",",
"contextKey",
":",
"genera... | // NewSession returns a new session manager with the default options. It is
// safe for concurrent use. | [
"NewSession",
"returns",
"a",
"new",
"session",
"manager",
"with",
"the",
"default",
"options",
".",
"It",
"is",
"safe",
"for",
"concurrent",
"use",
"."
] | 7591275b1edfd53a361e4bdbe42148cbd1b00ac1 | https://github.com/alexedwards/scs/blob/7591275b1edfd53a361e4bdbe42148cbd1b00ac1/session.go#L80-L97 | train |
alexedwards/scs | session.go | LoadAndSave | func (s *Session) LoadAndSave(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
var token string
cookie, err := r.Cookie(s.Cookie.Name)
if err == nil {
token = cookie.Value
}
ctx, err := s.Load(r.Context(), token)
if err != nil {
log.Output(2, err.Error())
http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
return
}
sr := r.WithContext(ctx)
bw := &bufferedResponseWriter{ResponseWriter: w}
next.ServeHTTP(bw, sr)
switch s.Status(ctx) {
case Modified:
token, expiry, err := s.Commit(ctx)
if err != nil {
log.Output(2, err.Error())
http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
return
}
s.writeSessionCookie(w, token, expiry)
case Destroyed:
s.writeSessionCookie(w, "", time.Time{})
}
if bw.code != 0 {
w.WriteHeader(bw.code)
}
w.Write(bw.buf.Bytes())
})
} | go | func (s *Session) LoadAndSave(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
var token string
cookie, err := r.Cookie(s.Cookie.Name)
if err == nil {
token = cookie.Value
}
ctx, err := s.Load(r.Context(), token)
if err != nil {
log.Output(2, err.Error())
http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
return
}
sr := r.WithContext(ctx)
bw := &bufferedResponseWriter{ResponseWriter: w}
next.ServeHTTP(bw, sr)
switch s.Status(ctx) {
case Modified:
token, expiry, err := s.Commit(ctx)
if err != nil {
log.Output(2, err.Error())
http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
return
}
s.writeSessionCookie(w, token, expiry)
case Destroyed:
s.writeSessionCookie(w, "", time.Time{})
}
if bw.code != 0 {
w.WriteHeader(bw.code)
}
w.Write(bw.buf.Bytes())
})
} | [
"func",
"(",
"s",
"*",
"Session",
")",
"LoadAndSave",
"(",
"next",
"http",
".",
"Handler",
")",
"http",
".",
"Handler",
"{",
"return",
"http",
".",
"HandlerFunc",
"(",
"func",
"(",
"w",
"http",
".",
"ResponseWriter",
",",
"r",
"*",
"http",
".",
"Requ... | // LoadAndSave provides middleware which automatically loads and saves session
// data for the current request, and communicates the session token to and from
// the client in a cookie. | [
"LoadAndSave",
"provides",
"middleware",
"which",
"automatically",
"loads",
"and",
"saves",
"session",
"data",
"for",
"the",
"current",
"request",
"and",
"communicates",
"the",
"session",
"token",
"to",
"and",
"from",
"the",
"client",
"in",
"a",
"cookie",
"."
] | 7591275b1edfd53a361e4bdbe42148cbd1b00ac1 | https://github.com/alexedwards/scs/blob/7591275b1edfd53a361e4bdbe42148cbd1b00ac1/session.go#L102-L139 | train |
rogpeppe/godef | go/ast/resolve.go | NewPackage | func NewPackage(fset *token.FileSet, files map[string]*File, importer Importer, universe *Scope) (*Package, error) {
var p pkgBuilder
p.fset = fset
// complete package scope
pkgName := ""
pkgScope := NewScope(universe)
for _, file := range files {
// package names must match
switch name := file.Name.Name; {
case pkgName == "":
pkgName = name
case name != pkgName:
p.errorf(file.Package, "package %s; expected %s", name, pkgName)
continue // ignore this file
}
// collect top-level file objects in package scope
for _, obj := range file.Scope.Objects {
p.declare(pkgScope, nil, obj)
}
}
// package global mapping of imported package ids to package objects
imports := make(map[string]*Object)
// complete file scopes with imports and resolve identifiers
for _, file := range files {
// ignore file if it belongs to a different package
// (error has already been reported)
if file.Name.Name != pkgName {
continue
}
// build file scope by processing all imports
importErrors := false
fileScope := NewScope(pkgScope)
for _, spec := range file.Imports {
if importer == nil {
importErrors = true
continue
}
path, _ := strconv.Unquote(string(spec.Path.Value))
pkg, err := importer(imports, path)
if err != nil {
p.errorf(spec.Path.Pos(), "could not import %s (%s)", path, err)
importErrors = true
continue
}
// TODO(gri) If a local package name != "." is provided,
// global identifier resolution could proceed even if the
// import failed. Consider adjusting the logic here a bit.
// local name overrides imported package name
name := pkg.Name
if spec.Name != nil {
name = spec.Name.Name
}
// add import to file scope
if name == "." {
// merge imported scope with file scope
for _, obj := range pkg.Data.(*Scope).Objects {
p.declare(fileScope, pkgScope, obj)
}
} else {
// declare imported package object in file scope
// (do not re-use pkg in the file scope but create
// a new object instead; the Decl field is different
// for different files)
obj := NewObj(Pkg, name)
obj.Decl = spec
obj.Data = pkg.Data
p.declare(fileScope, pkgScope, obj)
}
}
// resolve identifiers
if importErrors {
// don't use the universe scope without correct imports
// (objects in the universe may be shadowed by imports;
// with missing imports, identifiers might get resolved
// incorrectly to universe objects)
pkgScope.Outer = nil
}
i := 0
for _, ident := range file.Unresolved {
if !resolve(fileScope, ident) {
p.errorf(ident.Pos(), "undeclared name: %s", ident.Name)
file.Unresolved[i] = ident
i++
}
}
file.Unresolved = file.Unresolved[0:i]
pkgScope.Outer = universe // reset universe scope
}
return &Package{pkgName, pkgScope, imports, files}, p.GetError(scanner.Sorted)
} | go | func NewPackage(fset *token.FileSet, files map[string]*File, importer Importer, universe *Scope) (*Package, error) {
var p pkgBuilder
p.fset = fset
// complete package scope
pkgName := ""
pkgScope := NewScope(universe)
for _, file := range files {
// package names must match
switch name := file.Name.Name; {
case pkgName == "":
pkgName = name
case name != pkgName:
p.errorf(file.Package, "package %s; expected %s", name, pkgName)
continue // ignore this file
}
// collect top-level file objects in package scope
for _, obj := range file.Scope.Objects {
p.declare(pkgScope, nil, obj)
}
}
// package global mapping of imported package ids to package objects
imports := make(map[string]*Object)
// complete file scopes with imports and resolve identifiers
for _, file := range files {
// ignore file if it belongs to a different package
// (error has already been reported)
if file.Name.Name != pkgName {
continue
}
// build file scope by processing all imports
importErrors := false
fileScope := NewScope(pkgScope)
for _, spec := range file.Imports {
if importer == nil {
importErrors = true
continue
}
path, _ := strconv.Unquote(string(spec.Path.Value))
pkg, err := importer(imports, path)
if err != nil {
p.errorf(spec.Path.Pos(), "could not import %s (%s)", path, err)
importErrors = true
continue
}
// TODO(gri) If a local package name != "." is provided,
// global identifier resolution could proceed even if the
// import failed. Consider adjusting the logic here a bit.
// local name overrides imported package name
name := pkg.Name
if spec.Name != nil {
name = spec.Name.Name
}
// add import to file scope
if name == "." {
// merge imported scope with file scope
for _, obj := range pkg.Data.(*Scope).Objects {
p.declare(fileScope, pkgScope, obj)
}
} else {
// declare imported package object in file scope
// (do not re-use pkg in the file scope but create
// a new object instead; the Decl field is different
// for different files)
obj := NewObj(Pkg, name)
obj.Decl = spec
obj.Data = pkg.Data
p.declare(fileScope, pkgScope, obj)
}
}
// resolve identifiers
if importErrors {
// don't use the universe scope without correct imports
// (objects in the universe may be shadowed by imports;
// with missing imports, identifiers might get resolved
// incorrectly to universe objects)
pkgScope.Outer = nil
}
i := 0
for _, ident := range file.Unresolved {
if !resolve(fileScope, ident) {
p.errorf(ident.Pos(), "undeclared name: %s", ident.Name)
file.Unresolved[i] = ident
i++
}
}
file.Unresolved = file.Unresolved[0:i]
pkgScope.Outer = universe // reset universe scope
}
return &Package{pkgName, pkgScope, imports, files}, p.GetError(scanner.Sorted)
} | [
"func",
"NewPackage",
"(",
"fset",
"*",
"token",
".",
"FileSet",
",",
"files",
"map",
"[",
"string",
"]",
"*",
"File",
",",
"importer",
"Importer",
",",
"universe",
"*",
"Scope",
")",
"(",
"*",
"Package",
",",
"error",
")",
"{",
"var",
"p",
"pkgBuild... | // NewPackage creates a new Package node from a set of File nodes. It resolves
// unresolved identifiers across files and updates each file's Unresolved list
// accordingly. If a non-nil importer and universe scope are provided, they are
// used to resolve identifiers not declared in any of the package files. Any
// remaining unresolved identifiers are reported as undeclared. If the files
// belong to different packages, one package name is selected and files with
// different package names are reported and then ignored.
// The result is a package node and a scanner.ErrorList if there were errors.
// | [
"NewPackage",
"creates",
"a",
"new",
"Package",
"node",
"from",
"a",
"set",
"of",
"File",
"nodes",
".",
"It",
"resolves",
"unresolved",
"identifiers",
"across",
"files",
"and",
"updates",
"each",
"file",
"s",
"Unresolved",
"list",
"accordingly",
".",
"If",
"... | 5784335da72394c8f53d9036c26fcc876718879b | https://github.com/rogpeppe/godef/blob/5784335da72394c8f53d9036c26fcc876718879b/go/ast/resolve.go#L75-L174 | train |
rogpeppe/godef | go/printer/printer.go | nlines | func (p *printer) nlines(n, min int) int {
const max = 2 // max. number of newlines
switch {
case n < min:
return min
case n > max:
return max
}
return n
} | go | func (p *printer) nlines(n, min int) int {
const max = 2 // max. number of newlines
switch {
case n < min:
return min
case n > max:
return max
}
return n
} | [
"func",
"(",
"p",
"*",
"printer",
")",
"nlines",
"(",
"n",
",",
"min",
"int",
")",
"int",
"{",
"const",
"max",
"=",
"2",
"// max. number of newlines",
"\n",
"switch",
"{",
"case",
"n",
"<",
"min",
":",
"return",
"min",
"\n",
"case",
"n",
">",
"max"... | // nlines returns the adjusted number of linebreaks given the desired number
// of breaks n such that min <= result <= max.
// | [
"nlines",
"returns",
"the",
"adjusted",
"number",
"of",
"linebreaks",
"given",
"the",
"desired",
"number",
"of",
"breaks",
"n",
"such",
"that",
"min",
"<",
"=",
"result",
"<",
"=",
"max",
"."
] | 5784335da72394c8f53d9036c26fcc876718879b | https://github.com/rogpeppe/godef/blob/5784335da72394c8f53d9036c26fcc876718879b/go/printer/printer.go#L127-L136 | train |
rogpeppe/godef | go/printer/printer.go | write | func (p *printer) write(data []byte) {
i0 := 0
for i, b := range data {
switch b {
case '\n', '\f':
// write segment ending in b
p.write0(data[i0 : i+1])
// update p.pos
p.pos.Offset += i + 1 - i0
p.pos.Line++
p.pos.Column = 1
if p.mode&inLiteral == 0 {
// write indentation
// use "hard" htabs - indentation columns
// must not be discarded by the tabwriter
j := p.indent
for ; j > len(htabs); j -= len(htabs) {
p.write0(htabs)
}
p.write0(htabs[0:j])
// update p.pos
p.pos.Offset += p.indent
p.pos.Column += p.indent
}
// next segment start
i0 = i + 1
case tabwriter.Escape:
p.mode ^= inLiteral
// ignore escape chars introduced by printer - they are
// invisible and must not affect p.pos (was issue #1089)
p.pos.Offset--
p.pos.Column--
}
}
// write remaining segment
p.write0(data[i0:])
// update p.pos
d := len(data) - i0
p.pos.Offset += d
p.pos.Column += d
} | go | func (p *printer) write(data []byte) {
i0 := 0
for i, b := range data {
switch b {
case '\n', '\f':
// write segment ending in b
p.write0(data[i0 : i+1])
// update p.pos
p.pos.Offset += i + 1 - i0
p.pos.Line++
p.pos.Column = 1
if p.mode&inLiteral == 0 {
// write indentation
// use "hard" htabs - indentation columns
// must not be discarded by the tabwriter
j := p.indent
for ; j > len(htabs); j -= len(htabs) {
p.write0(htabs)
}
p.write0(htabs[0:j])
// update p.pos
p.pos.Offset += p.indent
p.pos.Column += p.indent
}
// next segment start
i0 = i + 1
case tabwriter.Escape:
p.mode ^= inLiteral
// ignore escape chars introduced by printer - they are
// invisible and must not affect p.pos (was issue #1089)
p.pos.Offset--
p.pos.Column--
}
}
// write remaining segment
p.write0(data[i0:])
// update p.pos
d := len(data) - i0
p.pos.Offset += d
p.pos.Column += d
} | [
"func",
"(",
"p",
"*",
"printer",
")",
"write",
"(",
"data",
"[",
"]",
"byte",
")",
"{",
"i0",
":=",
"0",
"\n",
"for",
"i",
",",
"b",
":=",
"range",
"data",
"{",
"switch",
"b",
"{",
"case",
"'\\n'",
",",
"'\\f'",
":",
"// write segment ending in b"... | // write interprets data and writes it to p.output. It inserts indentation
// after a line break unless in a tabwriter escape sequence.
// It updates p.pos as a side-effect.
// | [
"write",
"interprets",
"data",
"and",
"writes",
"it",
"to",
"p",
".",
"output",
".",
"It",
"inserts",
"indentation",
"after",
"a",
"line",
"break",
"unless",
"in",
"a",
"tabwriter",
"escape",
"sequence",
".",
"It",
"updates",
"p",
".",
"pos",
"as",
"a",
... | 5784335da72394c8f53d9036c26fcc876718879b | https://github.com/rogpeppe/godef/blob/5784335da72394c8f53d9036c26fcc876718879b/go/printer/printer.go#L156-L204 | train |
rogpeppe/godef | go/printer/printer.go | writeWhitespace | func (p *printer) writeWhitespace(n int) {
// write entries
var data [1]byte
for i := 0; i < n; i++ {
switch ch := p.wsbuf[i]; ch {
case ignore:
// ignore!
case indent:
p.indent++
case unindent:
p.indent--
if p.indent < 0 {
p.internalError("negative indentation:", p.indent)
p.indent = 0
}
case newline, formfeed:
// A line break immediately followed by a "correcting"
// unindent is swapped with the unindent - this permits
// proper label positioning. If a comment is between
// the line break and the label, the unindent is not
// part of the comment whitespace prefix and the comment
// will be positioned correctly indented.
if i+1 < n && p.wsbuf[i+1] == unindent {
// Use a formfeed to terminate the current section.
// Otherwise, a long label name on the next line leading
// to a wide column may increase the indentation column
// of lines before the label; effectively leading to wrong
// indentation.
p.wsbuf[i], p.wsbuf[i+1] = unindent, formfeed
i-- // do it again
continue
}
fallthrough
default:
data[0] = byte(ch)
p.write(data[0:])
}
}
// shift remaining entries down
i := 0
for ; n < len(p.wsbuf); n++ {
p.wsbuf[i] = p.wsbuf[n]
i++
}
p.wsbuf = p.wsbuf[0:i]
} | go | func (p *printer) writeWhitespace(n int) {
// write entries
var data [1]byte
for i := 0; i < n; i++ {
switch ch := p.wsbuf[i]; ch {
case ignore:
// ignore!
case indent:
p.indent++
case unindent:
p.indent--
if p.indent < 0 {
p.internalError("negative indentation:", p.indent)
p.indent = 0
}
case newline, formfeed:
// A line break immediately followed by a "correcting"
// unindent is swapped with the unindent - this permits
// proper label positioning. If a comment is between
// the line break and the label, the unindent is not
// part of the comment whitespace prefix and the comment
// will be positioned correctly indented.
if i+1 < n && p.wsbuf[i+1] == unindent {
// Use a formfeed to terminate the current section.
// Otherwise, a long label name on the next line leading
// to a wide column may increase the indentation column
// of lines before the label; effectively leading to wrong
// indentation.
p.wsbuf[i], p.wsbuf[i+1] = unindent, formfeed
i-- // do it again
continue
}
fallthrough
default:
data[0] = byte(ch)
p.write(data[0:])
}
}
// shift remaining entries down
i := 0
for ; n < len(p.wsbuf); n++ {
p.wsbuf[i] = p.wsbuf[n]
i++
}
p.wsbuf = p.wsbuf[0:i]
} | [
"func",
"(",
"p",
"*",
"printer",
")",
"writeWhitespace",
"(",
"n",
"int",
")",
"{",
"// write entries",
"var",
"data",
"[",
"1",
"]",
"byte",
"\n",
"for",
"i",
":=",
"0",
";",
"i",
"<",
"n",
";",
"i",
"++",
"{",
"switch",
"ch",
":=",
"p",
".",... | // whiteWhitespace writes the first n whitespace entries. | [
"whiteWhitespace",
"writes",
"the",
"first",
"n",
"whitespace",
"entries",
"."
] | 5784335da72394c8f53d9036c26fcc876718879b | https://github.com/rogpeppe/godef/blob/5784335da72394c8f53d9036c26fcc876718879b/go/printer/printer.go#L628-L674 | train |
rogpeppe/godef | go/printer/printer.go | commentBefore | func (p *printer) commentBefore(next token.Position) bool {
return p.cindex < len(p.comments) && p.fset.Position(p.comments[p.cindex].List[0].Pos()).Offset < next.Offset
} | go | func (p *printer) commentBefore(next token.Position) bool {
return p.cindex < len(p.comments) && p.fset.Position(p.comments[p.cindex].List[0].Pos()).Offset < next.Offset
} | [
"func",
"(",
"p",
"*",
"printer",
")",
"commentBefore",
"(",
"next",
"token",
".",
"Position",
")",
"bool",
"{",
"return",
"p",
".",
"cindex",
"<",
"len",
"(",
"p",
".",
"comments",
")",
"&&",
"p",
".",
"fset",
".",
"Position",
"(",
"p",
".",
"co... | // commentBefore returns true iff the current comment occurs
// before the next position in the source code.
// | [
"commentBefore",
"returns",
"true",
"iff",
"the",
"current",
"comment",
"occurs",
"before",
"the",
"next",
"position",
"in",
"the",
"source",
"code",
"."
] | 5784335da72394c8f53d9036c26fcc876718879b | https://github.com/rogpeppe/godef/blob/5784335da72394c8f53d9036c26fcc876718879b/go/printer/printer.go#L789-L791 | train |
rogpeppe/godef | go/printer/printer.go | flush | func (p *printer) flush(next token.Position, tok token.Token) (droppedFF bool) {
if p.commentBefore(next) {
// if there are comments before the next item, intersperse them
droppedFF = p.intersperseComments(next, tok)
} else {
// otherwise, write any leftover whitespace
p.writeWhitespace(len(p.wsbuf))
}
return
} | go | func (p *printer) flush(next token.Position, tok token.Token) (droppedFF bool) {
if p.commentBefore(next) {
// if there are comments before the next item, intersperse them
droppedFF = p.intersperseComments(next, tok)
} else {
// otherwise, write any leftover whitespace
p.writeWhitespace(len(p.wsbuf))
}
return
} | [
"func",
"(",
"p",
"*",
"printer",
")",
"flush",
"(",
"next",
"token",
".",
"Position",
",",
"tok",
"token",
".",
"Token",
")",
"(",
"droppedFF",
"bool",
")",
"{",
"if",
"p",
".",
"commentBefore",
"(",
"next",
")",
"{",
"// if there are comments before th... | // Flush prints any pending comments and whitespace occurring
// textually before the position of the next token tok. Flush
// returns true if a pending formfeed character was dropped
// from the whitespace buffer as a result of interspersing
// comments.
// | [
"Flush",
"prints",
"any",
"pending",
"comments",
"and",
"whitespace",
"occurring",
"textually",
"before",
"the",
"position",
"of",
"the",
"next",
"token",
"tok",
".",
"Flush",
"returns",
"true",
"if",
"a",
"pending",
"formfeed",
"character",
"was",
"dropped",
... | 5784335da72394c8f53d9036c26fcc876718879b | https://github.com/rogpeppe/godef/blob/5784335da72394c8f53d9036c26fcc876718879b/go/printer/printer.go#L799-L808 | train |
rogpeppe/godef | go/printer/printer.go | fprint | func (cfg *Config) fprint(output io.Writer, fset *token.FileSet, node interface{}, nodeSizes map[ast.Node]int) (int, error) {
// redirect output through a trimmer to eliminate trailing whitespace
// (Input to a tabwriter must be untrimmed since trailing tabs provide
// formatting information. The tabwriter could provide trimming
// functionality but no tabwriter is used when RawFormat is set.)
output = &trimmer{output: output}
// setup tabwriter if needed and redirect output
var tw *tabwriter.Writer
if cfg.Mode&RawFormat == 0 {
minwidth := cfg.Tabwidth
padchar := byte('\t')
if cfg.Mode&UseSpaces != 0 {
padchar = ' '
}
twmode := tabwriter.DiscardEmptyColumns
if cfg.Mode&TabIndent != 0 {
minwidth = 0
twmode |= tabwriter.TabIndent
}
tw = tabwriter.NewWriter(output, minwidth, cfg.Tabwidth, 1, padchar, twmode)
output = tw
}
// setup printer and print node
var p printer
p.init(output, cfg, fset, nodeSizes)
go func() {
switch n := node.(type) {
case ast.Expr:
p.useNodeComments = true
p.expr(n, ignoreMultiLine)
case ast.Stmt:
p.useNodeComments = true
// A labeled statement will un-indent to position the
// label. Set indent to 1 so we don't get indent "underflow".
if _, labeledStmt := n.(*ast.LabeledStmt); labeledStmt {
p.indent = 1
}
p.stmt(n, false, ignoreMultiLine)
case ast.Decl:
p.useNodeComments = true
p.decl(n, ignoreMultiLine)
case ast.Spec:
p.useNodeComments = true
p.spec(n, 1, false, ignoreMultiLine)
case *ast.File:
p.comments = n.Comments
p.useNodeComments = n.Comments == nil
p.file(n)
default:
p.errors <- fmt.Errorf("printer.Fprint: unsupported node type %T", n)
runtime.Goexit()
}
p.flush(token.Position{Offset: infinity, Line: infinity}, token.EOF)
p.errors <- nil // no errors
}()
err := <-p.errors // wait for completion of goroutine
// flush tabwriter, if any
if tw != nil {
tw.Flush() // ignore errors
}
return p.written, err
} | go | func (cfg *Config) fprint(output io.Writer, fset *token.FileSet, node interface{}, nodeSizes map[ast.Node]int) (int, error) {
// redirect output through a trimmer to eliminate trailing whitespace
// (Input to a tabwriter must be untrimmed since trailing tabs provide
// formatting information. The tabwriter could provide trimming
// functionality but no tabwriter is used when RawFormat is set.)
output = &trimmer{output: output}
// setup tabwriter if needed and redirect output
var tw *tabwriter.Writer
if cfg.Mode&RawFormat == 0 {
minwidth := cfg.Tabwidth
padchar := byte('\t')
if cfg.Mode&UseSpaces != 0 {
padchar = ' '
}
twmode := tabwriter.DiscardEmptyColumns
if cfg.Mode&TabIndent != 0 {
minwidth = 0
twmode |= tabwriter.TabIndent
}
tw = tabwriter.NewWriter(output, minwidth, cfg.Tabwidth, 1, padchar, twmode)
output = tw
}
// setup printer and print node
var p printer
p.init(output, cfg, fset, nodeSizes)
go func() {
switch n := node.(type) {
case ast.Expr:
p.useNodeComments = true
p.expr(n, ignoreMultiLine)
case ast.Stmt:
p.useNodeComments = true
// A labeled statement will un-indent to position the
// label. Set indent to 1 so we don't get indent "underflow".
if _, labeledStmt := n.(*ast.LabeledStmt); labeledStmt {
p.indent = 1
}
p.stmt(n, false, ignoreMultiLine)
case ast.Decl:
p.useNodeComments = true
p.decl(n, ignoreMultiLine)
case ast.Spec:
p.useNodeComments = true
p.spec(n, 1, false, ignoreMultiLine)
case *ast.File:
p.comments = n.Comments
p.useNodeComments = n.Comments == nil
p.file(n)
default:
p.errors <- fmt.Errorf("printer.Fprint: unsupported node type %T", n)
runtime.Goexit()
}
p.flush(token.Position{Offset: infinity, Line: infinity}, token.EOF)
p.errors <- nil // no errors
}()
err := <-p.errors // wait for completion of goroutine
// flush tabwriter, if any
if tw != nil {
tw.Flush() // ignore errors
}
return p.written, err
} | [
"func",
"(",
"cfg",
"*",
"Config",
")",
"fprint",
"(",
"output",
"io",
".",
"Writer",
",",
"fset",
"*",
"token",
".",
"FileSet",
",",
"node",
"interface",
"{",
"}",
",",
"nodeSizes",
"map",
"[",
"ast",
".",
"Node",
"]",
"int",
")",
"(",
"int",
",... | // fprint implements Fprint and takes a nodesSizes map for setting up the printer state. | [
"fprint",
"implements",
"Fprint",
"and",
"takes",
"a",
"nodesSizes",
"map",
"for",
"setting",
"up",
"the",
"printer",
"state",
"."
] | 5784335da72394c8f53d9036c26fcc876718879b | https://github.com/rogpeppe/godef/blob/5784335da72394c8f53d9036c26fcc876718879b/go/printer/printer.go#L927-L995 | train |
rogpeppe/godef | go/printer/printer.go | Fprint | func Fprint(output io.Writer, fset *token.FileSet, node interface{}) error {
_, err := (&Config{Tabwidth: 8}).Fprint(output, fset, node) // don't care about number of bytes written
return err
} | go | func Fprint(output io.Writer, fset *token.FileSet, node interface{}) error {
_, err := (&Config{Tabwidth: 8}).Fprint(output, fset, node) // don't care about number of bytes written
return err
} | [
"func",
"Fprint",
"(",
"output",
"io",
".",
"Writer",
",",
"fset",
"*",
"token",
".",
"FileSet",
",",
"node",
"interface",
"{",
"}",
")",
"error",
"{",
"_",
",",
"err",
":=",
"(",
"&",
"Config",
"{",
"Tabwidth",
":",
"8",
"}",
")",
".",
"Fprint",... | // Fprint "pretty-prints" an AST node to output.
// It calls Config.Fprint with default settings.
// | [
"Fprint",
"pretty",
"-",
"prints",
"an",
"AST",
"node",
"to",
"output",
".",
"It",
"calls",
"Config",
".",
"Fprint",
"with",
"default",
"settings",
"."
] | 5784335da72394c8f53d9036c26fcc876718879b | https://github.com/rogpeppe/godef/blob/5784335da72394c8f53d9036c26fcc876718879b/go/printer/printer.go#L1010-L1013 | train |
rogpeppe/godef | go/scanner/scanner.go | next | func (S *Scanner) next() {
if S.rdOffset < len(S.src) {
S.offset = S.rdOffset
if S.ch == '\n' {
S.lineOffset = S.offset
S.file.AddLine(S.offset)
}
r, w := rune(S.src[S.rdOffset]), 1
switch {
case r == 0:
S.error(S.offset, "illegal character NUL")
case r >= 0x80:
// not ASCII
r, w = utf8.DecodeRune(S.src[S.rdOffset:])
if r == utf8.RuneError && w == 1 {
S.error(S.offset, "illegal UTF-8 encoding")
}
}
S.rdOffset += w
S.ch = r
} else {
S.offset = len(S.src)
if S.ch == '\n' {
S.lineOffset = S.offset
S.file.AddLine(S.offset)
}
S.ch = -1 // eof
}
} | go | func (S *Scanner) next() {
if S.rdOffset < len(S.src) {
S.offset = S.rdOffset
if S.ch == '\n' {
S.lineOffset = S.offset
S.file.AddLine(S.offset)
}
r, w := rune(S.src[S.rdOffset]), 1
switch {
case r == 0:
S.error(S.offset, "illegal character NUL")
case r >= 0x80:
// not ASCII
r, w = utf8.DecodeRune(S.src[S.rdOffset:])
if r == utf8.RuneError && w == 1 {
S.error(S.offset, "illegal UTF-8 encoding")
}
}
S.rdOffset += w
S.ch = r
} else {
S.offset = len(S.src)
if S.ch == '\n' {
S.lineOffset = S.offset
S.file.AddLine(S.offset)
}
S.ch = -1 // eof
}
} | [
"func",
"(",
"S",
"*",
"Scanner",
")",
"next",
"(",
")",
"{",
"if",
"S",
".",
"rdOffset",
"<",
"len",
"(",
"S",
".",
"src",
")",
"{",
"S",
".",
"offset",
"=",
"S",
".",
"rdOffset",
"\n",
"if",
"S",
".",
"ch",
"==",
"'\\n'",
"{",
"S",
".",
... | // Read the next Unicode char into S.ch.
// S.ch < 0 means end-of-file.
// | [
"Read",
"the",
"next",
"Unicode",
"char",
"into",
"S",
".",
"ch",
".",
"S",
".",
"ch",
"<",
"0",
"means",
"end",
"-",
"of",
"-",
"file",
"."
] | 5784335da72394c8f53d9036c26fcc876718879b | https://github.com/rogpeppe/godef/blob/5784335da72394c8f53d9036c26fcc876718879b/go/scanner/scanner.go#L60-L88 | train |
rogpeppe/godef | go/scanner/scanner.go | Init | func (S *Scanner) Init(file *token.File, src []byte, err ErrorHandler, mode uint) {
// Explicitly initialize all fields since a scanner may be reused.
if file.Size() != len(src) {
panic("file size does not match src len")
}
S.file = file
S.dir, _ = filepath.Split(file.Name())
S.src = src
S.err = err
S.mode = mode
S.ch = ' '
S.offset = 0
S.rdOffset = 0
S.lineOffset = 0
S.insertSemi = false
S.ErrorCount = 0
S.next()
} | go | func (S *Scanner) Init(file *token.File, src []byte, err ErrorHandler, mode uint) {
// Explicitly initialize all fields since a scanner may be reused.
if file.Size() != len(src) {
panic("file size does not match src len")
}
S.file = file
S.dir, _ = filepath.Split(file.Name())
S.src = src
S.err = err
S.mode = mode
S.ch = ' '
S.offset = 0
S.rdOffset = 0
S.lineOffset = 0
S.insertSemi = false
S.ErrorCount = 0
S.next()
} | [
"func",
"(",
"S",
"*",
"Scanner",
")",
"Init",
"(",
"file",
"*",
"token",
".",
"File",
",",
"src",
"[",
"]",
"byte",
",",
"err",
"ErrorHandler",
",",
"mode",
"uint",
")",
"{",
"// Explicitly initialize all fields since a scanner may be reused.",
"if",
"file",
... | // Init prepares the scanner S to tokenize the text src by setting the
// scanner at the beginning of src. The scanner uses the file set file
// for position information and it adds line information for each line.
// It is ok to re-use the same file when re-scanning the same file as
// line information which is already present is ignored. Init causes a
// panic if the file size does not match the src size.
//
// Calls to Scan will use the error handler err if they encounter a
// syntax error and err is not nil. Also, for each error encountered,
// the Scanner field ErrorCount is incremented by one. The mode parameter
// determines how comments, illegal characters, and semicolons are handled.
//
// Note that Init may call err if there is an error in the first character
// of the file.
// | [
"Init",
"prepares",
"the",
"scanner",
"S",
"to",
"tokenize",
"the",
"text",
"src",
"by",
"setting",
"the",
"scanner",
"at",
"the",
"beginning",
"of",
"src",
".",
"The",
"scanner",
"uses",
"the",
"file",
"set",
"file",
"for",
"position",
"information",
"and... | 5784335da72394c8f53d9036c26fcc876718879b | https://github.com/rogpeppe/godef/blob/5784335da72394c8f53d9036c26fcc876718879b/go/scanner/scanner.go#L114-L133 | train |
rogpeppe/godef | go/scanner/scanner.go | switch2 | func (S *Scanner) switch2(tok0, tok1 token.Token) token.Token {
if S.ch == '=' {
S.next()
return tok1
}
return tok0
} | go | func (S *Scanner) switch2(tok0, tok1 token.Token) token.Token {
if S.ch == '=' {
S.next()
return tok1
}
return tok0
} | [
"func",
"(",
"S",
"*",
"Scanner",
")",
"switch2",
"(",
"tok0",
",",
"tok1",
"token",
".",
"Token",
")",
"token",
".",
"Token",
"{",
"if",
"S",
".",
"ch",
"==",
"'='",
"{",
"S",
".",
"next",
"(",
")",
"\n",
"return",
"tok1",
"\n",
"}",
"\n",
"... | // Helper functions for scanning multi-byte tokens such as >> += >>= .
// Different routines recognize different length tok_i based on matches
// of ch_i. If a token ends in '=', the result is tok1 or tok3
// respectively. Otherwise, the result is tok0 if there was no other
// matching character, or tok2 if the matching character was ch2. | [
"Helper",
"functions",
"for",
"scanning",
"multi",
"-",
"byte",
"tokens",
"such",
"as",
">>",
"+",
"=",
">>",
"=",
".",
"Different",
"routines",
"recognize",
"different",
"length",
"tok_i",
"based",
"on",
"matches",
"of",
"ch_i",
".",
"If",
"a",
"token",
... | 5784335da72394c8f53d9036c26fcc876718879b | https://github.com/rogpeppe/godef/blob/5784335da72394c8f53d9036c26fcc876718879b/go/scanner/scanner.go#L459-L465 | train |
rogpeppe/godef | go/sym/sym.go | Import | func (ctxt *Context) Import(path, srcDir string) *ast.Package {
// TODO return error.
return ctxt.importer(path, srcDir)
} | go | func (ctxt *Context) Import(path, srcDir string) *ast.Package {
// TODO return error.
return ctxt.importer(path, srcDir)
} | [
"func",
"(",
"ctxt",
"*",
"Context",
")",
"Import",
"(",
"path",
",",
"srcDir",
"string",
")",
"*",
"ast",
".",
"Package",
"{",
"// TODO return error.",
"return",
"ctxt",
".",
"importer",
"(",
"path",
",",
"srcDir",
")",
"\n",
"}"
] | // Import imports and parses the package with the given path.
// It returns nil if it fails. | [
"Import",
"imports",
"and",
"parses",
"the",
"package",
"with",
"the",
"given",
"path",
".",
"It",
"returns",
"nil",
"if",
"it",
"fails",
"."
] | 5784335da72394c8f53d9036c26fcc876718879b | https://github.com/rogpeppe/godef/blob/5784335da72394c8f53d9036c26fcc876718879b/go/sym/sym.go#L61-L64 | train |
rogpeppe/godef | go/sym/sym.go | IterateSyms | func (ctxt *Context) IterateSyms(f *ast.File, visitf func(info *Info) bool) {
var visit astVisitor
ok := true
local := false // TODO set to true inside function body
visit = func(n ast.Node) bool {
if !ok {
return false
}
switch n := n.(type) {
case *ast.ImportSpec:
// If the file imports a package to ".", abort
// because we don't support that (yet).
if n.Name != nil && n.Name.Name == "." {
ctxt.logf(n.Pos(), "import to . not supported")
ok = false
return false
}
return true
case *ast.FuncDecl:
// add object for init functions
if n.Recv == nil && n.Name.Name == "init" {
n.Name.Obj = ast.NewObj(ast.Fun, "init")
}
if n.Recv != nil {
ast.Walk(visit, n.Recv)
}
var e ast.Expr = n.Name
if n.Recv != nil {
// It's a method, so we need to synthesise a
// selector expression so that visitExpr doesn't
// just see a blank name.
if len(n.Recv.List) != 1 {
ctxt.logf(n.Pos(), "expected one receiver only!")
return true
}
e = &ast.SelectorExpr{
X: n.Recv.List[0].Type,
Sel: n.Name,
}
}
ok = ctxt.visitExpr(f, e, false, visitf)
local = true
ast.Walk(visit, n.Type)
if n.Body != nil {
ast.Walk(visit, n.Body)
}
local = false
return false
case *ast.Ident:
ok = ctxt.visitExpr(f, n, local, visitf)
return false
case *ast.KeyValueExpr:
// don't try to resolve the key part of a key-value
// because it might be a map key which doesn't
// need resolving, and we can't tell without being
// complicated with types.
ast.Walk(visit, n.Value)
return false
case *ast.SelectorExpr:
ast.Walk(visit, n.X)
ok = ctxt.visitExpr(f, n, local, visitf)
return false
case *ast.File:
for _, d := range n.Decls {
ast.Walk(visit, d)
}
return false
}
return true
}
ast.Walk(visit, f)
} | go | func (ctxt *Context) IterateSyms(f *ast.File, visitf func(info *Info) bool) {
var visit astVisitor
ok := true
local := false // TODO set to true inside function body
visit = func(n ast.Node) bool {
if !ok {
return false
}
switch n := n.(type) {
case *ast.ImportSpec:
// If the file imports a package to ".", abort
// because we don't support that (yet).
if n.Name != nil && n.Name.Name == "." {
ctxt.logf(n.Pos(), "import to . not supported")
ok = false
return false
}
return true
case *ast.FuncDecl:
// add object for init functions
if n.Recv == nil && n.Name.Name == "init" {
n.Name.Obj = ast.NewObj(ast.Fun, "init")
}
if n.Recv != nil {
ast.Walk(visit, n.Recv)
}
var e ast.Expr = n.Name
if n.Recv != nil {
// It's a method, so we need to synthesise a
// selector expression so that visitExpr doesn't
// just see a blank name.
if len(n.Recv.List) != 1 {
ctxt.logf(n.Pos(), "expected one receiver only!")
return true
}
e = &ast.SelectorExpr{
X: n.Recv.List[0].Type,
Sel: n.Name,
}
}
ok = ctxt.visitExpr(f, e, false, visitf)
local = true
ast.Walk(visit, n.Type)
if n.Body != nil {
ast.Walk(visit, n.Body)
}
local = false
return false
case *ast.Ident:
ok = ctxt.visitExpr(f, n, local, visitf)
return false
case *ast.KeyValueExpr:
// don't try to resolve the key part of a key-value
// because it might be a map key which doesn't
// need resolving, and we can't tell without being
// complicated with types.
ast.Walk(visit, n.Value)
return false
case *ast.SelectorExpr:
ast.Walk(visit, n.X)
ok = ctxt.visitExpr(f, n, local, visitf)
return false
case *ast.File:
for _, d := range n.Decls {
ast.Walk(visit, d)
}
return false
}
return true
}
ast.Walk(visit, f)
} | [
"func",
"(",
"ctxt",
"*",
"Context",
")",
"IterateSyms",
"(",
"f",
"*",
"ast",
".",
"File",
",",
"visitf",
"func",
"(",
"info",
"*",
"Info",
")",
"bool",
")",
"{",
"var",
"visit",
"astVisitor",
"\n",
"ok",
":=",
"true",
"\n",
"local",
":=",
"false"... | // IterateSyms calls visitf for each identifier in the given file. If
// visitf returns false, the iteration stops. If visitf changes
// info.Ident.Name, the file is added to ctxt.ChangedFiles. | [
"IterateSyms",
"calls",
"visitf",
"for",
"each",
"identifier",
"in",
"the",
"given",
"file",
".",
"If",
"visitf",
"returns",
"false",
"the",
"iteration",
"stops",
".",
"If",
"visitf",
"changes",
"info",
".",
"Ident",
".",
"Name",
"the",
"file",
"is",
"adde... | 5784335da72394c8f53d9036c26fcc876718879b | https://github.com/rogpeppe/godef/blob/5784335da72394c8f53d9036c26fcc876718879b/go/sym/sym.go#L123-L200 | train |
rogpeppe/godef | go/sym/sym.go | WriteFiles | func (ctxt *Context) WriteFiles(files map[string]*ast.File) error {
// TODO should we try to continue changing files even after an error?
for _, f := range files {
name := ctxt.filename(f)
newSrc, err := ctxt.gofmtFile(f)
if err != nil {
return fmt.Errorf("cannot format %q: %v", name, err)
}
err = ioutil.WriteFile(name, newSrc, 0666)
if err != nil {
return fmt.Errorf("cannot write %q: %v", name, err)
}
}
return nil
} | go | func (ctxt *Context) WriteFiles(files map[string]*ast.File) error {
// TODO should we try to continue changing files even after an error?
for _, f := range files {
name := ctxt.filename(f)
newSrc, err := ctxt.gofmtFile(f)
if err != nil {
return fmt.Errorf("cannot format %q: %v", name, err)
}
err = ioutil.WriteFile(name, newSrc, 0666)
if err != nil {
return fmt.Errorf("cannot write %q: %v", name, err)
}
}
return nil
} | [
"func",
"(",
"ctxt",
"*",
"Context",
")",
"WriteFiles",
"(",
"files",
"map",
"[",
"string",
"]",
"*",
"ast",
".",
"File",
")",
"error",
"{",
"// TODO should we try to continue changing files even after an error?",
"for",
"_",
",",
"f",
":=",
"range",
"files",
... | // WriteFiles writes the given files, formatted as with gofmt. | [
"WriteFiles",
"writes",
"the",
"given",
"files",
"formatted",
"as",
"with",
"gofmt",
"."
] | 5784335da72394c8f53d9036c26fcc876718879b | https://github.com/rogpeppe/godef/blob/5784335da72394c8f53d9036c26fcc876718879b/go/sym/sym.go#L249-L263 | train |
rogpeppe/godef | go/ast/scope.go | NewScope | func NewScope(outer *Scope) *Scope {
const n = 4 // initial scope capacity
return &Scope{outer, make(map[string]*Object, n)}
} | go | func NewScope(outer *Scope) *Scope {
const n = 4 // initial scope capacity
return &Scope{outer, make(map[string]*Object, n)}
} | [
"func",
"NewScope",
"(",
"outer",
"*",
"Scope",
")",
"*",
"Scope",
"{",
"const",
"n",
"=",
"4",
"// initial scope capacity",
"\n",
"return",
"&",
"Scope",
"{",
"outer",
",",
"make",
"(",
"map",
"[",
"string",
"]",
"*",
"Object",
",",
"n",
")",
"}",
... | // NewScope creates a new scope nested in the outer scope. | [
"NewScope",
"creates",
"a",
"new",
"scope",
"nested",
"in",
"the",
"outer",
"scope",
"."
] | 5784335da72394c8f53d9036c26fcc876718879b | https://github.com/rogpeppe/godef/blob/5784335da72394c8f53d9036c26fcc876718879b/go/ast/scope.go#L26-L29 | train |
rogpeppe/godef | go/ast/scope.go | Insert | func (s *Scope) Insert(obj *Object) (alt *Object) {
if alt = s.Objects[obj.Name]; alt == nil {
s.Objects[obj.Name] = obj
}
return
} | go | func (s *Scope) Insert(obj *Object) (alt *Object) {
if alt = s.Objects[obj.Name]; alt == nil {
s.Objects[obj.Name] = obj
}
return
} | [
"func",
"(",
"s",
"*",
"Scope",
")",
"Insert",
"(",
"obj",
"*",
"Object",
")",
"(",
"alt",
"*",
"Object",
")",
"{",
"if",
"alt",
"=",
"s",
".",
"Objects",
"[",
"obj",
".",
"Name",
"]",
";",
"alt",
"==",
"nil",
"{",
"s",
".",
"Objects",
"[",
... | // Insert attempts to insert a named object obj into the scope s.
// If the scope already contains an object alt with the same name,
// Insert leaves the scope unchanged and returns alt. Otherwise
// it inserts obj and returns nil."
// | [
"Insert",
"attempts",
"to",
"insert",
"a",
"named",
"object",
"obj",
"into",
"the",
"scope",
"s",
".",
"If",
"the",
"scope",
"already",
"contains",
"an",
"object",
"alt",
"with",
"the",
"same",
"name",
"Insert",
"leaves",
"the",
"scope",
"unchanged",
"and"... | 5784335da72394c8f53d9036c26fcc876718879b | https://github.com/rogpeppe/godef/blob/5784335da72394c8f53d9036c26fcc876718879b/go/ast/scope.go#L44-L49 | train |
rogpeppe/godef | go/ast/scope.go | NewObj | func NewObj(kind ObjKind, name string) *Object {
return &Object{Kind: kind, Name: name}
} | go | func NewObj(kind ObjKind, name string) *Object {
return &Object{Kind: kind, Name: name}
} | [
"func",
"NewObj",
"(",
"kind",
"ObjKind",
",",
"name",
"string",
")",
"*",
"Object",
"{",
"return",
"&",
"Object",
"{",
"Kind",
":",
"kind",
",",
"Name",
":",
"name",
"}",
"\n",
"}"
] | // NewObj creates a new object of a given kind and name. | [
"NewObj",
"creates",
"a",
"new",
"object",
"of",
"a",
"given",
"kind",
"and",
"name",
"."
] | 5784335da72394c8f53d9036c26fcc876718879b | https://github.com/rogpeppe/godef/blob/5784335da72394c8f53d9036c26fcc876718879b/go/ast/scope.go#L90-L92 | train |
rogpeppe/godef | go/ast/ast.go | Pos | func (s *ImportSpec) Pos() token.Pos {
if s.Name != nil {
return s.Name.Pos()
}
return s.Path.Pos()
} | go | func (s *ImportSpec) Pos() token.Pos {
if s.Name != nil {
return s.Name.Pos()
}
return s.Path.Pos()
} | [
"func",
"(",
"s",
"*",
"ImportSpec",
")",
"Pos",
"(",
")",
"token",
".",
"Pos",
"{",
"if",
"s",
".",
"Name",
"!=",
"nil",
"{",
"return",
"s",
".",
"Name",
".",
"Pos",
"(",
")",
"\n",
"}",
"\n",
"return",
"s",
".",
"Path",
".",
"Pos",
"(",
"... | // Pos and End implementations for spec nodes.
// | [
"Pos",
"and",
"End",
"implementations",
"for",
"spec",
"nodes",
"."
] | 5784335da72394c8f53d9036c26fcc876718879b | https://github.com/rogpeppe/godef/blob/5784335da72394c8f53d9036c26fcc876718879b/go/ast/ast.go#L783-L788 | train |
rogpeppe/godef | go/token/token.go | Precedence | func (op Token) Precedence() int {
switch op {
case LOR:
return 1
case LAND:
return 2
case EQL, NEQ, LSS, LEQ, GTR, GEQ:
return 3
case ADD, SUB, OR, XOR:
return 4
case MUL, QUO, REM, SHL, SHR, AND, AND_NOT:
return 5
}
return LowestPrec
} | go | func (op Token) Precedence() int {
switch op {
case LOR:
return 1
case LAND:
return 2
case EQL, NEQ, LSS, LEQ, GTR, GEQ:
return 3
case ADD, SUB, OR, XOR:
return 4
case MUL, QUO, REM, SHL, SHR, AND, AND_NOT:
return 5
}
return LowestPrec
} | [
"func",
"(",
"op",
"Token",
")",
"Precedence",
"(",
")",
"int",
"{",
"switch",
"op",
"{",
"case",
"LOR",
":",
"return",
"1",
"\n",
"case",
"LAND",
":",
"return",
"2",
"\n",
"case",
"EQL",
",",
"NEQ",
",",
"LSS",
",",
"LEQ",
",",
"GTR",
",",
"GE... | // Precedence returns the operator precedence of the binary
// operator op. If op is not a binary operator, the result
// is LowestPrecedence.
// | [
"Precedence",
"returns",
"the",
"operator",
"precedence",
"of",
"the",
"binary",
"operator",
"op",
".",
"If",
"op",
"is",
"not",
"a",
"binary",
"operator",
"the",
"result",
"is",
"LowestPrecedence",
"."
] | 5784335da72394c8f53d9036c26fcc876718879b | https://github.com/rogpeppe/godef/blob/5784335da72394c8f53d9036c26fcc876718879b/go/token/token.go#L260-L274 | train |
rogpeppe/godef | go/types/types.go | DefaultImporter | func DefaultImporter(path string, srcDir string) *ast.Package {
bpkg, err := build.Default.Import(path, srcDir, 0)
if err != nil {
return nil
}
goFiles := make(map[string]bool)
for _, f := range bpkg.GoFiles {
goFiles[f] = true
}
for _, f := range bpkg.CgoFiles {
goFiles[f] = true
}
shouldInclude := func(d os.FileInfo) bool {
return goFiles[d.Name()]
}
pkgs, err := parser.ParseDir(FileSet, bpkg.Dir, shouldInclude, 0, DefaultImportPathToName)
if err != nil {
if Debug {
switch err := err.(type) {
case scanner.ErrorList:
for _, e := range err {
debugp("\t%v: %s", e.Pos, e.Msg)
}
default:
debugp("\terror parsing %s: %v", bpkg.Dir, err)
}
}
return nil
}
if pkg := pkgs[bpkg.Name]; pkg != nil {
return pkg
}
if Debug {
debugp("package not found by ParseDir!")
}
return nil
} | go | func DefaultImporter(path string, srcDir string) *ast.Package {
bpkg, err := build.Default.Import(path, srcDir, 0)
if err != nil {
return nil
}
goFiles := make(map[string]bool)
for _, f := range bpkg.GoFiles {
goFiles[f] = true
}
for _, f := range bpkg.CgoFiles {
goFiles[f] = true
}
shouldInclude := func(d os.FileInfo) bool {
return goFiles[d.Name()]
}
pkgs, err := parser.ParseDir(FileSet, bpkg.Dir, shouldInclude, 0, DefaultImportPathToName)
if err != nil {
if Debug {
switch err := err.(type) {
case scanner.ErrorList:
for _, e := range err {
debugp("\t%v: %s", e.Pos, e.Msg)
}
default:
debugp("\terror parsing %s: %v", bpkg.Dir, err)
}
}
return nil
}
if pkg := pkgs[bpkg.Name]; pkg != nil {
return pkg
}
if Debug {
debugp("package not found by ParseDir!")
}
return nil
} | [
"func",
"DefaultImporter",
"(",
"path",
"string",
",",
"srcDir",
"string",
")",
"*",
"ast",
".",
"Package",
"{",
"bpkg",
",",
"err",
":=",
"build",
".",
"Default",
".",
"Import",
"(",
"path",
",",
"srcDir",
",",
"0",
")",
"\n",
"if",
"err",
"!=",
"... | // DefaultImporter looks for the package; if it finds it,
// it parses and returns it. If no package was found, it returns nil. | [
"DefaultImporter",
"looks",
"for",
"the",
"package",
";",
"if",
"it",
"finds",
"it",
"it",
"parses",
"and",
"returns",
"it",
".",
"If",
"no",
"package",
"was",
"found",
"it",
"returns",
"nil",
"."
] | 5784335da72394c8f53d9036c26fcc876718879b | https://github.com/rogpeppe/godef/blob/5784335da72394c8f53d9036c26fcc876718879b/go/types/types.go#L80-L116 | train |
rogpeppe/godef | go/types/types.go | String | func (t Type) String() string {
return fmt.Sprintf("Type{%v %q %T %v}", t.Kind, t.Pkg, t.Node, pretty{t.Node})
} | go | func (t Type) String() string {
return fmt.Sprintf("Type{%v %q %T %v}", t.Kind, t.Pkg, t.Node, pretty{t.Node})
} | [
"func",
"(",
"t",
"Type",
")",
"String",
"(",
")",
"string",
"{",
"return",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"t",
".",
"Kind",
",",
"t",
".",
"Pkg",
",",
"t",
".",
"Node",
",",
"pretty",
"{",
"t",
".",
"Node",
"}",
")",
"\n",
"}... | // String is for debugging purposes. | [
"String",
"is",
"for",
"debugging",
"purposes",
"."
] | 5784335da72394c8f53d9036c26fcc876718879b | https://github.com/rogpeppe/godef/blob/5784335da72394c8f53d9036c26fcc876718879b/go/types/types.go#L144-L146 | train |
rogpeppe/godef | go/printer/nodes.go | setComment | func (p *printer) setComment(g *ast.CommentGroup) {
if g == nil || !p.useNodeComments {
return
}
if p.comments == nil {
// initialize p.comments lazily
p.comments = make([]*ast.CommentGroup, 1)
} else if p.cindex < len(p.comments) {
// for some reason there are pending comments; this
// should never happen - handle gracefully and flush
// all comments up to g, ignore anything after that
p.flush(p.fset.Position(g.List[0].Pos()), token.ILLEGAL)
}
p.comments[0] = g
p.cindex = 0
} | go | func (p *printer) setComment(g *ast.CommentGroup) {
if g == nil || !p.useNodeComments {
return
}
if p.comments == nil {
// initialize p.comments lazily
p.comments = make([]*ast.CommentGroup, 1)
} else if p.cindex < len(p.comments) {
// for some reason there are pending comments; this
// should never happen - handle gracefully and flush
// all comments up to g, ignore anything after that
p.flush(p.fset.Position(g.List[0].Pos()), token.ILLEGAL)
}
p.comments[0] = g
p.cindex = 0
} | [
"func",
"(",
"p",
"*",
"printer",
")",
"setComment",
"(",
"g",
"*",
"ast",
".",
"CommentGroup",
")",
"{",
"if",
"g",
"==",
"nil",
"||",
"!",
"p",
".",
"useNodeComments",
"{",
"return",
"\n",
"}",
"\n",
"if",
"p",
".",
"comments",
"==",
"nil",
"{"... | // setComment sets g as the next comment if g != nil and if node comments
// are enabled - this mode is used when printing source code fragments such
// as exports only. It assumes that there are no other pending comments to
// intersperse. | [
"setComment",
"sets",
"g",
"as",
"the",
"next",
"comment",
"if",
"g",
"!",
"=",
"nil",
"and",
"if",
"node",
"comments",
"are",
"enabled",
"-",
"this",
"mode",
"is",
"used",
"when",
"printing",
"source",
"code",
"fragments",
"such",
"as",
"exports",
"only... | 5784335da72394c8f53d9036c26fcc876718879b | https://github.com/rogpeppe/godef/blob/5784335da72394c8f53d9036c26fcc876718879b/go/printer/nodes.go#L62-L77 | train |
rogpeppe/godef | go/printer/nodes.go | identList | func (p *printer) identList(list []*ast.Ident, indent bool, multiLine *bool) {
// convert into an expression list so we can re-use exprList formatting
xlist := make([]ast.Expr, len(list))
for i, x := range list {
xlist[i] = x
}
mode := commaSep
if !indent {
mode |= noIndent
}
p.exprList(token.NoPos, xlist, 1, mode, multiLine, token.NoPos)
} | go | func (p *printer) identList(list []*ast.Ident, indent bool, multiLine *bool) {
// convert into an expression list so we can re-use exprList formatting
xlist := make([]ast.Expr, len(list))
for i, x := range list {
xlist[i] = x
}
mode := commaSep
if !indent {
mode |= noIndent
}
p.exprList(token.NoPos, xlist, 1, mode, multiLine, token.NoPos)
} | [
"func",
"(",
"p",
"*",
"printer",
")",
"identList",
"(",
"list",
"[",
"]",
"*",
"ast",
".",
"Ident",
",",
"indent",
"bool",
",",
"multiLine",
"*",
"bool",
")",
"{",
"// convert into an expression list so we can re-use exprList formatting",
"xlist",
":=",
"make",... | // Sets multiLine to true if the identifier list spans multiple lines.
// If indent is set, a multi-line identifier list is indented after the
// first linebreak encountered. | [
"Sets",
"multiLine",
"to",
"true",
"if",
"the",
"identifier",
"list",
"spans",
"multiple",
"lines",
".",
"If",
"indent",
"is",
"set",
"a",
"multi",
"-",
"line",
"identifier",
"list",
"is",
"indented",
"after",
"the",
"first",
"linebreak",
"encountered",
"."
... | 5784335da72394c8f53d9036c26fcc876718879b | https://github.com/rogpeppe/godef/blob/5784335da72394c8f53d9036c26fcc876718879b/go/printer/nodes.go#L93-L104 | train |
rogpeppe/godef | go/printer/nodes.go | parameters | func (p *printer) parameters(fields *ast.FieldList, multiLine *bool) {
p.print(fields.Opening, token.LPAREN)
if len(fields.List) > 0 {
var prevLine, line int
for i, par := range fields.List {
if i > 0 {
p.print(token.COMMA)
if len(par.Names) > 0 {
line = p.fset.Position(par.Names[0].Pos()).Line
} else {
line = p.fset.Position(par.Type.Pos()).Line
}
if 0 < prevLine && prevLine < line && p.linebreak(line, 0, ignore, true) {
*multiLine = true
} else {
p.print(blank)
}
}
if len(par.Names) > 0 {
p.identList(par.Names, false, multiLine)
p.print(blank)
}
p.expr(par.Type, multiLine)
prevLine = p.fset.Position(par.Type.Pos()).Line
}
}
p.print(fields.Closing, token.RPAREN)
} | go | func (p *printer) parameters(fields *ast.FieldList, multiLine *bool) {
p.print(fields.Opening, token.LPAREN)
if len(fields.List) > 0 {
var prevLine, line int
for i, par := range fields.List {
if i > 0 {
p.print(token.COMMA)
if len(par.Names) > 0 {
line = p.fset.Position(par.Names[0].Pos()).Line
} else {
line = p.fset.Position(par.Type.Pos()).Line
}
if 0 < prevLine && prevLine < line && p.linebreak(line, 0, ignore, true) {
*multiLine = true
} else {
p.print(blank)
}
}
if len(par.Names) > 0 {
p.identList(par.Names, false, multiLine)
p.print(blank)
}
p.expr(par.Type, multiLine)
prevLine = p.fset.Position(par.Type.Pos()).Line
}
}
p.print(fields.Closing, token.RPAREN)
} | [
"func",
"(",
"p",
"*",
"printer",
")",
"parameters",
"(",
"fields",
"*",
"ast",
".",
"FieldList",
",",
"multiLine",
"*",
"bool",
")",
"{",
"p",
".",
"print",
"(",
"fields",
".",
"Opening",
",",
"token",
".",
"LPAREN",
")",
"\n",
"if",
"len",
"(",
... | // Sets multiLine to true if the the parameter list spans multiple lines. | [
"Sets",
"multiLine",
"to",
"true",
"if",
"the",
"the",
"parameter",
"list",
"spans",
"multiple",
"lines",
"."
] | 5784335da72394c8f53d9036c26fcc876718879b | https://github.com/rogpeppe/godef/blob/5784335da72394c8f53d9036c26fcc876718879b/go/printer/nodes.go#L270-L297 | train |
rogpeppe/godef | go/printer/nodes.go | signature | func (p *printer) signature(params, result *ast.FieldList, multiLine *bool) {
p.parameters(params, multiLine)
n := result.NumFields()
if n > 0 {
p.print(blank)
if n == 1 && result.List[0].Names == nil {
// single anonymous result; no ()'s
p.expr(result.List[0].Type, multiLine)
return
}
p.parameters(result, multiLine)
}
} | go | func (p *printer) signature(params, result *ast.FieldList, multiLine *bool) {
p.parameters(params, multiLine)
n := result.NumFields()
if n > 0 {
p.print(blank)
if n == 1 && result.List[0].Names == nil {
// single anonymous result; no ()'s
p.expr(result.List[0].Type, multiLine)
return
}
p.parameters(result, multiLine)
}
} | [
"func",
"(",
"p",
"*",
"printer",
")",
"signature",
"(",
"params",
",",
"result",
"*",
"ast",
".",
"FieldList",
",",
"multiLine",
"*",
"bool",
")",
"{",
"p",
".",
"parameters",
"(",
"params",
",",
"multiLine",
")",
"\n",
"n",
":=",
"result",
".",
"... | // Sets multiLine to true if the signature spans multiple lines. | [
"Sets",
"multiLine",
"to",
"true",
"if",
"the",
"signature",
"spans",
"multiple",
"lines",
"."
] | 5784335da72394c8f53d9036c26fcc876718879b | https://github.com/rogpeppe/godef/blob/5784335da72394c8f53d9036c26fcc876718879b/go/printer/nodes.go#L300-L312 | train |
rogpeppe/godef | go/printer/nodes.go | splitSelector | func splitSelector(expr ast.Expr) (body, suffix ast.Expr) {
switch x := expr.(type) {
case *ast.SelectorExpr:
body, suffix = x.X, x.Sel
return
case *ast.CallExpr:
body, suffix = splitSelector(x.Fun)
if body != nil {
suffix = &ast.CallExpr{suffix, x.Lparen, x.Args, x.Ellipsis, x.Rparen}
return
}
case *ast.IndexExpr:
body, suffix = splitSelector(x.X)
if body != nil {
suffix = &ast.IndexExpr{suffix, x.Lbrack, x.Index, x.Rbrack}
return
}
case *ast.SliceExpr:
body, suffix = splitSelector(x.X)
if body != nil {
suffix = &ast.SliceExpr{X: suffix, Lbrack: x.Lbrack, Low: x.Low, High: x.High, Rbrack: x.Rbrack, Slice3: false}
return
}
case *ast.TypeAssertExpr:
body, suffix = splitSelector(x.X)
if body != nil {
suffix = &ast.TypeAssertExpr{suffix, x.Type}
return
}
}
suffix = expr
return
} | go | func splitSelector(expr ast.Expr) (body, suffix ast.Expr) {
switch x := expr.(type) {
case *ast.SelectorExpr:
body, suffix = x.X, x.Sel
return
case *ast.CallExpr:
body, suffix = splitSelector(x.Fun)
if body != nil {
suffix = &ast.CallExpr{suffix, x.Lparen, x.Args, x.Ellipsis, x.Rparen}
return
}
case *ast.IndexExpr:
body, suffix = splitSelector(x.X)
if body != nil {
suffix = &ast.IndexExpr{suffix, x.Lbrack, x.Index, x.Rbrack}
return
}
case *ast.SliceExpr:
body, suffix = splitSelector(x.X)
if body != nil {
suffix = &ast.SliceExpr{X: suffix, Lbrack: x.Lbrack, Low: x.Low, High: x.High, Rbrack: x.Rbrack, Slice3: false}
return
}
case *ast.TypeAssertExpr:
body, suffix = splitSelector(x.X)
if body != nil {
suffix = &ast.TypeAssertExpr{suffix, x.Type}
return
}
}
suffix = expr
return
} | [
"func",
"splitSelector",
"(",
"expr",
"ast",
".",
"Expr",
")",
"(",
"body",
",",
"suffix",
"ast",
".",
"Expr",
")",
"{",
"switch",
"x",
":=",
"expr",
".",
"(",
"type",
")",
"{",
"case",
"*",
"ast",
".",
"SelectorExpr",
":",
"body",
",",
"suffix",
... | // If the expression contains one or more selector expressions, splits it into
// two expressions at the rightmost period. Writes entire expr to suffix when
// selector isn't found. Rewrites AST nodes for calls, index expressions and
// type assertions, all of which may be found in selector chains, to make them
// parts of the chain. | [
"If",
"the",
"expression",
"contains",
"one",
"or",
"more",
"selector",
"expressions",
"splits",
"it",
"into",
"two",
"expressions",
"at",
"the",
"rightmost",
"period",
".",
"Writes",
"entire",
"expr",
"to",
"suffix",
"when",
"selector",
"isn",
"t",
"found",
... | 5784335da72394c8f53d9036c26fcc876718879b | https://github.com/rogpeppe/godef/blob/5784335da72394c8f53d9036c26fcc876718879b/go/printer/nodes.go#L640-L672 | train |
rogpeppe/godef | go/printer/nodes.go | selectorExprList | func selectorExprList(expr ast.Expr) (list []ast.Expr) {
// split expression
for expr != nil {
var suffix ast.Expr
expr, suffix = splitSelector(expr)
list = append(list, suffix)
}
// reverse list
for i, j := 0, len(list)-1; i < j; i, j = i+1, j-1 {
list[i], list[j] = list[j], list[i]
}
return
} | go | func selectorExprList(expr ast.Expr) (list []ast.Expr) {
// split expression
for expr != nil {
var suffix ast.Expr
expr, suffix = splitSelector(expr)
list = append(list, suffix)
}
// reverse list
for i, j := 0, len(list)-1; i < j; i, j = i+1, j-1 {
list[i], list[j] = list[j], list[i]
}
return
} | [
"func",
"selectorExprList",
"(",
"expr",
"ast",
".",
"Expr",
")",
"(",
"list",
"[",
"]",
"ast",
".",
"Expr",
")",
"{",
"// split expression",
"for",
"expr",
"!=",
"nil",
"{",
"var",
"suffix",
"ast",
".",
"Expr",
"\n",
"expr",
",",
"suffix",
"=",
"spl... | // Convert an expression into an expression list split at the periods of
// selector expressions. | [
"Convert",
"an",
"expression",
"into",
"an",
"expression",
"list",
"split",
"at",
"the",
"periods",
"of",
"selector",
"expressions",
"."
] | 5784335da72394c8f53d9036c26fcc876718879b | https://github.com/rogpeppe/godef/blob/5784335da72394c8f53d9036c26fcc876718879b/go/printer/nodes.go#L676-L690 | train |
rogpeppe/godef | go/printer/nodes.go | spec | func (p *printer) spec(spec ast.Spec, n int, doIndent bool, multiLine *bool) {
switch s := spec.(type) {
case *ast.ImportSpec:
p.setComment(s.Doc)
if s.Name != nil {
p.expr(s.Name, multiLine)
p.print(blank)
}
p.expr(s.Path, multiLine)
p.setComment(s.Comment)
case *ast.ValueSpec:
if n != 1 {
p.internalError("expected n = 1; got", n)
}
p.setComment(s.Doc)
p.identList(s.Names, doIndent, multiLine) // always present
if s.Type != nil {
p.print(blank)
p.expr(s.Type, multiLine)
}
if s.Values != nil {
p.print(blank, token.ASSIGN)
p.exprList(token.NoPos, s.Values, 1, blankStart|commaSep, multiLine, token.NoPos)
}
p.setComment(s.Comment)
case *ast.TypeSpec:
p.setComment(s.Doc)
p.expr(s.Name, multiLine)
if n == 1 {
p.print(blank)
} else {
p.print(vtab)
}
p.expr(s.Type, multiLine)
p.setComment(s.Comment)
default:
panic("unreachable")
}
} | go | func (p *printer) spec(spec ast.Spec, n int, doIndent bool, multiLine *bool) {
switch s := spec.(type) {
case *ast.ImportSpec:
p.setComment(s.Doc)
if s.Name != nil {
p.expr(s.Name, multiLine)
p.print(blank)
}
p.expr(s.Path, multiLine)
p.setComment(s.Comment)
case *ast.ValueSpec:
if n != 1 {
p.internalError("expected n = 1; got", n)
}
p.setComment(s.Doc)
p.identList(s.Names, doIndent, multiLine) // always present
if s.Type != nil {
p.print(blank)
p.expr(s.Type, multiLine)
}
if s.Values != nil {
p.print(blank, token.ASSIGN)
p.exprList(token.NoPos, s.Values, 1, blankStart|commaSep, multiLine, token.NoPos)
}
p.setComment(s.Comment)
case *ast.TypeSpec:
p.setComment(s.Doc)
p.expr(s.Name, multiLine)
if n == 1 {
p.print(blank)
} else {
p.print(vtab)
}
p.expr(s.Type, multiLine)
p.setComment(s.Comment)
default:
panic("unreachable")
}
} | [
"func",
"(",
"p",
"*",
"printer",
")",
"spec",
"(",
"spec",
"ast",
".",
"Spec",
",",
"n",
"int",
",",
"doIndent",
"bool",
",",
"multiLine",
"*",
"bool",
")",
"{",
"switch",
"s",
":=",
"spec",
".",
"(",
"type",
")",
"{",
"case",
"*",
"ast",
".",... | // The parameter n is the number of specs in the group. If doIndent is set,
// multi-line identifier lists in the spec are indented when the first
// linebreak is encountered.
// Sets multiLine to true if the spec spans multiple lines.
// | [
"The",
"parameter",
"n",
"is",
"the",
"number",
"of",
"specs",
"in",
"the",
"group",
".",
"If",
"doIndent",
"is",
"set",
"multi",
"-",
"line",
"identifier",
"lists",
"in",
"the",
"spec",
"are",
"indented",
"when",
"the",
"first",
"linebreak",
"is",
"enco... | 5784335da72394c8f53d9036c26fcc876718879b | https://github.com/rogpeppe/godef/blob/5784335da72394c8f53d9036c26fcc876718879b/go/printer/nodes.go#L1265-L1306 | train |
rogpeppe/godef | go/printer/nodes.go | funcBody | func (p *printer) funcBody(b *ast.BlockStmt, headerSize int, isLit bool, multiLine *bool) {
if b == nil {
return
}
if p.isOneLineFunc(b, headerSize) {
sep := vtab
if isLit {
sep = blank
}
p.print(sep, b.Lbrace, token.LBRACE)
if len(b.List) > 0 {
p.print(blank)
for i, s := range b.List {
if i > 0 {
p.print(token.SEMICOLON, blank)
}
p.stmt(s, i == len(b.List)-1, ignoreMultiLine)
}
p.print(blank)
}
p.print(b.Rbrace, token.RBRACE)
return
}
p.print(blank)
p.block(b, 1)
*multiLine = true
} | go | func (p *printer) funcBody(b *ast.BlockStmt, headerSize int, isLit bool, multiLine *bool) {
if b == nil {
return
}
if p.isOneLineFunc(b, headerSize) {
sep := vtab
if isLit {
sep = blank
}
p.print(sep, b.Lbrace, token.LBRACE)
if len(b.List) > 0 {
p.print(blank)
for i, s := range b.List {
if i > 0 {
p.print(token.SEMICOLON, blank)
}
p.stmt(s, i == len(b.List)-1, ignoreMultiLine)
}
p.print(blank)
}
p.print(b.Rbrace, token.RBRACE)
return
}
p.print(blank)
p.block(b, 1)
*multiLine = true
} | [
"func",
"(",
"p",
"*",
"printer",
")",
"funcBody",
"(",
"b",
"*",
"ast",
".",
"BlockStmt",
",",
"headerSize",
"int",
",",
"isLit",
"bool",
",",
"multiLine",
"*",
"bool",
")",
"{",
"if",
"b",
"==",
"nil",
"{",
"return",
"\n",
"}",
"\n\n",
"if",
"p... | // Sets multiLine to true if the function body spans multiple lines. | [
"Sets",
"multiLine",
"to",
"true",
"if",
"the",
"function",
"body",
"spans",
"multiple",
"lines",
"."
] | 5784335da72394c8f53d9036c26fcc876718879b | https://github.com/rogpeppe/godef/blob/5784335da72394c8f53d9036c26fcc876718879b/go/printer/nodes.go#L1412-L1440 | train |
rogpeppe/godef | go/ast/print.go | NotNilFilter | func NotNilFilter(_ string, v reflect.Value) bool {
switch v.Kind() {
case reflect.Chan, reflect.Func, reflect.Interface, reflect.Map, reflect.Ptr, reflect.Slice:
return !v.IsNil()
}
return true
} | go | func NotNilFilter(_ string, v reflect.Value) bool {
switch v.Kind() {
case reflect.Chan, reflect.Func, reflect.Interface, reflect.Map, reflect.Ptr, reflect.Slice:
return !v.IsNil()
}
return true
} | [
"func",
"NotNilFilter",
"(",
"_",
"string",
",",
"v",
"reflect",
".",
"Value",
")",
"bool",
"{",
"switch",
"v",
".",
"Kind",
"(",
")",
"{",
"case",
"reflect",
".",
"Chan",
",",
"reflect",
".",
"Func",
",",
"reflect",
".",
"Interface",
",",
"reflect",... | // NotNilFilter returns true for field values that are not nil;
// it returns false otherwise. | [
"NotNilFilter",
"returns",
"true",
"for",
"field",
"values",
"that",
"are",
"not",
"nil",
";",
"it",
"returns",
"false",
"otherwise",
"."
] | 5784335da72394c8f53d9036c26fcc876718879b | https://github.com/rogpeppe/godef/blob/5784335da72394c8f53d9036c26fcc876718879b/go/ast/print.go#L23-L29 | train |
rogpeppe/godef | go/ast/print.go | printf | func (p *printer) printf(format string, args ...interface{}) {
n, err := fmt.Fprintf(p, format, args...)
p.written += n
if err != nil {
panic(localError{err})
}
} | go | func (p *printer) printf(format string, args ...interface{}) {
n, err := fmt.Fprintf(p, format, args...)
p.written += n
if err != nil {
panic(localError{err})
}
} | [
"func",
"(",
"p",
"*",
"printer",
")",
"printf",
"(",
"format",
"string",
",",
"args",
"...",
"interface",
"{",
"}",
")",
"{",
"n",
",",
"err",
":=",
"fmt",
".",
"Fprintf",
"(",
"p",
",",
"format",
",",
"args",
"...",
")",
"\n",
"p",
".",
"writ... | // printf is a convenience wrapper that takes care of print errors. | [
"printf",
"is",
"a",
"convenience",
"wrapper",
"that",
"takes",
"care",
"of",
"print",
"errors",
"."
] | 5784335da72394c8f53d9036c26fcc876718879b | https://github.com/rogpeppe/godef/blob/5784335da72394c8f53d9036c26fcc876718879b/go/ast/print.go#L129-L135 | train |
rogpeppe/godef | go/scanner/errors.go | GetErrorList | func (h *ErrorVector) GetErrorList(mode int) ErrorList {
if len(h.errors) == 0 {
return nil
}
list := make(ErrorList, len(h.errors))
copy(list, h.errors)
if mode >= Sorted {
sort.Sort(list)
}
if mode >= NoMultiples {
var last token.Position // initial last.Line is != any legal error line
i := 0
for _, e := range list {
if e.Pos.Filename != last.Filename || e.Pos.Line != last.Line {
last = e.Pos
list[i] = e
i++
}
}
list = list[0:i]
}
return list
} | go | func (h *ErrorVector) GetErrorList(mode int) ErrorList {
if len(h.errors) == 0 {
return nil
}
list := make(ErrorList, len(h.errors))
copy(list, h.errors)
if mode >= Sorted {
sort.Sort(list)
}
if mode >= NoMultiples {
var last token.Position // initial last.Line is != any legal error line
i := 0
for _, e := range list {
if e.Pos.Filename != last.Filename || e.Pos.Line != last.Line {
last = e.Pos
list[i] = e
i++
}
}
list = list[0:i]
}
return list
} | [
"func",
"(",
"h",
"*",
"ErrorVector",
")",
"GetErrorList",
"(",
"mode",
"int",
")",
"ErrorList",
"{",
"if",
"len",
"(",
"h",
".",
"errors",
")",
"==",
"0",
"{",
"return",
"nil",
"\n",
"}",
"\n\n",
"list",
":=",
"make",
"(",
"ErrorList",
",",
"len",... | // GetErrorList returns the list of errors collected by an ErrorVector.
// The construction of the ErrorList returned is controlled by the mode
// parameter. If there are no errors, the result is nil.
// | [
"GetErrorList",
"returns",
"the",
"list",
"of",
"errors",
"collected",
"by",
"an",
"ErrorVector",
".",
"The",
"construction",
"of",
"the",
"ErrorList",
"returned",
"is",
"controlled",
"by",
"the",
"mode",
"parameter",
".",
"If",
"there",
"are",
"no",
"errors",... | 5784335da72394c8f53d9036c26fcc876718879b | https://github.com/rogpeppe/godef/blob/5784335da72394c8f53d9036c26fcc876718879b/go/scanner/errors.go#L111-L137 | train |
rogpeppe/godef | go/scanner/errors.go | GetError | func (h *ErrorVector) GetError(mode int) error {
if len(h.errors) == 0 {
return nil
}
return h.GetErrorList(mode)
} | go | func (h *ErrorVector) GetError(mode int) error {
if len(h.errors) == 0 {
return nil
}
return h.GetErrorList(mode)
} | [
"func",
"(",
"h",
"*",
"ErrorVector",
")",
"GetError",
"(",
"mode",
"int",
")",
"error",
"{",
"if",
"len",
"(",
"h",
".",
"errors",
")",
"==",
"0",
"{",
"return",
"nil",
"\n",
"}",
"\n\n",
"return",
"h",
".",
"GetErrorList",
"(",
"mode",
")",
"\n... | // GetError is like GetErrorList, but it returns an os.Error instead
// so that a nil result can be assigned to an os.Error variable and
// remains nil.
// | [
"GetError",
"is",
"like",
"GetErrorList",
"but",
"it",
"returns",
"an",
"os",
".",
"Error",
"instead",
"so",
"that",
"a",
"nil",
"result",
"can",
"be",
"assigned",
"to",
"an",
"os",
".",
"Error",
"variable",
"and",
"remains",
"nil",
"."
] | 5784335da72394c8f53d9036c26fcc876718879b | https://github.com/rogpeppe/godef/blob/5784335da72394c8f53d9036c26fcc876718879b/go/scanner/errors.go#L143-L149 | train |
rogpeppe/godef | go/scanner/errors.go | Error | func (h *ErrorVector) Error(pos token.Position, msg string) {
h.errors = append(h.errors, &Error{pos, msg})
} | go | func (h *ErrorVector) Error(pos token.Position, msg string) {
h.errors = append(h.errors, &Error{pos, msg})
} | [
"func",
"(",
"h",
"*",
"ErrorVector",
")",
"Error",
"(",
"pos",
"token",
".",
"Position",
",",
"msg",
"string",
")",
"{",
"h",
".",
"errors",
"=",
"append",
"(",
"h",
".",
"errors",
",",
"&",
"Error",
"{",
"pos",
",",
"msg",
"}",
")",
"\n",
"}"... | // ErrorVector implements the ErrorHandler interface. | [
"ErrorVector",
"implements",
"the",
"ErrorHandler",
"interface",
"."
] | 5784335da72394c8f53d9036c26fcc876718879b | https://github.com/rogpeppe/godef/blob/5784335da72394c8f53d9036c26fcc876718879b/go/scanner/errors.go#L152-L154 | train |
rogpeppe/godef | go/parser/interface.go | ParseStmtList | func ParseStmtList(fset *token.FileSet, filename string, src interface{}, scope *ast.Scope, pathToName ImportPathToName) ([]ast.Stmt, error) {
data, err := readSource(filename, src)
if err != nil {
return nil, err
}
var p parser
p.init(fset, filename, data, 0, scope, pathToName)
return p.parseStmtList(), p.parseEOF()
} | go | func ParseStmtList(fset *token.FileSet, filename string, src interface{}, scope *ast.Scope, pathToName ImportPathToName) ([]ast.Stmt, error) {
data, err := readSource(filename, src)
if err != nil {
return nil, err
}
var p parser
p.init(fset, filename, data, 0, scope, pathToName)
return p.parseStmtList(), p.parseEOF()
} | [
"func",
"ParseStmtList",
"(",
"fset",
"*",
"token",
".",
"FileSet",
",",
"filename",
"string",
",",
"src",
"interface",
"{",
"}",
",",
"scope",
"*",
"ast",
".",
"Scope",
",",
"pathToName",
"ImportPathToName",
")",
"(",
"[",
"]",
"ast",
".",
"Stmt",
","... | // ParseStmtList parses a list of Go statements and returns the list
// of corresponding AST nodes. The fset, filename, and src arguments have the same
// interpretation as for ParseFile. If there is an error, the node
// list may be nil or contain partial ASTs.
//
// if scope is non-nil, it will be used as the scope for the statements.
// | [
"ParseStmtList",
"parses",
"a",
"list",
"of",
"Go",
"statements",
"and",
"returns",
"the",
"list",
"of",
"corresponding",
"AST",
"nodes",
".",
"The",
"fset",
"filename",
"and",
"src",
"arguments",
"have",
"the",
"same",
"interpretation",
"as",
"for",
"ParseFil... | 5784335da72394c8f53d9036c26fcc876718879b | https://github.com/rogpeppe/godef/blob/5784335da72394c8f53d9036c26fcc876718879b/go/parser/interface.go#L93-L102 | train |
rogpeppe/godef | go/parser/interface.go | ParseDeclList | func ParseDeclList(fset *token.FileSet, filename string, src interface{}, scope *ast.Scope, pathToName ImportPathToName) ([]ast.Decl, error) {
data, err := readSource(filename, src)
if err != nil {
return nil, err
}
var p parser
p.init(fset, filename, data, 0, scope, pathToName)
p.pkgScope = scope
p.fileScope = scope
return p.parseDeclList(), p.parseEOF()
} | go | func ParseDeclList(fset *token.FileSet, filename string, src interface{}, scope *ast.Scope, pathToName ImportPathToName) ([]ast.Decl, error) {
data, err := readSource(filename, src)
if err != nil {
return nil, err
}
var p parser
p.init(fset, filename, data, 0, scope, pathToName)
p.pkgScope = scope
p.fileScope = scope
return p.parseDeclList(), p.parseEOF()
} | [
"func",
"ParseDeclList",
"(",
"fset",
"*",
"token",
".",
"FileSet",
",",
"filename",
"string",
",",
"src",
"interface",
"{",
"}",
",",
"scope",
"*",
"ast",
".",
"Scope",
",",
"pathToName",
"ImportPathToName",
")",
"(",
"[",
"]",
"ast",
".",
"Decl",
","... | // ParseDeclList parses a list of Go declarations and returns the list
// of corresponding AST nodes. The fset, filename, and src arguments have the same
// interpretation as for ParseFile. If there is an error, the node
// list may be nil or contain partial ASTs.
//
// If scope is non-nil, it will be used for declarations.
// | [
"ParseDeclList",
"parses",
"a",
"list",
"of",
"Go",
"declarations",
"and",
"returns",
"the",
"list",
"of",
"corresponding",
"AST",
"nodes",
".",
"The",
"fset",
"filename",
"and",
"src",
"arguments",
"have",
"the",
"same",
"interpretation",
"as",
"for",
"ParseF... | 5784335da72394c8f53d9036c26fcc876718879b | https://github.com/rogpeppe/godef/blob/5784335da72394c8f53d9036c26fcc876718879b/go/parser/interface.go#L111-L122 | train |
rogpeppe/godef | go/token/position.go | Position | func (s *FileSet) Position(p Pos) (pos Position) {
if p != NoPos {
// TODO(gri) consider optimizing the case where p
// is in the last file addded, or perhaps
// looked at - will eliminate one level
// of search
s.mutex.RLock()
if f := s.file(p); f != nil {
pos = f.position(p)
}
s.mutex.RUnlock()
}
return
} | go | func (s *FileSet) Position(p Pos) (pos Position) {
if p != NoPos {
// TODO(gri) consider optimizing the case where p
// is in the last file addded, or perhaps
// looked at - will eliminate one level
// of search
s.mutex.RLock()
if f := s.file(p); f != nil {
pos = f.position(p)
}
s.mutex.RUnlock()
}
return
} | [
"func",
"(",
"s",
"*",
"FileSet",
")",
"Position",
"(",
"p",
"Pos",
")",
"(",
"pos",
"Position",
")",
"{",
"if",
"p",
"!=",
"NoPos",
"{",
"// TODO(gri) consider optimizing the case where p",
"// is in the last file addded, or perhaps",
"// looked at ... | // Position converts a Pos in the fileset into a general Position. | [
"Position",
"converts",
"a",
"Pos",
"in",
"the",
"fileset",
"into",
"a",
"general",
"Position",
"."
] | 5784335da72394c8f53d9036c26fcc876718879b | https://github.com/rogpeppe/godef/blob/5784335da72394c8f53d9036c26fcc876718879b/go/token/position.go#L120-L133 | train |
rogpeppe/godef | go/token/position.go | LineCount | func (f *File) LineCount() int {
f.set.mutex.RLock()
n := len(f.lines)
f.set.mutex.RUnlock()
return n
} | go | func (f *File) LineCount() int {
f.set.mutex.RLock()
n := len(f.lines)
f.set.mutex.RUnlock()
return n
} | [
"func",
"(",
"f",
"*",
"File",
")",
"LineCount",
"(",
")",
"int",
"{",
"f",
".",
"set",
".",
"mutex",
".",
"RLock",
"(",
")",
"\n",
"n",
":=",
"len",
"(",
"f",
".",
"lines",
")",
"\n",
"f",
".",
"set",
".",
"mutex",
".",
"RUnlock",
"(",
")"... | // LineCount returns the number of lines in file f. | [
"LineCount",
"returns",
"the",
"number",
"of",
"lines",
"in",
"file",
"f",
"."
] | 5784335da72394c8f53d9036c26fcc876718879b | https://github.com/rogpeppe/godef/blob/5784335da72394c8f53d9036c26fcc876718879b/go/token/position.go#L187-L192 | train |
rogpeppe/godef | go/token/position.go | AddLine | func (f *File) AddLine(offset int) {
f.set.mutex.Lock()
if i := len(f.lines); (i == 0 || f.lines[i-1] < offset) && offset < f.size {
f.lines = append(f.lines, offset)
}
f.set.mutex.Unlock()
} | go | func (f *File) AddLine(offset int) {
f.set.mutex.Lock()
if i := len(f.lines); (i == 0 || f.lines[i-1] < offset) && offset < f.size {
f.lines = append(f.lines, offset)
}
f.set.mutex.Unlock()
} | [
"func",
"(",
"f",
"*",
"File",
")",
"AddLine",
"(",
"offset",
"int",
")",
"{",
"f",
".",
"set",
".",
"mutex",
".",
"Lock",
"(",
")",
"\n",
"if",
"i",
":=",
"len",
"(",
"f",
".",
"lines",
")",
";",
"(",
"i",
"==",
"0",
"||",
"f",
".",
"lin... | // AddLine adds the line offset for a new line.
// The line offset must be larger than the offset for the previous line
// and smaller than the file size; otherwise the line offset is ignored.
// | [
"AddLine",
"adds",
"the",
"line",
"offset",
"for",
"a",
"new",
"line",
".",
"The",
"line",
"offset",
"must",
"be",
"larger",
"than",
"the",
"offset",
"for",
"the",
"previous",
"line",
"and",
"smaller",
"than",
"the",
"file",
"size",
";",
"otherwise",
"th... | 5784335da72394c8f53d9036c26fcc876718879b | https://github.com/rogpeppe/godef/blob/5784335da72394c8f53d9036c26fcc876718879b/go/token/position.go#L198-L204 | train |
rogpeppe/godef | go/token/position.go | SetLinesForContent | func (f *File) SetLinesForContent(content []byte) {
var lines []int
line := 0
for offset, b := range content {
if line >= 0 {
lines = append(lines, line)
}
line = -1
if b == '\n' {
line = offset + 1
}
}
// set lines table
f.set.mutex.Lock()
f.lines = lines
f.set.mutex.Unlock()
} | go | func (f *File) SetLinesForContent(content []byte) {
var lines []int
line := 0
for offset, b := range content {
if line >= 0 {
lines = append(lines, line)
}
line = -1
if b == '\n' {
line = offset + 1
}
}
// set lines table
f.set.mutex.Lock()
f.lines = lines
f.set.mutex.Unlock()
} | [
"func",
"(",
"f",
"*",
"File",
")",
"SetLinesForContent",
"(",
"content",
"[",
"]",
"byte",
")",
"{",
"var",
"lines",
"[",
"]",
"int",
"\n",
"line",
":=",
"0",
"\n",
"for",
"offset",
",",
"b",
":=",
"range",
"content",
"{",
"if",
"line",
">=",
"0... | // SetLinesForContent sets the line offsets for the given file content. | [
"SetLinesForContent",
"sets",
"the",
"line",
"offsets",
"for",
"the",
"given",
"file",
"content",
"."
] | 5784335da72394c8f53d9036c26fcc876718879b | https://github.com/rogpeppe/godef/blob/5784335da72394c8f53d9036c26fcc876718879b/go/token/position.go#L231-L248 | train |
rogpeppe/godef | go/token/position.go | Line | func (f *File) Line(p Pos) int {
// TODO(gri) this can be implemented much more efficiently
return f.Position(p).Line
} | go | func (f *File) Line(p Pos) int {
// TODO(gri) this can be implemented much more efficiently
return f.Position(p).Line
} | [
"func",
"(",
"f",
"*",
"File",
")",
"Line",
"(",
"p",
"Pos",
")",
"int",
"{",
"// TODO(gri) this can be implemented much more efficiently",
"return",
"f",
".",
"Position",
"(",
"p",
")",
".",
"Line",
"\n",
"}"
] | // Line returns the line number for the given file position p;
// p must be a Pos value in that file or NoPos.
// | [
"Line",
"returns",
"the",
"line",
"number",
"for",
"the",
"given",
"file",
"position",
"p",
";",
"p",
"must",
"be",
"a",
"Pos",
"value",
"in",
"that",
"file",
"or",
"NoPos",
"."
] | 5784335da72394c8f53d9036c26fcc876718879b | https://github.com/rogpeppe/godef/blob/5784335da72394c8f53d9036c26fcc876718879b/go/token/position.go#L275-L278 | train |
rogpeppe/godef | go/token/position.go | Position | func (f *File) Position(p Pos) (pos Position) {
if p != NoPos {
if int(p) < f.base || int(p) > f.base+f.size {
panic("illegal Pos value")
}
pos = f.position(p)
}
return
} | go | func (f *File) Position(p Pos) (pos Position) {
if p != NoPos {
if int(p) < f.base || int(p) > f.base+f.size {
panic("illegal Pos value")
}
pos = f.position(p)
}
return
} | [
"func",
"(",
"f",
"*",
"File",
")",
"Position",
"(",
"p",
"Pos",
")",
"(",
"pos",
"Position",
")",
"{",
"if",
"p",
"!=",
"NoPos",
"{",
"if",
"int",
"(",
"p",
")",
"<",
"f",
".",
"base",
"||",
"int",
"(",
"p",
")",
">",
"f",
".",
"base",
"... | // Position returns the Position value for the given file position p;
// p must be a Pos value in that file or NoPos.
// | [
"Position",
"returns",
"the",
"Position",
"value",
"for",
"the",
"given",
"file",
"position",
"p",
";",
"p",
"must",
"be",
"a",
"Pos",
"value",
"in",
"that",
"file",
"or",
"NoPos",
"."
] | 5784335da72394c8f53d9036c26fcc876718879b | https://github.com/rogpeppe/godef/blob/5784335da72394c8f53d9036c26fcc876718879b/go/token/position.go#L283-L291 | train |
rogpeppe/godef | go/token/position.go | NewFileSet | func NewFileSet() *FileSet {
s := new(FileSet)
s.base = 1 // 0 == NoPos
s.index = make(map[*File]int)
return s
} | go | func NewFileSet() *FileSet {
s := new(FileSet)
s.base = 1 // 0 == NoPos
s.index = make(map[*File]int)
return s
} | [
"func",
"NewFileSet",
"(",
")",
"*",
"FileSet",
"{",
"s",
":=",
"new",
"(",
"FileSet",
")",
"\n",
"s",
".",
"base",
"=",
"1",
"// 0 == NoPos",
"\n",
"s",
".",
"index",
"=",
"make",
"(",
"map",
"[",
"*",
"File",
"]",
"int",
")",
"\n",
"return",
... | // NewFileSet creates a new file set. | [
"NewFileSet",
"creates",
"a",
"new",
"file",
"set",
"."
] | 5784335da72394c8f53d9036c26fcc876718879b | https://github.com/rogpeppe/godef/blob/5784335da72394c8f53d9036c26fcc876718879b/go/token/position.go#L329-L334 | train |
rogpeppe/godef | go/token/position.go | Base | func (s *FileSet) Base() int {
s.mutex.RLock()
b := s.base
s.mutex.RUnlock()
return b
} | go | func (s *FileSet) Base() int {
s.mutex.RLock()
b := s.base
s.mutex.RUnlock()
return b
} | [
"func",
"(",
"s",
"*",
"FileSet",
")",
"Base",
"(",
")",
"int",
"{",
"s",
".",
"mutex",
".",
"RLock",
"(",
")",
"\n",
"b",
":=",
"s",
".",
"base",
"\n",
"s",
".",
"mutex",
".",
"RUnlock",
"(",
")",
"\n",
"return",
"b",
"\n\n",
"}"
] | // Base returns the minimum base offset that must be provided to
// AddFile when adding the next file.
// | [
"Base",
"returns",
"the",
"minimum",
"base",
"offset",
"that",
"must",
"be",
"provided",
"to",
"AddFile",
"when",
"adding",
"the",
"next",
"file",
"."
] | 5784335da72394c8f53d9036c26fcc876718879b | https://github.com/rogpeppe/godef/blob/5784335da72394c8f53d9036c26fcc876718879b/go/token/position.go#L339-L345 | train |
rogpeppe/godef | go/token/position.go | Iterate | func (s *FileSet) Iterate(f func(*File) bool) {
for i := 0; ; i++ {
var file *File
s.mutex.RLock()
if i < len(s.files) {
file = s.files[i]
}
s.mutex.RUnlock()
if file == nil || !f(file) {
break
}
}
} | go | func (s *FileSet) Iterate(f func(*File) bool) {
for i := 0; ; i++ {
var file *File
s.mutex.RLock()
if i < len(s.files) {
file = s.files[i]
}
s.mutex.RUnlock()
if file == nil || !f(file) {
break
}
}
} | [
"func",
"(",
"s",
"*",
"FileSet",
")",
"Iterate",
"(",
"f",
"func",
"(",
"*",
"File",
")",
"bool",
")",
"{",
"for",
"i",
":=",
"0",
";",
";",
"i",
"++",
"{",
"var",
"file",
"*",
"File",
"\n",
"s",
".",
"mutex",
".",
"RLock",
"(",
")",
"\n",... | // Files returns the files added to the file set. | [
"Files",
"returns",
"the",
"files",
"added",
"to",
"the",
"file",
"set",
"."
] | 5784335da72394c8f53d9036c26fcc876718879b | https://github.com/rogpeppe/godef/blob/5784335da72394c8f53d9036c26fcc876718879b/go/token/position.go#L382-L394 | train |
rogpeppe/godef | adapt.go | cleanFilename | func cleanFilename(path string) string {
const prefix = "$GOROOT"
if len(path) < len(prefix) || !strings.EqualFold(prefix, path[:len(prefix)]) {
return path
}
//TODO: we need a better way to get the GOROOT that uses the packages api
return runtime.GOROOT() + path[len(prefix):]
} | go | func cleanFilename(path string) string {
const prefix = "$GOROOT"
if len(path) < len(prefix) || !strings.EqualFold(prefix, path[:len(prefix)]) {
return path
}
//TODO: we need a better way to get the GOROOT that uses the packages api
return runtime.GOROOT() + path[len(prefix):]
} | [
"func",
"cleanFilename",
"(",
"path",
"string",
")",
"string",
"{",
"const",
"prefix",
"=",
"\"",
"\"",
"\n",
"if",
"len",
"(",
"path",
")",
"<",
"len",
"(",
"prefix",
")",
"||",
"!",
"strings",
".",
"EqualFold",
"(",
"prefix",
",",
"path",
"[",
":... | // cleanFilename normalizes any file names that come out of the fileset. | [
"cleanFilename",
"normalizes",
"any",
"file",
"names",
"that",
"come",
"out",
"of",
"the",
"fileset",
"."
] | 5784335da72394c8f53d9036c26fcc876718879b | https://github.com/rogpeppe/godef/blob/5784335da72394c8f53d9036c26fcc876718879b/adapt.go#L251-L258 | train |
rogpeppe/godef | go/ast/filter.go | fieldName | func fieldName(x Expr) *Ident {
switch t := x.(type) {
case *Ident:
return t
case *SelectorExpr:
if _, ok := t.X.(*Ident); ok {
return t.Sel
}
case *StarExpr:
return fieldName(t.X)
}
return nil
} | go | func fieldName(x Expr) *Ident {
switch t := x.(type) {
case *Ident:
return t
case *SelectorExpr:
if _, ok := t.X.(*Ident); ok {
return t.Sel
}
case *StarExpr:
return fieldName(t.X)
}
return nil
} | [
"func",
"fieldName",
"(",
"x",
"Expr",
")",
"*",
"Ident",
"{",
"switch",
"t",
":=",
"x",
".",
"(",
"type",
")",
"{",
"case",
"*",
"Ident",
":",
"return",
"t",
"\n",
"case",
"*",
"SelectorExpr",
":",
"if",
"_",
",",
"ok",
":=",
"t",
".",
"X",
... | // fieldName assumes that x is the type of an anonymous field and
// returns the corresponding field name. If x is not an acceptable
// anonymous field, the result is nil.
// | [
"fieldName",
"assumes",
"that",
"x",
"is",
"the",
"type",
"of",
"an",
"anonymous",
"field",
"and",
"returns",
"the",
"corresponding",
"field",
"name",
".",
"If",
"x",
"is",
"not",
"an",
"acceptable",
"anonymous",
"field",
"the",
"result",
"is",
"nil",
"."
... | 5784335da72394c8f53d9036c26fcc876718879b | https://github.com/rogpeppe/godef/blob/5784335da72394c8f53d9036c26fcc876718879b/go/ast/filter.go#L27-L39 | train |
rogpeppe/godef | go/ast/filter.go | PackageExports | func PackageExports(pkg *Package) bool {
hasExports := false
for _, f := range pkg.Files {
if FileExports(f) {
hasExports = true
}
}
return hasExports
} | go | func PackageExports(pkg *Package) bool {
hasExports := false
for _, f := range pkg.Files {
if FileExports(f) {
hasExports = true
}
}
return hasExports
} | [
"func",
"PackageExports",
"(",
"pkg",
"*",
"Package",
")",
"bool",
"{",
"hasExports",
":=",
"false",
"\n",
"for",
"_",
",",
"f",
":=",
"range",
"pkg",
".",
"Files",
"{",
"if",
"FileExports",
"(",
"f",
")",
"{",
"hasExports",
"=",
"true",
"\n",
"}",
... | // PackageExports trims the AST for a Go package in place such that only
// exported nodes remain. The pkg.Files list is not changed, so that file
// names and top-level package comments don't get lost.
//
// PackageExports returns true if there is an exported declaration; it
// returns false otherwise.
// | [
"PackageExports",
"trims",
"the",
"AST",
"for",
"a",
"Go",
"package",
"in",
"place",
"such",
"that",
"only",
"exported",
"nodes",
"remain",
".",
"The",
"pkg",
".",
"Files",
"list",
"is",
"not",
"changed",
"so",
"that",
"file",
"names",
"and",
"top",
"-",... | 5784335da72394c8f53d9036c26fcc876718879b | https://github.com/rogpeppe/godef/blob/5784335da72394c8f53d9036c26fcc876718879b/go/ast/filter.go#L180-L188 | train |
rogpeppe/godef | go/ast/filter.go | MergePackageFiles | func MergePackageFiles(pkg *Package, mode MergeMode) *File {
// Count the number of package docs, comments and declarations across
// all package files.
ndocs := 0
ncomments := 0
ndecls := 0
for _, f := range pkg.Files {
if f.Doc != nil {
ndocs += len(f.Doc.List) + 1 // +1 for separator
}
ncomments += len(f.Comments)
ndecls += len(f.Decls)
}
// Collect package comments from all package files into a single
// CommentGroup - the collected package documentation. The order
// is unspecified. In general there should be only one file with
// a package comment; but it's better to collect extra comments
// than drop them on the floor.
var doc *CommentGroup
var pos token.Pos
if ndocs > 0 {
list := make([]*Comment, ndocs-1) // -1: no separator before first group
i := 0
for _, f := range pkg.Files {
if f.Doc != nil {
if i > 0 {
// not the first group - add separator
list[i] = separator
i++
}
for _, c := range f.Doc.List {
list[i] = c
i++
}
if f.Package > pos {
// Keep the maximum package clause position as
// position for the package clause of the merged
// files.
pos = f.Package
}
}
}
doc = &CommentGroup{list}
}
// Collect declarations from all package files.
var decls []Decl
if ndecls > 0 {
decls = make([]Decl, ndecls)
funcs := make(map[string]int) // map of global function name -> decls index
i := 0 // current index
n := 0 // number of filtered entries
for _, f := range pkg.Files {
for _, d := range f.Decls {
if mode&FilterFuncDuplicates != 0 {
// A language entity may be declared multiple
// times in different package files; only at
// build time declarations must be unique.
// For now, exclude multiple declarations of
// functions - keep the one with documentation.
//
// TODO(gri): Expand this filtering to other
// entities (const, type, vars) if
// multiple declarations are common.
if f, isFun := d.(*FuncDecl); isFun {
name := f.Name.Name
if j, exists := funcs[name]; exists {
// function declared already
if decls[j] != nil && decls[j].(*FuncDecl).Doc == nil {
// existing declaration has no documentation;
// ignore the existing declaration
decls[j] = nil
} else {
// ignore the new declaration
d = nil
}
n++ // filtered an entry
} else {
funcs[name] = i
}
}
}
decls[i] = d
i++
}
}
// Eliminate nil entries from the decls list if entries were
// filtered. We do this using a 2nd pass in order to not disturb
// the original declaration order in the source (otherwise, this
// would also invalidate the monotonically increasing position
// info within a single file).
if n > 0 {
i = 0
for _, d := range decls {
if d != nil {
decls[i] = d
i++
}
}
decls = decls[0:i]
}
}
// Collect comments from all package files.
var comments []*CommentGroup
if mode&FilterUnassociatedComments == 0 {
comments = make([]*CommentGroup, ncomments)
i := 0
for _, f := range pkg.Files {
i += copy(comments[i:], f.Comments)
}
}
// TODO(gri) need to compute pkgScope and unresolved identifiers!
// TODO(gri) need to compute imports!
return &File{doc, pos, NewIdent(pkg.Name), decls, nil, nil, nil, comments}
} | go | func MergePackageFiles(pkg *Package, mode MergeMode) *File {
// Count the number of package docs, comments and declarations across
// all package files.
ndocs := 0
ncomments := 0
ndecls := 0
for _, f := range pkg.Files {
if f.Doc != nil {
ndocs += len(f.Doc.List) + 1 // +1 for separator
}
ncomments += len(f.Comments)
ndecls += len(f.Decls)
}
// Collect package comments from all package files into a single
// CommentGroup - the collected package documentation. The order
// is unspecified. In general there should be only one file with
// a package comment; but it's better to collect extra comments
// than drop them on the floor.
var doc *CommentGroup
var pos token.Pos
if ndocs > 0 {
list := make([]*Comment, ndocs-1) // -1: no separator before first group
i := 0
for _, f := range pkg.Files {
if f.Doc != nil {
if i > 0 {
// not the first group - add separator
list[i] = separator
i++
}
for _, c := range f.Doc.List {
list[i] = c
i++
}
if f.Package > pos {
// Keep the maximum package clause position as
// position for the package clause of the merged
// files.
pos = f.Package
}
}
}
doc = &CommentGroup{list}
}
// Collect declarations from all package files.
var decls []Decl
if ndecls > 0 {
decls = make([]Decl, ndecls)
funcs := make(map[string]int) // map of global function name -> decls index
i := 0 // current index
n := 0 // number of filtered entries
for _, f := range pkg.Files {
for _, d := range f.Decls {
if mode&FilterFuncDuplicates != 0 {
// A language entity may be declared multiple
// times in different package files; only at
// build time declarations must be unique.
// For now, exclude multiple declarations of
// functions - keep the one with documentation.
//
// TODO(gri): Expand this filtering to other
// entities (const, type, vars) if
// multiple declarations are common.
if f, isFun := d.(*FuncDecl); isFun {
name := f.Name.Name
if j, exists := funcs[name]; exists {
// function declared already
if decls[j] != nil && decls[j].(*FuncDecl).Doc == nil {
// existing declaration has no documentation;
// ignore the existing declaration
decls[j] = nil
} else {
// ignore the new declaration
d = nil
}
n++ // filtered an entry
} else {
funcs[name] = i
}
}
}
decls[i] = d
i++
}
}
// Eliminate nil entries from the decls list if entries were
// filtered. We do this using a 2nd pass in order to not disturb
// the original declaration order in the source (otherwise, this
// would also invalidate the monotonically increasing position
// info within a single file).
if n > 0 {
i = 0
for _, d := range decls {
if d != nil {
decls[i] = d
i++
}
}
decls = decls[0:i]
}
}
// Collect comments from all package files.
var comments []*CommentGroup
if mode&FilterUnassociatedComments == 0 {
comments = make([]*CommentGroup, ncomments)
i := 0
for _, f := range pkg.Files {
i += copy(comments[i:], f.Comments)
}
}
// TODO(gri) need to compute pkgScope and unresolved identifiers!
// TODO(gri) need to compute imports!
return &File{doc, pos, NewIdent(pkg.Name), decls, nil, nil, nil, comments}
} | [
"func",
"MergePackageFiles",
"(",
"pkg",
"*",
"Package",
",",
"mode",
"MergeMode",
")",
"*",
"File",
"{",
"// Count the number of package docs, comments and declarations across",
"// all package files.",
"ndocs",
":=",
"0",
"\n",
"ncomments",
":=",
"0",
"\n",
"ndecls",
... | // MergePackageFiles creates a file AST by merging the ASTs of the
// files belonging to a package. The mode flags control merging behavior.
// | [
"MergePackageFiles",
"creates",
"a",
"file",
"AST",
"by",
"merging",
"the",
"ASTs",
"of",
"the",
"files",
"belonging",
"to",
"a",
"package",
".",
"The",
"mode",
"flags",
"control",
"merging",
"behavior",
"."
] | 5784335da72394c8f53d9036c26fcc876718879b | https://github.com/rogpeppe/godef/blob/5784335da72394c8f53d9036c26fcc876718879b/go/ast/filter.go#L357-L475 | train |
rogpeppe/godef | acme.go | readBody | func readBody(win *acme.Win) ([]byte, error) {
var body []byte
buf := make([]byte, 8000)
for {
n, err := win.Read("body", buf)
if err == io.EOF {
break
}
if err != nil {
return nil, err
}
body = append(body, buf[0:n]...)
}
return body, nil
} | go | func readBody(win *acme.Win) ([]byte, error) {
var body []byte
buf := make([]byte, 8000)
for {
n, err := win.Read("body", buf)
if err == io.EOF {
break
}
if err != nil {
return nil, err
}
body = append(body, buf[0:n]...)
}
return body, nil
} | [
"func",
"readBody",
"(",
"win",
"*",
"acme",
".",
"Win",
")",
"(",
"[",
"]",
"byte",
",",
"error",
")",
"{",
"var",
"body",
"[",
"]",
"byte",
"\n",
"buf",
":=",
"make",
"(",
"[",
"]",
"byte",
",",
"8000",
")",
"\n",
"for",
"{",
"n",
",",
"e... | // We would use win.ReadAll except for a bug in acme
// where it crashes when reading trying to read more
// than the negotiated 9P message size. | [
"We",
"would",
"use",
"win",
".",
"ReadAll",
"except",
"for",
"a",
"bug",
"in",
"acme",
"where",
"it",
"crashes",
"when",
"reading",
"trying",
"to",
"read",
"more",
"than",
"the",
"negotiated",
"9P",
"message",
"size",
"."
] | 5784335da72394c8f53d9036c26fcc876718879b | https://github.com/rogpeppe/godef/blob/5784335da72394c8f53d9036c26fcc876718879b/acme.go#L65-L79 | train |
rogpeppe/godef | packages.go | parseFile | func parseFile(filename string, searchpos int) (func(*token.FileSet, string, []byte) (*ast.File, error), chan match) {
result := make(chan match, 1)
isInputFile := newFileCompare(filename)
return func(fset *token.FileSet, fname string, filedata []byte) (*ast.File, error) {
isInput := isInputFile(fname)
file, err := parser.ParseFile(fset, fname, filedata, 0)
if file == nil {
return nil, err
}
pos := token.Pos(-1)
if isInput {
tfile := fset.File(file.Pos())
if tfile == nil {
return file, fmt.Errorf("cursor %d is beyond end of file %s (%d)", searchpos, fname, file.End()-file.Pos())
}
if searchpos > tfile.Size() {
return file, fmt.Errorf("cursor %d is beyond end of file %s (%d)", searchpos, fname, tfile.Size())
}
pos = tfile.Pos(searchpos)
m, err := findMatch(file, pos)
if err != nil {
return nil, err
}
result <- m
}
// Trim unneeded parts from the AST to make the type checking faster.
trimAST(file, pos)
return file, err
}, result
} | go | func parseFile(filename string, searchpos int) (func(*token.FileSet, string, []byte) (*ast.File, error), chan match) {
result := make(chan match, 1)
isInputFile := newFileCompare(filename)
return func(fset *token.FileSet, fname string, filedata []byte) (*ast.File, error) {
isInput := isInputFile(fname)
file, err := parser.ParseFile(fset, fname, filedata, 0)
if file == nil {
return nil, err
}
pos := token.Pos(-1)
if isInput {
tfile := fset.File(file.Pos())
if tfile == nil {
return file, fmt.Errorf("cursor %d is beyond end of file %s (%d)", searchpos, fname, file.End()-file.Pos())
}
if searchpos > tfile.Size() {
return file, fmt.Errorf("cursor %d is beyond end of file %s (%d)", searchpos, fname, tfile.Size())
}
pos = tfile.Pos(searchpos)
m, err := findMatch(file, pos)
if err != nil {
return nil, err
}
result <- m
}
// Trim unneeded parts from the AST to make the type checking faster.
trimAST(file, pos)
return file, err
}, result
} | [
"func",
"parseFile",
"(",
"filename",
"string",
",",
"searchpos",
"int",
")",
"(",
"func",
"(",
"*",
"token",
".",
"FileSet",
",",
"string",
",",
"[",
"]",
"byte",
")",
"(",
"*",
"ast",
".",
"File",
",",
"error",
")",
",",
"chan",
"match",
")",
"... | // parseFile returns a function that can be used as a Parser in packages.Config
// and a channel which will be sent a value when a token is found at the given
// search position.
// It replaces the contents of a file that matches filename with the src.
// It also drops all function bodies that do not contain the searchpos. | [
"parseFile",
"returns",
"a",
"function",
"that",
"can",
"be",
"used",
"as",
"a",
"Parser",
"in",
"packages",
".",
"Config",
"and",
"a",
"channel",
"which",
"will",
"be",
"sent",
"a",
"value",
"when",
"a",
"token",
"is",
"found",
"at",
"the",
"given",
"... | 5784335da72394c8f53d9036c26fcc876718879b | https://github.com/rogpeppe/godef/blob/5784335da72394c8f53d9036c26fcc876718879b/packages.go#L78-L107 | train |
rogpeppe/godef | packages.go | newFileCompare | func newFileCompare(filename string) func(string) bool {
fstat, fstatErr := os.Stat(filename)
return func(compare string) bool {
if filename == compare {
return true
}
if fstatErr != nil {
return false
}
if s, err := os.Stat(compare); err == nil {
return os.SameFile(fstat, s)
}
return false
}
} | go | func newFileCompare(filename string) func(string) bool {
fstat, fstatErr := os.Stat(filename)
return func(compare string) bool {
if filename == compare {
return true
}
if fstatErr != nil {
return false
}
if s, err := os.Stat(compare); err == nil {
return os.SameFile(fstat, s)
}
return false
}
} | [
"func",
"newFileCompare",
"(",
"filename",
"string",
")",
"func",
"(",
"string",
")",
"bool",
"{",
"fstat",
",",
"fstatErr",
":=",
"os",
".",
"Stat",
"(",
"filename",
")",
"\n",
"return",
"func",
"(",
"compare",
"string",
")",
"bool",
"{",
"if",
"filen... | // newFileCompare returns a function that reports whether its argument
// refers to the same file as the given filename. | [
"newFileCompare",
"returns",
"a",
"function",
"that",
"reports",
"whether",
"its",
"argument",
"refers",
"to",
"the",
"same",
"file",
"as",
"the",
"given",
"filename",
"."
] | 5784335da72394c8f53d9036c26fcc876718879b | https://github.com/rogpeppe/godef/blob/5784335da72394c8f53d9036c26fcc876718879b/packages.go#L111-L125 | train |
rogpeppe/godef | packages.go | checkMatch | func checkMatch(f *ast.File, pos token.Pos) (match, error) {
path, _ := astutil.PathEnclosingInterval(f, pos, pos)
result := match{}
if path == nil {
return result, fmt.Errorf("can't find node enclosing position")
}
switch node := path[0].(type) {
case *ast.Ident:
result.ident = node
case *ast.SelectorExpr:
result.ident = node.Sel
case *ast.BasicLit:
// if there was a literal import path, we build a special ident of
// the same value, which we eventually use to print the path
if len(path) > 1 {
if spec, ok := path[1].(*ast.ImportSpec); ok {
if p, err := strconv.Unquote(spec.Path.Value); err == nil {
result.ident = ast.NewIdent(p)
}
}
}
}
if result.ident != nil {
for _, n := range path[1:] {
if field, ok := n.(*ast.Field); ok {
result.wasEmbeddedField = len(field.Names) == 0
}
}
}
return result, nil
} | go | func checkMatch(f *ast.File, pos token.Pos) (match, error) {
path, _ := astutil.PathEnclosingInterval(f, pos, pos)
result := match{}
if path == nil {
return result, fmt.Errorf("can't find node enclosing position")
}
switch node := path[0].(type) {
case *ast.Ident:
result.ident = node
case *ast.SelectorExpr:
result.ident = node.Sel
case *ast.BasicLit:
// if there was a literal import path, we build a special ident of
// the same value, which we eventually use to print the path
if len(path) > 1 {
if spec, ok := path[1].(*ast.ImportSpec); ok {
if p, err := strconv.Unquote(spec.Path.Value); err == nil {
result.ident = ast.NewIdent(p)
}
}
}
}
if result.ident != nil {
for _, n := range path[1:] {
if field, ok := n.(*ast.Field); ok {
result.wasEmbeddedField = len(field.Names) == 0
}
}
}
return result, nil
} | [
"func",
"checkMatch",
"(",
"f",
"*",
"ast",
".",
"File",
",",
"pos",
"token",
".",
"Pos",
")",
"(",
"match",
",",
"error",
")",
"{",
"path",
",",
"_",
":=",
"astutil",
".",
"PathEnclosingInterval",
"(",
"f",
",",
"pos",
",",
"pos",
")",
"\n",
"re... | // checkMatch checks a single position for a potential identifier. | [
"checkMatch",
"checks",
"a",
"single",
"position",
"for",
"a",
"potential",
"identifier",
"."
] | 5784335da72394c8f53d9036c26fcc876718879b | https://github.com/rogpeppe/godef/blob/5784335da72394c8f53d9036c26fcc876718879b/packages.go#L142-L172 | train |
mvdan/xurls | xurls.go | Strict | func Strict() *regexp.Regexp {
re := regexp.MustCompile(strictExp())
re.Longest()
return re
} | go | func Strict() *regexp.Regexp {
re := regexp.MustCompile(strictExp())
re.Longest()
return re
} | [
"func",
"Strict",
"(",
")",
"*",
"regexp",
".",
"Regexp",
"{",
"re",
":=",
"regexp",
".",
"MustCompile",
"(",
"strictExp",
"(",
")",
")",
"\n",
"re",
".",
"Longest",
"(",
")",
"\n",
"return",
"re",
"\n",
"}"
] | // Strict produces a regexp that matches any URL with a scheme in either the
// Schemes or SchemesNoAuthority lists. | [
"Strict",
"produces",
"a",
"regexp",
"that",
"matches",
"any",
"URL",
"with",
"a",
"scheme",
"in",
"either",
"the",
"Schemes",
"or",
"SchemesNoAuthority",
"lists",
"."
] | 20723a7d9031ce424dd37d4b43ee581b1b8680ba | https://github.com/mvdan/xurls/blob/20723a7d9031ce424dd37d4b43ee581b1b8680ba/xurls.go#L83-L87 | train |
mvdan/xurls | xurls.go | Relaxed | func Relaxed() *regexp.Regexp {
re := regexp.MustCompile(relaxedExp())
re.Longest()
return re
} | go | func Relaxed() *regexp.Regexp {
re := regexp.MustCompile(relaxedExp())
re.Longest()
return re
} | [
"func",
"Relaxed",
"(",
")",
"*",
"regexp",
".",
"Regexp",
"{",
"re",
":=",
"regexp",
".",
"MustCompile",
"(",
"relaxedExp",
"(",
")",
")",
"\n",
"re",
".",
"Longest",
"(",
")",
"\n",
"return",
"re",
"\n",
"}"
] | // Relaxed produces a regexp that matches any URL matched by Strict, plus any
// URL with no scheme. | [
"Relaxed",
"produces",
"a",
"regexp",
"that",
"matches",
"any",
"URL",
"matched",
"by",
"Strict",
"plus",
"any",
"URL",
"with",
"no",
"scheme",
"."
] | 20723a7d9031ce424dd37d4b43ee581b1b8680ba | https://github.com/mvdan/xurls/blob/20723a7d9031ce424dd37d4b43ee581b1b8680ba/xurls.go#L91-L95 | train |
mvdan/xurls | xurls.go | StrictMatchingScheme | func StrictMatchingScheme(exp string) (*regexp.Regexp, error) {
strictMatching := `(?i)(` + exp + `)(?-i)` + pathCont
re, err := regexp.Compile(strictMatching)
if err != nil {
return nil, err
}
re.Longest()
return re, nil
} | go | func StrictMatchingScheme(exp string) (*regexp.Regexp, error) {
strictMatching := `(?i)(` + exp + `)(?-i)` + pathCont
re, err := regexp.Compile(strictMatching)
if err != nil {
return nil, err
}
re.Longest()
return re, nil
} | [
"func",
"StrictMatchingScheme",
"(",
"exp",
"string",
")",
"(",
"*",
"regexp",
".",
"Regexp",
",",
"error",
")",
"{",
"strictMatching",
":=",
"`(?i)(`",
"+",
"exp",
"+",
"`)(?-i)`",
"+",
"pathCont",
"\n",
"re",
",",
"err",
":=",
"regexp",
".",
"Compile",... | // StrictMatchingScheme produces a regexp similar to Strict, but requiring that
// the scheme match the given regular expression. See AnyScheme too. | [
"StrictMatchingScheme",
"produces",
"a",
"regexp",
"similar",
"to",
"Strict",
"but",
"requiring",
"that",
"the",
"scheme",
"match",
"the",
"given",
"regular",
"expression",
".",
"See",
"AnyScheme",
"too",
"."
] | 20723a7d9031ce424dd37d4b43ee581b1b8680ba | https://github.com/mvdan/xurls/blob/20723a7d9031ce424dd37d4b43ee581b1b8680ba/xurls.go#L99-L107 | train |
kubernetes-incubator/custom-metrics-apiserver | pkg/provider/helpers/helpers.go | ResourceFor | func ResourceFor(mapper apimeta.RESTMapper, info provider.CustomMetricInfo) (schema.GroupVersionResource, error) {
fullResources, err := mapper.ResourcesFor(info.GroupResource.WithVersion(""))
if err == nil && len(fullResources) == 0 {
err = fmt.Errorf("no fully versioned resources known for group-resource %v", info.GroupResource)
}
if err != nil {
return schema.GroupVersionResource{}, fmt.Errorf("unable to find preferred version to list matching resource names: %v", err)
}
return fullResources[0], nil
} | go | func ResourceFor(mapper apimeta.RESTMapper, info provider.CustomMetricInfo) (schema.GroupVersionResource, error) {
fullResources, err := mapper.ResourcesFor(info.GroupResource.WithVersion(""))
if err == nil && len(fullResources) == 0 {
err = fmt.Errorf("no fully versioned resources known for group-resource %v", info.GroupResource)
}
if err != nil {
return schema.GroupVersionResource{}, fmt.Errorf("unable to find preferred version to list matching resource names: %v", err)
}
return fullResources[0], nil
} | [
"func",
"ResourceFor",
"(",
"mapper",
"apimeta",
".",
"RESTMapper",
",",
"info",
"provider",
".",
"CustomMetricInfo",
")",
"(",
"schema",
".",
"GroupVersionResource",
",",
"error",
")",
"{",
"fullResources",
",",
"err",
":=",
"mapper",
".",
"ResourcesFor",
"("... | // ResourceFor attempts to resolve a single qualified resource for the given metric.
// You can use this to resolve a particular piece of CustomMetricInfo to the underlying
// resource that it describes, so that you can list matching objects in the cluster. | [
"ResourceFor",
"attempts",
"to",
"resolve",
"a",
"single",
"qualified",
"resource",
"for",
"the",
"given",
"metric",
".",
"You",
"can",
"use",
"this",
"to",
"resolve",
"a",
"particular",
"piece",
"of",
"CustomMetricInfo",
"to",
"the",
"underlying",
"resource",
... | e303a5e75372662801308008ccdff9b57717e75d | https://github.com/kubernetes-incubator/custom-metrics-apiserver/blob/e303a5e75372662801308008ccdff9b57717e75d/pkg/provider/helpers/helpers.go#L38-L48 | train |
kubernetes-incubator/custom-metrics-apiserver | pkg/provider/helpers/helpers.go | ReferenceFor | func ReferenceFor(mapper apimeta.RESTMapper, name types.NamespacedName, info provider.CustomMetricInfo) (custom_metrics.ObjectReference, error) {
kind, err := mapper.KindFor(info.GroupResource.WithVersion(""))
if err != nil {
return custom_metrics.ObjectReference{}, err
}
// NB: return straight value, not a reference, so that the object can easily
// be copied for use multiple times with a different name.
return custom_metrics.ObjectReference{
APIVersion: kind.Group + "/" + kind.Version,
Kind: kind.Kind,
Name: name.Name,
Namespace: name.Namespace,
}, nil
} | go | func ReferenceFor(mapper apimeta.RESTMapper, name types.NamespacedName, info provider.CustomMetricInfo) (custom_metrics.ObjectReference, error) {
kind, err := mapper.KindFor(info.GroupResource.WithVersion(""))
if err != nil {
return custom_metrics.ObjectReference{}, err
}
// NB: return straight value, not a reference, so that the object can easily
// be copied for use multiple times with a different name.
return custom_metrics.ObjectReference{
APIVersion: kind.Group + "/" + kind.Version,
Kind: kind.Kind,
Name: name.Name,
Namespace: name.Namespace,
}, nil
} | [
"func",
"ReferenceFor",
"(",
"mapper",
"apimeta",
".",
"RESTMapper",
",",
"name",
"types",
".",
"NamespacedName",
",",
"info",
"provider",
".",
"CustomMetricInfo",
")",
"(",
"custom_metrics",
".",
"ObjectReference",
",",
"error",
")",
"{",
"kind",
",",
"err",
... | // ReferenceFor returns a new ObjectReference for the given group-resource and name.
// The group-resource is converted into a group-version-kind using the given RESTMapper.
// You can use this to easily construct an object reference for use in the DescribedObject
// field of CustomMetricInfo. | [
"ReferenceFor",
"returns",
"a",
"new",
"ObjectReference",
"for",
"the",
"given",
"group",
"-",
"resource",
"and",
"name",
".",
"The",
"group",
"-",
"resource",
"is",
"converted",
"into",
"a",
"group",
"-",
"version",
"-",
"kind",
"using",
"the",
"given",
"... | e303a5e75372662801308008ccdff9b57717e75d | https://github.com/kubernetes-incubator/custom-metrics-apiserver/blob/e303a5e75372662801308008ccdff9b57717e75d/pkg/provider/helpers/helpers.go#L54-L68 | train |
kubernetes-incubator/custom-metrics-apiserver | pkg/provider/helpers/helpers.go | ListObjectNames | func ListObjectNames(mapper apimeta.RESTMapper, client dynamic.Interface, namespace string, selector labels.Selector, info provider.CustomMetricInfo) ([]string, error) {
res, err := ResourceFor(mapper, info)
if err != nil {
return nil, err
}
var resClient dynamic.ResourceInterface
if info.Namespaced {
resClient = client.Resource(res).Namespace(namespace)
} else {
resClient = client.Resource(res)
}
matchingObjectsRaw, err := resClient.List(metav1.ListOptions{LabelSelector: selector.String()})
if err != nil {
return nil, err
}
if !apimeta.IsListType(matchingObjectsRaw) {
return nil, fmt.Errorf("result of label selector list operation was not a list")
}
var names []string
err = apimeta.EachListItem(matchingObjectsRaw, func(item runtime.Object) error {
objName := item.(*unstructured.Unstructured).GetName()
names = append(names, objName)
return nil
})
if err != nil {
return nil, err
}
return names, nil
} | go | func ListObjectNames(mapper apimeta.RESTMapper, client dynamic.Interface, namespace string, selector labels.Selector, info provider.CustomMetricInfo) ([]string, error) {
res, err := ResourceFor(mapper, info)
if err != nil {
return nil, err
}
var resClient dynamic.ResourceInterface
if info.Namespaced {
resClient = client.Resource(res).Namespace(namespace)
} else {
resClient = client.Resource(res)
}
matchingObjectsRaw, err := resClient.List(metav1.ListOptions{LabelSelector: selector.String()})
if err != nil {
return nil, err
}
if !apimeta.IsListType(matchingObjectsRaw) {
return nil, fmt.Errorf("result of label selector list operation was not a list")
}
var names []string
err = apimeta.EachListItem(matchingObjectsRaw, func(item runtime.Object) error {
objName := item.(*unstructured.Unstructured).GetName()
names = append(names, objName)
return nil
})
if err != nil {
return nil, err
}
return names, nil
} | [
"func",
"ListObjectNames",
"(",
"mapper",
"apimeta",
".",
"RESTMapper",
",",
"client",
"dynamic",
".",
"Interface",
",",
"namespace",
"string",
",",
"selector",
"labels",
".",
"Selector",
",",
"info",
"provider",
".",
"CustomMetricInfo",
")",
"(",
"[",
"]",
... | // ListObjectNames uses the given dynamic client to list the names of all objects
// of the given resource matching the given selector. Namespace may be empty
// if the metric is for a root-scoped resource. | [
"ListObjectNames",
"uses",
"the",
"given",
"dynamic",
"client",
"to",
"list",
"the",
"names",
"of",
"all",
"objects",
"of",
"the",
"given",
"resource",
"matching",
"the",
"given",
"selector",
".",
"Namespace",
"may",
"be",
"empty",
"if",
"the",
"metric",
"is... | e303a5e75372662801308008ccdff9b57717e75d | https://github.com/kubernetes-incubator/custom-metrics-apiserver/blob/e303a5e75372662801308008ccdff9b57717e75d/pkg/provider/helpers/helpers.go#L73-L106 | train |
kubernetes-incubator/custom-metrics-apiserver | pkg/provider/errors.go | NewMetricNotFoundError | func NewMetricNotFoundError(resource schema.GroupResource, metricName string) *apierr.StatusError {
return &apierr.StatusError{metav1.Status{
Status: metav1.StatusFailure,
Code: int32(http.StatusNotFound),
Reason: metav1.StatusReasonNotFound,
Message: fmt.Sprintf("the server could not find the metric %s for %s", metricName, resource.String()),
}}
} | go | func NewMetricNotFoundError(resource schema.GroupResource, metricName string) *apierr.StatusError {
return &apierr.StatusError{metav1.Status{
Status: metav1.StatusFailure,
Code: int32(http.StatusNotFound),
Reason: metav1.StatusReasonNotFound,
Message: fmt.Sprintf("the server could not find the metric %s for %s", metricName, resource.String()),
}}
} | [
"func",
"NewMetricNotFoundError",
"(",
"resource",
"schema",
".",
"GroupResource",
",",
"metricName",
"string",
")",
"*",
"apierr",
".",
"StatusError",
"{",
"return",
"&",
"apierr",
".",
"StatusError",
"{",
"metav1",
".",
"Status",
"{",
"Status",
":",
"metav1"... | // NewMetricNotFoundError returns a StatusError indicating the given metric could not be found.
// It is similar to NewNotFound, but more specialized | [
"NewMetricNotFoundError",
"returns",
"a",
"StatusError",
"indicating",
"the",
"given",
"metric",
"could",
"not",
"be",
"found",
".",
"It",
"is",
"similar",
"to",
"NewNotFound",
"but",
"more",
"specialized"
] | e303a5e75372662801308008ccdff9b57717e75d | https://github.com/kubernetes-incubator/custom-metrics-apiserver/blob/e303a5e75372662801308008ccdff9b57717e75d/pkg/provider/errors.go#L31-L38 | train |
kubernetes-incubator/custom-metrics-apiserver | pkg/cmd/builder.go | InstallFlags | func (b *AdapterBase) InstallFlags() {
b.initFlagSet()
b.flagOnce.Do(func() {
if b.CustomMetricsAdapterServerOptions == nil {
b.CustomMetricsAdapterServerOptions = server.NewCustomMetricsAdapterServerOptions()
}
b.SecureServing.AddFlags(b.FlagSet)
b.Authentication.AddFlags(b.FlagSet)
b.Authorization.AddFlags(b.FlagSet)
b.Features.AddFlags(b.FlagSet)
b.FlagSet.StringVar(&b.RemoteKubeConfigFile, "lister-kubeconfig", b.RemoteKubeConfigFile,
"kubeconfig file pointing at the 'core' kubernetes server with enough rights to list "+
"any described objects")
b.FlagSet.DurationVar(&b.DiscoveryInterval, "discovery-interval", b.DiscoveryInterval,
"interval at which to refresh API discovery information")
})
} | go | func (b *AdapterBase) InstallFlags() {
b.initFlagSet()
b.flagOnce.Do(func() {
if b.CustomMetricsAdapterServerOptions == nil {
b.CustomMetricsAdapterServerOptions = server.NewCustomMetricsAdapterServerOptions()
}
b.SecureServing.AddFlags(b.FlagSet)
b.Authentication.AddFlags(b.FlagSet)
b.Authorization.AddFlags(b.FlagSet)
b.Features.AddFlags(b.FlagSet)
b.FlagSet.StringVar(&b.RemoteKubeConfigFile, "lister-kubeconfig", b.RemoteKubeConfigFile,
"kubeconfig file pointing at the 'core' kubernetes server with enough rights to list "+
"any described objects")
b.FlagSet.DurationVar(&b.DiscoveryInterval, "discovery-interval", b.DiscoveryInterval,
"interval at which to refresh API discovery information")
})
} | [
"func",
"(",
"b",
"*",
"AdapterBase",
")",
"InstallFlags",
"(",
")",
"{",
"b",
".",
"initFlagSet",
"(",
")",
"\n",
"b",
".",
"flagOnce",
".",
"Do",
"(",
"func",
"(",
")",
"{",
"if",
"b",
".",
"CustomMetricsAdapterServerOptions",
"==",
"nil",
"{",
"b"... | // InstallFlags installs the minimum required set of flags into the flagset. | [
"InstallFlags",
"installs",
"the",
"minimum",
"required",
"set",
"of",
"flags",
"into",
"the",
"flagset",
"."
] | e303a5e75372662801308008ccdff9b57717e75d | https://github.com/kubernetes-incubator/custom-metrics-apiserver/blob/e303a5e75372662801308008ccdff9b57717e75d/pkg/cmd/builder.go#L86-L104 | train |
kubernetes-incubator/custom-metrics-apiserver | pkg/cmd/builder.go | initFlagSet | func (b *AdapterBase) initFlagSet() {
if b.FlagSet == nil {
// default to the normal commandline flags
b.FlagSet = pflag.CommandLine
}
} | go | func (b *AdapterBase) initFlagSet() {
if b.FlagSet == nil {
// default to the normal commandline flags
b.FlagSet = pflag.CommandLine
}
} | [
"func",
"(",
"b",
"*",
"AdapterBase",
")",
"initFlagSet",
"(",
")",
"{",
"if",
"b",
".",
"FlagSet",
"==",
"nil",
"{",
"// default to the normal commandline flags",
"b",
".",
"FlagSet",
"=",
"pflag",
".",
"CommandLine",
"\n",
"}",
"\n",
"}"
] | // initFlagSet populates the flagset to the CommandLine flags if it's not already set. | [
"initFlagSet",
"populates",
"the",
"flagset",
"to",
"the",
"CommandLine",
"flags",
"if",
"it",
"s",
"not",
"already",
"set",
"."
] | e303a5e75372662801308008ccdff9b57717e75d | https://github.com/kubernetes-incubator/custom-metrics-apiserver/blob/e303a5e75372662801308008ccdff9b57717e75d/pkg/cmd/builder.go#L107-L112 | train |
kubernetes-incubator/custom-metrics-apiserver | pkg/cmd/builder.go | Flags | func (b *AdapterBase) Flags() *pflag.FlagSet {
b.initFlagSet()
b.InstallFlags()
return b.FlagSet
} | go | func (b *AdapterBase) Flags() *pflag.FlagSet {
b.initFlagSet()
b.InstallFlags()
return b.FlagSet
} | [
"func",
"(",
"b",
"*",
"AdapterBase",
")",
"Flags",
"(",
")",
"*",
"pflag",
".",
"FlagSet",
"{",
"b",
".",
"initFlagSet",
"(",
")",
"\n",
"b",
".",
"InstallFlags",
"(",
")",
"\n\n",
"return",
"b",
".",
"FlagSet",
"\n",
"}"
] | // Flags returns the flagset used by this adapter.
// It will initialize the flagset with the minimum required set
// of flags as well. | [
"Flags",
"returns",
"the",
"flagset",
"used",
"by",
"this",
"adapter",
".",
"It",
"will",
"initialize",
"the",
"flagset",
"with",
"the",
"minimum",
"required",
"set",
"of",
"flags",
"as",
"well",
"."
] | e303a5e75372662801308008ccdff9b57717e75d | https://github.com/kubernetes-incubator/custom-metrics-apiserver/blob/e303a5e75372662801308008ccdff9b57717e75d/pkg/cmd/builder.go#L117-L122 | train |
kubernetes-incubator/custom-metrics-apiserver | pkg/cmd/builder.go | ClientConfig | func (b *AdapterBase) ClientConfig() (*rest.Config, error) {
if b.clientConfig == nil {
var clientConfig *rest.Config
var err error
if len(b.RemoteKubeConfigFile) > 0 {
loadingRules := &clientcmd.ClientConfigLoadingRules{ExplicitPath: b.RemoteKubeConfigFile}
loader := clientcmd.NewNonInteractiveDeferredLoadingClientConfig(loadingRules, &clientcmd.ConfigOverrides{})
clientConfig, err = loader.ClientConfig()
} else {
clientConfig, err = rest.InClusterConfig()
}
if err != nil {
return nil, fmt.Errorf("unable to construct lister client config to initialize provider: %v", err)
}
b.clientConfig = clientConfig
}
return b.clientConfig, nil
} | go | func (b *AdapterBase) ClientConfig() (*rest.Config, error) {
if b.clientConfig == nil {
var clientConfig *rest.Config
var err error
if len(b.RemoteKubeConfigFile) > 0 {
loadingRules := &clientcmd.ClientConfigLoadingRules{ExplicitPath: b.RemoteKubeConfigFile}
loader := clientcmd.NewNonInteractiveDeferredLoadingClientConfig(loadingRules, &clientcmd.ConfigOverrides{})
clientConfig, err = loader.ClientConfig()
} else {
clientConfig, err = rest.InClusterConfig()
}
if err != nil {
return nil, fmt.Errorf("unable to construct lister client config to initialize provider: %v", err)
}
b.clientConfig = clientConfig
}
return b.clientConfig, nil
} | [
"func",
"(",
"b",
"*",
"AdapterBase",
")",
"ClientConfig",
"(",
")",
"(",
"*",
"rest",
".",
"Config",
",",
"error",
")",
"{",
"if",
"b",
".",
"clientConfig",
"==",
"nil",
"{",
"var",
"clientConfig",
"*",
"rest",
".",
"Config",
"\n",
"var",
"err",
"... | // ClientConfig returns the REST client configuration used to construct
// clients for the clients and RESTMapper, and may be used for other
// purposes as well. If you need to mutate it, be sure to copy it with
// rest.CopyConfig first. | [
"ClientConfig",
"returns",
"the",
"REST",
"client",
"configuration",
"used",
"to",
"construct",
"clients",
"for",
"the",
"clients",
"and",
"RESTMapper",
"and",
"may",
"be",
"used",
"for",
"other",
"purposes",
"as",
"well",
".",
"If",
"you",
"need",
"to",
"mu... | e303a5e75372662801308008ccdff9b57717e75d | https://github.com/kubernetes-incubator/custom-metrics-apiserver/blob/e303a5e75372662801308008ccdff9b57717e75d/pkg/cmd/builder.go#L128-L146 | train |
kubernetes-incubator/custom-metrics-apiserver | pkg/cmd/builder.go | DiscoveryClient | func (b *AdapterBase) DiscoveryClient() (discovery.DiscoveryInterface, error) {
if b.discoveryClient == nil {
clientConfig, err := b.ClientConfig()
if err != nil {
return nil, err
}
discoveryClient, err := discovery.NewDiscoveryClientForConfig(clientConfig)
if err != nil {
return nil, fmt.Errorf("unable to construct discovery client for dynamic client: %v", err)
}
b.discoveryClient = discoveryClient
}
return b.discoveryClient, nil
} | go | func (b *AdapterBase) DiscoveryClient() (discovery.DiscoveryInterface, error) {
if b.discoveryClient == nil {
clientConfig, err := b.ClientConfig()
if err != nil {
return nil, err
}
discoveryClient, err := discovery.NewDiscoveryClientForConfig(clientConfig)
if err != nil {
return nil, fmt.Errorf("unable to construct discovery client for dynamic client: %v", err)
}
b.discoveryClient = discoveryClient
}
return b.discoveryClient, nil
} | [
"func",
"(",
"b",
"*",
"AdapterBase",
")",
"DiscoveryClient",
"(",
")",
"(",
"discovery",
".",
"DiscoveryInterface",
",",
"error",
")",
"{",
"if",
"b",
".",
"discoveryClient",
"==",
"nil",
"{",
"clientConfig",
",",
"err",
":=",
"b",
".",
"ClientConfig",
... | // DiscoveryClient returns a DiscoveryInterface suitable to for discovering resources
// available on the cluster. | [
"DiscoveryClient",
"returns",
"a",
"DiscoveryInterface",
"suitable",
"to",
"for",
"discovering",
"resources",
"available",
"on",
"the",
"cluster",
"."
] | e303a5e75372662801308008ccdff9b57717e75d | https://github.com/kubernetes-incubator/custom-metrics-apiserver/blob/e303a5e75372662801308008ccdff9b57717e75d/pkg/cmd/builder.go#L150-L163 | train |
kubernetes-incubator/custom-metrics-apiserver | pkg/cmd/builder.go | RESTMapper | func (b *AdapterBase) RESTMapper() (apimeta.RESTMapper, error) {
if b.restMapper == nil {
discoveryClient, err := b.DiscoveryClient()
if err != nil {
return nil, err
}
// NB: since we never actually look at the contents of
// the objects we fetch (beyond ObjectMeta), unstructured should be fine
dynamicMapper, err := dynamicmapper.NewRESTMapper(discoveryClient, b.DiscoveryInterval)
if err != nil {
return nil, fmt.Errorf("unable to construct dynamic discovery mapper: %v", err)
}
b.restMapper = dynamicMapper
}
return b.restMapper, nil
} | go | func (b *AdapterBase) RESTMapper() (apimeta.RESTMapper, error) {
if b.restMapper == nil {
discoveryClient, err := b.DiscoveryClient()
if err != nil {
return nil, err
}
// NB: since we never actually look at the contents of
// the objects we fetch (beyond ObjectMeta), unstructured should be fine
dynamicMapper, err := dynamicmapper.NewRESTMapper(discoveryClient, b.DiscoveryInterval)
if err != nil {
return nil, fmt.Errorf("unable to construct dynamic discovery mapper: %v", err)
}
b.restMapper = dynamicMapper
}
return b.restMapper, nil
} | [
"func",
"(",
"b",
"*",
"AdapterBase",
")",
"RESTMapper",
"(",
")",
"(",
"apimeta",
".",
"RESTMapper",
",",
"error",
")",
"{",
"if",
"b",
".",
"restMapper",
"==",
"nil",
"{",
"discoveryClient",
",",
"err",
":=",
"b",
".",
"DiscoveryClient",
"(",
")",
... | // RESTMapper returns a RESTMapper dynamically populated with discovery information.
// The discovery information will be periodically repopulated according to DiscoveryInterval. | [
"RESTMapper",
"returns",
"a",
"RESTMapper",
"dynamically",
"populated",
"with",
"discovery",
"information",
".",
"The",
"discovery",
"information",
"will",
"be",
"periodically",
"repopulated",
"according",
"to",
"DiscoveryInterval",
"."
] | e303a5e75372662801308008ccdff9b57717e75d | https://github.com/kubernetes-incubator/custom-metrics-apiserver/blob/e303a5e75372662801308008ccdff9b57717e75d/pkg/cmd/builder.go#L167-L183 | train |
kubernetes-incubator/custom-metrics-apiserver | pkg/cmd/builder.go | DynamicClient | func (b *AdapterBase) DynamicClient() (dynamic.Interface, error) {
if b.dynamicClient == nil {
clientConfig, err := b.ClientConfig()
if err != nil {
return nil, err
}
dynClient, err := dynamic.NewForConfig(clientConfig)
if err != nil {
return nil, fmt.Errorf("unable to construct lister client to initialize provider: %v", err)
}
b.dynamicClient = dynClient
}
return b.dynamicClient, nil
} | go | func (b *AdapterBase) DynamicClient() (dynamic.Interface, error) {
if b.dynamicClient == nil {
clientConfig, err := b.ClientConfig()
if err != nil {
return nil, err
}
dynClient, err := dynamic.NewForConfig(clientConfig)
if err != nil {
return nil, fmt.Errorf("unable to construct lister client to initialize provider: %v", err)
}
b.dynamicClient = dynClient
}
return b.dynamicClient, nil
} | [
"func",
"(",
"b",
"*",
"AdapterBase",
")",
"DynamicClient",
"(",
")",
"(",
"dynamic",
".",
"Interface",
",",
"error",
")",
"{",
"if",
"b",
".",
"dynamicClient",
"==",
"nil",
"{",
"clientConfig",
",",
"err",
":=",
"b",
".",
"ClientConfig",
"(",
")",
"... | // DynamicClient returns a dynamic Kubernetes client capable of listing and fetching
// any resources on the cluster. | [
"DynamicClient",
"returns",
"a",
"dynamic",
"Kubernetes",
"client",
"capable",
"of",
"listing",
"and",
"fetching",
"any",
"resources",
"on",
"the",
"cluster",
"."
] | e303a5e75372662801308008ccdff9b57717e75d | https://github.com/kubernetes-incubator/custom-metrics-apiserver/blob/e303a5e75372662801308008ccdff9b57717e75d/pkg/cmd/builder.go#L187-L200 | train |
kubernetes-incubator/custom-metrics-apiserver | pkg/cmd/builder.go | Informers | func (b *AdapterBase) Informers() (informers.SharedInformerFactory, error) {
if b.informers == nil {
clientConfig, err := b.ClientConfig()
if err != nil {
return nil, err
}
kubeClient, err := kubernetes.NewForConfig(clientConfig)
if err != nil {
return nil, err
}
b.informers = informers.NewSharedInformerFactory(kubeClient, 0)
}
return b.informers, nil
} | go | func (b *AdapterBase) Informers() (informers.SharedInformerFactory, error) {
if b.informers == nil {
clientConfig, err := b.ClientConfig()
if err != nil {
return nil, err
}
kubeClient, err := kubernetes.NewForConfig(clientConfig)
if err != nil {
return nil, err
}
b.informers = informers.NewSharedInformerFactory(kubeClient, 0)
}
return b.informers, nil
} | [
"func",
"(",
"b",
"*",
"AdapterBase",
")",
"Informers",
"(",
")",
"(",
"informers",
".",
"SharedInformerFactory",
",",
"error",
")",
"{",
"if",
"b",
".",
"informers",
"==",
"nil",
"{",
"clientConfig",
",",
"err",
":=",
"b",
".",
"ClientConfig",
"(",
")... | // Informers returns a SharedInformerFactory for constructing new informers.
// The informers will be automatically started as part of starting the adapter. | [
"Informers",
"returns",
"a",
"SharedInformerFactory",
"for",
"constructing",
"new",
"informers",
".",
"The",
"informers",
"will",
"be",
"automatically",
"started",
"as",
"part",
"of",
"starting",
"the",
"adapter",
"."
] | e303a5e75372662801308008ccdff9b57717e75d | https://github.com/kubernetes-incubator/custom-metrics-apiserver/blob/e303a5e75372662801308008ccdff9b57717e75d/pkg/cmd/builder.go#L259-L273 | train |
kubernetes-incubator/custom-metrics-apiserver | pkg/cmd/builder.go | Run | func (b *AdapterBase) Run(stopCh <-chan struct{}) error {
server, err := b.Server()
if err != nil {
return err
}
return server.GenericAPIServer.PrepareRun().Run(stopCh)
} | go | func (b *AdapterBase) Run(stopCh <-chan struct{}) error {
server, err := b.Server()
if err != nil {
return err
}
return server.GenericAPIServer.PrepareRun().Run(stopCh)
} | [
"func",
"(",
"b",
"*",
"AdapterBase",
")",
"Run",
"(",
"stopCh",
"<-",
"chan",
"struct",
"{",
"}",
")",
"error",
"{",
"server",
",",
"err",
":=",
"b",
".",
"Server",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n... | // Run runs this custom metrics adapter until the given stop channel is closed. | [
"Run",
"runs",
"this",
"custom",
"metrics",
"adapter",
"until",
"the",
"given",
"stop",
"channel",
"is",
"closed",
"."
] | e303a5e75372662801308008ccdff9b57717e75d | https://github.com/kubernetes-incubator/custom-metrics-apiserver/blob/e303a5e75372662801308008ccdff9b57717e75d/pkg/cmd/builder.go#L276-L283 | train |
kubernetes-incubator/custom-metrics-apiserver | pkg/registry/external_metrics/reststorage.go | List | func (r *REST) List(ctx context.Context, options *metainternalversion.ListOptions) (runtime.Object, error) {
// populate the label selector, defaulting to all
metricSelector := labels.Everything()
if options != nil && options.LabelSelector != nil {
metricSelector = options.LabelSelector
}
namespace := genericapirequest.NamespaceValue(ctx)
requestInfo, ok := request.RequestInfoFrom(ctx)
if !ok {
return nil, fmt.Errorf("unable to get resource and metric name from request")
}
metricName := requestInfo.Resource
return r.emProvider.GetExternalMetric(namespace, metricSelector, provider.ExternalMetricInfo{Metric: metricName})
} | go | func (r *REST) List(ctx context.Context, options *metainternalversion.ListOptions) (runtime.Object, error) {
// populate the label selector, defaulting to all
metricSelector := labels.Everything()
if options != nil && options.LabelSelector != nil {
metricSelector = options.LabelSelector
}
namespace := genericapirequest.NamespaceValue(ctx)
requestInfo, ok := request.RequestInfoFrom(ctx)
if !ok {
return nil, fmt.Errorf("unable to get resource and metric name from request")
}
metricName := requestInfo.Resource
return r.emProvider.GetExternalMetric(namespace, metricSelector, provider.ExternalMetricInfo{Metric: metricName})
} | [
"func",
"(",
"r",
"*",
"REST",
")",
"List",
"(",
"ctx",
"context",
".",
"Context",
",",
"options",
"*",
"metainternalversion",
".",
"ListOptions",
")",
"(",
"runtime",
".",
"Object",
",",
"error",
")",
"{",
"// populate the label selector, defaulting to all",
... | // List selects resources in the storage which match to the selector. | [
"List",
"selects",
"resources",
"in",
"the",
"storage",
"which",
"match",
"to",
"the",
"selector",
"."
] | e303a5e75372662801308008ccdff9b57717e75d | https://github.com/kubernetes-incubator/custom-metrics-apiserver/blob/e303a5e75372662801308008ccdff9b57717e75d/pkg/registry/external_metrics/reststorage.go#L64-L80 | train |
kubernetes-incubator/custom-metrics-apiserver | pkg/provider/resource_lister.go | ListAPIResources | func (l *externalMetricsResourceLister) ListAPIResources() []metav1.APIResource {
metrics := l.provider.ListAllExternalMetrics()
resources := make([]metav1.APIResource, len(metrics))
for i, metric := range metrics {
resources[i] = metav1.APIResource{
Name: metric.Metric,
Namespaced: true,
Kind: "ExternalMetricValueList",
Verbs: metav1.Verbs{"get"},
}
}
return resources
} | go | func (l *externalMetricsResourceLister) ListAPIResources() []metav1.APIResource {
metrics := l.provider.ListAllExternalMetrics()
resources := make([]metav1.APIResource, len(metrics))
for i, metric := range metrics {
resources[i] = metav1.APIResource{
Name: metric.Metric,
Namespaced: true,
Kind: "ExternalMetricValueList",
Verbs: metav1.Verbs{"get"},
}
}
return resources
} | [
"func",
"(",
"l",
"*",
"externalMetricsResourceLister",
")",
"ListAPIResources",
"(",
")",
"[",
"]",
"metav1",
".",
"APIResource",
"{",
"metrics",
":=",
"l",
".",
"provider",
".",
"ListAllExternalMetrics",
"(",
")",
"\n",
"resources",
":=",
"make",
"(",
"[",... | // ListAPIResources lists all supported custom metrics. | [
"ListAPIResources",
"lists",
"all",
"supported",
"custom",
"metrics",
"."
] | e303a5e75372662801308008ccdff9b57717e75d | https://github.com/kubernetes-incubator/custom-metrics-apiserver/blob/e303a5e75372662801308008ccdff9b57717e75d/pkg/provider/resource_lister.go#L63-L77 | train |
kubernetes-incubator/custom-metrics-apiserver | pkg/apiserver/installer/installer.go | InstallREST | func (g *MetricsAPIGroupVersion) InstallREST(container *restful.Container) error {
installer := g.newDynamicInstaller()
ws := installer.NewWebService()
registrationErrors := installer.Install(ws)
lister := g.ResourceLister
if lister == nil {
return fmt.Errorf("must provide a dynamic lister for dynamic API groups")
}
versionDiscoveryHandler := discovery.NewAPIVersionHandler(g.Serializer, g.GroupVersion, lister)
versionDiscoveryHandler.AddToWebService(ws)
container.Add(ws)
return utilerrors.NewAggregate(registrationErrors)
} | go | func (g *MetricsAPIGroupVersion) InstallREST(container *restful.Container) error {
installer := g.newDynamicInstaller()
ws := installer.NewWebService()
registrationErrors := installer.Install(ws)
lister := g.ResourceLister
if lister == nil {
return fmt.Errorf("must provide a dynamic lister for dynamic API groups")
}
versionDiscoveryHandler := discovery.NewAPIVersionHandler(g.Serializer, g.GroupVersion, lister)
versionDiscoveryHandler.AddToWebService(ws)
container.Add(ws)
return utilerrors.NewAggregate(registrationErrors)
} | [
"func",
"(",
"g",
"*",
"MetricsAPIGroupVersion",
")",
"InstallREST",
"(",
"container",
"*",
"restful",
".",
"Container",
")",
"error",
"{",
"installer",
":=",
"g",
".",
"newDynamicInstaller",
"(",
")",
"\n",
"ws",
":=",
"installer",
".",
"NewWebService",
"("... | // InstallDynamicREST registers the dynamic REST handlers into a restful Container.
// It is expected that the provided path root prefix will serve all operations. Root MUST
// NOT end in a slash. It should mirror InstallREST in the plain APIGroupVersion. | [
"InstallDynamicREST",
"registers",
"the",
"dynamic",
"REST",
"handlers",
"into",
"a",
"restful",
"Container",
".",
"It",
"is",
"expected",
"that",
"the",
"provided",
"path",
"root",
"prefix",
"will",
"serve",
"all",
"operations",
".",
"Root",
"MUST",
"NOT",
"e... | e303a5e75372662801308008ccdff9b57717e75d | https://github.com/kubernetes-incubator/custom-metrics-apiserver/blob/e303a5e75372662801308008ccdff9b57717e75d/pkg/apiserver/installer/installer.go#L68-L81 | train |
kubernetes-incubator/custom-metrics-apiserver | pkg/apiserver/installer/installer.go | newDynamicInstaller | func (g *MetricsAPIGroupVersion) newDynamicInstaller() *MetricsAPIInstaller {
prefix := gpath.Join(g.Root, g.GroupVersion.Group, g.GroupVersion.Version)
installer := &MetricsAPIInstaller{
group: g,
prefix: prefix,
minRequestTimeout: g.MinRequestTimeout,
handlers: g.Handlers,
}
return installer
} | go | func (g *MetricsAPIGroupVersion) newDynamicInstaller() *MetricsAPIInstaller {
prefix := gpath.Join(g.Root, g.GroupVersion.Group, g.GroupVersion.Version)
installer := &MetricsAPIInstaller{
group: g,
prefix: prefix,
minRequestTimeout: g.MinRequestTimeout,
handlers: g.Handlers,
}
return installer
} | [
"func",
"(",
"g",
"*",
"MetricsAPIGroupVersion",
")",
"newDynamicInstaller",
"(",
")",
"*",
"MetricsAPIInstaller",
"{",
"prefix",
":=",
"gpath",
".",
"Join",
"(",
"g",
".",
"Root",
",",
"g",
".",
"GroupVersion",
".",
"Group",
",",
"g",
".",
"GroupVersion",... | // newDynamicInstaller is a helper to create the installer. It mirrors
// newInstaller in APIGroupVersion. | [
"newDynamicInstaller",
"is",
"a",
"helper",
"to",
"create",
"the",
"installer",
".",
"It",
"mirrors",
"newInstaller",
"in",
"APIGroupVersion",
"."
] | e303a5e75372662801308008ccdff9b57717e75d | https://github.com/kubernetes-incubator/custom-metrics-apiserver/blob/e303a5e75372662801308008ccdff9b57717e75d/pkg/apiserver/installer/installer.go#L85-L95 | train |
kubernetes-incubator/custom-metrics-apiserver | pkg/apiserver/installer/installer.go | Install | func (a *MetricsAPIInstaller) Install(ws *restful.WebService) (errors []error) {
errors = make([]error, 0)
err := a.handlers.registerResourceHandlers(a, ws)
if err != nil {
errors = append(errors, fmt.Errorf("error in registering custom metrics resource: %v", err))
}
return errors
} | go | func (a *MetricsAPIInstaller) Install(ws *restful.WebService) (errors []error) {
errors = make([]error, 0)
err := a.handlers.registerResourceHandlers(a, ws)
if err != nil {
errors = append(errors, fmt.Errorf("error in registering custom metrics resource: %v", err))
}
return errors
} | [
"func",
"(",
"a",
"*",
"MetricsAPIInstaller",
")",
"Install",
"(",
"ws",
"*",
"restful",
".",
"WebService",
")",
"(",
"errors",
"[",
"]",
"error",
")",
"{",
"errors",
"=",
"make",
"(",
"[",
"]",
"error",
",",
"0",
")",
"\n\n",
"err",
":=",
"a",
"... | // Install installs handlers for External Metrics API resources. | [
"Install",
"installs",
"handlers",
"for",
"External",
"Metrics",
"API",
"resources",
"."
] | e303a5e75372662801308008ccdff9b57717e75d | https://github.com/kubernetes-incubator/custom-metrics-apiserver/blob/e303a5e75372662801308008ccdff9b57717e75d/pkg/apiserver/installer/installer.go#L112-L121 | train |
kubernetes-incubator/custom-metrics-apiserver | pkg/apiserver/installer/installer.go | NewWebService | func (a *MetricsAPIInstaller) NewWebService() *restful.WebService {
ws := new(restful.WebService)
ws.Path(a.prefix)
// a.prefix contains "prefix/group/version"
ws.Doc("API at " + a.prefix)
// Backwards compatibility, we accepted objects with empty content-type at V1.
// If we stop using go-restful, we can default empty content-type to application/json on an
// endpoint by endpoint basis
ws.Consumes("*/*")
mediaTypes, streamMediaTypes := negotiation.MediaTypesForSerializer(a.group.Serializer)
ws.Produces(append(mediaTypes, streamMediaTypes...)...)
ws.ApiVersion(a.group.GroupVersion.String())
return ws
} | go | func (a *MetricsAPIInstaller) NewWebService() *restful.WebService {
ws := new(restful.WebService)
ws.Path(a.prefix)
// a.prefix contains "prefix/group/version"
ws.Doc("API at " + a.prefix)
// Backwards compatibility, we accepted objects with empty content-type at V1.
// If we stop using go-restful, we can default empty content-type to application/json on an
// endpoint by endpoint basis
ws.Consumes("*/*")
mediaTypes, streamMediaTypes := negotiation.MediaTypesForSerializer(a.group.Serializer)
ws.Produces(append(mediaTypes, streamMediaTypes...)...)
ws.ApiVersion(a.group.GroupVersion.String())
return ws
} | [
"func",
"(",
"a",
"*",
"MetricsAPIInstaller",
")",
"NewWebService",
"(",
")",
"*",
"restful",
".",
"WebService",
"{",
"ws",
":=",
"new",
"(",
"restful",
".",
"WebService",
")",
"\n",
"ws",
".",
"Path",
"(",
"a",
".",
"prefix",
")",
"\n",
"// a.prefix c... | // NewWebService creates a new restful webservice with the api installer's prefix and version. | [
"NewWebService",
"creates",
"a",
"new",
"restful",
"webservice",
"with",
"the",
"api",
"installer",
"s",
"prefix",
"and",
"version",
"."
] | e303a5e75372662801308008ccdff9b57717e75d | https://github.com/kubernetes-incubator/custom-metrics-apiserver/blob/e303a5e75372662801308008ccdff9b57717e75d/pkg/apiserver/installer/installer.go#L124-L138 | train |
kubernetes-incubator/custom-metrics-apiserver | pkg/apiserver/installer/installer.go | getResourceKind | func (a *MetricsAPIInstaller) getResourceKind(storage rest.Storage) (schema.GroupVersionKind, error) {
object := storage.New()
fqKinds, _, err := a.group.Typer.ObjectKinds(object)
if err != nil {
return schema.GroupVersionKind{}, err
}
// a given go type can have multiple potential fully qualified kinds. Find the one that corresponds with the group
// we're trying to register here
fqKindToRegister := schema.GroupVersionKind{}
for _, fqKind := range fqKinds {
if fqKind.Group == a.group.GroupVersion.Group {
fqKindToRegister = a.group.GroupVersion.WithKind(fqKind.Kind)
break
}
// TODO: keep rid of extensions api group dependency here
// This keeps it doing what it was doing before, but it doesn't feel right.
if fqKind.Group == "extensions" && fqKind.Kind == "ThirdPartyResourceData" {
fqKindToRegister = a.group.GroupVersion.WithKind(fqKind.Kind)
}
}
if fqKindToRegister.Empty() {
return schema.GroupVersionKind{}, fmt.Errorf("unable to locate fully qualified kind for %v: found %v when registering for %v", reflect.TypeOf(object), fqKinds, a.group.GroupVersion)
}
return fqKindToRegister, nil
} | go | func (a *MetricsAPIInstaller) getResourceKind(storage rest.Storage) (schema.GroupVersionKind, error) {
object := storage.New()
fqKinds, _, err := a.group.Typer.ObjectKinds(object)
if err != nil {
return schema.GroupVersionKind{}, err
}
// a given go type can have multiple potential fully qualified kinds. Find the one that corresponds with the group
// we're trying to register here
fqKindToRegister := schema.GroupVersionKind{}
for _, fqKind := range fqKinds {
if fqKind.Group == a.group.GroupVersion.Group {
fqKindToRegister = a.group.GroupVersion.WithKind(fqKind.Kind)
break
}
// TODO: keep rid of extensions api group dependency here
// This keeps it doing what it was doing before, but it doesn't feel right.
if fqKind.Group == "extensions" && fqKind.Kind == "ThirdPartyResourceData" {
fqKindToRegister = a.group.GroupVersion.WithKind(fqKind.Kind)
}
}
if fqKindToRegister.Empty() {
return schema.GroupVersionKind{}, fmt.Errorf("unable to locate fully qualified kind for %v: found %v when registering for %v", reflect.TypeOf(object), fqKinds, a.group.GroupVersion)
}
return fqKindToRegister, nil
} | [
"func",
"(",
"a",
"*",
"MetricsAPIInstaller",
")",
"getResourceKind",
"(",
"storage",
"rest",
".",
"Storage",
")",
"(",
"schema",
".",
"GroupVersionKind",
",",
"error",
")",
"{",
"object",
":=",
"storage",
".",
"New",
"(",
")",
"\n",
"fqKinds",
",",
"_",... | // getResourceKind returns the external group version kind registered for the given storage object. | [
"getResourceKind",
"returns",
"the",
"external",
"group",
"version",
"kind",
"registered",
"for",
"the",
"given",
"storage",
"object",
"."
] | e303a5e75372662801308008ccdff9b57717e75d | https://github.com/kubernetes-incubator/custom-metrics-apiserver/blob/e303a5e75372662801308008ccdff9b57717e75d/pkg/apiserver/installer/installer.go#L146-L172 | train |
kubernetes-incubator/custom-metrics-apiserver | pkg/provider/interfaces.go | Normalized | func (i CustomMetricInfo) Normalized(mapper apimeta.RESTMapper) (normalizedInfo CustomMetricInfo, singluarResource string, err error) {
normalizedGroupRes, err := mapper.ResourceFor(i.GroupResource.WithVersion(""))
if err != nil {
return i, "", err
}
i.GroupResource = normalizedGroupRes.GroupResource()
singularResource, err := mapper.ResourceSingularizer(i.GroupResource.Resource)
if err != nil {
return i, "", err
}
return i, singularResource, nil
} | go | func (i CustomMetricInfo) Normalized(mapper apimeta.RESTMapper) (normalizedInfo CustomMetricInfo, singluarResource string, err error) {
normalizedGroupRes, err := mapper.ResourceFor(i.GroupResource.WithVersion(""))
if err != nil {
return i, "", err
}
i.GroupResource = normalizedGroupRes.GroupResource()
singularResource, err := mapper.ResourceSingularizer(i.GroupResource.Resource)
if err != nil {
return i, "", err
}
return i, singularResource, nil
} | [
"func",
"(",
"i",
"CustomMetricInfo",
")",
"Normalized",
"(",
"mapper",
"apimeta",
".",
"RESTMapper",
")",
"(",
"normalizedInfo",
"CustomMetricInfo",
",",
"singluarResource",
"string",
",",
"err",
"error",
")",
"{",
"normalizedGroupRes",
",",
"err",
":=",
"mappe... | // Normalized returns a copy of the current MetricInfo with the GroupResource resolved using the
// provided REST mapper, to ensure consistent pluralization, etc, for use when looking up or comparing
// the MetricInfo. It also returns the singular form of the GroupResource associated with the given
// MetricInfo. | [
"Normalized",
"returns",
"a",
"copy",
"of",
"the",
"current",
"MetricInfo",
"with",
"the",
"GroupResource",
"resolved",
"using",
"the",
"provided",
"REST",
"mapper",
"to",
"ensure",
"consistent",
"pluralization",
"etc",
"for",
"use",
"when",
"looking",
"up",
"or... | e303a5e75372662801308008ccdff9b57717e75d | https://github.com/kubernetes-incubator/custom-metrics-apiserver/blob/e303a5e75372662801308008ccdff9b57717e75d/pkg/provider/interfaces.go#L55-L68 | train |
kubernetes-incubator/custom-metrics-apiserver | pkg/dynamicmapper/mapper.go | RunUntil | func (m *RegeneratingDiscoveryRESTMapper) RunUntil(stop <-chan struct{}) {
go wait.Until(func() {
if err := m.RegenerateMappings(); err != nil {
klog.Errorf("error regenerating REST mappings from discovery: %v", err)
}
}, m.refreshInterval, stop)
} | go | func (m *RegeneratingDiscoveryRESTMapper) RunUntil(stop <-chan struct{}) {
go wait.Until(func() {
if err := m.RegenerateMappings(); err != nil {
klog.Errorf("error regenerating REST mappings from discovery: %v", err)
}
}, m.refreshInterval, stop)
} | [
"func",
"(",
"m",
"*",
"RegeneratingDiscoveryRESTMapper",
")",
"RunUntil",
"(",
"stop",
"<-",
"chan",
"struct",
"{",
"}",
")",
"{",
"go",
"wait",
".",
"Until",
"(",
"func",
"(",
")",
"{",
"if",
"err",
":=",
"m",
".",
"RegenerateMappings",
"(",
")",
"... | // RunUtil runs the mapping refresher until the given stop channel is closed. | [
"RunUtil",
"runs",
"the",
"mapping",
"refresher",
"until",
"the",
"given",
"stop",
"channel",
"is",
"closed",
"."
] | e303a5e75372662801308008ccdff9b57717e75d | https://github.com/kubernetes-incubator/custom-metrics-apiserver/blob/e303a5e75372662801308008ccdff9b57717e75d/pkg/dynamicmapper/mapper.go#L43-L49 | train |
linkedin/goavro | ocf_reader.go | CompressionName | func (ocfr *OCFReader) CompressionName() string {
switch ocfr.header.compressionID {
case compressionNull:
return CompressionNullLabel
case compressionDeflate:
return CompressionDeflateLabel
case compressionSnappy:
return CompressionSnappyLabel
default:
return "should not get here: unrecognized compression algorithm"
}
} | go | func (ocfr *OCFReader) CompressionName() string {
switch ocfr.header.compressionID {
case compressionNull:
return CompressionNullLabel
case compressionDeflate:
return CompressionDeflateLabel
case compressionSnappy:
return CompressionSnappyLabel
default:
return "should not get here: unrecognized compression algorithm"
}
} | [
"func",
"(",
"ocfr",
"*",
"OCFReader",
")",
"CompressionName",
"(",
")",
"string",
"{",
"switch",
"ocfr",
".",
"header",
".",
"compressionID",
"{",
"case",
"compressionNull",
":",
"return",
"CompressionNullLabel",
"\n",
"case",
"compressionDeflate",
":",
"return... | // CompressionName returns the name of the compression algorithm found within
// the OCF file. | [
"CompressionName",
"returns",
"the",
"name",
"of",
"the",
"compression",
"algorithm",
"found",
"within",
"the",
"OCF",
"file",
"."
] | 45f9a215035e4767b6a0848975ec3df73ed9c1b0 | https://github.com/linkedin/goavro/blob/45f9a215035e4767b6a0848975ec3df73ed9c1b0/ocf_reader.go#L75-L86 | train |
linkedin/goavro | ocf_reader.go | Read | func (ocfr *OCFReader) Read() (interface{}, error) {
// NOTE: Test previous error before testing readReady to prevent overwriting
// previous error.
if ocfr.rerr != nil {
return nil, ocfr.rerr
}
if !ocfr.readReady {
ocfr.rerr = errors.New("Read called without successful Scan")
return nil, ocfr.rerr
}
ocfr.readReady = false
// decode one datum value from block
var datum interface{}
datum, ocfr.block, ocfr.rerr = ocfr.header.codec.NativeFromBinary(ocfr.block)
if ocfr.rerr != nil {
return false, ocfr.rerr
}
ocfr.remainingBlockItems--
return datum, nil
} | go | func (ocfr *OCFReader) Read() (interface{}, error) {
// NOTE: Test previous error before testing readReady to prevent overwriting
// previous error.
if ocfr.rerr != nil {
return nil, ocfr.rerr
}
if !ocfr.readReady {
ocfr.rerr = errors.New("Read called without successful Scan")
return nil, ocfr.rerr
}
ocfr.readReady = false
// decode one datum value from block
var datum interface{}
datum, ocfr.block, ocfr.rerr = ocfr.header.codec.NativeFromBinary(ocfr.block)
if ocfr.rerr != nil {
return false, ocfr.rerr
}
ocfr.remainingBlockItems--
return datum, nil
} | [
"func",
"(",
"ocfr",
"*",
"OCFReader",
")",
"Read",
"(",
")",
"(",
"interface",
"{",
"}",
",",
"error",
")",
"{",
"// NOTE: Test previous error before testing readReady to prevent overwriting",
"// previous error.",
"if",
"ocfr",
".",
"rerr",
"!=",
"nil",
"{",
"re... | // Read consumes one datum value from the Avro OCF stream and returns it. Read
// is designed to be called only once after each invocation of the Scan method.
// See `NewOCFReader` documentation for an example. | [
"Read",
"consumes",
"one",
"datum",
"value",
"from",
"the",
"Avro",
"OCF",
"stream",
"and",
"returns",
"it",
".",
"Read",
"is",
"designed",
"to",
"be",
"called",
"only",
"once",
"after",
"each",
"invocation",
"of",
"the",
"Scan",
"method",
".",
"See",
"N... | 45f9a215035e4767b6a0848975ec3df73ed9c1b0 | https://github.com/linkedin/goavro/blob/45f9a215035e4767b6a0848975ec3df73ed9c1b0/ocf_reader.go#L97-L118 | train |
Subsets and Splits
SQL Console for semeru/code-text-go
Retrieves a limited set of code samples with their languages, with a specific case adjustment for 'Go' language.