repo
stringlengths
5
67
path
stringlengths
4
218
func_name
stringlengths
0
151
original_string
stringlengths
52
373k
language
stringclasses
6 values
code
stringlengths
52
373k
code_tokens
listlengths
10
512
docstring
stringlengths
3
47.2k
docstring_tokens
listlengths
3
234
sha
stringlengths
40
40
url
stringlengths
85
339
partition
stringclasses
3 values
rqlite/rqlite
http/service.go
level
func level(req *http.Request) (store.ConsistencyLevel, error) { q := req.URL.Query() lvl := strings.TrimSpace(q.Get("level")) switch strings.ToLower(lvl) { case "none": return store.None, nil case "weak": return store.Weak, nil case "strong": return store.Strong, nil default: return store.Weak, nil } }
go
func level(req *http.Request) (store.ConsistencyLevel, error) { q := req.URL.Query() lvl := strings.TrimSpace(q.Get("level")) switch strings.ToLower(lvl) { case "none": return store.None, nil case "weak": return store.Weak, nil case "strong": return store.Strong, nil default: return store.Weak, nil } }
[ "func", "level", "(", "req", "*", "http", ".", "Request", ")", "(", "store", ".", "ConsistencyLevel", ",", "error", ")", "{", "q", ":=", "req", ".", "URL", ".", "Query", "(", ")", "\n", "lvl", ":=", "strings", ".", "TrimSpace", "(", "q", ".", "Get", "(", "\"level\"", ")", ")", "\n", "switch", "strings", ".", "ToLower", "(", "lvl", ")", "{", "case", "\"none\"", ":", "return", "store", ".", "None", ",", "nil", "\n", "case", "\"weak\"", ":", "return", "store", ".", "Weak", ",", "nil", "\n", "case", "\"strong\"", ":", "return", "store", ".", "Strong", ",", "nil", "\n", "default", ":", "return", "store", ".", "Weak", ",", "nil", "\n", "}", "\n", "}" ]
// level returns the requested consistency level for a query
[ "level", "returns", "the", "requested", "consistency", "level", "for", "a", "query" ]
12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3
https://github.com/rqlite/rqlite/blob/12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3/http/service.go#L863-L877
train
rqlite/rqlite
http/service.go
backupFormat
func backupFormat(w http.ResponseWriter, r *http.Request) (store.BackupFormat, error) { fmt, err := fmtParam(r) if err != nil { return store.BackupBinary, err } if fmt == "sql" { w.Header().Set("Content-Type", "application/sql") return store.BackupSQL, nil } w.Header().Set("Content-Type", "application/octet-stream") return store.BackupBinary, nil }
go
func backupFormat(w http.ResponseWriter, r *http.Request) (store.BackupFormat, error) { fmt, err := fmtParam(r) if err != nil { return store.BackupBinary, err } if fmt == "sql" { w.Header().Set("Content-Type", "application/sql") return store.BackupSQL, nil } w.Header().Set("Content-Type", "application/octet-stream") return store.BackupBinary, nil }
[ "func", "backupFormat", "(", "w", "http", ".", "ResponseWriter", ",", "r", "*", "http", ".", "Request", ")", "(", "store", ".", "BackupFormat", ",", "error", ")", "{", "fmt", ",", "err", ":=", "fmtParam", "(", "r", ")", "\n", "if", "err", "!=", "nil", "{", "return", "store", ".", "BackupBinary", ",", "err", "\n", "}", "\n", "if", "fmt", "==", "\"sql\"", "{", "w", ".", "Header", "(", ")", ".", "Set", "(", "\"Content-Type\"", ",", "\"application/sql\"", ")", "\n", "return", "store", ".", "BackupSQL", ",", "nil", "\n", "}", "\n", "w", ".", "Header", "(", ")", ".", "Set", "(", "\"Content-Type\"", ",", "\"application/octet-stream\"", ")", "\n", "return", "store", ".", "BackupBinary", ",", "nil", "\n", "}" ]
// backuFormat returns the request backup format, setting the response header // accordingly.
[ "backuFormat", "returns", "the", "request", "backup", "format", "setting", "the", "response", "header", "accordingly", "." ]
12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3
https://github.com/rqlite/rqlite/blob/12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3/http/service.go#L881-L892
train
rqlite/rqlite
db/db.go
New
func New(path, dsnQuery string, memory bool) (*DB, error) { q, err := url.ParseQuery(dsnQuery) if err != nil { return nil, err } if memory { q.Set("mode", "memory") q.Set("cache", "shared") } if !strings.HasPrefix(path, "file:") { path = fmt.Sprintf("file:%s", path) } var fqdsn string if len(q) > 0 { fqdsn = fmt.Sprintf("%s?%s", path, q.Encode()) } else { fqdsn = path } return &DB{ path: path, dsnQuery: dsnQuery, memory: memory, fqdsn: fqdsn, }, nil }
go
func New(path, dsnQuery string, memory bool) (*DB, error) { q, err := url.ParseQuery(dsnQuery) if err != nil { return nil, err } if memory { q.Set("mode", "memory") q.Set("cache", "shared") } if !strings.HasPrefix(path, "file:") { path = fmt.Sprintf("file:%s", path) } var fqdsn string if len(q) > 0 { fqdsn = fmt.Sprintf("%s?%s", path, q.Encode()) } else { fqdsn = path } return &DB{ path: path, dsnQuery: dsnQuery, memory: memory, fqdsn: fqdsn, }, nil }
[ "func", "New", "(", "path", ",", "dsnQuery", "string", ",", "memory", "bool", ")", "(", "*", "DB", ",", "error", ")", "{", "q", ",", "err", ":=", "url", ".", "ParseQuery", "(", "dsnQuery", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "if", "memory", "{", "q", ".", "Set", "(", "\"mode\"", ",", "\"memory\"", ")", "\n", "q", ".", "Set", "(", "\"cache\"", ",", "\"shared\"", ")", "\n", "}", "\n", "if", "!", "strings", ".", "HasPrefix", "(", "path", ",", "\"file:\"", ")", "{", "path", "=", "fmt", ".", "Sprintf", "(", "\"file:%s\"", ",", "path", ")", "\n", "}", "\n", "var", "fqdsn", "string", "\n", "if", "len", "(", "q", ")", ">", "0", "{", "fqdsn", "=", "fmt", ".", "Sprintf", "(", "\"%s?%s\"", ",", "path", ",", "q", ".", "Encode", "(", ")", ")", "\n", "}", "else", "{", "fqdsn", "=", "path", "\n", "}", "\n", "return", "&", "DB", "{", "path", ":", "path", ",", "dsnQuery", ":", "dsnQuery", ",", "memory", ":", "memory", ",", "fqdsn", ":", "fqdsn", ",", "}", ",", "nil", "\n", "}" ]
// New returns an instance of the database at path. If the database // has already been created and opened, this database will share // the data of that database when connected.
[ "New", "returns", "an", "instance", "of", "the", "database", "at", "path", ".", "If", "the", "database", "has", "already", "been", "created", "and", "opened", "this", "database", "will", "share", "the", "data", "of", "that", "database", "when", "connected", "." ]
12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3
https://github.com/rqlite/rqlite/blob/12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3/db/db.go#L75-L102
train
rqlite/rqlite
db/db.go
Connect
func (d *DB) Connect() (*Conn, error) { drv := sqlite3.SQLiteDriver{} c, err := drv.Open(d.fqdsn) if err != nil { return nil, err } return &Conn{ sqlite: c.(*sqlite3.SQLiteConn), }, nil }
go
func (d *DB) Connect() (*Conn, error) { drv := sqlite3.SQLiteDriver{} c, err := drv.Open(d.fqdsn) if err != nil { return nil, err } return &Conn{ sqlite: c.(*sqlite3.SQLiteConn), }, nil }
[ "func", "(", "d", "*", "DB", ")", "Connect", "(", ")", "(", "*", "Conn", ",", "error", ")", "{", "drv", ":=", "sqlite3", ".", "SQLiteDriver", "{", "}", "\n", "c", ",", "err", ":=", "drv", ".", "Open", "(", "d", ".", "fqdsn", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "return", "&", "Conn", "{", "sqlite", ":", "c", ".", "(", "*", "sqlite3", ".", "SQLiteConn", ")", ",", "}", ",", "nil", "\n", "}" ]
// Connect returns a connection to the database.
[ "Connect", "returns", "a", "connection", "to", "the", "database", "." ]
12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3
https://github.com/rqlite/rqlite/blob/12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3/db/db.go#L105-L115
train
rqlite/rqlite
db/db.go
Execute
func (c *Conn) Execute(queries []string, tx, xTime bool) ([]*Result, error) { stats.Add(numExecutions, int64(len(queries))) if tx { stats.Add(numETx, 1) } type Execer interface { Exec(query string, args []driver.Value) (driver.Result, error) } var allResults []*Result err := func() error { var execer Execer var rollback bool var t driver.Tx var err error // Check for the err, if set rollback. defer func() { if t != nil { if rollback { t.Rollback() return } t.Commit() } }() // handleError sets the error field on the given result. It returns // whether the caller should continue processing or break. handleError := func(result *Result, err error) bool { stats.Add(numExecutionErrors, 1) result.Error = err.Error() allResults = append(allResults, result) if tx { rollback = true // Will trigger the rollback. return false } return true } execer = c.sqlite // Create the correct execution object, depending on whether a // transaction was requested. if tx { t, err = c.sqlite.Begin() if err != nil { return err } } // Execute each query. for _, q := range queries { if q == "" { continue } result := &Result{} start := time.Now() r, err := execer.Exec(q, nil) if err != nil { if handleError(result, err) { continue } break } if r == nil { continue } lid, err := r.LastInsertId() if err != nil { if handleError(result, err) { continue } break } result.LastInsertID = lid ra, err := r.RowsAffected() if err != nil { if handleError(result, err) { continue } break } result.RowsAffected = ra if xTime { result.Time = time.Now().Sub(start).Seconds() } allResults = append(allResults, result) } return nil }() return allResults, err }
go
func (c *Conn) Execute(queries []string, tx, xTime bool) ([]*Result, error) { stats.Add(numExecutions, int64(len(queries))) if tx { stats.Add(numETx, 1) } type Execer interface { Exec(query string, args []driver.Value) (driver.Result, error) } var allResults []*Result err := func() error { var execer Execer var rollback bool var t driver.Tx var err error // Check for the err, if set rollback. defer func() { if t != nil { if rollback { t.Rollback() return } t.Commit() } }() // handleError sets the error field on the given result. It returns // whether the caller should continue processing or break. handleError := func(result *Result, err error) bool { stats.Add(numExecutionErrors, 1) result.Error = err.Error() allResults = append(allResults, result) if tx { rollback = true // Will trigger the rollback. return false } return true } execer = c.sqlite // Create the correct execution object, depending on whether a // transaction was requested. if tx { t, err = c.sqlite.Begin() if err != nil { return err } } // Execute each query. for _, q := range queries { if q == "" { continue } result := &Result{} start := time.Now() r, err := execer.Exec(q, nil) if err != nil { if handleError(result, err) { continue } break } if r == nil { continue } lid, err := r.LastInsertId() if err != nil { if handleError(result, err) { continue } break } result.LastInsertID = lid ra, err := r.RowsAffected() if err != nil { if handleError(result, err) { continue } break } result.RowsAffected = ra if xTime { result.Time = time.Now().Sub(start).Seconds() } allResults = append(allResults, result) } return nil }() return allResults, err }
[ "func", "(", "c", "*", "Conn", ")", "Execute", "(", "queries", "[", "]", "string", ",", "tx", ",", "xTime", "bool", ")", "(", "[", "]", "*", "Result", ",", "error", ")", "{", "stats", ".", "Add", "(", "numExecutions", ",", "int64", "(", "len", "(", "queries", ")", ")", ")", "\n", "if", "tx", "{", "stats", ".", "Add", "(", "numETx", ",", "1", ")", "\n", "}", "\n", "type", "Execer", "interface", "{", "Exec", "(", "query", "string", ",", "args", "[", "]", "driver", ".", "Value", ")", "(", "driver", ".", "Result", ",", "error", ")", "\n", "}", "\n", "var", "allResults", "[", "]", "*", "Result", "\n", "err", ":=", "func", "(", ")", "error", "{", "var", "execer", "Execer", "\n", "var", "rollback", "bool", "\n", "var", "t", "driver", ".", "Tx", "\n", "var", "err", "error", "\n", "defer", "func", "(", ")", "{", "if", "t", "!=", "nil", "{", "if", "rollback", "{", "t", ".", "Rollback", "(", ")", "\n", "return", "\n", "}", "\n", "t", ".", "Commit", "(", ")", "\n", "}", "\n", "}", "(", ")", "\n", "handleError", ":=", "func", "(", "result", "*", "Result", ",", "err", "error", ")", "bool", "{", "stats", ".", "Add", "(", "numExecutionErrors", ",", "1", ")", "\n", "result", ".", "Error", "=", "err", ".", "Error", "(", ")", "\n", "allResults", "=", "append", "(", "allResults", ",", "result", ")", "\n", "if", "tx", "{", "rollback", "=", "true", "\n", "return", "false", "\n", "}", "\n", "return", "true", "\n", "}", "\n", "execer", "=", "c", ".", "sqlite", "\n", "if", "tx", "{", "t", ",", "err", "=", "c", ".", "sqlite", ".", "Begin", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "}", "\n", "for", "_", ",", "q", ":=", "range", "queries", "{", "if", "q", "==", "\"\"", "{", "continue", "\n", "}", "\n", "result", ":=", "&", "Result", "{", "}", "\n", "start", ":=", "time", ".", "Now", "(", ")", "\n", "r", ",", "err", ":=", "execer", ".", "Exec", "(", "q", ",", "nil", ")", "\n", "if", "err", "!=", "nil", "{", "if", "handleError", "(", "result", ",", "err", ")", "{", "continue", "\n", "}", "\n", "break", "\n", "}", "\n", "if", "r", "==", "nil", "{", "continue", "\n", "}", "\n", "lid", ",", "err", ":=", "r", ".", "LastInsertId", "(", ")", "\n", "if", "err", "!=", "nil", "{", "if", "handleError", "(", "result", ",", "err", ")", "{", "continue", "\n", "}", "\n", "break", "\n", "}", "\n", "result", ".", "LastInsertID", "=", "lid", "\n", "ra", ",", "err", ":=", "r", ".", "RowsAffected", "(", ")", "\n", "if", "err", "!=", "nil", "{", "if", "handleError", "(", "result", ",", "err", ")", "{", "continue", "\n", "}", "\n", "break", "\n", "}", "\n", "result", ".", "RowsAffected", "=", "ra", "\n", "if", "xTime", "{", "result", ".", "Time", "=", "time", ".", "Now", "(", ")", ".", "Sub", "(", "start", ")", ".", "Seconds", "(", ")", "\n", "}", "\n", "allResults", "=", "append", "(", "allResults", ",", "result", ")", "\n", "}", "\n", "return", "nil", "\n", "}", "(", ")", "\n", "return", "allResults", ",", "err", "\n", "}" ]
// Execute executes queries that modify the database.
[ "Execute", "executes", "queries", "that", "modify", "the", "database", "." ]
12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3
https://github.com/rqlite/rqlite/blob/12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3/db/db.go#L139-L239
train
rqlite/rqlite
db/db.go
Query
func (c *Conn) Query(queries []string, tx, xTime bool) ([]*Rows, error) { stats.Add(numQueries, int64(len(queries))) if tx { stats.Add(numQTx, 1) } type Queryer interface { Query(query string, args []driver.Value) (driver.Rows, error) } var allRows []*Rows err := func() (err error) { var queryer Queryer var t driver.Tx defer func() { // XXX THIS DOESN'T ACTUALLY WORK! Might as WELL JUST COMMIT? if t != nil { if err != nil { t.Rollback() return } t.Commit() } }() queryer = c.sqlite // Create the correct query object, depending on whether a // transaction was requested. if tx { t, err = c.sqlite.Begin() if err != nil { return err } } for _, q := range queries { if q == "" { continue } rows := &Rows{} start := time.Now() rs, err := queryer.Query(q, nil) if err != nil { rows.Error = err.Error() allRows = append(allRows, rows) continue } defer rs.Close() columns := rs.Columns() rows.Columns = columns rows.Types = rs.(*sqlite3.SQLiteRows).DeclTypes() dest := make([]driver.Value, len(rows.Columns)) for { err := rs.Next(dest) if err != nil { if err != io.EOF { rows.Error = err.Error() } break } values := normalizeRowValues(dest, rows.Types) rows.Values = append(rows.Values, values) } if xTime { rows.Time = time.Now().Sub(start).Seconds() } allRows = append(allRows, rows) } return nil }() return allRows, err }
go
func (c *Conn) Query(queries []string, tx, xTime bool) ([]*Rows, error) { stats.Add(numQueries, int64(len(queries))) if tx { stats.Add(numQTx, 1) } type Queryer interface { Query(query string, args []driver.Value) (driver.Rows, error) } var allRows []*Rows err := func() (err error) { var queryer Queryer var t driver.Tx defer func() { // XXX THIS DOESN'T ACTUALLY WORK! Might as WELL JUST COMMIT? if t != nil { if err != nil { t.Rollback() return } t.Commit() } }() queryer = c.sqlite // Create the correct query object, depending on whether a // transaction was requested. if tx { t, err = c.sqlite.Begin() if err != nil { return err } } for _, q := range queries { if q == "" { continue } rows := &Rows{} start := time.Now() rs, err := queryer.Query(q, nil) if err != nil { rows.Error = err.Error() allRows = append(allRows, rows) continue } defer rs.Close() columns := rs.Columns() rows.Columns = columns rows.Types = rs.(*sqlite3.SQLiteRows).DeclTypes() dest := make([]driver.Value, len(rows.Columns)) for { err := rs.Next(dest) if err != nil { if err != io.EOF { rows.Error = err.Error() } break } values := normalizeRowValues(dest, rows.Types) rows.Values = append(rows.Values, values) } if xTime { rows.Time = time.Now().Sub(start).Seconds() } allRows = append(allRows, rows) } return nil }() return allRows, err }
[ "func", "(", "c", "*", "Conn", ")", "Query", "(", "queries", "[", "]", "string", ",", "tx", ",", "xTime", "bool", ")", "(", "[", "]", "*", "Rows", ",", "error", ")", "{", "stats", ".", "Add", "(", "numQueries", ",", "int64", "(", "len", "(", "queries", ")", ")", ")", "\n", "if", "tx", "{", "stats", ".", "Add", "(", "numQTx", ",", "1", ")", "\n", "}", "\n", "type", "Queryer", "interface", "{", "Query", "(", "query", "string", ",", "args", "[", "]", "driver", ".", "Value", ")", "(", "driver", ".", "Rows", ",", "error", ")", "\n", "}", "\n", "var", "allRows", "[", "]", "*", "Rows", "\n", "err", ":=", "func", "(", ")", "(", "err", "error", ")", "{", "var", "queryer", "Queryer", "\n", "var", "t", "driver", ".", "Tx", "\n", "defer", "func", "(", ")", "{", "if", "t", "!=", "nil", "{", "if", "err", "!=", "nil", "{", "t", ".", "Rollback", "(", ")", "\n", "return", "\n", "}", "\n", "t", ".", "Commit", "(", ")", "\n", "}", "\n", "}", "(", ")", "\n", "queryer", "=", "c", ".", "sqlite", "\n", "if", "tx", "{", "t", ",", "err", "=", "c", ".", "sqlite", ".", "Begin", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "}", "\n", "for", "_", ",", "q", ":=", "range", "queries", "{", "if", "q", "==", "\"\"", "{", "continue", "\n", "}", "\n", "rows", ":=", "&", "Rows", "{", "}", "\n", "start", ":=", "time", ".", "Now", "(", ")", "\n", "rs", ",", "err", ":=", "queryer", ".", "Query", "(", "q", ",", "nil", ")", "\n", "if", "err", "!=", "nil", "{", "rows", ".", "Error", "=", "err", ".", "Error", "(", ")", "\n", "allRows", "=", "append", "(", "allRows", ",", "rows", ")", "\n", "continue", "\n", "}", "\n", "defer", "rs", ".", "Close", "(", ")", "\n", "columns", ":=", "rs", ".", "Columns", "(", ")", "\n", "rows", ".", "Columns", "=", "columns", "\n", "rows", ".", "Types", "=", "rs", ".", "(", "*", "sqlite3", ".", "SQLiteRows", ")", ".", "DeclTypes", "(", ")", "\n", "dest", ":=", "make", "(", "[", "]", "driver", ".", "Value", ",", "len", "(", "rows", ".", "Columns", ")", ")", "\n", "for", "{", "err", ":=", "rs", ".", "Next", "(", "dest", ")", "\n", "if", "err", "!=", "nil", "{", "if", "err", "!=", "io", ".", "EOF", "{", "rows", ".", "Error", "=", "err", ".", "Error", "(", ")", "\n", "}", "\n", "break", "\n", "}", "\n", "values", ":=", "normalizeRowValues", "(", "dest", ",", "rows", ".", "Types", ")", "\n", "rows", ".", "Values", "=", "append", "(", "rows", ".", "Values", ",", "values", ")", "\n", "}", "\n", "if", "xTime", "{", "rows", ".", "Time", "=", "time", ".", "Now", "(", ")", ".", "Sub", "(", "start", ")", ".", "Seconds", "(", ")", "\n", "}", "\n", "allRows", "=", "append", "(", "allRows", ",", "rows", ")", "\n", "}", "\n", "return", "nil", "\n", "}", "(", ")", "\n", "return", "allRows", ",", "err", "\n", "}" ]
// Query executes queries that return rows, but don't modify the database.
[ "Query", "executes", "queries", "that", "return", "rows", "but", "don", "t", "modify", "the", "database", "." ]
12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3
https://github.com/rqlite/rqlite/blob/12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3/db/db.go#L242-L320
train
rqlite/rqlite
db/db.go
EnableFKConstraints
func (c *Conn) EnableFKConstraints(e bool) error { q := fkChecksEnabled if !e { q = fkChecksDisabled } _, err := c.sqlite.Exec(q, nil) return err }
go
func (c *Conn) EnableFKConstraints(e bool) error { q := fkChecksEnabled if !e { q = fkChecksDisabled } _, err := c.sqlite.Exec(q, nil) return err }
[ "func", "(", "c", "*", "Conn", ")", "EnableFKConstraints", "(", "e", "bool", ")", "error", "{", "q", ":=", "fkChecksEnabled", "\n", "if", "!", "e", "{", "q", "=", "fkChecksDisabled", "\n", "}", "\n", "_", ",", "err", ":=", "c", ".", "sqlite", ".", "Exec", "(", "q", ",", "nil", ")", "\n", "return", "err", "\n", "}" ]
// EnableFKConstraints allows control of foreign key constraint checks.
[ "EnableFKConstraints", "allows", "control", "of", "foreign", "key", "constraint", "checks", "." ]
12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3
https://github.com/rqlite/rqlite/blob/12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3/db/db.go#L323-L330
train
rqlite/rqlite
db/db.go
FKConstraints
func (c *Conn) FKConstraints() (bool, error) { r, err := c.sqlite.Query(fkChecks, nil) if err != nil { return false, err } dest := make([]driver.Value, len(r.Columns())) types := r.(*sqlite3.SQLiteRows).DeclTypes() if err := r.Next(dest); err != nil { return false, err } values := normalizeRowValues(dest, types) if values[0] == int64(1) { return true, nil } return false, nil }
go
func (c *Conn) FKConstraints() (bool, error) { r, err := c.sqlite.Query(fkChecks, nil) if err != nil { return false, err } dest := make([]driver.Value, len(r.Columns())) types := r.(*sqlite3.SQLiteRows).DeclTypes() if err := r.Next(dest); err != nil { return false, err } values := normalizeRowValues(dest, types) if values[0] == int64(1) { return true, nil } return false, nil }
[ "func", "(", "c", "*", "Conn", ")", "FKConstraints", "(", ")", "(", "bool", ",", "error", ")", "{", "r", ",", "err", ":=", "c", ".", "sqlite", ".", "Query", "(", "fkChecks", ",", "nil", ")", "\n", "if", "err", "!=", "nil", "{", "return", "false", ",", "err", "\n", "}", "\n", "dest", ":=", "make", "(", "[", "]", "driver", ".", "Value", ",", "len", "(", "r", ".", "Columns", "(", ")", ")", ")", "\n", "types", ":=", "r", ".", "(", "*", "sqlite3", ".", "SQLiteRows", ")", ".", "DeclTypes", "(", ")", "\n", "if", "err", ":=", "r", ".", "Next", "(", "dest", ")", ";", "err", "!=", "nil", "{", "return", "false", ",", "err", "\n", "}", "\n", "values", ":=", "normalizeRowValues", "(", "dest", ",", "types", ")", "\n", "if", "values", "[", "0", "]", "==", "int64", "(", "1", ")", "{", "return", "true", ",", "nil", "\n", "}", "\n", "return", "false", ",", "nil", "\n", "}" ]
// FKConstraints returns whether FK constraints are set or not.
[ "FKConstraints", "returns", "whether", "FK", "constraints", "are", "set", "or", "not", "." ]
12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3
https://github.com/rqlite/rqlite/blob/12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3/db/db.go#L333-L350
train
rqlite/rqlite
db/db.go
Load
func (c *Conn) Load(src *Conn) error { return copyDatabase(c.sqlite, src.sqlite) }
go
func (c *Conn) Load(src *Conn) error { return copyDatabase(c.sqlite, src.sqlite) }
[ "func", "(", "c", "*", "Conn", ")", "Load", "(", "src", "*", "Conn", ")", "error", "{", "return", "copyDatabase", "(", "c", ".", "sqlite", ",", "src", ".", "sqlite", ")", "\n", "}" ]
// Load loads the connected database from the database connected to src. // It overwrites the data contained in this database. It is the caller's // responsibility to ensure that no other connections to this database // are accessed while this operation is in progress.
[ "Load", "loads", "the", "connected", "database", "from", "the", "database", "connected", "to", "src", ".", "It", "overwrites", "the", "data", "contained", "in", "this", "database", ".", "It", "is", "the", "caller", "s", "responsibility", "to", "ensure", "that", "no", "other", "connections", "to", "this", "database", "are", "accessed", "while", "this", "operation", "is", "in", "progress", "." ]
12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3
https://github.com/rqlite/rqlite/blob/12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3/db/db.go#L356-L358
train
rqlite/rqlite
db/db.go
Backup
func (c *Conn) Backup(dst *Conn) error { return copyDatabase(dst.sqlite, c.sqlite) }
go
func (c *Conn) Backup(dst *Conn) error { return copyDatabase(dst.sqlite, c.sqlite) }
[ "func", "(", "c", "*", "Conn", ")", "Backup", "(", "dst", "*", "Conn", ")", "error", "{", "return", "copyDatabase", "(", "dst", ".", "sqlite", ",", "c", ".", "sqlite", ")", "\n", "}" ]
// Backup writes a snapshot of the database over the given database // connection, erasing all the contents of the destination database. // The consistency of the snapshot is READ_COMMITTED relative to any // other connections currently open to this database. The caller must // ensure that all connections to the destination database are not // accessed during this operation.
[ "Backup", "writes", "a", "snapshot", "of", "the", "database", "over", "the", "given", "database", "connection", "erasing", "all", "the", "contents", "of", "the", "destination", "database", ".", "The", "consistency", "of", "the", "snapshot", "is", "READ_COMMITTED", "relative", "to", "any", "other", "connections", "currently", "open", "to", "this", "database", ".", "The", "caller", "must", "ensure", "that", "all", "connections", "to", "the", "destination", "database", "are", "not", "accessed", "during", "this", "operation", "." ]
12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3
https://github.com/rqlite/rqlite/blob/12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3/db/db.go#L366-L368
train
rqlite/rqlite
db/db.go
Dump
func (c *Conn) Dump(w io.Writer) error { if _, err := w.Write([]byte("PRAGMA foreign_keys=OFF;\nBEGIN TRANSACTION;\n")); err != nil { return err } // Get the schema. query := `SELECT "name", "type", "sql" FROM "sqlite_master" WHERE "sql" NOT NULL AND "type" == 'table' ORDER BY "name"` rows, err := c.Query([]string{query}, false, false) if err != nil { return err } row := rows[0] for _, v := range row.Values { table := v[0].(string) var stmt string if table == "sqlite_sequence" { stmt = `DELETE FROM "sqlite_sequence";` } else if table == "sqlite_stat1" { stmt = `ANALYZE "sqlite_master";` } else if strings.HasPrefix(table, "sqlite_") { continue } else { stmt = v[2].(string) } if _, err := w.Write([]byte(fmt.Sprintf("%s;\n", stmt))); err != nil { return err } tableIndent := strings.Replace(table, `"`, `""`, -1) query = fmt.Sprintf(`PRAGMA table_info("%s")`, tableIndent) r, err := c.Query([]string{query}, false, false) if err != nil { return err } var columnNames []string for _, w := range r[0].Values { columnNames = append(columnNames, fmt.Sprintf(`'||quote("%s")||'`, w[1].(string))) } query = fmt.Sprintf(`SELECT 'INSERT INTO "%s" VALUES(%s)' FROM "%s";`, tableIndent, strings.Join(columnNames, ","), tableIndent) r, err = c.Query([]string{query}, false, false) if err != nil { return err } for _, x := range r[0].Values { y := fmt.Sprintf("%s;\n", x[0].(string)) if _, err := w.Write([]byte(y)); err != nil { return err } } } // Do indexes, triggers, and views. query = `SELECT "name", "type", "sql" FROM "sqlite_master" WHERE "sql" NOT NULL AND "type" IN ('index', 'trigger', 'view')` rows, err = c.Query([]string{query}, false, false) if err != nil { return err } row = rows[0] for _, v := range row.Values { if _, err := w.Write([]byte(fmt.Sprintf("%s;\n", v[2]))); err != nil { return err } } if _, err := w.Write([]byte("COMMIT;\n")); err != nil { return err } return nil }
go
func (c *Conn) Dump(w io.Writer) error { if _, err := w.Write([]byte("PRAGMA foreign_keys=OFF;\nBEGIN TRANSACTION;\n")); err != nil { return err } // Get the schema. query := `SELECT "name", "type", "sql" FROM "sqlite_master" WHERE "sql" NOT NULL AND "type" == 'table' ORDER BY "name"` rows, err := c.Query([]string{query}, false, false) if err != nil { return err } row := rows[0] for _, v := range row.Values { table := v[0].(string) var stmt string if table == "sqlite_sequence" { stmt = `DELETE FROM "sqlite_sequence";` } else if table == "sqlite_stat1" { stmt = `ANALYZE "sqlite_master";` } else if strings.HasPrefix(table, "sqlite_") { continue } else { stmt = v[2].(string) } if _, err := w.Write([]byte(fmt.Sprintf("%s;\n", stmt))); err != nil { return err } tableIndent := strings.Replace(table, `"`, `""`, -1) query = fmt.Sprintf(`PRAGMA table_info("%s")`, tableIndent) r, err := c.Query([]string{query}, false, false) if err != nil { return err } var columnNames []string for _, w := range r[0].Values { columnNames = append(columnNames, fmt.Sprintf(`'||quote("%s")||'`, w[1].(string))) } query = fmt.Sprintf(`SELECT 'INSERT INTO "%s" VALUES(%s)' FROM "%s";`, tableIndent, strings.Join(columnNames, ","), tableIndent) r, err = c.Query([]string{query}, false, false) if err != nil { return err } for _, x := range r[0].Values { y := fmt.Sprintf("%s;\n", x[0].(string)) if _, err := w.Write([]byte(y)); err != nil { return err } } } // Do indexes, triggers, and views. query = `SELECT "name", "type", "sql" FROM "sqlite_master" WHERE "sql" NOT NULL AND "type" IN ('index', 'trigger', 'view')` rows, err = c.Query([]string{query}, false, false) if err != nil { return err } row = rows[0] for _, v := range row.Values { if _, err := w.Write([]byte(fmt.Sprintf("%s;\n", v[2]))); err != nil { return err } } if _, err := w.Write([]byte("COMMIT;\n")); err != nil { return err } return nil }
[ "func", "(", "c", "*", "Conn", ")", "Dump", "(", "w", "io", ".", "Writer", ")", "error", "{", "if", "_", ",", "err", ":=", "w", ".", "Write", "(", "[", "]", "byte", "(", "\"PRAGMA foreign_keys=OFF;\\nBEGIN TRANSACTION;\\n\"", ")", ")", ";", "\\n", "\\n", "\n", "err", "!=", "nil", "\n", "{", "return", "err", "\n", "}", "\n", "query", ":=", "`SELECT \"name\", \"type\", \"sql\" FROM \"sqlite_master\" WHERE \"sql\" NOT NULL AND \"type\" == 'table' ORDER BY \"name\"`", "\n", "rows", ",", "err", ":=", "c", ".", "Query", "(", "[", "]", "string", "{", "query", "}", ",", "false", ",", "false", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "row", ":=", "rows", "[", "0", "]", "\n", "for", "_", ",", "v", ":=", "range", "row", ".", "Values", "{", "table", ":=", "v", "[", "0", "]", ".", "(", "string", ")", "\n", "var", "stmt", "string", "\n", "if", "table", "==", "\"sqlite_sequence\"", "{", "stmt", "=", "`DELETE FROM \"sqlite_sequence\";`", "\n", "}", "else", "if", "table", "==", "\"sqlite_stat1\"", "{", "stmt", "=", "`ANALYZE \"sqlite_master\";`", "\n", "}", "else", "if", "strings", ".", "HasPrefix", "(", "table", ",", "\"sqlite_\"", ")", "{", "continue", "\n", "}", "else", "{", "stmt", "=", "v", "[", "2", "]", ".", "(", "string", ")", "\n", "}", "\n", "if", "_", ",", "err", ":=", "w", ".", "Write", "(", "[", "]", "byte", "(", "fmt", ".", "Sprintf", "(", "\"%s;\\n\"", ",", "\\n", ")", ")", ")", ";", "stmt", "err", "!=", "nil", "\n", "{", "return", "err", "\n", "}", "\n", "tableIndent", ":=", "strings", ".", "Replace", "(", "table", ",", "`\"`", ",", "`\"\"`", ",", "-", "1", ")", "\n", "query", "=", "fmt", ".", "Sprintf", "(", "`PRAGMA table_info(\"%s\")`", ",", "tableIndent", ")", "\n", "r", ",", "err", ":=", "c", ".", "Query", "(", "[", "]", "string", "{", "query", "}", ",", "false", ",", "false", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "var", "columnNames", "[", "]", "string", "\n", "for", "_", ",", "w", ":=", "range", "r", "[", "0", "]", ".", "Values", "{", "columnNames", "=", "append", "(", "columnNames", ",", "fmt", ".", "Sprintf", "(", "`'||quote(\"%s\")||'`", ",", "w", "[", "1", "]", ".", "(", "string", ")", ")", ")", "\n", "}", "\n", "query", "=", "fmt", ".", "Sprintf", "(", "`SELECT 'INSERT INTO \"%s\" VALUES(%s)' FROM \"%s\";`", ",", "tableIndent", ",", "strings", ".", "Join", "(", "columnNames", ",", "\",\"", ")", ",", "tableIndent", ")", "\n", "r", ",", "err", "=", "c", ".", "Query", "(", "[", "]", "string", "{", "query", "}", ",", "false", ",", "false", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "}", "\n", "for", "_", ",", "x", ":=", "range", "r", "[", "0", "]", ".", "Values", "{", "y", ":=", "fmt", ".", "Sprintf", "(", "\"%s;\\n\"", ",", "\\n", ")", "\n", "x", "[", "0", "]", ".", "(", "string", ")", "\n", "}", "\n", "if", "_", ",", "err", ":=", "w", ".", "Write", "(", "[", "]", "byte", "(", "y", ")", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "query", "=", "`SELECT \"name\", \"type\", \"sql\" FROM \"sqlite_master\"\t\t\t WHERE \"sql\" NOT NULL AND \"type\" IN ('index', 'trigger', 'view')`", "\n", "rows", ",", "err", "=", "c", ".", "Query", "(", "[", "]", "string", "{", "query", "}", ",", "false", ",", "false", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "}" ]
// Dump writes a snapshot of the database in SQL text format. The consistency // of the snapshot is READ_COMMITTED relative to any other connections // currently open to this database.
[ "Dump", "writes", "a", "snapshot", "of", "the", "database", "in", "SQL", "text", "format", ".", "The", "consistency", "of", "the", "snapshot", "is", "READ_COMMITTED", "relative", "to", "any", "other", "connections", "currently", "open", "to", "this", "database", "." ]
12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3
https://github.com/rqlite/rqlite/blob/12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3/db/db.go#L373-L450
train
rqlite/rqlite
cmd/rqlite/main.go
cliJSON
func cliJSON(ctx *cli.Context, cmd, line, url string, argv *argT) error { // Recursive JSON printer. var pprint func(indent int, m map[string]interface{}) pprint = func(indent int, m map[string]interface{}) { indentation := " " for k, v := range m { if v == nil { continue } switch v.(type) { case map[string]interface{}: for i := 0; i < indent; i++ { fmt.Print(indentation) } fmt.Printf("%s:\n", k) pprint(indent+1, v.(map[string]interface{})) default: for i := 0; i < indent; i++ { fmt.Print(indentation) } fmt.Printf("%s: %v\n", k, v) } } } client := http.Client{Transport: &http.Transport{ TLSClientConfig: &tls.Config{InsecureSkipVerify: argv.Insecure}, }} resp, err := client.Get(url) if err != nil { return err } defer resp.Body.Close() if resp.StatusCode == http.StatusUnauthorized { return fmt.Errorf("unauthorized") } body, err := ioutil.ReadAll(resp.Body) if err != nil { return err } ret := make(map[string]interface{}) if err := json.Unmarshal(body, &ret); err != nil { return err } // Specific key requested? parts := strings.Split(line, " ") if len(parts) >= 2 { ret = map[string]interface{}{parts[1]: ret[parts[1]]} } pprint(0, ret) return nil }
go
func cliJSON(ctx *cli.Context, cmd, line, url string, argv *argT) error { // Recursive JSON printer. var pprint func(indent int, m map[string]interface{}) pprint = func(indent int, m map[string]interface{}) { indentation := " " for k, v := range m { if v == nil { continue } switch v.(type) { case map[string]interface{}: for i := 0; i < indent; i++ { fmt.Print(indentation) } fmt.Printf("%s:\n", k) pprint(indent+1, v.(map[string]interface{})) default: for i := 0; i < indent; i++ { fmt.Print(indentation) } fmt.Printf("%s: %v\n", k, v) } } } client := http.Client{Transport: &http.Transport{ TLSClientConfig: &tls.Config{InsecureSkipVerify: argv.Insecure}, }} resp, err := client.Get(url) if err != nil { return err } defer resp.Body.Close() if resp.StatusCode == http.StatusUnauthorized { return fmt.Errorf("unauthorized") } body, err := ioutil.ReadAll(resp.Body) if err != nil { return err } ret := make(map[string]interface{}) if err := json.Unmarshal(body, &ret); err != nil { return err } // Specific key requested? parts := strings.Split(line, " ") if len(parts) >= 2 { ret = map[string]interface{}{parts[1]: ret[parts[1]]} } pprint(0, ret) return nil }
[ "func", "cliJSON", "(", "ctx", "*", "cli", ".", "Context", ",", "cmd", ",", "line", ",", "url", "string", ",", "argv", "*", "argT", ")", "error", "{", "var", "pprint", "func", "(", "indent", "int", ",", "m", "map", "[", "string", "]", "interface", "{", "}", ")", "\n", "pprint", "=", "func", "(", "indent", "int", ",", "m", "map", "[", "string", "]", "interface", "{", "}", ")", "{", "indentation", ":=", "\" \"", "\n", "for", "k", ",", "v", ":=", "range", "m", "{", "if", "v", "==", "nil", "{", "continue", "\n", "}", "\n", "switch", "v", ".", "(", "type", ")", "{", "case", "map", "[", "string", "]", "interface", "{", "}", ":", "for", "i", ":=", "0", ";", "i", "<", "indent", ";", "i", "++", "{", "fmt", ".", "Print", "(", "indentation", ")", "\n", "}", "\n", "fmt", ".", "Printf", "(", "\"%s:\\n\"", ",", "\\n", ")", "\n", "k", "\n", "pprint", "(", "indent", "+", "1", ",", "v", ".", "(", "map", "[", "string", "]", "interface", "{", "}", ")", ")", "}", "\n", "}", "\n", "}", "\n", "default", ":", "for", "i", ":=", "0", ";", "i", "<", "indent", ";", "i", "++", "{", "fmt", ".", "Print", "(", "indentation", ")", "\n", "}", "\n", "fmt", ".", "Printf", "(", "\"%s: %v\\n\"", ",", "\\n", ",", "k", ")", "\n", "\n", "v", "\n", "client", ":=", "http", ".", "Client", "{", "Transport", ":", "&", "http", ".", "Transport", "{", "TLSClientConfig", ":", "&", "tls", ".", "Config", "{", "InsecureSkipVerify", ":", "argv", ".", "Insecure", "}", ",", "}", "}", "\n", "resp", ",", "err", ":=", "client", ".", "Get", "(", "url", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "defer", "resp", ".", "Body", ".", "Close", "(", ")", "\n", "if", "resp", ".", "StatusCode", "==", "http", ".", "StatusUnauthorized", "{", "return", "fmt", ".", "Errorf", "(", "\"unauthorized\"", ")", "\n", "}", "\n", "body", ",", "err", ":=", "ioutil", ".", "ReadAll", "(", "resp", ".", "Body", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "ret", ":=", "make", "(", "map", "[", "string", "]", "interface", "{", "}", ")", "\n", "if", "err", ":=", "json", ".", "Unmarshal", "(", "body", ",", "&", "ret", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "parts", ":=", "strings", ".", "Split", "(", "line", ",", "\" \"", ")", "\n", "if", "len", "(", "parts", ")", ">=", "2", "{", "ret", "=", "map", "[", "string", "]", "interface", "{", "}", "{", "parts", "[", "1", "]", ":", "ret", "[", "parts", "[", "1", "]", "]", "}", "\n", "}", "\n", "}" ]
// cliJSON fetches JSON from a URL, and displays it at the CLI.
[ "cliJSON", "fetches", "JSON", "from", "a", "URL", "and", "displays", "it", "at", "the", "CLI", "." ]
12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3
https://github.com/rqlite/rqlite/blob/12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3/cmd/rqlite/main.go#L233-L289
train
rqlite/rqlite
disco/client.go
New
func New(url string) *Client { return &Client{ url: url, logger: log.New(os.Stderr, "[discovery] ", log.LstdFlags), } }
go
func New(url string) *Client { return &Client{ url: url, logger: log.New(os.Stderr, "[discovery] ", log.LstdFlags), } }
[ "func", "New", "(", "url", "string", ")", "*", "Client", "{", "return", "&", "Client", "{", "url", ":", "url", ",", "logger", ":", "log", ".", "New", "(", "os", ".", "Stderr", ",", "\"[discovery] \"", ",", "log", ".", "LstdFlags", ")", ",", "}", "\n", "}" ]
// New returns an initialized Discovery Service client.
[ "New", "returns", "an", "initialized", "Discovery", "Service", "client", "." ]
12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3
https://github.com/rqlite/rqlite/blob/12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3/disco/client.go#L29-L34
train
rqlite/rqlite
disco/client.go
Register
func (c *Client) Register(id, addr string) (*Response, error) { m := map[string]string{ "addr": addr, } url := c.registrationURL(c.url, id) client := &http.Client{} client.CheckRedirect = func(req *http.Request, via []*http.Request) error { return http.ErrUseLastResponse } for { b, err := json.Marshal(m) if err != nil { return nil, err } c.logger.Printf("discovery client attempting registration of %s at %s", addr, url) resp, err := client.Post(url, "application-type/json", bytes.NewReader(b)) if err != nil { return nil, err } defer resp.Body.Close() b, err = ioutil.ReadAll(resp.Body) if err != nil { return nil, err } switch resp.StatusCode { case http.StatusOK: r := &Response{} if err := json.Unmarshal(b, r); err != nil { return nil, err } c.logger.Printf("discovery client successfully registered %s at %s", addr, url) return r, nil case http.StatusMovedPermanently: url = resp.Header.Get("location") c.logger.Println("discovery client redirecting to", url) continue default: return nil, errors.New(resp.Status) } } }
go
func (c *Client) Register(id, addr string) (*Response, error) { m := map[string]string{ "addr": addr, } url := c.registrationURL(c.url, id) client := &http.Client{} client.CheckRedirect = func(req *http.Request, via []*http.Request) error { return http.ErrUseLastResponse } for { b, err := json.Marshal(m) if err != nil { return nil, err } c.logger.Printf("discovery client attempting registration of %s at %s", addr, url) resp, err := client.Post(url, "application-type/json", bytes.NewReader(b)) if err != nil { return nil, err } defer resp.Body.Close() b, err = ioutil.ReadAll(resp.Body) if err != nil { return nil, err } switch resp.StatusCode { case http.StatusOK: r := &Response{} if err := json.Unmarshal(b, r); err != nil { return nil, err } c.logger.Printf("discovery client successfully registered %s at %s", addr, url) return r, nil case http.StatusMovedPermanently: url = resp.Header.Get("location") c.logger.Println("discovery client redirecting to", url) continue default: return nil, errors.New(resp.Status) } } }
[ "func", "(", "c", "*", "Client", ")", "Register", "(", "id", ",", "addr", "string", ")", "(", "*", "Response", ",", "error", ")", "{", "m", ":=", "map", "[", "string", "]", "string", "{", "\"addr\"", ":", "addr", ",", "}", "\n", "url", ":=", "c", ".", "registrationURL", "(", "c", ".", "url", ",", "id", ")", "\n", "client", ":=", "&", "http", ".", "Client", "{", "}", "\n", "client", ".", "CheckRedirect", "=", "func", "(", "req", "*", "http", ".", "Request", ",", "via", "[", "]", "*", "http", ".", "Request", ")", "error", "{", "return", "http", ".", "ErrUseLastResponse", "\n", "}", "\n", "for", "{", "b", ",", "err", ":=", "json", ".", "Marshal", "(", "m", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "c", ".", "logger", ".", "Printf", "(", "\"discovery client attempting registration of %s at %s\"", ",", "addr", ",", "url", ")", "\n", "resp", ",", "err", ":=", "client", ".", "Post", "(", "url", ",", "\"application-type/json\"", ",", "bytes", ".", "NewReader", "(", "b", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "defer", "resp", ".", "Body", ".", "Close", "(", ")", "\n", "b", ",", "err", "=", "ioutil", ".", "ReadAll", "(", "resp", ".", "Body", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "switch", "resp", ".", "StatusCode", "{", "case", "http", ".", "StatusOK", ":", "r", ":=", "&", "Response", "{", "}", "\n", "if", "err", ":=", "json", ".", "Unmarshal", "(", "b", ",", "r", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "c", ".", "logger", ".", "Printf", "(", "\"discovery client successfully registered %s at %s\"", ",", "addr", ",", "url", ")", "\n", "return", "r", ",", "nil", "\n", "case", "http", ".", "StatusMovedPermanently", ":", "url", "=", "resp", ".", "Header", ".", "Get", "(", "\"location\"", ")", "\n", "c", ".", "logger", ".", "Println", "(", "\"discovery client redirecting to\"", ",", "url", ")", "\n", "continue", "\n", "default", ":", "return", "nil", ",", "errors", ".", "New", "(", "resp", ".", "Status", ")", "\n", "}", "\n", "}", "\n", "}" ]
// Register attempts to register with the Discovery Service, using the given // address.
[ "Register", "attempts", "to", "register", "with", "the", "Discovery", "Service", "using", "the", "given", "address", "." ]
12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3
https://github.com/rqlite/rqlite/blob/12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3/disco/client.go#L43-L88
train
rqlite/rqlite
cmd/rqlited/main.go
startProfile
func startProfile(cpuprofile, memprofile string) { if cpuprofile != "" { f, err := os.Create(cpuprofile) if err != nil { log.Fatalf("failed to create CPU profile file at %s: %s", cpuprofile, err.Error()) } log.Printf("writing CPU profile to: %s\n", cpuprofile) prof.cpu = f pprof.StartCPUProfile(prof.cpu) } if memprofile != "" { f, err := os.Create(memprofile) if err != nil { log.Fatalf("failed to create memory profile file at %s: %s", cpuprofile, err.Error()) } log.Printf("writing memory profile to: %s\n", memprofile) prof.mem = f runtime.MemProfileRate = 4096 } }
go
func startProfile(cpuprofile, memprofile string) { if cpuprofile != "" { f, err := os.Create(cpuprofile) if err != nil { log.Fatalf("failed to create CPU profile file at %s: %s", cpuprofile, err.Error()) } log.Printf("writing CPU profile to: %s\n", cpuprofile) prof.cpu = f pprof.StartCPUProfile(prof.cpu) } if memprofile != "" { f, err := os.Create(memprofile) if err != nil { log.Fatalf("failed to create memory profile file at %s: %s", cpuprofile, err.Error()) } log.Printf("writing memory profile to: %s\n", memprofile) prof.mem = f runtime.MemProfileRate = 4096 } }
[ "func", "startProfile", "(", "cpuprofile", ",", "memprofile", "string", ")", "{", "if", "cpuprofile", "!=", "\"\"", "{", "f", ",", "err", ":=", "os", ".", "Create", "(", "cpuprofile", ")", "\n", "if", "err", "!=", "nil", "{", "log", ".", "Fatalf", "(", "\"failed to create CPU profile file at %s: %s\"", ",", "cpuprofile", ",", "err", ".", "Error", "(", ")", ")", "\n", "}", "\n", "log", ".", "Printf", "(", "\"writing CPU profile to: %s\\n\"", ",", "\\n", ")", "\n", "cpuprofile", "\n", "prof", ".", "cpu", "=", "f", "\n", "}", "\n", "pprof", ".", "StartCPUProfile", "(", "prof", ".", "cpu", ")", "\n", "}" ]
// startProfile initializes the CPU and memory profile, if specified.
[ "startProfile", "initializes", "the", "CPU", "and", "memory", "profile", "if", "specified", "." ]
12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3
https://github.com/rqlite/rqlite/blob/12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3/cmd/rqlited/main.go#L374-L394
train
rqlite/rqlite
cmd/rqlited/main.go
stopProfile
func stopProfile() { if prof.cpu != nil { pprof.StopCPUProfile() prof.cpu.Close() log.Println("CPU profiling stopped") } if prof.mem != nil { pprof.Lookup("heap").WriteTo(prof.mem, 0) prof.mem.Close() log.Println("memory profiling stopped") } }
go
func stopProfile() { if prof.cpu != nil { pprof.StopCPUProfile() prof.cpu.Close() log.Println("CPU profiling stopped") } if prof.mem != nil { pprof.Lookup("heap").WriteTo(prof.mem, 0) prof.mem.Close() log.Println("memory profiling stopped") } }
[ "func", "stopProfile", "(", ")", "{", "if", "prof", ".", "cpu", "!=", "nil", "{", "pprof", ".", "StopCPUProfile", "(", ")", "\n", "prof", ".", "cpu", ".", "Close", "(", ")", "\n", "log", ".", "Println", "(", "\"CPU profiling stopped\"", ")", "\n", "}", "\n", "if", "prof", ".", "mem", "!=", "nil", "{", "pprof", ".", "Lookup", "(", "\"heap\"", ")", ".", "WriteTo", "(", "prof", ".", "mem", ",", "0", ")", "\n", "prof", ".", "mem", ".", "Close", "(", ")", "\n", "log", ".", "Println", "(", "\"memory profiling stopped\"", ")", "\n", "}", "\n", "}" ]
// stopProfile closes the CPU and memory profiles if they are running.
[ "stopProfile", "closes", "the", "CPU", "and", "memory", "profiles", "if", "they", "are", "running", "." ]
12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3
https://github.com/rqlite/rqlite/blob/12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3/cmd/rqlited/main.go#L397-L408
train
rqlite/rqlite
cluster/join.go
Join
func Join(joinAddr []string, id, addr string, meta map[string]string, skip bool) (string, error) { var err error var j string logger := log.New(os.Stderr, "[cluster-join] ", log.LstdFlags) for i := 0; i < numAttempts; i++ { for _, a := range joinAddr { j, err = join(a, id, addr, meta, skip) if err == nil { // Success! return j, nil } } logger.Printf("failed to join cluster at %s, sleeping %s before retry", joinAddr, attemptInterval) time.Sleep(attemptInterval) } logger.Printf("failed to join cluster at %s, after %d attempts", joinAddr, numAttempts) return "", err }
go
func Join(joinAddr []string, id, addr string, meta map[string]string, skip bool) (string, error) { var err error var j string logger := log.New(os.Stderr, "[cluster-join] ", log.LstdFlags) for i := 0; i < numAttempts; i++ { for _, a := range joinAddr { j, err = join(a, id, addr, meta, skip) if err == nil { // Success! return j, nil } } logger.Printf("failed to join cluster at %s, sleeping %s before retry", joinAddr, attemptInterval) time.Sleep(attemptInterval) } logger.Printf("failed to join cluster at %s, after %d attempts", joinAddr, numAttempts) return "", err }
[ "func", "Join", "(", "joinAddr", "[", "]", "string", ",", "id", ",", "addr", "string", ",", "meta", "map", "[", "string", "]", "string", ",", "skip", "bool", ")", "(", "string", ",", "error", ")", "{", "var", "err", "error", "\n", "var", "j", "string", "\n", "logger", ":=", "log", ".", "New", "(", "os", ".", "Stderr", ",", "\"[cluster-join] \"", ",", "log", ".", "LstdFlags", ")", "\n", "for", "i", ":=", "0", ";", "i", "<", "numAttempts", ";", "i", "++", "{", "for", "_", ",", "a", ":=", "range", "joinAddr", "{", "j", ",", "err", "=", "join", "(", "a", ",", "id", ",", "addr", ",", "meta", ",", "skip", ")", "\n", "if", "err", "==", "nil", "{", "return", "j", ",", "nil", "\n", "}", "\n", "}", "\n", "logger", ".", "Printf", "(", "\"failed to join cluster at %s, sleeping %s before retry\"", ",", "joinAddr", ",", "attemptInterval", ")", "\n", "time", ".", "Sleep", "(", "attemptInterval", ")", "\n", "}", "\n", "logger", ".", "Printf", "(", "\"failed to join cluster at %s, after %d attempts\"", ",", "joinAddr", ",", "numAttempts", ")", "\n", "return", "\"\"", ",", "err", "\n", "}" ]
// Join attempts to join the cluster at one of the addresses given in joinAddr. // It walks through joinAddr in order, and sets the node ID and Raft address of // the joining node as id addr respectively. It returns the endpoint // successfully used to join the cluster.
[ "Join", "attempts", "to", "join", "the", "cluster", "at", "one", "of", "the", "addresses", "given", "in", "joinAddr", ".", "It", "walks", "through", "joinAddr", "in", "order", "and", "sets", "the", "node", "ID", "and", "Raft", "address", "of", "the", "joining", "node", "as", "id", "addr", "respectively", ".", "It", "returns", "the", "endpoint", "successfully", "used", "to", "join", "the", "cluster", "." ]
12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3
https://github.com/rqlite/rqlite/blob/12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3/cluster/join.go#L25-L43
train
rqlite/rqlite
cmd/rqlite/query.go
Get
func (r *Rows) Get(i, j int) string { if i == 0 { if j >= len(r.Columns) { return "" } return r.Columns[j] } if r.Values == nil { return "NULL" } if i-1 >= len(r.Values) { return "NULL" } if j >= len(r.Values[i-1]) { return "NULL" } return fmt.Sprintf("%v", r.Values[i-1][j]) }
go
func (r *Rows) Get(i, j int) string { if i == 0 { if j >= len(r.Columns) { return "" } return r.Columns[j] } if r.Values == nil { return "NULL" } if i-1 >= len(r.Values) { return "NULL" } if j >= len(r.Values[i-1]) { return "NULL" } return fmt.Sprintf("%v", r.Values[i-1][j]) }
[ "func", "(", "r", "*", "Rows", ")", "Get", "(", "i", ",", "j", "int", ")", "string", "{", "if", "i", "==", "0", "{", "if", "j", ">=", "len", "(", "r", ".", "Columns", ")", "{", "return", "\"\"", "\n", "}", "\n", "return", "r", ".", "Columns", "[", "j", "]", "\n", "}", "\n", "if", "r", ".", "Values", "==", "nil", "{", "return", "\"NULL\"", "\n", "}", "\n", "if", "i", "-", "1", ">=", "len", "(", "r", ".", "Values", ")", "{", "return", "\"NULL\"", "\n", "}", "\n", "if", "j", ">=", "len", "(", "r", ".", "Values", "[", "i", "-", "1", "]", ")", "{", "return", "\"NULL\"", "\n", "}", "\n", "return", "fmt", ".", "Sprintf", "(", "\"%v\"", ",", "r", ".", "Values", "[", "i", "-", "1", "]", "[", "j", "]", ")", "\n", "}" ]
// Get implements textutil.Table interface
[ "Get", "implements", "textutil", ".", "Table", "interface" ]
12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3
https://github.com/rqlite/rqlite/blob/12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3/cmd/rqlite/query.go#L33-L52
train
rqlite/rqlite
auth/credential_store.go
NewCredentialsStore
func NewCredentialsStore() *CredentialsStore { return &CredentialsStore{ store: make(map[string]string), perms: make(map[string]map[string]bool), } }
go
func NewCredentialsStore() *CredentialsStore { return &CredentialsStore{ store: make(map[string]string), perms: make(map[string]map[string]bool), } }
[ "func", "NewCredentialsStore", "(", ")", "*", "CredentialsStore", "{", "return", "&", "CredentialsStore", "{", "store", ":", "make", "(", "map", "[", "string", "]", "string", ")", ",", "perms", ":", "make", "(", "map", "[", "string", "]", "map", "[", "string", "]", "bool", ")", ",", "}", "\n", "}" ]
// NewCredentialsStore returns a new instance of a CredentialStore.
[ "NewCredentialsStore", "returns", "a", "new", "instance", "of", "a", "CredentialStore", "." ]
12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3
https://github.com/rqlite/rqlite/blob/12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3/auth/credential_store.go#L31-L36
train
rqlite/rqlite
auth/credential_store.go
Load
func (c *CredentialsStore) Load(r io.Reader) error { dec := json.NewDecoder(r) // Read open bracket _, err := dec.Token() if err != nil { return err } var cred Credential for dec.More() { err := dec.Decode(&cred) if err != nil { return err } c.store[cred.Username] = cred.Password c.perms[cred.Username] = make(map[string]bool, len(cred.Perms)) for _, p := range cred.Perms { c.perms[cred.Username][p] = true } } // Read closing bracket. _, err = dec.Token() if err != nil { return err } return nil }
go
func (c *CredentialsStore) Load(r io.Reader) error { dec := json.NewDecoder(r) // Read open bracket _, err := dec.Token() if err != nil { return err } var cred Credential for dec.More() { err := dec.Decode(&cred) if err != nil { return err } c.store[cred.Username] = cred.Password c.perms[cred.Username] = make(map[string]bool, len(cred.Perms)) for _, p := range cred.Perms { c.perms[cred.Username][p] = true } } // Read closing bracket. _, err = dec.Token() if err != nil { return err } return nil }
[ "func", "(", "c", "*", "CredentialsStore", ")", "Load", "(", "r", "io", ".", "Reader", ")", "error", "{", "dec", ":=", "json", ".", "NewDecoder", "(", "r", ")", "\n", "_", ",", "err", ":=", "dec", ".", "Token", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "var", "cred", "Credential", "\n", "for", "dec", ".", "More", "(", ")", "{", "err", ":=", "dec", ".", "Decode", "(", "&", "cred", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "c", ".", "store", "[", "cred", ".", "Username", "]", "=", "cred", ".", "Password", "\n", "c", ".", "perms", "[", "cred", ".", "Username", "]", "=", "make", "(", "map", "[", "string", "]", "bool", ",", "len", "(", "cred", ".", "Perms", ")", ")", "\n", "for", "_", ",", "p", ":=", "range", "cred", ".", "Perms", "{", "c", ".", "perms", "[", "cred", ".", "Username", "]", "[", "p", "]", "=", "true", "\n", "}", "\n", "}", "\n", "_", ",", "err", "=", "dec", ".", "Token", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// Load loads credential information from a reader.
[ "Load", "loads", "credential", "information", "from", "a", "reader", "." ]
12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3
https://github.com/rqlite/rqlite/blob/12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3/auth/credential_store.go#L39-L67
train
rqlite/rqlite
auth/credential_store.go
Check
func (c *CredentialsStore) Check(username, password string) bool { pw, ok := c.store[username] if !ok { return false } return password == pw || bcrypt.CompareHashAndPassword([]byte(pw), []byte(password)) == nil }
go
func (c *CredentialsStore) Check(username, password string) bool { pw, ok := c.store[username] if !ok { return false } return password == pw || bcrypt.CompareHashAndPassword([]byte(pw), []byte(password)) == nil }
[ "func", "(", "c", "*", "CredentialsStore", ")", "Check", "(", "username", ",", "password", "string", ")", "bool", "{", "pw", ",", "ok", ":=", "c", ".", "store", "[", "username", "]", "\n", "if", "!", "ok", "{", "return", "false", "\n", "}", "\n", "return", "password", "==", "pw", "||", "bcrypt", ".", "CompareHashAndPassword", "(", "[", "]", "byte", "(", "pw", ")", ",", "[", "]", "byte", "(", "password", ")", ")", "==", "nil", "\n", "}" ]
// Check returns true if the password is correct for the given username.
[ "Check", "returns", "true", "if", "the", "password", "is", "correct", "for", "the", "given", "username", "." ]
12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3
https://github.com/rqlite/rqlite/blob/12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3/auth/credential_store.go#L70-L77
train
rqlite/rqlite
auth/credential_store.go
CheckRequest
func (c *CredentialsStore) CheckRequest(b BasicAuther) bool { username, password, ok := b.BasicAuth() if !ok || !c.Check(username, password) { return false } return true }
go
func (c *CredentialsStore) CheckRequest(b BasicAuther) bool { username, password, ok := b.BasicAuth() if !ok || !c.Check(username, password) { return false } return true }
[ "func", "(", "c", "*", "CredentialsStore", ")", "CheckRequest", "(", "b", "BasicAuther", ")", "bool", "{", "username", ",", "password", ",", "ok", ":=", "b", ".", "BasicAuth", "(", ")", "\n", "if", "!", "ok", "||", "!", "c", ".", "Check", "(", "username", ",", "password", ")", "{", "return", "false", "\n", "}", "\n", "return", "true", "\n", "}" ]
// CheckRequest returns true if b contains a valid username and password.
[ "CheckRequest", "returns", "true", "if", "b", "contains", "a", "valid", "username", "and", "password", "." ]
12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3
https://github.com/rqlite/rqlite/blob/12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3/auth/credential_store.go#L80-L86
train
rqlite/rqlite
auth/credential_store.go
HasPerm
func (c *CredentialsStore) HasPerm(username string, perm string) bool { m, ok := c.perms[username] if !ok { return false } if _, ok := m[perm]; !ok { return false } return true }
go
func (c *CredentialsStore) HasPerm(username string, perm string) bool { m, ok := c.perms[username] if !ok { return false } if _, ok := m[perm]; !ok { return false } return true }
[ "func", "(", "c", "*", "CredentialsStore", ")", "HasPerm", "(", "username", "string", ",", "perm", "string", ")", "bool", "{", "m", ",", "ok", ":=", "c", ".", "perms", "[", "username", "]", "\n", "if", "!", "ok", "{", "return", "false", "\n", "}", "\n", "if", "_", ",", "ok", ":=", "m", "[", "perm", "]", ";", "!", "ok", "{", "return", "false", "\n", "}", "\n", "return", "true", "\n", "}" ]
// HasPerm returns true if username has the given perm. It does not // perform any password checking.
[ "HasPerm", "returns", "true", "if", "username", "has", "the", "given", "perm", ".", "It", "does", "not", "perform", "any", "password", "checking", "." ]
12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3
https://github.com/rqlite/rqlite/blob/12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3/auth/credential_store.go#L90-L100
train
rqlite/rqlite
auth/credential_store.go
HasAnyPerm
func (c *CredentialsStore) HasAnyPerm(username string, perm ...string) bool { return func(p []string) bool { for i := range p { if c.HasPerm(username, p[i]) { return true } } return false }(perm) }
go
func (c *CredentialsStore) HasAnyPerm(username string, perm ...string) bool { return func(p []string) bool { for i := range p { if c.HasPerm(username, p[i]) { return true } } return false }(perm) }
[ "func", "(", "c", "*", "CredentialsStore", ")", "HasAnyPerm", "(", "username", "string", ",", "perm", "...", "string", ")", "bool", "{", "return", "func", "(", "p", "[", "]", "string", ")", "bool", "{", "for", "i", ":=", "range", "p", "{", "if", "c", ".", "HasPerm", "(", "username", ",", "p", "[", "i", "]", ")", "{", "return", "true", "\n", "}", "\n", "}", "\n", "return", "false", "\n", "}", "(", "perm", ")", "\n", "}" ]
// HasAnyPerm returns true if username has at least one of the given perms. // It does not perform any password checking.
[ "HasAnyPerm", "returns", "true", "if", "username", "has", "at", "least", "one", "of", "the", "given", "perms", ".", "It", "does", "not", "perform", "any", "password", "checking", "." ]
12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3
https://github.com/rqlite/rqlite/blob/12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3/auth/credential_store.go#L104-L113
train
rqlite/rqlite
auth/credential_store.go
HasPermRequest
func (c *CredentialsStore) HasPermRequest(b BasicAuther, perm string) bool { username, _, ok := b.BasicAuth() if !ok { return false } return c.HasPerm(username, perm) }
go
func (c *CredentialsStore) HasPermRequest(b BasicAuther, perm string) bool { username, _, ok := b.BasicAuth() if !ok { return false } return c.HasPerm(username, perm) }
[ "func", "(", "c", "*", "CredentialsStore", ")", "HasPermRequest", "(", "b", "BasicAuther", ",", "perm", "string", ")", "bool", "{", "username", ",", "_", ",", "ok", ":=", "b", ".", "BasicAuth", "(", ")", "\n", "if", "!", "ok", "{", "return", "false", "\n", "}", "\n", "return", "c", ".", "HasPerm", "(", "username", ",", "perm", ")", "\n", "}" ]
// HasPermRequest returns true if the username returned by b has the givem perm. // It does not perform any password checking, but if there is no username // in the request, it returns false.
[ "HasPermRequest", "returns", "true", "if", "the", "username", "returned", "by", "b", "has", "the", "givem", "perm", ".", "It", "does", "not", "perform", "any", "password", "checking", "but", "if", "there", "is", "no", "username", "in", "the", "request", "it", "returns", "false", "." ]
12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3
https://github.com/rqlite/rqlite/blob/12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3/auth/credential_store.go#L118-L124
train
rqlite/rqlite
store/connection.go
NewConnection
func NewConnection(c *sdb.Conn, s *Store, id uint64, it, tt time.Duration) *Connection { now := time.Now() conn := Connection{ db: c, store: s, ID: id, CreatedAt: now, LastUsedAt: now, IdleTimeout: it, TxTimeout: tt, logger: log.New(os.Stderr, connectionLogPrefix(id), log.LstdFlags), } return &conn }
go
func NewConnection(c *sdb.Conn, s *Store, id uint64, it, tt time.Duration) *Connection { now := time.Now() conn := Connection{ db: c, store: s, ID: id, CreatedAt: now, LastUsedAt: now, IdleTimeout: it, TxTimeout: tt, logger: log.New(os.Stderr, connectionLogPrefix(id), log.LstdFlags), } return &conn }
[ "func", "NewConnection", "(", "c", "*", "sdb", ".", "Conn", ",", "s", "*", "Store", ",", "id", "uint64", ",", "it", ",", "tt", "time", ".", "Duration", ")", "*", "Connection", "{", "now", ":=", "time", ".", "Now", "(", ")", "\n", "conn", ":=", "Connection", "{", "db", ":", "c", ",", "store", ":", "s", ",", "ID", ":", "id", ",", "CreatedAt", ":", "now", ",", "LastUsedAt", ":", "now", ",", "IdleTimeout", ":", "it", ",", "TxTimeout", ":", "tt", ",", "logger", ":", "log", ".", "New", "(", "os", ".", "Stderr", ",", "connectionLogPrefix", "(", "id", ")", ",", "log", ".", "LstdFlags", ")", ",", "}", "\n", "return", "&", "conn", "\n", "}" ]
// NewConnection returns a connection to the database.
[ "NewConnection", "returns", "a", "connection", "to", "the", "database", "." ]
12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3
https://github.com/rqlite/rqlite/blob/12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3/store/connection.go#L41-L54
train
rqlite/rqlite
store/connection.go
Restore
func (c *Connection) Restore(dbConn *sdb.Conn, s *Store) { c.dbMu.Lock() defer c.dbMu.Unlock() c.db = dbConn c.store = s c.logger = log.New(os.Stderr, connectionLogPrefix(c.ID), log.LstdFlags) }
go
func (c *Connection) Restore(dbConn *sdb.Conn, s *Store) { c.dbMu.Lock() defer c.dbMu.Unlock() c.db = dbConn c.store = s c.logger = log.New(os.Stderr, connectionLogPrefix(c.ID), log.LstdFlags) }
[ "func", "(", "c", "*", "Connection", ")", "Restore", "(", "dbConn", "*", "sdb", ".", "Conn", ",", "s", "*", "Store", ")", "{", "c", ".", "dbMu", ".", "Lock", "(", ")", "\n", "defer", "c", ".", "dbMu", ".", "Unlock", "(", ")", "\n", "c", ".", "db", "=", "dbConn", "\n", "c", ".", "store", "=", "s", "\n", "c", ".", "logger", "=", "log", ".", "New", "(", "os", ".", "Stderr", ",", "connectionLogPrefix", "(", "c", ".", "ID", ")", ",", "log", ".", "LstdFlags", ")", "\n", "}" ]
// Restore prepares a partially ready connection.
[ "Restore", "prepares", "a", "partially", "ready", "connection", "." ]
12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3
https://github.com/rqlite/rqlite/blob/12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3/store/connection.go#L57-L63
train
rqlite/rqlite
store/connection.go
SetLastUsedNow
func (c *Connection) SetLastUsedNow() { c.timeMu.Lock() defer c.timeMu.Unlock() c.LastUsedAt = time.Now() }
go
func (c *Connection) SetLastUsedNow() { c.timeMu.Lock() defer c.timeMu.Unlock() c.LastUsedAt = time.Now() }
[ "func", "(", "c", "*", "Connection", ")", "SetLastUsedNow", "(", ")", "{", "c", ".", "timeMu", ".", "Lock", "(", ")", "\n", "defer", "c", ".", "timeMu", ".", "Unlock", "(", ")", "\n", "c", ".", "LastUsedAt", "=", "time", ".", "Now", "(", ")", "\n", "}" ]
// SetLastUsedNow marks the connection as being used now.
[ "SetLastUsedNow", "marks", "the", "connection", "as", "being", "used", "now", "." ]
12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3
https://github.com/rqlite/rqlite/blob/12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3/store/connection.go#L66-L70
train
rqlite/rqlite
store/connection.go
TransactionActive
func (c *Connection) TransactionActive() bool { c.dbMu.RLock() defer c.dbMu.RUnlock() if c.db == nil { return false } return c.db.TransactionActive() }
go
func (c *Connection) TransactionActive() bool { c.dbMu.RLock() defer c.dbMu.RUnlock() if c.db == nil { return false } return c.db.TransactionActive() }
[ "func", "(", "c", "*", "Connection", ")", "TransactionActive", "(", ")", "bool", "{", "c", ".", "dbMu", ".", "RLock", "(", ")", "\n", "defer", "c", ".", "dbMu", ".", "RUnlock", "(", ")", "\n", "if", "c", ".", "db", "==", "nil", "{", "return", "false", "\n", "}", "\n", "return", "c", ".", "db", ".", "TransactionActive", "(", ")", "\n", "}" ]
// TransactionActive returns whether a transaction is active on the connection.
[ "TransactionActive", "returns", "whether", "a", "transaction", "is", "active", "on", "the", "connection", "." ]
12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3
https://github.com/rqlite/rqlite/blob/12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3/store/connection.go#L78-L85
train
rqlite/rqlite
store/connection.go
Execute
func (c *Connection) Execute(ex *ExecuteRequest) (*ExecuteResponse, error) { c.dbMu.RLock() defer c.dbMu.RUnlock() if c.db == nil { return nil, ErrConnectionDoesNotExist } return c.store.execute(c, ex) }
go
func (c *Connection) Execute(ex *ExecuteRequest) (*ExecuteResponse, error) { c.dbMu.RLock() defer c.dbMu.RUnlock() if c.db == nil { return nil, ErrConnectionDoesNotExist } return c.store.execute(c, ex) }
[ "func", "(", "c", "*", "Connection", ")", "Execute", "(", "ex", "*", "ExecuteRequest", ")", "(", "*", "ExecuteResponse", ",", "error", ")", "{", "c", ".", "dbMu", ".", "RLock", "(", ")", "\n", "defer", "c", ".", "dbMu", ".", "RUnlock", "(", ")", "\n", "if", "c", ".", "db", "==", "nil", "{", "return", "nil", ",", "ErrConnectionDoesNotExist", "\n", "}", "\n", "return", "c", ".", "store", ".", "execute", "(", "c", ",", "ex", ")", "\n", "}" ]
// Execute executes queries that return no rows, but do modify the database.
[ "Execute", "executes", "queries", "that", "return", "no", "rows", "but", "do", "modify", "the", "database", "." ]
12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3
https://github.com/rqlite/rqlite/blob/12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3/store/connection.go#L88-L95
train
rqlite/rqlite
store/connection.go
ExecuteOrAbort
func (c *Connection) ExecuteOrAbort(ex *ExecuteRequest) (resp *ExecuteResponse, retErr error) { c.dbMu.RLock() defer c.dbMu.RUnlock() if c.db == nil { return nil, ErrConnectionDoesNotExist } return c.store.executeOrAbort(c, ex) }
go
func (c *Connection) ExecuteOrAbort(ex *ExecuteRequest) (resp *ExecuteResponse, retErr error) { c.dbMu.RLock() defer c.dbMu.RUnlock() if c.db == nil { return nil, ErrConnectionDoesNotExist } return c.store.executeOrAbort(c, ex) }
[ "func", "(", "c", "*", "Connection", ")", "ExecuteOrAbort", "(", "ex", "*", "ExecuteRequest", ")", "(", "resp", "*", "ExecuteResponse", ",", "retErr", "error", ")", "{", "c", ".", "dbMu", ".", "RLock", "(", ")", "\n", "defer", "c", ".", "dbMu", ".", "RUnlock", "(", ")", "\n", "if", "c", ".", "db", "==", "nil", "{", "return", "nil", ",", "ErrConnectionDoesNotExist", "\n", "}", "\n", "return", "c", ".", "store", ".", "executeOrAbort", "(", "c", ",", "ex", ")", "\n", "}" ]
// ExecuteOrAbort executes the requests, but aborts any active transaction // on the underlying database in the case of any error.
[ "ExecuteOrAbort", "executes", "the", "requests", "but", "aborts", "any", "active", "transaction", "on", "the", "underlying", "database", "in", "the", "case", "of", "any", "error", "." ]
12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3
https://github.com/rqlite/rqlite/blob/12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3/store/connection.go#L99-L106
train
rqlite/rqlite
store/connection.go
Query
func (c *Connection) Query(qr *QueryRequest) (*QueryResponse, error) { c.dbMu.RLock() defer c.dbMu.RUnlock() if c.db == nil { return nil, ErrConnectionDoesNotExist } return c.store.query(c, qr) }
go
func (c *Connection) Query(qr *QueryRequest) (*QueryResponse, error) { c.dbMu.RLock() defer c.dbMu.RUnlock() if c.db == nil { return nil, ErrConnectionDoesNotExist } return c.store.query(c, qr) }
[ "func", "(", "c", "*", "Connection", ")", "Query", "(", "qr", "*", "QueryRequest", ")", "(", "*", "QueryResponse", ",", "error", ")", "{", "c", ".", "dbMu", ".", "RLock", "(", ")", "\n", "defer", "c", ".", "dbMu", ".", "RUnlock", "(", ")", "\n", "if", "c", ".", "db", "==", "nil", "{", "return", "nil", ",", "ErrConnectionDoesNotExist", "\n", "}", "\n", "return", "c", ".", "store", ".", "query", "(", "c", ",", "qr", ")", "\n", "}" ]
// Query executes queries that return rows, and do not modify the database.
[ "Query", "executes", "queries", "that", "return", "rows", "and", "do", "not", "modify", "the", "database", "." ]
12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3
https://github.com/rqlite/rqlite/blob/12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3/store/connection.go#L109-L116
train
rqlite/rqlite
store/connection.go
Close
func (c *Connection) Close() error { c.dbMu.Lock() defer c.dbMu.Unlock() if c.store != nil { if err := c.store.disconnect(c); err != nil { return err } } if c.db == nil { return nil } if err := c.db.Close(); err != nil { return err } c.db = nil return nil }
go
func (c *Connection) Close() error { c.dbMu.Lock() defer c.dbMu.Unlock() if c.store != nil { if err := c.store.disconnect(c); err != nil { return err } } if c.db == nil { return nil } if err := c.db.Close(); err != nil { return err } c.db = nil return nil }
[ "func", "(", "c", "*", "Connection", ")", "Close", "(", ")", "error", "{", "c", ".", "dbMu", ".", "Lock", "(", ")", "\n", "defer", "c", ".", "dbMu", ".", "Unlock", "(", ")", "\n", "if", "c", ".", "store", "!=", "nil", "{", "if", "err", ":=", "c", ".", "store", ".", "disconnect", "(", "c", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "}", "\n", "if", "c", ".", "db", "==", "nil", "{", "return", "nil", "\n", "}", "\n", "if", "err", ":=", "c", ".", "db", ".", "Close", "(", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "c", ".", "db", "=", "nil", "\n", "return", "nil", "\n", "}" ]
// Close closes the connection via consensus.
[ "Close", "closes", "the", "connection", "via", "consensus", "." ]
12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3
https://github.com/rqlite/rqlite/blob/12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3/store/connection.go#L133-L151
train
rqlite/rqlite
store/connection.go
Stats
func (c *Connection) Stats() (interface{}, error) { c.dbMu.RLock() defer c.dbMu.RUnlock() c.timeMu.Lock() defer c.timeMu.Unlock() c.txStateMu.Lock() defer c.txStateMu.Unlock() fkEnabled, err := c.db.FKConstraints() if err != nil { return nil, err } m := make(map[string]interface{}) m["last_used_at"] = c.LastUsedAt m["created_at"] = c.CreatedAt m["idle_timeout"] = c.IdleTimeout.String() m["tx_timeout"] = c.TxTimeout.String() m["id"] = c.ID m["fk_constraints"] = enabledFromBool(fkEnabled) if !c.TxStartedAt.IsZero() { m["tx_started_at"] = c.TxStartedAt.String() } return m, nil }
go
func (c *Connection) Stats() (interface{}, error) { c.dbMu.RLock() defer c.dbMu.RUnlock() c.timeMu.Lock() defer c.timeMu.Unlock() c.txStateMu.Lock() defer c.txStateMu.Unlock() fkEnabled, err := c.db.FKConstraints() if err != nil { return nil, err } m := make(map[string]interface{}) m["last_used_at"] = c.LastUsedAt m["created_at"] = c.CreatedAt m["idle_timeout"] = c.IdleTimeout.String() m["tx_timeout"] = c.TxTimeout.String() m["id"] = c.ID m["fk_constraints"] = enabledFromBool(fkEnabled) if !c.TxStartedAt.IsZero() { m["tx_started_at"] = c.TxStartedAt.String() } return m, nil }
[ "func", "(", "c", "*", "Connection", ")", "Stats", "(", ")", "(", "interface", "{", "}", ",", "error", ")", "{", "c", ".", "dbMu", ".", "RLock", "(", ")", "\n", "defer", "c", ".", "dbMu", ".", "RUnlock", "(", ")", "\n", "c", ".", "timeMu", ".", "Lock", "(", ")", "\n", "defer", "c", ".", "timeMu", ".", "Unlock", "(", ")", "\n", "c", ".", "txStateMu", ".", "Lock", "(", ")", "\n", "defer", "c", ".", "txStateMu", ".", "Unlock", "(", ")", "\n", "fkEnabled", ",", "err", ":=", "c", ".", "db", ".", "FKConstraints", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "m", ":=", "make", "(", "map", "[", "string", "]", "interface", "{", "}", ")", "\n", "m", "[", "\"last_used_at\"", "]", "=", "c", ".", "LastUsedAt", "\n", "m", "[", "\"created_at\"", "]", "=", "c", ".", "CreatedAt", "\n", "m", "[", "\"idle_timeout\"", "]", "=", "c", ".", "IdleTimeout", ".", "String", "(", ")", "\n", "m", "[", "\"tx_timeout\"", "]", "=", "c", ".", "TxTimeout", ".", "String", "(", ")", "\n", "m", "[", "\"id\"", "]", "=", "c", ".", "ID", "\n", "m", "[", "\"fk_constraints\"", "]", "=", "enabledFromBool", "(", "fkEnabled", ")", "\n", "if", "!", "c", ".", "TxStartedAt", ".", "IsZero", "(", ")", "{", "m", "[", "\"tx_started_at\"", "]", "=", "c", ".", "TxStartedAt", ".", "String", "(", ")", "\n", "}", "\n", "return", "m", ",", "nil", "\n", "}" ]
// Stats returns the status of the connection.
[ "Stats", "returns", "the", "status", "of", "the", "connection", "." ]
12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3
https://github.com/rqlite/rqlite/blob/12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3/store/connection.go#L154-L178
train
rqlite/rqlite
store/connection.go
IdleTimedOut
func (c *Connection) IdleTimedOut() bool { c.timeMu.Lock() defer c.timeMu.Unlock() return time.Since(c.LastUsedAt) > c.IdleTimeout && c.IdleTimeout != 0 }
go
func (c *Connection) IdleTimedOut() bool { c.timeMu.Lock() defer c.timeMu.Unlock() return time.Since(c.LastUsedAt) > c.IdleTimeout && c.IdleTimeout != 0 }
[ "func", "(", "c", "*", "Connection", ")", "IdleTimedOut", "(", ")", "bool", "{", "c", ".", "timeMu", ".", "Lock", "(", ")", "\n", "defer", "c", ".", "timeMu", ".", "Unlock", "(", ")", "\n", "return", "time", ".", "Since", "(", "c", ".", "LastUsedAt", ")", ">", "c", ".", "IdleTimeout", "&&", "c", ".", "IdleTimeout", "!=", "0", "\n", "}" ]
// IdleTimedOut returns if the connection has not been active in the idle time.
[ "IdleTimedOut", "returns", "if", "the", "connection", "has", "not", "been", "active", "in", "the", "idle", "time", "." ]
12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3
https://github.com/rqlite/rqlite/blob/12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3/store/connection.go#L181-L185
train
rqlite/rqlite
store/connection.go
TxTimedOut
func (c *Connection) TxTimedOut() bool { c.timeMu.Lock() defer c.timeMu.Unlock() c.txStateMu.Lock() defer c.txStateMu.Unlock() lau := c.LastUsedAt return !c.TxStartedAt.IsZero() && time.Since(lau) > c.TxTimeout && c.TxTimeout != 0 }
go
func (c *Connection) TxTimedOut() bool { c.timeMu.Lock() defer c.timeMu.Unlock() c.txStateMu.Lock() defer c.txStateMu.Unlock() lau := c.LastUsedAt return !c.TxStartedAt.IsZero() && time.Since(lau) > c.TxTimeout && c.TxTimeout != 0 }
[ "func", "(", "c", "*", "Connection", ")", "TxTimedOut", "(", ")", "bool", "{", "c", ".", "timeMu", ".", "Lock", "(", ")", "\n", "defer", "c", ".", "timeMu", ".", "Unlock", "(", ")", "\n", "c", ".", "txStateMu", ".", "Lock", "(", ")", "\n", "defer", "c", ".", "txStateMu", ".", "Unlock", "(", ")", "\n", "lau", ":=", "c", ".", "LastUsedAt", "\n", "return", "!", "c", ".", "TxStartedAt", ".", "IsZero", "(", ")", "&&", "time", ".", "Since", "(", "lau", ")", ">", "c", ".", "TxTimeout", "&&", "c", ".", "TxTimeout", "!=", "0", "\n", "}" ]
// TxTimedOut returns if the transaction has been open, without activity in // transaction-idle time.
[ "TxTimedOut", "returns", "if", "the", "transaction", "has", "been", "open", "without", "activity", "in", "transaction", "-", "idle", "time", "." ]
12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3
https://github.com/rqlite/rqlite/blob/12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3/store/connection.go#L189-L196
train
rqlite/rqlite
store/connection.go
NewTxStateChange
func NewTxStateChange(c *Connection) *TxStateChange { return &TxStateChange{ c: c, tx: c.TransactionActive(), } }
go
func NewTxStateChange(c *Connection) *TxStateChange { return &TxStateChange{ c: c, tx: c.TransactionActive(), } }
[ "func", "NewTxStateChange", "(", "c", "*", "Connection", ")", "*", "TxStateChange", "{", "return", "&", "TxStateChange", "{", "c", ":", "c", ",", "tx", ":", "c", ".", "TransactionActive", "(", ")", ",", "}", "\n", "}" ]
// NewTxStateChange returns an initialized TxStateChange
[ "NewTxStateChange", "returns", "an", "initialized", "TxStateChange" ]
12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3
https://github.com/rqlite/rqlite/blob/12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3/store/connection.go#L211-L216
train
rqlite/rqlite
store/connection.go
CheckAndSet
func (t *TxStateChange) CheckAndSet() { t.c.txStateMu.Lock() defer t.c.txStateMu.Unlock() defer func() { t.done = true }() if t.done { panic("CheckAndSet should only be called once") } if !t.tx && t.c.TransactionActive() && t.c.TxStartedAt.IsZero() { t.c.TxStartedAt = time.Now() } else if t.tx && !t.c.TransactionActive() && !t.c.TxStartedAt.IsZero() { t.c.TxStartedAt = time.Time{} } }
go
func (t *TxStateChange) CheckAndSet() { t.c.txStateMu.Lock() defer t.c.txStateMu.Unlock() defer func() { t.done = true }() if t.done { panic("CheckAndSet should only be called once") } if !t.tx && t.c.TransactionActive() && t.c.TxStartedAt.IsZero() { t.c.TxStartedAt = time.Now() } else if t.tx && !t.c.TransactionActive() && !t.c.TxStartedAt.IsZero() { t.c.TxStartedAt = time.Time{} } }
[ "func", "(", "t", "*", "TxStateChange", ")", "CheckAndSet", "(", ")", "{", "t", ".", "c", ".", "txStateMu", ".", "Lock", "(", ")", "\n", "defer", "t", ".", "c", ".", "txStateMu", ".", "Unlock", "(", ")", "\n", "defer", "func", "(", ")", "{", "t", ".", "done", "=", "true", "}", "(", ")", "\n", "if", "t", ".", "done", "{", "panic", "(", "\"CheckAndSet should only be called once\"", ")", "\n", "}", "\n", "if", "!", "t", ".", "tx", "&&", "t", ".", "c", ".", "TransactionActive", "(", ")", "&&", "t", ".", "c", ".", "TxStartedAt", ".", "IsZero", "(", ")", "{", "t", ".", "c", ".", "TxStartedAt", "=", "time", ".", "Now", "(", ")", "\n", "}", "else", "if", "t", ".", "tx", "&&", "!", "t", ".", "c", ".", "TransactionActive", "(", ")", "&&", "!", "t", ".", "c", ".", "TxStartedAt", ".", "IsZero", "(", ")", "{", "t", ".", "c", ".", "TxStartedAt", "=", "time", ".", "Time", "{", "}", "\n", "}", "\n", "}" ]
// CheckAndSet sets whether a transaction has begun or ended on the // connection since the TxStateChange was created. Once CheckAndSet // has been called, this function will panic if called a second time.
[ "CheckAndSet", "sets", "whether", "a", "transaction", "has", "begun", "or", "ended", "on", "the", "connection", "since", "the", "TxStateChange", "was", "created", ".", "Once", "CheckAndSet", "has", "been", "called", "this", "function", "will", "panic", "if", "called", "a", "second", "time", "." ]
12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3
https://github.com/rqlite/rqlite/blob/12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3/store/connection.go#L221-L235
train
rqlite/rqlite
store/db_config.go
NewDBConfig
func NewDBConfig(dsn string, memory bool) *DBConfig { return &DBConfig{DSN: dsn, Memory: memory} }
go
func NewDBConfig(dsn string, memory bool) *DBConfig { return &DBConfig{DSN: dsn, Memory: memory} }
[ "func", "NewDBConfig", "(", "dsn", "string", ",", "memory", "bool", ")", "*", "DBConfig", "{", "return", "&", "DBConfig", "{", "DSN", ":", "dsn", ",", "Memory", ":", "memory", "}", "\n", "}" ]
// NewDBConfig returns a new DB config instance.
[ "NewDBConfig", "returns", "a", "new", "DB", "config", "instance", "." ]
12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3
https://github.com/rqlite/rqlite/blob/12a954c7ef29a9060870c0b5c6c4d8a9e8c35ce3/store/db_config.go#L10-L12
train
Shopify/go-lua
string.go
StringOpen
func StringOpen(l *State) int { NewLibrary(l, stringLibrary) l.CreateTable(0, 1) l.PushString("") l.PushValue(-2) l.SetMetaTable(-2) l.Pop(1) l.PushValue(-2) l.SetField(-2, "__index") l.Pop(1) return 1 }
go
func StringOpen(l *State) int { NewLibrary(l, stringLibrary) l.CreateTable(0, 1) l.PushString("") l.PushValue(-2) l.SetMetaTable(-2) l.Pop(1) l.PushValue(-2) l.SetField(-2, "__index") l.Pop(1) return 1 }
[ "func", "StringOpen", "(", "l", "*", "State", ")", "int", "{", "NewLibrary", "(", "l", ",", "stringLibrary", ")", "\n", "l", ".", "CreateTable", "(", "0", ",", "1", ")", "\n", "l", ".", "PushString", "(", "\"\"", ")", "\n", "l", ".", "PushValue", "(", "-", "2", ")", "\n", "l", ".", "SetMetaTable", "(", "-", "2", ")", "\n", "l", ".", "Pop", "(", "1", ")", "\n", "l", ".", "PushValue", "(", "-", "2", ")", "\n", "l", ".", "SetField", "(", "-", "2", ",", "\"__index\"", ")", "\n", "l", ".", "Pop", "(", "1", ")", "\n", "return", "1", "\n", "}" ]
// StringOpen opens the string library. Usually passed to Require.
[ "StringOpen", "opens", "the", "string", "library", ".", "Usually", "passed", "to", "Require", "." ]
48449c60c0a91cdc83cf554aa0931380393b9b02
https://github.com/Shopify/go-lua/blob/48449c60c0a91cdc83cf554aa0931380393b9b02/string.go#L235-L246
train
Shopify/go-lua
lua.go
AtPanic
func AtPanic(l *State, panicFunction Function) Function { panicFunction, l.global.panicFunction = l.global.panicFunction, panicFunction return panicFunction }
go
func AtPanic(l *State, panicFunction Function) Function { panicFunction, l.global.panicFunction = l.global.panicFunction, panicFunction return panicFunction }
[ "func", "AtPanic", "(", "l", "*", "State", ",", "panicFunction", "Function", ")", "Function", "{", "panicFunction", ",", "l", ".", "global", ".", "panicFunction", "=", "l", ".", "global", ".", "panicFunction", ",", "panicFunction", "\n", "return", "panicFunction", "\n", "}" ]
// AtPanic sets a new panic function and returns the old one.
[ "AtPanic", "sets", "a", "new", "panic", "function", "and", "returns", "the", "old", "one", "." ]
48449c60c0a91cdc83cf554aa0931380393b9b02
https://github.com/Shopify/go-lua/blob/48449c60c0a91cdc83cf554aa0931380393b9b02/lua.go#L628-L631
train
Shopify/go-lua
lua.go
UpValue
func UpValue(l *State, function, index int) (name string, ok bool) { if c, isClosure := l.indexToValue(function).(closure); isClosure { if ok = 1 <= index && index <= c.upValueCount(); ok { if c, isLua := c.(*luaClosure); isLua { name = c.prototype.upValues[index-1].name } l.apiPush(c.upValue(index - 1)) } } return }
go
func UpValue(l *State, function, index int) (name string, ok bool) { if c, isClosure := l.indexToValue(function).(closure); isClosure { if ok = 1 <= index && index <= c.upValueCount(); ok { if c, isLua := c.(*luaClosure); isLua { name = c.prototype.upValues[index-1].name } l.apiPush(c.upValue(index - 1)) } } return }
[ "func", "UpValue", "(", "l", "*", "State", ",", "function", ",", "index", "int", ")", "(", "name", "string", ",", "ok", "bool", ")", "{", "if", "c", ",", "isClosure", ":=", "l", ".", "indexToValue", "(", "function", ")", ".", "(", "closure", ")", ";", "isClosure", "{", "if", "ok", "=", "1", "<=", "index", "&&", "index", "<=", "c", ".", "upValueCount", "(", ")", ";", "ok", "{", "if", "c", ",", "isLua", ":=", "c", ".", "(", "*", "luaClosure", ")", ";", "isLua", "{", "name", "=", "c", ".", "prototype", ".", "upValues", "[", "index", "-", "1", "]", ".", "name", "\n", "}", "\n", "l", ".", "apiPush", "(", "c", ".", "upValue", "(", "index", "-", "1", ")", ")", "\n", "}", "\n", "}", "\n", "return", "\n", "}" ]
// UpValue returns the name of the upvalue at index away from function, // where index cannot be greater than the number of upvalues. // // Returns an empty string and false if the index is greater than the number // of upvalues.
[ "UpValue", "returns", "the", "name", "of", "the", "upvalue", "at", "index", "away", "from", "function", "where", "index", "cannot", "be", "greater", "than", "the", "number", "of", "upvalues", ".", "Returns", "an", "empty", "string", "and", "false", "if", "the", "index", "is", "greater", "than", "the", "number", "of", "upvalues", "." ]
48449c60c0a91cdc83cf554aa0931380393b9b02
https://github.com/Shopify/go-lua/blob/48449c60c0a91cdc83cf554aa0931380393b9b02/lua.go#L1258-L1268
train
Shopify/go-lua
lua.go
UpValueJoin
func UpValueJoin(l *State, f1, n1, f2, n2 int) { u1 := l.upValue(f1, n1) u2 := l.upValue(f2, n2) *u1 = *u2 }
go
func UpValueJoin(l *State, f1, n1, f2, n2 int) { u1 := l.upValue(f1, n1) u2 := l.upValue(f2, n2) *u1 = *u2 }
[ "func", "UpValueJoin", "(", "l", "*", "State", ",", "f1", ",", "n1", ",", "f2", ",", "n2", "int", ")", "{", "u1", ":=", "l", ".", "upValue", "(", "f1", ",", "n1", ")", "\n", "u2", ":=", "l", ".", "upValue", "(", "f2", ",", "n2", ")", "\n", "*", "u1", "=", "*", "u2", "\n", "}" ]
// UpValueJoin makes the n1-th upvalue of the Lua closure at index f1 refer to // the n2-th upvalue of the Lua closure at index f2.
[ "UpValueJoin", "makes", "the", "n1", "-", "th", "upvalue", "of", "the", "Lua", "closure", "at", "index", "f1", "refer", "to", "the", "n2", "-", "th", "upvalue", "of", "the", "Lua", "closure", "at", "index", "f2", "." ]
48449c60c0a91cdc83cf554aa0931380393b9b02
https://github.com/Shopify/go-lua/blob/48449c60c0a91cdc83cf554aa0931380393b9b02/lua.go#L1315-L1319
train
Shopify/go-lua
math.go
MathOpen
func MathOpen(l *State) int { NewLibrary(l, mathLibrary) l.PushNumber(3.1415926535897932384626433832795) // TODO use math.Pi instead? Values differ. l.SetField(-2, "pi") l.PushNumber(math.MaxFloat64) l.SetField(-2, "huge") return 1 }
go
func MathOpen(l *State) int { NewLibrary(l, mathLibrary) l.PushNumber(3.1415926535897932384626433832795) // TODO use math.Pi instead? Values differ. l.SetField(-2, "pi") l.PushNumber(math.MaxFloat64) l.SetField(-2, "huge") return 1 }
[ "func", "MathOpen", "(", "l", "*", "State", ")", "int", "{", "NewLibrary", "(", "l", ",", "mathLibrary", ")", "\n", "l", ".", "PushNumber", "(", "3.1415926535897932384626433832795", ")", "\n", "l", ".", "SetField", "(", "-", "2", ",", "\"pi\"", ")", "\n", "l", ".", "PushNumber", "(", "math", ".", "MaxFloat64", ")", "\n", "l", ".", "SetField", "(", "-", "2", ",", "\"huge\"", ")", "\n", "return", "1", "\n", "}" ]
// MathOpen opens the math library. Usually passed to Require.
[ "MathOpen", "opens", "the", "math", "library", ".", "Usually", "passed", "to", "Require", "." ]
48449c60c0a91cdc83cf554aa0931380393b9b02
https://github.com/Shopify/go-lua/blob/48449c60c0a91cdc83cf554aa0931380393b9b02/math.go#L112-L119
train
Shopify/go-lua
io.go
IOOpen
func IOOpen(l *State) int { NewLibrary(l, ioLibrary) NewMetaTable(l, fileHandle) l.PushValue(-1) l.SetField(-2, "__index") SetFunctions(l, fileHandleMethods, 0) l.Pop(1) registerStdFile(l, os.Stdin, input, "stdin") registerStdFile(l, os.Stdout, output, "stdout") registerStdFile(l, os.Stderr, "", "stderr") return 1 }
go
func IOOpen(l *State) int { NewLibrary(l, ioLibrary) NewMetaTable(l, fileHandle) l.PushValue(-1) l.SetField(-2, "__index") SetFunctions(l, fileHandleMethods, 0) l.Pop(1) registerStdFile(l, os.Stdin, input, "stdin") registerStdFile(l, os.Stdout, output, "stdout") registerStdFile(l, os.Stderr, "", "stderr") return 1 }
[ "func", "IOOpen", "(", "l", "*", "State", ")", "int", "{", "NewLibrary", "(", "l", ",", "ioLibrary", ")", "\n", "NewMetaTable", "(", "l", ",", "fileHandle", ")", "\n", "l", ".", "PushValue", "(", "-", "1", ")", "\n", "l", ".", "SetField", "(", "-", "2", ",", "\"__index\"", ")", "\n", "SetFunctions", "(", "l", ",", "fileHandleMethods", ",", "0", ")", "\n", "l", ".", "Pop", "(", "1", ")", "\n", "registerStdFile", "(", "l", ",", "os", ".", "Stdin", ",", "input", ",", "\"stdin\"", ")", "\n", "registerStdFile", "(", "l", ",", "os", ".", "Stdout", ",", "output", ",", "\"stdout\"", ")", "\n", "registerStdFile", "(", "l", ",", "os", ".", "Stderr", ",", "\"\"", ",", "\"stderr\"", ")", "\n", "return", "1", "\n", "}" ]
// IOOpen opens the io library. Usually passed to Require.
[ "IOOpen", "opens", "the", "io", "library", ".", "Usually", "passed", "to", "Require", "." ]
48449c60c0a91cdc83cf554aa0931380393b9b02
https://github.com/Shopify/go-lua/blob/48449c60c0a91cdc83cf554aa0931380393b9b02/io.go#L310-L324
train
Shopify/go-lua
auxiliary.go
Traceback
func Traceback(l, l1 *State, message string, level int) { const levels1, levels2 = 12, 10 levels := countLevels(l1) mark := 0 if levels > levels1+levels2 { mark = levels1 } buf := message if buf != "" { buf += "\n" } buf += "stack traceback:" for f, ok := Stack(l1, level); ok; f, ok = Stack(l1, level) { if level++; level == mark { buf += "\n\t..." level = levels - levels2 } else { d, _ := Info(l1, "Slnt", f) buf += "\n\t" + d.ShortSource + ":" if d.CurrentLine > 0 { buf += fmt.Sprintf("%d:", d.CurrentLine) } buf += " in " + functionName(l, d) if d.IsTailCall { buf += "\n\t(...tail calls...)" } } } l.PushString(buf) }
go
func Traceback(l, l1 *State, message string, level int) { const levels1, levels2 = 12, 10 levels := countLevels(l1) mark := 0 if levels > levels1+levels2 { mark = levels1 } buf := message if buf != "" { buf += "\n" } buf += "stack traceback:" for f, ok := Stack(l1, level); ok; f, ok = Stack(l1, level) { if level++; level == mark { buf += "\n\t..." level = levels - levels2 } else { d, _ := Info(l1, "Slnt", f) buf += "\n\t" + d.ShortSource + ":" if d.CurrentLine > 0 { buf += fmt.Sprintf("%d:", d.CurrentLine) } buf += " in " + functionName(l, d) if d.IsTailCall { buf += "\n\t(...tail calls...)" } } } l.PushString(buf) }
[ "func", "Traceback", "(", "l", ",", "l1", "*", "State", ",", "message", "string", ",", "level", "int", ")", "{", "const", "levels1", ",", "levels2", "=", "12", ",", "10", "\n", "levels", ":=", "countLevels", "(", "l1", ")", "\n", "mark", ":=", "0", "\n", "if", "levels", ">", "levels1", "+", "levels2", "{", "mark", "=", "levels1", "\n", "}", "\n", "buf", ":=", "message", "\n", "if", "buf", "!=", "\"\"", "{", "buf", "+=", "\"\\n\"", "\n", "}", "\n", "\\n", "\n", "buf", "+=", "\"stack traceback:\"", "\n", "for", "f", ",", "ok", ":=", "Stack", "(", "l1", ",", "level", ")", ";", "ok", ";", "f", ",", "ok", "=", "Stack", "(", "l1", ",", "level", ")", "{", "if", "level", "++", ";", "level", "==", "mark", "{", "buf", "+=", "\"\\n\\t...\"", "\n", "\\n", "\n", "}", "else", "\\t", "\n", "}", "\n", "}" ]
// Traceback creates and pushes a traceback of the stack l1. If message is not // nil it is appended at the beginning of the traceback. The level parameter // tells at which level to start the traceback.
[ "Traceback", "creates", "and", "pushes", "a", "traceback", "of", "the", "stack", "l1", ".", "If", "message", "is", "not", "nil", "it", "is", "appended", "at", "the", "beginning", "of", "the", "traceback", ".", "The", "level", "parameter", "tells", "at", "which", "level", "to", "start", "the", "traceback", "." ]
48449c60c0a91cdc83cf554aa0931380393b9b02
https://github.com/Shopify/go-lua/blob/48449c60c0a91cdc83cf554aa0931380393b9b02/auxiliary.go#L48-L77
train
Shopify/go-lua
auxiliary.go
MetaField
func MetaField(l *State, index int, event string) bool { if !l.MetaTable(index) { return false } l.PushString(event) l.RawGet(-2) if l.IsNil(-1) { l.Pop(2) // remove metatable and metafield return false } l.Remove(-2) // remove only metatable return true }
go
func MetaField(l *State, index int, event string) bool { if !l.MetaTable(index) { return false } l.PushString(event) l.RawGet(-2) if l.IsNil(-1) { l.Pop(2) // remove metatable and metafield return false } l.Remove(-2) // remove only metatable return true }
[ "func", "MetaField", "(", "l", "*", "State", ",", "index", "int", ",", "event", "string", ")", "bool", "{", "if", "!", "l", ".", "MetaTable", "(", "index", ")", "{", "return", "false", "\n", "}", "\n", "l", ".", "PushString", "(", "event", ")", "\n", "l", ".", "RawGet", "(", "-", "2", ")", "\n", "if", "l", ".", "IsNil", "(", "-", "1", ")", "{", "l", ".", "Pop", "(", "2", ")", "\n", "return", "false", "\n", "}", "\n", "l", ".", "Remove", "(", "-", "2", ")", "\n", "return", "true", "\n", "}" ]
// MetaField pushes onto the stack the field event from the metatable of the // object at index. If the object does not have a metatable, or if the // metatable does not have this field, returns false and pushes nothing.
[ "MetaField", "pushes", "onto", "the", "stack", "the", "field", "event", "from", "the", "metatable", "of", "the", "object", "at", "index", ".", "If", "the", "object", "does", "not", "have", "a", "metatable", "or", "if", "the", "metatable", "does", "not", "have", "this", "field", "returns", "false", "and", "pushes", "nothing", "." ]
48449c60c0a91cdc83cf554aa0931380393b9b02
https://github.com/Shopify/go-lua/blob/48449c60c0a91cdc83cf554aa0931380393b9b02/auxiliary.go#L82-L94
train
Shopify/go-lua
auxiliary.go
NewMetaTable
func NewMetaTable(l *State, name string) bool { if MetaTableNamed(l, name); !l.IsNil(-1) { return false } l.Pop(1) l.NewTable() l.PushValue(-1) l.SetField(RegistryIndex, name) return true }
go
func NewMetaTable(l *State, name string) bool { if MetaTableNamed(l, name); !l.IsNil(-1) { return false } l.Pop(1) l.NewTable() l.PushValue(-1) l.SetField(RegistryIndex, name) return true }
[ "func", "NewMetaTable", "(", "l", "*", "State", ",", "name", "string", ")", "bool", "{", "if", "MetaTableNamed", "(", "l", ",", "name", ")", ";", "!", "l", ".", "IsNil", "(", "-", "1", ")", "{", "return", "false", "\n", "}", "\n", "l", ".", "Pop", "(", "1", ")", "\n", "l", ".", "NewTable", "(", ")", "\n", "l", ".", "PushValue", "(", "-", "1", ")", "\n", "l", ".", "SetField", "(", "RegistryIndex", ",", "name", ")", "\n", "return", "true", "\n", "}" ]
// NewMetaTable returns false if the registry already has the key name. Otherwise, // creates a new table to be used as a metatable for userdata, adds it to the // registry with key name, and returns true. // // In both cases it pushes onto the stack the final value associated with name in // the registry.
[ "NewMetaTable", "returns", "false", "if", "the", "registry", "already", "has", "the", "key", "name", ".", "Otherwise", "creates", "a", "new", "table", "to", "be", "used", "as", "a", "metatable", "for", "userdata", "adds", "it", "to", "the", "registry", "with", "key", "name", "and", "returns", "true", ".", "In", "both", "cases", "it", "pushes", "onto", "the", "stack", "the", "final", "value", "associated", "with", "name", "in", "the", "registry", "." ]
48449c60c0a91cdc83cf554aa0931380393b9b02
https://github.com/Shopify/go-lua/blob/48449c60c0a91cdc83cf554aa0931380393b9b02/auxiliary.go#L249-L258
train
Shopify/go-lua
auxiliary.go
CheckType
func CheckType(l *State, index int, t Type) { if l.TypeOf(index) != t { tagError(l, index, t) } }
go
func CheckType(l *State, index int, t Type) { if l.TypeOf(index) != t { tagError(l, index, t) } }
[ "func", "CheckType", "(", "l", "*", "State", ",", "index", "int", ",", "t", "Type", ")", "{", "if", "l", ".", "TypeOf", "(", "index", ")", "!=", "t", "{", "tagError", "(", "l", ",", "index", ",", "t", ")", "\n", "}", "\n", "}" ]
// CheckType checks whether the function argument at index has type t. See Type for the encoding of types for t.
[ "CheckType", "checks", "whether", "the", "function", "argument", "at", "index", "has", "type", "t", ".", "See", "Type", "for", "the", "encoding", "of", "types", "for", "t", "." ]
48449c60c0a91cdc83cf554aa0931380393b9b02
https://github.com/Shopify/go-lua/blob/48449c60c0a91cdc83cf554aa0931380393b9b02/auxiliary.go#L294-L298
train
Shopify/go-lua
auxiliary.go
ArgumentCheck
func ArgumentCheck(l *State, cond bool, index int, extraMessage string) { if !cond { ArgumentError(l, index, extraMessage) } }
go
func ArgumentCheck(l *State, cond bool, index int, extraMessage string) { if !cond { ArgumentError(l, index, extraMessage) } }
[ "func", "ArgumentCheck", "(", "l", "*", "State", ",", "cond", "bool", ",", "index", "int", ",", "extraMessage", "string", ")", "{", "if", "!", "cond", "{", "ArgumentError", "(", "l", ",", "index", ",", "extraMessage", ")", "\n", "}", "\n", "}" ]
// ArgumentCheck checks whether cond is true. If not, raises an error with a standard message.
[ "ArgumentCheck", "checks", "whether", "cond", "is", "true", ".", "If", "not", "raises", "an", "error", "with", "a", "standard", "message", "." ]
48449c60c0a91cdc83cf554aa0931380393b9b02
https://github.com/Shopify/go-lua/blob/48449c60c0a91cdc83cf554aa0931380393b9b02/auxiliary.go#L308-L312
train
Shopify/go-lua
auxiliary.go
CheckString
func CheckString(l *State, index int) string { if s, ok := l.ToString(index); ok { return s } tagError(l, index, TypeString) panic("unreachable") }
go
func CheckString(l *State, index int) string { if s, ok := l.ToString(index); ok { return s } tagError(l, index, TypeString) panic("unreachable") }
[ "func", "CheckString", "(", "l", "*", "State", ",", "index", "int", ")", "string", "{", "if", "s", ",", "ok", ":=", "l", ".", "ToString", "(", "index", ")", ";", "ok", "{", "return", "s", "\n", "}", "\n", "tagError", "(", "l", ",", "index", ",", "TypeString", ")", "\n", "panic", "(", "\"unreachable\"", ")", "\n", "}" ]
// CheckString checks whether the function argument at index is a string and returns this string. // // This function uses ToString to get its result, so all conversions and caveats of that function apply here.
[ "CheckString", "checks", "whether", "the", "function", "argument", "at", "index", "is", "a", "string", "and", "returns", "this", "string", ".", "This", "function", "uses", "ToString", "to", "get", "its", "result", "so", "all", "conversions", "and", "caveats", "of", "that", "function", "apply", "here", "." ]
48449c60c0a91cdc83cf554aa0931380393b9b02
https://github.com/Shopify/go-lua/blob/48449c60c0a91cdc83cf554aa0931380393b9b02/auxiliary.go#L317-L323
train
Shopify/go-lua
auxiliary.go
OptString
func OptString(l *State, index int, def string) string { if l.IsNoneOrNil(index) { return def } return CheckString(l, index) }
go
func OptString(l *State, index int, def string) string { if l.IsNoneOrNil(index) { return def } return CheckString(l, index) }
[ "func", "OptString", "(", "l", "*", "State", ",", "index", "int", ",", "def", "string", ")", "string", "{", "if", "l", ".", "IsNoneOrNil", "(", "index", ")", "{", "return", "def", "\n", "}", "\n", "return", "CheckString", "(", "l", ",", "index", ")", "\n", "}" ]
// OptString returns the string at index if it is a string. If this argument is // absent or is nil, returns def. Otherwise, raises an error.
[ "OptString", "returns", "the", "string", "at", "index", "if", "it", "is", "a", "string", ".", "If", "this", "argument", "is", "absent", "or", "is", "nil", "returns", "def", ".", "Otherwise", "raises", "an", "error", "." ]
48449c60c0a91cdc83cf554aa0931380393b9b02
https://github.com/Shopify/go-lua/blob/48449c60c0a91cdc83cf554aa0931380393b9b02/auxiliary.go#L327-L332
train
Shopify/go-lua
auxiliary.go
NewStateEx
func NewStateEx() *State { l := NewState() if l != nil { _ = AtPanic(l, func(l *State) int { s, _ := l.ToString(-1) fmt.Fprintf(os.Stderr, "PANIC: unprotected error in call to Lua API (%s)\n", s) return 0 }) } return l }
go
func NewStateEx() *State { l := NewState() if l != nil { _ = AtPanic(l, func(l *State) int { s, _ := l.ToString(-1) fmt.Fprintf(os.Stderr, "PANIC: unprotected error in call to Lua API (%s)\n", s) return 0 }) } return l }
[ "func", "NewStateEx", "(", ")", "*", "State", "{", "l", ":=", "NewState", "(", ")", "\n", "if", "l", "!=", "nil", "{", "_", "=", "AtPanic", "(", "l", ",", "func", "(", "l", "*", "State", ")", "int", "{", "s", ",", "_", ":=", "l", ".", "ToString", "(", "-", "1", ")", "\n", "fmt", ".", "Fprintf", "(", "os", ".", "Stderr", ",", "\"PANIC: unprotected error in call to Lua API (%s)\\n\"", ",", "\\n", ")", "\n", "s", "\n", "}", ")", "\n", "}", "\n", "return", "0", "\n", "}" ]
// NewStateEx creates a new Lua state. It calls NewState and then sets a panic // function that prints an error message to the standard error output in case // of fatal errors. // // Returns the new state.
[ "NewStateEx", "creates", "a", "new", "Lua", "state", ".", "It", "calls", "NewState", "and", "then", "sets", "a", "panic", "function", "that", "prints", "an", "error", "message", "to", "the", "standard", "error", "output", "in", "case", "of", "fatal", "errors", ".", "Returns", "the", "new", "state", "." ]
48449c60c0a91cdc83cf554aa0931380393b9b02
https://github.com/Shopify/go-lua/blob/48449c60c0a91cdc83cf554aa0931380393b9b02/auxiliary.go#L536-L546
train
Shopify/go-lua
auxiliary.go
DoFile
func DoFile(l *State, fileName string) error { if err := LoadFile(l, fileName, ""); err != nil { return err } return l.ProtectedCall(0, MultipleReturns, 0) }
go
func DoFile(l *State, fileName string) error { if err := LoadFile(l, fileName, ""); err != nil { return err } return l.ProtectedCall(0, MultipleReturns, 0) }
[ "func", "DoFile", "(", "l", "*", "State", ",", "fileName", "string", ")", "error", "{", "if", "err", ":=", "LoadFile", "(", "l", ",", "fileName", ",", "\"\"", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "return", "l", ".", "ProtectedCall", "(", "0", ",", "MultipleReturns", ",", "0", ")", "\n", "}" ]
// DoFile loads and runs the given file.
[ "DoFile", "loads", "and", "runs", "the", "given", "file", "." ]
48449c60c0a91cdc83cf554aa0931380393b9b02
https://github.com/Shopify/go-lua/blob/48449c60c0a91cdc83cf554aa0931380393b9b02/auxiliary.go#L576-L581
train
Shopify/go-lua
auxiliary.go
DoString
func DoString(l *State, s string) error { if err := LoadString(l, s); err != nil { return err } return l.ProtectedCall(0, MultipleReturns, 0) }
go
func DoString(l *State, s string) error { if err := LoadString(l, s); err != nil { return err } return l.ProtectedCall(0, MultipleReturns, 0) }
[ "func", "DoString", "(", "l", "*", "State", ",", "s", "string", ")", "error", "{", "if", "err", ":=", "LoadString", "(", "l", ",", "s", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "return", "l", ".", "ProtectedCall", "(", "0", ",", "MultipleReturns", ",", "0", ")", "\n", "}" ]
// DoString loads and runs the given string.
[ "DoString", "loads", "and", "runs", "the", "given", "string", "." ]
48449c60c0a91cdc83cf554aa0931380393b9b02
https://github.com/Shopify/go-lua/blob/48449c60c0a91cdc83cf554aa0931380393b9b02/auxiliary.go#L584-L589
train
Shopify/go-lua
stack.go
call
func (l *State) call(function int, resultCount int, allowYield bool) { if l.nestedGoCallCount++; l.nestedGoCallCount == maxCallCount { l.runtimeError("Go stack overflow") } else if l.nestedGoCallCount >= maxCallCount+maxCallCount>>3 { l.throw(ErrorError) // error while handling stack error } if !allowYield { l.nonYieldableCallCount++ } if !l.preCall(function, resultCount) { // is a Lua function? l.execute() // call it } if !allowYield { l.nonYieldableCallCount-- } l.nestedGoCallCount-- }
go
func (l *State) call(function int, resultCount int, allowYield bool) { if l.nestedGoCallCount++; l.nestedGoCallCount == maxCallCount { l.runtimeError("Go stack overflow") } else if l.nestedGoCallCount >= maxCallCount+maxCallCount>>3 { l.throw(ErrorError) // error while handling stack error } if !allowYield { l.nonYieldableCallCount++ } if !l.preCall(function, resultCount) { // is a Lua function? l.execute() // call it } if !allowYield { l.nonYieldableCallCount-- } l.nestedGoCallCount-- }
[ "func", "(", "l", "*", "State", ")", "call", "(", "function", "int", ",", "resultCount", "int", ",", "allowYield", "bool", ")", "{", "if", "l", ".", "nestedGoCallCount", "++", ";", "l", ".", "nestedGoCallCount", "==", "maxCallCount", "{", "l", ".", "runtimeError", "(", "\"Go stack overflow\"", ")", "\n", "}", "else", "if", "l", ".", "nestedGoCallCount", ">=", "maxCallCount", "+", "maxCallCount", ">>", "3", "{", "l", ".", "throw", "(", "ErrorError", ")", "\n", "}", "\n", "if", "!", "allowYield", "{", "l", ".", "nonYieldableCallCount", "++", "\n", "}", "\n", "if", "!", "l", ".", "preCall", "(", "function", ",", "resultCount", ")", "{", "l", ".", "execute", "(", ")", "\n", "}", "\n", "if", "!", "allowYield", "{", "l", ".", "nonYieldableCallCount", "--", "\n", "}", "\n", "l", ".", "nestedGoCallCount", "--", "\n", "}" ]
// Call a Go or Lua function. The function to be called is at function. // The arguments are on the stack, right after the function. On return, all the // results are on the stack, starting at the original function position.
[ "Call", "a", "Go", "or", "Lua", "function", ".", "The", "function", "to", "be", "called", "is", "at", "function", ".", "The", "arguments", "are", "on", "the", "stack", "right", "after", "the", "function", ".", "On", "return", "all", "the", "results", "are", "on", "the", "stack", "starting", "at", "the", "original", "function", "position", "." ]
48449c60c0a91cdc83cf554aa0931380393b9b02
https://github.com/Shopify/go-lua/blob/48449c60c0a91cdc83cf554aa0931380393b9b02/stack.go#L371-L387
train
Shopify/go-lua
load.go
PackageOpen
func PackageOpen(l *State) int { NewLibrary(l, packageLibrary) createSearchersTable(l) l.SetField(-2, "searchers") setPath(l, "path", "LUA_PATH", defaultPath) l.PushString(fmt.Sprintf("%c\n%c\n?\n!\n-\n", filepath.Separator, pathListSeparator)) l.SetField(-2, "config") SubTable(l, RegistryIndex, "_LOADED") l.SetField(-2, "loaded") SubTable(l, RegistryIndex, "_PRELOAD") l.SetField(-2, "preload") l.PushGlobalTable() l.PushValue(-2) SetFunctions(l, []RegistryFunction{{"require", func(l *State) int { name := CheckString(l, 1) l.SetTop(1) l.Field(RegistryIndex, "_LOADED") l.Field(2, name) if l.ToBoolean(-1) { return 1 } l.Pop(1) findLoader(l, name) l.PushString(name) l.Insert(-2) l.Call(2, 1) if !l.IsNil(-1) { l.SetField(2, name) } l.Field(2, name) if l.IsNil(-1) { l.PushBoolean(true) l.PushValue(-1) l.SetField(2, name) } return 1 }}}, 1) l.Pop(1) return 1 }
go
func PackageOpen(l *State) int { NewLibrary(l, packageLibrary) createSearchersTable(l) l.SetField(-2, "searchers") setPath(l, "path", "LUA_PATH", defaultPath) l.PushString(fmt.Sprintf("%c\n%c\n?\n!\n-\n", filepath.Separator, pathListSeparator)) l.SetField(-2, "config") SubTable(l, RegistryIndex, "_LOADED") l.SetField(-2, "loaded") SubTable(l, RegistryIndex, "_PRELOAD") l.SetField(-2, "preload") l.PushGlobalTable() l.PushValue(-2) SetFunctions(l, []RegistryFunction{{"require", func(l *State) int { name := CheckString(l, 1) l.SetTop(1) l.Field(RegistryIndex, "_LOADED") l.Field(2, name) if l.ToBoolean(-1) { return 1 } l.Pop(1) findLoader(l, name) l.PushString(name) l.Insert(-2) l.Call(2, 1) if !l.IsNil(-1) { l.SetField(2, name) } l.Field(2, name) if l.IsNil(-1) { l.PushBoolean(true) l.PushValue(-1) l.SetField(2, name) } return 1 }}}, 1) l.Pop(1) return 1 }
[ "func", "PackageOpen", "(", "l", "*", "State", ")", "int", "{", "NewLibrary", "(", "l", ",", "packageLibrary", ")", "\n", "createSearchersTable", "(", "l", ")", "\n", "l", ".", "SetField", "(", "-", "2", ",", "\"searchers\"", ")", "\n", "setPath", "(", "l", ",", "\"path\"", ",", "\"LUA_PATH\"", ",", "defaultPath", ")", "\n", "l", ".", "PushString", "(", "fmt", ".", "Sprintf", "(", "\"%c\\n%c\\n?\\n!\\n-\\n\"", ",", "\\n", ",", "\\n", ")", ")", "\n", "\\n", "\n", "\\n", "\n", "\\n", "\n", "filepath", ".", "Separator", "\n", "pathListSeparator", "\n", "l", ".", "SetField", "(", "-", "2", ",", "\"config\"", ")", "\n", "SubTable", "(", "l", ",", "RegistryIndex", ",", "\"_LOADED\"", ")", "\n", "l", ".", "SetField", "(", "-", "2", ",", "\"loaded\"", ")", "\n", "SubTable", "(", "l", ",", "RegistryIndex", ",", "\"_PRELOAD\"", ")", "\n", "l", ".", "SetField", "(", "-", "2", ",", "\"preload\"", ")", "\n", "}" ]
// PackageOpen opens the package library. Usually passed to Require.
[ "PackageOpen", "opens", "the", "package", "library", ".", "Usually", "passed", "to", "Require", "." ]
48449c60c0a91cdc83cf554aa0931380393b9b02
https://github.com/Shopify/go-lua/blob/48449c60c0a91cdc83cf554aa0931380393b9b02/load.go#L152-L191
train
Shopify/go-lua
base.go
BaseOpen
func BaseOpen(l *State) int { l.PushGlobalTable() l.PushGlobalTable() l.SetField(-2, "_G") SetFunctions(l, baseLibrary, 0) l.PushString(VersionString) l.SetField(-2, "_VERSION") return 1 }
go
func BaseOpen(l *State) int { l.PushGlobalTable() l.PushGlobalTable() l.SetField(-2, "_G") SetFunctions(l, baseLibrary, 0) l.PushString(VersionString) l.SetField(-2, "_VERSION") return 1 }
[ "func", "BaseOpen", "(", "l", "*", "State", ")", "int", "{", "l", ".", "PushGlobalTable", "(", ")", "\n", "l", ".", "PushGlobalTable", "(", ")", "\n", "l", ".", "SetField", "(", "-", "2", ",", "\"_G\"", ")", "\n", "SetFunctions", "(", "l", ",", "baseLibrary", ",", "0", ")", "\n", "l", ".", "PushString", "(", "VersionString", ")", "\n", "l", ".", "SetField", "(", "-", "2", ",", "\"_VERSION\"", ")", "\n", "return", "1", "\n", "}" ]
// BaseOpen opens the basic library. Usually passed to Require.
[ "BaseOpen", "opens", "the", "basic", "library", ".", "Usually", "passed", "to", "Require", "." ]
48449c60c0a91cdc83cf554aa0931380393b9b02
https://github.com/Shopify/go-lua/blob/48449c60c0a91cdc83cf554aa0931380393b9b02/base.go#L322-L330
train
apex/apex
logs/log.go
start
func (l *Log) start(ch chan<- *Event) { defer close(ch) l.Log.Debug("enter") defer l.Log.Debug("exit") var start = l.StartTime.UnixNano() / int64(time.Millisecond) var nextToken *string var err error for { l.Log.WithField("start", start).Debug("request") nextToken, start, err = l.fetch(nextToken, start, ch) if err != nil { l.err = fmt.Errorf("log %q: %s", l.GroupName, err) break } if nextToken == nil && l.Follow { time.Sleep(l.PollInterval) l.Log.WithField("start", start).Debug("poll") continue } if nextToken == nil { break } } }
go
func (l *Log) start(ch chan<- *Event) { defer close(ch) l.Log.Debug("enter") defer l.Log.Debug("exit") var start = l.StartTime.UnixNano() / int64(time.Millisecond) var nextToken *string var err error for { l.Log.WithField("start", start).Debug("request") nextToken, start, err = l.fetch(nextToken, start, ch) if err != nil { l.err = fmt.Errorf("log %q: %s", l.GroupName, err) break } if nextToken == nil && l.Follow { time.Sleep(l.PollInterval) l.Log.WithField("start", start).Debug("poll") continue } if nextToken == nil { break } } }
[ "func", "(", "l", "*", "Log", ")", "start", "(", "ch", "chan", "<-", "*", "Event", ")", "{", "defer", "close", "(", "ch", ")", "\n", "l", ".", "Log", ".", "Debug", "(", "\"enter\"", ")", "\n", "defer", "l", ".", "Log", ".", "Debug", "(", "\"exit\"", ")", "\n", "var", "start", "=", "l", ".", "StartTime", ".", "UnixNano", "(", ")", "/", "int64", "(", "time", ".", "Millisecond", ")", "\n", "var", "nextToken", "*", "string", "\n", "var", "err", "error", "\n", "for", "{", "l", ".", "Log", ".", "WithField", "(", "\"start\"", ",", "start", ")", ".", "Debug", "(", "\"request\"", ")", "\n", "nextToken", ",", "start", ",", "err", "=", "l", ".", "fetch", "(", "nextToken", ",", "start", ",", "ch", ")", "\n", "if", "err", "!=", "nil", "{", "l", ".", "err", "=", "fmt", ".", "Errorf", "(", "\"log %q: %s\"", ",", "l", ".", "GroupName", ",", "err", ")", "\n", "break", "\n", "}", "\n", "if", "nextToken", "==", "nil", "&&", "l", ".", "Follow", "{", "time", ".", "Sleep", "(", "l", ".", "PollInterval", ")", "\n", "l", ".", "Log", ".", "WithField", "(", "\"start\"", ",", "start", ")", ".", "Debug", "(", "\"poll\"", ")", "\n", "continue", "\n", "}", "\n", "if", "nextToken", "==", "nil", "{", "break", "\n", "}", "\n", "}", "\n", "}" ]
// start consuming and exit after pagination if Follow is not enabled.
[ "start", "consuming", "and", "exit", "after", "pagination", "if", "Follow", "is", "not", "enabled", "." ]
c31f0a78ce189a8328563fa6a6eb97d04ace4284
https://github.com/apex/apex/blob/c31f0a78ce189a8328563fa6a6eb97d04ace4284/logs/log.go#L29-L58
train
apex/apex
logs/log.go
fetch
func (l *Log) fetch(nextToken *string, start int64, ch chan<- *Event) (*string, int64, error) { res, err := l.Service.FilterLogEvents(&cloudwatchlogs.FilterLogEventsInput{ LogGroupName: &l.GroupName, FilterPattern: &l.FilterPattern, StartTime: &start, NextToken: nextToken, }) if e, ok := err.(awserr.Error); ok { if e.Code() == "ResourceNotFoundException" { l.Log.Debug("not found") return nil, 0, nil } } if err != nil { return nil, 0, err } for _, event := range res.Events { start = *event.Timestamp + 1 ch <- &Event{ GroupName: l.GroupName, Message: *event.Message, } } return res.NextToken, start, nil }
go
func (l *Log) fetch(nextToken *string, start int64, ch chan<- *Event) (*string, int64, error) { res, err := l.Service.FilterLogEvents(&cloudwatchlogs.FilterLogEventsInput{ LogGroupName: &l.GroupName, FilterPattern: &l.FilterPattern, StartTime: &start, NextToken: nextToken, }) if e, ok := err.(awserr.Error); ok { if e.Code() == "ResourceNotFoundException" { l.Log.Debug("not found") return nil, 0, nil } } if err != nil { return nil, 0, err } for _, event := range res.Events { start = *event.Timestamp + 1 ch <- &Event{ GroupName: l.GroupName, Message: *event.Message, } } return res.NextToken, start, nil }
[ "func", "(", "l", "*", "Log", ")", "fetch", "(", "nextToken", "*", "string", ",", "start", "int64", ",", "ch", "chan", "<-", "*", "Event", ")", "(", "*", "string", ",", "int64", ",", "error", ")", "{", "res", ",", "err", ":=", "l", ".", "Service", ".", "FilterLogEvents", "(", "&", "cloudwatchlogs", ".", "FilterLogEventsInput", "{", "LogGroupName", ":", "&", "l", ".", "GroupName", ",", "FilterPattern", ":", "&", "l", ".", "FilterPattern", ",", "StartTime", ":", "&", "start", ",", "NextToken", ":", "nextToken", ",", "}", ")", "\n", "if", "e", ",", "ok", ":=", "err", ".", "(", "awserr", ".", "Error", ")", ";", "ok", "{", "if", "e", ".", "Code", "(", ")", "==", "\"ResourceNotFoundException\"", "{", "l", ".", "Log", ".", "Debug", "(", "\"not found\"", ")", "\n", "return", "nil", ",", "0", ",", "nil", "\n", "}", "\n", "}", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "0", ",", "err", "\n", "}", "\n", "for", "_", ",", "event", ":=", "range", "res", ".", "Events", "{", "start", "=", "*", "event", ".", "Timestamp", "+", "1", "\n", "ch", "<-", "&", "Event", "{", "GroupName", ":", "l", ".", "GroupName", ",", "Message", ":", "*", "event", ".", "Message", ",", "}", "\n", "}", "\n", "return", "res", ".", "NextToken", ",", "start", ",", "nil", "\n", "}" ]
// fetch logs relative to the given token and start time. We ignore when the log group is not found.
[ "fetch", "logs", "relative", "to", "the", "given", "token", "and", "start", "time", ".", "We", "ignore", "when", "the", "log", "group", "is", "not", "found", "." ]
c31f0a78ce189a8328563fa6a6eb97d04ace4284
https://github.com/apex/apex/blob/c31f0a78ce189a8328563fa6a6eb97d04ace4284/logs/log.go#L61-L89
train
apex/apex
function/function.go
Open
func (f *Function) Open(environment string) error { f.defaults() f.Log = f.Log.WithFields(log.Fields{ "function": f.Name, "env": environment, }) f.Log.Debug("open") if err := f.loadConfig(environment); err != nil { return errors.Wrap(err, "loading config") } if err := f.hookOpen(); err != nil { return errors.Wrap(err, "open hook") } if err := validator.Validate(&f.Config); err != nil { return errors.Wrap(err, "validating") } ignoreFile, err := utils.ReadIgnoreFile(f.Path) if err != nil { return errors.Wrap(err, "reading ignore file") } f.IgnoreFile = append(f.IgnoreFile, []byte("\n")...) f.IgnoreFile = append(f.IgnoreFile, ignoreFile...) return nil }
go
func (f *Function) Open(environment string) error { f.defaults() f.Log = f.Log.WithFields(log.Fields{ "function": f.Name, "env": environment, }) f.Log.Debug("open") if err := f.loadConfig(environment); err != nil { return errors.Wrap(err, "loading config") } if err := f.hookOpen(); err != nil { return errors.Wrap(err, "open hook") } if err := validator.Validate(&f.Config); err != nil { return errors.Wrap(err, "validating") } ignoreFile, err := utils.ReadIgnoreFile(f.Path) if err != nil { return errors.Wrap(err, "reading ignore file") } f.IgnoreFile = append(f.IgnoreFile, []byte("\n")...) f.IgnoreFile = append(f.IgnoreFile, ignoreFile...) return nil }
[ "func", "(", "f", "*", "Function", ")", "Open", "(", "environment", "string", ")", "error", "{", "f", ".", "defaults", "(", ")", "\n", "f", ".", "Log", "=", "f", ".", "Log", ".", "WithFields", "(", "log", ".", "Fields", "{", "\"function\"", ":", "f", ".", "Name", ",", "\"env\"", ":", "environment", ",", "}", ")", "\n", "f", ".", "Log", ".", "Debug", "(", "\"open\"", ")", "\n", "if", "err", ":=", "f", ".", "loadConfig", "(", "environment", ")", ";", "err", "!=", "nil", "{", "return", "errors", ".", "Wrap", "(", "err", ",", "\"loading config\"", ")", "\n", "}", "\n", "if", "err", ":=", "f", ".", "hookOpen", "(", ")", ";", "err", "!=", "nil", "{", "return", "errors", ".", "Wrap", "(", "err", ",", "\"open hook\"", ")", "\n", "}", "\n", "if", "err", ":=", "validator", ".", "Validate", "(", "&", "f", ".", "Config", ")", ";", "err", "!=", "nil", "{", "return", "errors", ".", "Wrap", "(", "err", ",", "\"validating\"", ")", "\n", "}", "\n", "ignoreFile", ",", "err", ":=", "utils", ".", "ReadIgnoreFile", "(", "f", ".", "Path", ")", "\n", "if", "err", "!=", "nil", "{", "return", "errors", ".", "Wrap", "(", "err", ",", "\"reading ignore file\"", ")", "\n", "}", "\n", "f", ".", "IgnoreFile", "=", "append", "(", "f", ".", "IgnoreFile", ",", "[", "]", "byte", "(", "\"\\n\"", ")", "...", ")", "\n", "\\n", "\n", "f", ".", "IgnoreFile", "=", "append", "(", "f", ".", "IgnoreFile", ",", "ignoreFile", "...", ")", "\n", "}" ]
// Open the function.json file and prime the config.
[ "Open", "the", "function", ".", "json", "file", "and", "prime", "the", "config", "." ]
c31f0a78ce189a8328563fa6a6eb97d04ace4284
https://github.com/apex/apex/blob/c31f0a78ce189a8328563fa6a6eb97d04ace4284/function/function.go#L122-L153
train
apex/apex
function/function.go
loadConfig
func (f *Function) loadConfig(environment string) error { path := fmt.Sprintf("function.%s.json", environment) ok, err := f.tryConfig(path) if err != nil { return err } if ok { f.Log.WithField("config", path).Debug("loaded config") return nil } ok, err = f.tryConfig("function.json") if err != nil { return err } if ok { f.Log.WithField("config", "function.json").Debug("loaded config") return nil } return nil }
go
func (f *Function) loadConfig(environment string) error { path := fmt.Sprintf("function.%s.json", environment) ok, err := f.tryConfig(path) if err != nil { return err } if ok { f.Log.WithField("config", path).Debug("loaded config") return nil } ok, err = f.tryConfig("function.json") if err != nil { return err } if ok { f.Log.WithField("config", "function.json").Debug("loaded config") return nil } return nil }
[ "func", "(", "f", "*", "Function", ")", "loadConfig", "(", "environment", "string", ")", "error", "{", "path", ":=", "fmt", ".", "Sprintf", "(", "\"function.%s.json\"", ",", "environment", ")", "\n", "ok", ",", "err", ":=", "f", ".", "tryConfig", "(", "path", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "if", "ok", "{", "f", ".", "Log", ".", "WithField", "(", "\"config\"", ",", "path", ")", ".", "Debug", "(", "\"loaded config\"", ")", "\n", "return", "nil", "\n", "}", "\n", "ok", ",", "err", "=", "f", ".", "tryConfig", "(", "\"function.json\"", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "if", "ok", "{", "f", ".", "Log", ".", "WithField", "(", "\"config\"", ",", "\"function.json\"", ")", ".", "Debug", "(", "\"loaded config\"", ")", "\n", "return", "nil", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// loadConfig for `environment`, attempt function.ENV.js first, then // fall back on function.json if it is available.
[ "loadConfig", "for", "environment", "attempt", "function", ".", "ENV", ".", "js", "first", "then", "fall", "back", "on", "function", ".", "json", "if", "it", "is", "available", "." ]
c31f0a78ce189a8328563fa6a6eb97d04ace4284
https://github.com/apex/apex/blob/c31f0a78ce189a8328563fa6a6eb97d04ace4284/function/function.go#L183-L207
train
apex/apex
function/function.go
Setenv
func (f *Function) Setenv(name, value string) { f.Environment[name] = value }
go
func (f *Function) Setenv(name, value string) { f.Environment[name] = value }
[ "func", "(", "f", "*", "Function", ")", "Setenv", "(", "name", ",", "value", "string", ")", "{", "f", ".", "Environment", "[", "name", "]", "=", "value", "\n", "}" ]
// Setenv sets environment variable `name` to `value`.
[ "Setenv", "sets", "environment", "variable", "name", "to", "value", "." ]
c31f0a78ce189a8328563fa6a6eb97d04ace4284
https://github.com/apex/apex/blob/c31f0a78ce189a8328563fa6a6eb97d04ace4284/function/function.go#L228-L230
train
apex/apex
function/function.go
Deploy
func (f *Function) Deploy() error { f.Log.Debug("deploying") zip, err := f.ZipBytes() if err != nil { return err } if err := f.hookDeploy(); err != nil { return err } config, err := f.GetConfig() if e, ok := err.(awserr.Error); ok { if e.Code() == "ResourceNotFoundException" { return f.Create(zip) } } if err != nil { return err } if f.configChanged(config) { f.Log.Debug("config changed") return f.DeployConfigAndCode(zip) } f.Log.Info("config unchanged") return f.DeployCode(zip, config) }
go
func (f *Function) Deploy() error { f.Log.Debug("deploying") zip, err := f.ZipBytes() if err != nil { return err } if err := f.hookDeploy(); err != nil { return err } config, err := f.GetConfig() if e, ok := err.(awserr.Error); ok { if e.Code() == "ResourceNotFoundException" { return f.Create(zip) } } if err != nil { return err } if f.configChanged(config) { f.Log.Debug("config changed") return f.DeployConfigAndCode(zip) } f.Log.Info("config unchanged") return f.DeployCode(zip, config) }
[ "func", "(", "f", "*", "Function", ")", "Deploy", "(", ")", "error", "{", "f", ".", "Log", ".", "Debug", "(", "\"deploying\"", ")", "\n", "zip", ",", "err", ":=", "f", ".", "ZipBytes", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "if", "err", ":=", "f", ".", "hookDeploy", "(", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "config", ",", "err", ":=", "f", ".", "GetConfig", "(", ")", "\n", "if", "e", ",", "ok", ":=", "err", ".", "(", "awserr", ".", "Error", ")", ";", "ok", "{", "if", "e", ".", "Code", "(", ")", "==", "\"ResourceNotFoundException\"", "{", "return", "f", ".", "Create", "(", "zip", ")", "\n", "}", "\n", "}", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "if", "f", ".", "configChanged", "(", "config", ")", "{", "f", ".", "Log", ".", "Debug", "(", "\"config changed\"", ")", "\n", "return", "f", ".", "DeployConfigAndCode", "(", "zip", ")", "\n", "}", "\n", "f", ".", "Log", ".", "Info", "(", "\"config unchanged\"", ")", "\n", "return", "f", ".", "DeployCode", "(", "zip", ",", "config", ")", "\n", "}" ]
// Deploy generates a zip and creates or deploy the function. // If the configuration hasn't been changed it will deploy only code, // otherwise it will deploy both configuration and code.
[ "Deploy", "generates", "a", "zip", "and", "creates", "or", "deploy", "the", "function", ".", "If", "the", "configuration", "hasn", "t", "been", "changed", "it", "will", "deploy", "only", "code", "otherwise", "it", "will", "deploy", "both", "configuration", "and", "code", "." ]
c31f0a78ce189a8328563fa6a6eb97d04ace4284
https://github.com/apex/apex/blob/c31f0a78ce189a8328563fa6a6eb97d04ace4284/function/function.go#L235-L266
train
apex/apex
function/function.go
DeployCode
func (f *Function) DeployCode(zip []byte, config *lambda.GetFunctionOutput) error { remoteHash := *config.Configuration.CodeSha256 localHash := utils.Sha256(zip) if localHash == remoteHash { f.Log.Info("code unchanged") version := config.Configuration.Version // Creating an alias to $LATEST would mean its tied to any future deploys. // To correct this behaviour, we take the latest version at the time of deploy. if *version == "$LATEST" { versions, err := f.versions() if err != nil { return err } version = versions[len(versions)-1].Version } return f.CreateOrUpdateAlias(f.Alias, *version) } f.Log.WithFields(log.Fields{ "local": localHash, "remote": remoteHash, }).Debug("code changed") return f.Update(zip) }
go
func (f *Function) DeployCode(zip []byte, config *lambda.GetFunctionOutput) error { remoteHash := *config.Configuration.CodeSha256 localHash := utils.Sha256(zip) if localHash == remoteHash { f.Log.Info("code unchanged") version := config.Configuration.Version // Creating an alias to $LATEST would mean its tied to any future deploys. // To correct this behaviour, we take the latest version at the time of deploy. if *version == "$LATEST" { versions, err := f.versions() if err != nil { return err } version = versions[len(versions)-1].Version } return f.CreateOrUpdateAlias(f.Alias, *version) } f.Log.WithFields(log.Fields{ "local": localHash, "remote": remoteHash, }).Debug("code changed") return f.Update(zip) }
[ "func", "(", "f", "*", "Function", ")", "DeployCode", "(", "zip", "[", "]", "byte", ",", "config", "*", "lambda", ".", "GetFunctionOutput", ")", "error", "{", "remoteHash", ":=", "*", "config", ".", "Configuration", ".", "CodeSha256", "\n", "localHash", ":=", "utils", ".", "Sha256", "(", "zip", ")", "\n", "if", "localHash", "==", "remoteHash", "{", "f", ".", "Log", ".", "Info", "(", "\"code unchanged\"", ")", "\n", "version", ":=", "config", ".", "Configuration", ".", "Version", "\n", "if", "*", "version", "==", "\"$LATEST\"", "{", "versions", ",", "err", ":=", "f", ".", "versions", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "version", "=", "versions", "[", "len", "(", "versions", ")", "-", "1", "]", ".", "Version", "\n", "}", "\n", "return", "f", ".", "CreateOrUpdateAlias", "(", "f", ".", "Alias", ",", "*", "version", ")", "\n", "}", "\n", "f", ".", "Log", ".", "WithFields", "(", "log", ".", "Fields", "{", "\"local\"", ":", "localHash", ",", "\"remote\"", ":", "remoteHash", ",", "}", ")", ".", "Debug", "(", "\"code changed\"", ")", "\n", "return", "f", ".", "Update", "(", "zip", ")", "\n", "}" ]
// DeployCode deploys function code when changed.
[ "DeployCode", "deploys", "function", "code", "when", "changed", "." ]
c31f0a78ce189a8328563fa6a6eb97d04ace4284
https://github.com/apex/apex/blob/c31f0a78ce189a8328563fa6a6eb97d04ace4284/function/function.go#L269-L298
train
apex/apex
function/function.go
DeployConfigAndCode
func (f *Function) DeployConfigAndCode(zip []byte) error { f.Log.Info("updating config") params := &lambda.UpdateFunctionConfigurationInput{ FunctionName: &f.FunctionName, MemorySize: &f.Memory, Timeout: &f.Timeout, Description: &f.Description, Role: &f.Role, Runtime: &f.Runtime, Handler: &f.Handler, KMSKeyArn: &f.KMSKeyArn, Environment: f.environment(), VpcConfig: &lambda.VpcConfig{ SecurityGroupIds: aws.StringSlice(f.VPC.SecurityGroups), SubnetIds: aws.StringSlice(f.VPC.Subnets), }, } if f.DeadLetterARN != "" { params.DeadLetterConfig = &lambda.DeadLetterConfig{ TargetArn: &f.DeadLetterARN, } } _, err := f.Service.UpdateFunctionConfiguration(params) if err != nil { return err } return f.Update(zip) }
go
func (f *Function) DeployConfigAndCode(zip []byte) error { f.Log.Info("updating config") params := &lambda.UpdateFunctionConfigurationInput{ FunctionName: &f.FunctionName, MemorySize: &f.Memory, Timeout: &f.Timeout, Description: &f.Description, Role: &f.Role, Runtime: &f.Runtime, Handler: &f.Handler, KMSKeyArn: &f.KMSKeyArn, Environment: f.environment(), VpcConfig: &lambda.VpcConfig{ SecurityGroupIds: aws.StringSlice(f.VPC.SecurityGroups), SubnetIds: aws.StringSlice(f.VPC.Subnets), }, } if f.DeadLetterARN != "" { params.DeadLetterConfig = &lambda.DeadLetterConfig{ TargetArn: &f.DeadLetterARN, } } _, err := f.Service.UpdateFunctionConfiguration(params) if err != nil { return err } return f.Update(zip) }
[ "func", "(", "f", "*", "Function", ")", "DeployConfigAndCode", "(", "zip", "[", "]", "byte", ")", "error", "{", "f", ".", "Log", ".", "Info", "(", "\"updating config\"", ")", "\n", "params", ":=", "&", "lambda", ".", "UpdateFunctionConfigurationInput", "{", "FunctionName", ":", "&", "f", ".", "FunctionName", ",", "MemorySize", ":", "&", "f", ".", "Memory", ",", "Timeout", ":", "&", "f", ".", "Timeout", ",", "Description", ":", "&", "f", ".", "Description", ",", "Role", ":", "&", "f", ".", "Role", ",", "Runtime", ":", "&", "f", ".", "Runtime", ",", "Handler", ":", "&", "f", ".", "Handler", ",", "KMSKeyArn", ":", "&", "f", ".", "KMSKeyArn", ",", "Environment", ":", "f", ".", "environment", "(", ")", ",", "VpcConfig", ":", "&", "lambda", ".", "VpcConfig", "{", "SecurityGroupIds", ":", "aws", ".", "StringSlice", "(", "f", ".", "VPC", ".", "SecurityGroups", ")", ",", "SubnetIds", ":", "aws", ".", "StringSlice", "(", "f", ".", "VPC", ".", "Subnets", ")", ",", "}", ",", "}", "\n", "if", "f", ".", "DeadLetterARN", "!=", "\"\"", "{", "params", ".", "DeadLetterConfig", "=", "&", "lambda", ".", "DeadLetterConfig", "{", "TargetArn", ":", "&", "f", ".", "DeadLetterARN", ",", "}", "\n", "}", "\n", "_", ",", "err", ":=", "f", ".", "Service", ".", "UpdateFunctionConfiguration", "(", "params", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "return", "f", ".", "Update", "(", "zip", ")", "\n", "}" ]
// DeployConfigAndCode updates config and updates function code.
[ "DeployConfigAndCode", "updates", "config", "and", "updates", "function", "code", "." ]
c31f0a78ce189a8328563fa6a6eb97d04ace4284
https://github.com/apex/apex/blob/c31f0a78ce189a8328563fa6a6eb97d04ace4284/function/function.go#L301-L332
train
apex/apex
function/function.go
Delete
func (f *Function) Delete() error { f.Log.Info("deleting") _, err := f.Service.DeleteFunction(&lambda.DeleteFunctionInput{ FunctionName: &f.FunctionName, }) if err != nil { return err } f.Log.Info("function deleted") return nil }
go
func (f *Function) Delete() error { f.Log.Info("deleting") _, err := f.Service.DeleteFunction(&lambda.DeleteFunctionInput{ FunctionName: &f.FunctionName, }) if err != nil { return err } f.Log.Info("function deleted") return nil }
[ "func", "(", "f", "*", "Function", ")", "Delete", "(", ")", "error", "{", "f", ".", "Log", ".", "Info", "(", "\"deleting\"", ")", "\n", "_", ",", "err", ":=", "f", ".", "Service", ".", "DeleteFunction", "(", "&", "lambda", ".", "DeleteFunctionInput", "{", "FunctionName", ":", "&", "f", ".", "FunctionName", ",", "}", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "f", ".", "Log", ".", "Info", "(", "\"function deleted\"", ")", "\n", "return", "nil", "\n", "}" ]
// Delete the function including all its versions
[ "Delete", "the", "function", "including", "all", "its", "versions" ]
c31f0a78ce189a8328563fa6a6eb97d04ace4284
https://github.com/apex/apex/blob/c31f0a78ce189a8328563fa6a6eb97d04ace4284/function/function.go#L335-L348
train
apex/apex
function/function.go
GetConfig
func (f *Function) GetConfig() (*lambda.GetFunctionOutput, error) { f.Log.Debug("fetching config") return f.Service.GetFunction(&lambda.GetFunctionInput{ FunctionName: &f.FunctionName, }) }
go
func (f *Function) GetConfig() (*lambda.GetFunctionOutput, error) { f.Log.Debug("fetching config") return f.Service.GetFunction(&lambda.GetFunctionInput{ FunctionName: &f.FunctionName, }) }
[ "func", "(", "f", "*", "Function", ")", "GetConfig", "(", ")", "(", "*", "lambda", ".", "GetFunctionOutput", ",", "error", ")", "{", "f", ".", "Log", ".", "Debug", "(", "\"fetching config\"", ")", "\n", "return", "f", ".", "Service", ".", "GetFunction", "(", "&", "lambda", ".", "GetFunctionInput", "{", "FunctionName", ":", "&", "f", ".", "FunctionName", ",", "}", ")", "\n", "}" ]
// GetConfig returns the function configuration.
[ "GetConfig", "returns", "the", "function", "configuration", "." ]
c31f0a78ce189a8328563fa6a6eb97d04ace4284
https://github.com/apex/apex/blob/c31f0a78ce189a8328563fa6a6eb97d04ace4284/function/function.go#L351-L356
train
apex/apex
function/function.go
GetConfigQualifier
func (f *Function) GetConfigQualifier(s string) (*lambda.GetFunctionOutput, error) { f.Log.Debug("fetching config") return f.Service.GetFunction(&lambda.GetFunctionInput{ FunctionName: &f.FunctionName, Qualifier: &s, }) }
go
func (f *Function) GetConfigQualifier(s string) (*lambda.GetFunctionOutput, error) { f.Log.Debug("fetching config") return f.Service.GetFunction(&lambda.GetFunctionInput{ FunctionName: &f.FunctionName, Qualifier: &s, }) }
[ "func", "(", "f", "*", "Function", ")", "GetConfigQualifier", "(", "s", "string", ")", "(", "*", "lambda", ".", "GetFunctionOutput", ",", "error", ")", "{", "f", ".", "Log", ".", "Debug", "(", "\"fetching config\"", ")", "\n", "return", "f", ".", "Service", ".", "GetFunction", "(", "&", "lambda", ".", "GetFunctionInput", "{", "FunctionName", ":", "&", "f", ".", "FunctionName", ",", "Qualifier", ":", "&", "s", ",", "}", ")", "\n", "}" ]
// GetConfigQualifier returns the function configuration for the given qualifier.
[ "GetConfigQualifier", "returns", "the", "function", "configuration", "for", "the", "given", "qualifier", "." ]
c31f0a78ce189a8328563fa6a6eb97d04ace4284
https://github.com/apex/apex/blob/c31f0a78ce189a8328563fa6a6eb97d04ace4284/function/function.go#L359-L365
train
apex/apex
function/function.go
GetConfigCurrent
func (f *Function) GetConfigCurrent() (*lambda.GetFunctionOutput, error) { return f.GetConfigQualifier(f.Alias) }
go
func (f *Function) GetConfigCurrent() (*lambda.GetFunctionOutput, error) { return f.GetConfigQualifier(f.Alias) }
[ "func", "(", "f", "*", "Function", ")", "GetConfigCurrent", "(", ")", "(", "*", "lambda", ".", "GetFunctionOutput", ",", "error", ")", "{", "return", "f", ".", "GetConfigQualifier", "(", "f", ".", "Alias", ")", "\n", "}" ]
// GetConfigCurrent returns the function configuration for the current version.
[ "GetConfigCurrent", "returns", "the", "function", "configuration", "for", "the", "current", "version", "." ]
c31f0a78ce189a8328563fa6a6eb97d04ace4284
https://github.com/apex/apex/blob/c31f0a78ce189a8328563fa6a6eb97d04ace4284/function/function.go#L368-L370
train
apex/apex
function/function.go
Update
func (f *Function) Update(zip []byte) error { f.Log.Info("updating function") updated, err := f.Service.UpdateFunctionCode(&lambda.UpdateFunctionCodeInput{ FunctionName: &f.FunctionName, Publish: aws.Bool(true), ZipFile: zip, }) if err != nil { return err } if err := f.CreateOrUpdateAlias(f.Alias, *updated.Version); err != nil { return err } f.Log.WithFields(log.Fields{ "version": *updated.Version, "name": f.FunctionName, }).Info("function updated") return f.cleanup() }
go
func (f *Function) Update(zip []byte) error { f.Log.Info("updating function") updated, err := f.Service.UpdateFunctionCode(&lambda.UpdateFunctionCodeInput{ FunctionName: &f.FunctionName, Publish: aws.Bool(true), ZipFile: zip, }) if err != nil { return err } if err := f.CreateOrUpdateAlias(f.Alias, *updated.Version); err != nil { return err } f.Log.WithFields(log.Fields{ "version": *updated.Version, "name": f.FunctionName, }).Info("function updated") return f.cleanup() }
[ "func", "(", "f", "*", "Function", ")", "Update", "(", "zip", "[", "]", "byte", ")", "error", "{", "f", ".", "Log", ".", "Info", "(", "\"updating function\"", ")", "\n", "updated", ",", "err", ":=", "f", ".", "Service", ".", "UpdateFunctionCode", "(", "&", "lambda", ".", "UpdateFunctionCodeInput", "{", "FunctionName", ":", "&", "f", ".", "FunctionName", ",", "Publish", ":", "aws", ".", "Bool", "(", "true", ")", ",", "ZipFile", ":", "zip", ",", "}", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "if", "err", ":=", "f", ".", "CreateOrUpdateAlias", "(", "f", ".", "Alias", ",", "*", "updated", ".", "Version", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "f", ".", "Log", ".", "WithFields", "(", "log", ".", "Fields", "{", "\"version\"", ":", "*", "updated", ".", "Version", ",", "\"name\"", ":", "f", ".", "FunctionName", ",", "}", ")", ".", "Info", "(", "\"function updated\"", ")", "\n", "return", "f", ".", "cleanup", "(", ")", "\n", "}" ]
// Update the function with the given `zip`.
[ "Update", "the", "function", "with", "the", "given", "zip", "." ]
c31f0a78ce189a8328563fa6a6eb97d04ace4284
https://github.com/apex/apex/blob/c31f0a78ce189a8328563fa6a6eb97d04ace4284/function/function.go#L373-L396
train
apex/apex
function/function.go
Create
func (f *Function) Create(zip []byte) error { f.Log.Info("creating function") params := &lambda.CreateFunctionInput{ FunctionName: &f.FunctionName, Description: &f.Description, MemorySize: &f.Memory, Timeout: &f.Timeout, Runtime: &f.Runtime, Handler: &f.Handler, Role: &f.Role, KMSKeyArn: &f.KMSKeyArn, Publish: aws.Bool(true), Environment: f.environment(), Code: &lambda.FunctionCode{ ZipFile: zip, }, VpcConfig: &lambda.VpcConfig{ SecurityGroupIds: aws.StringSlice(f.VPC.SecurityGroups), SubnetIds: aws.StringSlice(f.VPC.Subnets), }, } if f.DeadLetterARN != "" { params.DeadLetterConfig = &lambda.DeadLetterConfig{ TargetArn: &f.DeadLetterARN, } } created, err := f.Service.CreateFunction(params) if err != nil { return err } if err := f.CreateOrUpdateAlias(f.Alias, *created.Version); err != nil { return err } f.Log.WithFields(log.Fields{ "version": *created.Version, "name": f.FunctionName, }).Info("function created") return nil }
go
func (f *Function) Create(zip []byte) error { f.Log.Info("creating function") params := &lambda.CreateFunctionInput{ FunctionName: &f.FunctionName, Description: &f.Description, MemorySize: &f.Memory, Timeout: &f.Timeout, Runtime: &f.Runtime, Handler: &f.Handler, Role: &f.Role, KMSKeyArn: &f.KMSKeyArn, Publish: aws.Bool(true), Environment: f.environment(), Code: &lambda.FunctionCode{ ZipFile: zip, }, VpcConfig: &lambda.VpcConfig{ SecurityGroupIds: aws.StringSlice(f.VPC.SecurityGroups), SubnetIds: aws.StringSlice(f.VPC.Subnets), }, } if f.DeadLetterARN != "" { params.DeadLetterConfig = &lambda.DeadLetterConfig{ TargetArn: &f.DeadLetterARN, } } created, err := f.Service.CreateFunction(params) if err != nil { return err } if err := f.CreateOrUpdateAlias(f.Alias, *created.Version); err != nil { return err } f.Log.WithFields(log.Fields{ "version": *created.Version, "name": f.FunctionName, }).Info("function created") return nil }
[ "func", "(", "f", "*", "Function", ")", "Create", "(", "zip", "[", "]", "byte", ")", "error", "{", "f", ".", "Log", ".", "Info", "(", "\"creating function\"", ")", "\n", "params", ":=", "&", "lambda", ".", "CreateFunctionInput", "{", "FunctionName", ":", "&", "f", ".", "FunctionName", ",", "Description", ":", "&", "f", ".", "Description", ",", "MemorySize", ":", "&", "f", ".", "Memory", ",", "Timeout", ":", "&", "f", ".", "Timeout", ",", "Runtime", ":", "&", "f", ".", "Runtime", ",", "Handler", ":", "&", "f", ".", "Handler", ",", "Role", ":", "&", "f", ".", "Role", ",", "KMSKeyArn", ":", "&", "f", ".", "KMSKeyArn", ",", "Publish", ":", "aws", ".", "Bool", "(", "true", ")", ",", "Environment", ":", "f", ".", "environment", "(", ")", ",", "Code", ":", "&", "lambda", ".", "FunctionCode", "{", "ZipFile", ":", "zip", ",", "}", ",", "VpcConfig", ":", "&", "lambda", ".", "VpcConfig", "{", "SecurityGroupIds", ":", "aws", ".", "StringSlice", "(", "f", ".", "VPC", ".", "SecurityGroups", ")", ",", "SubnetIds", ":", "aws", ".", "StringSlice", "(", "f", ".", "VPC", ".", "Subnets", ")", ",", "}", ",", "}", "\n", "if", "f", ".", "DeadLetterARN", "!=", "\"\"", "{", "params", ".", "DeadLetterConfig", "=", "&", "lambda", ".", "DeadLetterConfig", "{", "TargetArn", ":", "&", "f", ".", "DeadLetterARN", ",", "}", "\n", "}", "\n", "created", ",", "err", ":=", "f", ".", "Service", ".", "CreateFunction", "(", "params", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "if", "err", ":=", "f", ".", "CreateOrUpdateAlias", "(", "f", ".", "Alias", ",", "*", "created", ".", "Version", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "f", ".", "Log", ".", "WithFields", "(", "log", ".", "Fields", "{", "\"version\"", ":", "*", "created", ".", "Version", ",", "\"name\"", ":", "f", ".", "FunctionName", ",", "}", ")", ".", "Info", "(", "\"function created\"", ")", "\n", "return", "nil", "\n", "}" ]
// Create the function with the given `zip`.
[ "Create", "the", "function", "with", "the", "given", "zip", "." ]
c31f0a78ce189a8328563fa6a6eb97d04ace4284
https://github.com/apex/apex/blob/c31f0a78ce189a8328563fa6a6eb97d04ace4284/function/function.go#L399-L443
train
apex/apex
function/function.go
CreateOrUpdateAlias
func (f *Function) CreateOrUpdateAlias(alias, version string) error { _, err := f.Service.CreateAlias(&lambda.CreateAliasInput{ FunctionName: &f.FunctionName, FunctionVersion: &version, Name: &alias, }) if err == nil { f.Log.WithField("version", version).Infof("created alias %s", alias) return nil } if e, ok := err.(awserr.Error); !ok || e.Code() != "ResourceConflictException" { return err } _, err = f.Service.UpdateAlias(&lambda.UpdateAliasInput{ FunctionName: &f.FunctionName, FunctionVersion: &version, Name: &alias, }) if err != nil { return err } f.Log.WithField("version", version).Infof("updated alias %s", alias) return nil }
go
func (f *Function) CreateOrUpdateAlias(alias, version string) error { _, err := f.Service.CreateAlias(&lambda.CreateAliasInput{ FunctionName: &f.FunctionName, FunctionVersion: &version, Name: &alias, }) if err == nil { f.Log.WithField("version", version).Infof("created alias %s", alias) return nil } if e, ok := err.(awserr.Error); !ok || e.Code() != "ResourceConflictException" { return err } _, err = f.Service.UpdateAlias(&lambda.UpdateAliasInput{ FunctionName: &f.FunctionName, FunctionVersion: &version, Name: &alias, }) if err != nil { return err } f.Log.WithField("version", version).Infof("updated alias %s", alias) return nil }
[ "func", "(", "f", "*", "Function", ")", "CreateOrUpdateAlias", "(", "alias", ",", "version", "string", ")", "error", "{", "_", ",", "err", ":=", "f", ".", "Service", ".", "CreateAlias", "(", "&", "lambda", ".", "CreateAliasInput", "{", "FunctionName", ":", "&", "f", ".", "FunctionName", ",", "FunctionVersion", ":", "&", "version", ",", "Name", ":", "&", "alias", ",", "}", ")", "\n", "if", "err", "==", "nil", "{", "f", ".", "Log", ".", "WithField", "(", "\"version\"", ",", "version", ")", ".", "Infof", "(", "\"created alias %s\"", ",", "alias", ")", "\n", "return", "nil", "\n", "}", "\n", "if", "e", ",", "ok", ":=", "err", ".", "(", "awserr", ".", "Error", ")", ";", "!", "ok", "||", "e", ".", "Code", "(", ")", "!=", "\"ResourceConflictException\"", "{", "return", "err", "\n", "}", "\n", "_", ",", "err", "=", "f", ".", "Service", ".", "UpdateAlias", "(", "&", "lambda", ".", "UpdateAliasInput", "{", "FunctionName", ":", "&", "f", ".", "FunctionName", ",", "FunctionVersion", ":", "&", "version", ",", "Name", ":", "&", "alias", ",", "}", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "f", ".", "Log", ".", "WithField", "(", "\"version\"", ",", "version", ")", ".", "Infof", "(", "\"updated alias %s\"", ",", "alias", ")", "\n", "return", "nil", "\n", "}" ]
// CreateOrUpdateAlias attempts creating the alias, or updates if it already exists.
[ "CreateOrUpdateAlias", "attempts", "creating", "the", "alias", "or", "updates", "if", "it", "already", "exists", "." ]
c31f0a78ce189a8328563fa6a6eb97d04ace4284
https://github.com/apex/apex/blob/c31f0a78ce189a8328563fa6a6eb97d04ace4284/function/function.go#L446-L474
train
apex/apex
function/function.go
GetAliases
func (f *Function) GetAliases() (*lambda.ListAliasesOutput, error) { f.Log.Debug("fetching aliases") return f.Service.ListAliases(&lambda.ListAliasesInput{ FunctionName: &f.FunctionName, }) }
go
func (f *Function) GetAliases() (*lambda.ListAliasesOutput, error) { f.Log.Debug("fetching aliases") return f.Service.ListAliases(&lambda.ListAliasesInput{ FunctionName: &f.FunctionName, }) }
[ "func", "(", "f", "*", "Function", ")", "GetAliases", "(", ")", "(", "*", "lambda", ".", "ListAliasesOutput", ",", "error", ")", "{", "f", ".", "Log", ".", "Debug", "(", "\"fetching aliases\"", ")", "\n", "return", "f", ".", "Service", ".", "ListAliases", "(", "&", "lambda", ".", "ListAliasesInput", "{", "FunctionName", ":", "&", "f", ".", "FunctionName", ",", "}", ")", "\n", "}" ]
// GetAliases fetches a list of aliases for the function.
[ "GetAliases", "fetches", "a", "list", "of", "aliases", "for", "the", "function", "." ]
c31f0a78ce189a8328563fa6a6eb97d04ace4284
https://github.com/apex/apex/blob/c31f0a78ce189a8328563fa6a6eb97d04ace4284/function/function.go#L477-L482
train
apex/apex
function/function.go
Invoke
func (f *Function) Invoke(event, context interface{}) (reply, logs io.Reader, err error) { eventBytes, err := json.Marshal(event) if err != nil { return nil, nil, err } contextBytes, err := json.Marshal(context) if err != nil { return nil, nil, err } res, err := f.Service.Invoke(&lambda.InvokeInput{ ClientContext: aws.String(base64.StdEncoding.EncodeToString(contextBytes)), FunctionName: &f.FunctionName, InvocationType: aws.String(string(RequestResponse)), LogType: aws.String("Tail"), Qualifier: &f.Alias, Payload: eventBytes, }) if err != nil { return nil, nil, err } logs = base64.NewDecoder(base64.StdEncoding, strings.NewReader(*res.LogResult)) if res.FunctionError != nil { e := &InvokeError{ Handled: *res.FunctionError == "Handled", } if err := json.Unmarshal(res.Payload, e); err != nil { return nil, logs, err } return nil, logs, e } reply = bytes.NewReader(res.Payload) return reply, logs, nil }
go
func (f *Function) Invoke(event, context interface{}) (reply, logs io.Reader, err error) { eventBytes, err := json.Marshal(event) if err != nil { return nil, nil, err } contextBytes, err := json.Marshal(context) if err != nil { return nil, nil, err } res, err := f.Service.Invoke(&lambda.InvokeInput{ ClientContext: aws.String(base64.StdEncoding.EncodeToString(contextBytes)), FunctionName: &f.FunctionName, InvocationType: aws.String(string(RequestResponse)), LogType: aws.String("Tail"), Qualifier: &f.Alias, Payload: eventBytes, }) if err != nil { return nil, nil, err } logs = base64.NewDecoder(base64.StdEncoding, strings.NewReader(*res.LogResult)) if res.FunctionError != nil { e := &InvokeError{ Handled: *res.FunctionError == "Handled", } if err := json.Unmarshal(res.Payload, e); err != nil { return nil, logs, err } return nil, logs, e } reply = bytes.NewReader(res.Payload) return reply, logs, nil }
[ "func", "(", "f", "*", "Function", ")", "Invoke", "(", "event", ",", "context", "interface", "{", "}", ")", "(", "reply", ",", "logs", "io", ".", "Reader", ",", "err", "error", ")", "{", "eventBytes", ",", "err", ":=", "json", ".", "Marshal", "(", "event", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "nil", ",", "err", "\n", "}", "\n", "contextBytes", ",", "err", ":=", "json", ".", "Marshal", "(", "context", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "nil", ",", "err", "\n", "}", "\n", "res", ",", "err", ":=", "f", ".", "Service", ".", "Invoke", "(", "&", "lambda", ".", "InvokeInput", "{", "ClientContext", ":", "aws", ".", "String", "(", "base64", ".", "StdEncoding", ".", "EncodeToString", "(", "contextBytes", ")", ")", ",", "FunctionName", ":", "&", "f", ".", "FunctionName", ",", "InvocationType", ":", "aws", ".", "String", "(", "string", "(", "RequestResponse", ")", ")", ",", "LogType", ":", "aws", ".", "String", "(", "\"Tail\"", ")", ",", "Qualifier", ":", "&", "f", ".", "Alias", ",", "Payload", ":", "eventBytes", ",", "}", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "nil", ",", "err", "\n", "}", "\n", "logs", "=", "base64", ".", "NewDecoder", "(", "base64", ".", "StdEncoding", ",", "strings", ".", "NewReader", "(", "*", "res", ".", "LogResult", ")", ")", "\n", "if", "res", ".", "FunctionError", "!=", "nil", "{", "e", ":=", "&", "InvokeError", "{", "Handled", ":", "*", "res", ".", "FunctionError", "==", "\"Handled\"", ",", "}", "\n", "if", "err", ":=", "json", ".", "Unmarshal", "(", "res", ".", "Payload", ",", "e", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "logs", ",", "err", "\n", "}", "\n", "return", "nil", ",", "logs", ",", "e", "\n", "}", "\n", "reply", "=", "bytes", ".", "NewReader", "(", "res", ".", "Payload", ")", "\n", "return", "reply", ",", "logs", ",", "nil", "\n", "}" ]
// Invoke the remote Lambda function, returning the response and logs, if any.
[ "Invoke", "the", "remote", "Lambda", "function", "returning", "the", "response", "and", "logs", "if", "any", "." ]
c31f0a78ce189a8328563fa6a6eb97d04ace4284
https://github.com/apex/apex/blob/c31f0a78ce189a8328563fa6a6eb97d04ace4284/function/function.go#L485-L525
train
apex/apex
function/function.go
Rollback
func (f *Function) Rollback() error { f.Log.Info("rolling back") alias, err := f.currentVersionAlias() if err != nil { return err } f.Log.Debugf("current version: %s", *alias.FunctionVersion) versions, err := f.versions() if err != nil { return err } if len(versions) < 2 { return errors.New("Can't rollback. Only one version deployed.") } latest := *versions[len(versions)-1].Version prev := *versions[len(versions)-2].Version rollback := latest if *alias.FunctionVersion == latest { rollback = prev } f.Log.Infof("rollback to version: %s", rollback) _, err = f.Service.UpdateAlias(&lambda.UpdateAliasInput{ FunctionName: &f.FunctionName, Name: &f.Alias, FunctionVersion: &rollback, }) if err != nil { return err } f.Log.WithField("current version", rollback).Info("function rolled back") return nil }
go
func (f *Function) Rollback() error { f.Log.Info("rolling back") alias, err := f.currentVersionAlias() if err != nil { return err } f.Log.Debugf("current version: %s", *alias.FunctionVersion) versions, err := f.versions() if err != nil { return err } if len(versions) < 2 { return errors.New("Can't rollback. Only one version deployed.") } latest := *versions[len(versions)-1].Version prev := *versions[len(versions)-2].Version rollback := latest if *alias.FunctionVersion == latest { rollback = prev } f.Log.Infof("rollback to version: %s", rollback) _, err = f.Service.UpdateAlias(&lambda.UpdateAliasInput{ FunctionName: &f.FunctionName, Name: &f.Alias, FunctionVersion: &rollback, }) if err != nil { return err } f.Log.WithField("current version", rollback).Info("function rolled back") return nil }
[ "func", "(", "f", "*", "Function", ")", "Rollback", "(", ")", "error", "{", "f", ".", "Log", ".", "Info", "(", "\"rolling back\"", ")", "\n", "alias", ",", "err", ":=", "f", ".", "currentVersionAlias", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "f", ".", "Log", ".", "Debugf", "(", "\"current version: %s\"", ",", "*", "alias", ".", "FunctionVersion", ")", "\n", "versions", ",", "err", ":=", "f", ".", "versions", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "if", "len", "(", "versions", ")", "<", "2", "{", "return", "errors", ".", "New", "(", "\"Can't rollback. Only one version deployed.\"", ")", "\n", "}", "\n", "latest", ":=", "*", "versions", "[", "len", "(", "versions", ")", "-", "1", "]", ".", "Version", "\n", "prev", ":=", "*", "versions", "[", "len", "(", "versions", ")", "-", "2", "]", ".", "Version", "\n", "rollback", ":=", "latest", "\n", "if", "*", "alias", ".", "FunctionVersion", "==", "latest", "{", "rollback", "=", "prev", "\n", "}", "\n", "f", ".", "Log", ".", "Infof", "(", "\"rollback to version: %s\"", ",", "rollback", ")", "\n", "_", ",", "err", "=", "f", ".", "Service", ".", "UpdateAlias", "(", "&", "lambda", ".", "UpdateAliasInput", "{", "FunctionName", ":", "&", "f", ".", "FunctionName", ",", "Name", ":", "&", "f", ".", "Alias", ",", "FunctionVersion", ":", "&", "rollback", ",", "}", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "f", ".", "Log", ".", "WithField", "(", "\"current version\"", ",", "rollback", ")", ".", "Info", "(", "\"function rolled back\"", ")", "\n", "return", "nil", "\n", "}" ]
// Rollback the function to the previous.
[ "Rollback", "the", "function", "to", "the", "previous", "." ]
c31f0a78ce189a8328563fa6a6eb97d04ace4284
https://github.com/apex/apex/blob/c31f0a78ce189a8328563fa6a6eb97d04ace4284/function/function.go#L528-L570
train
apex/apex
function/function.go
RollbackVersion
func (f *Function) RollbackVersion(version string) error { f.Log.Info("rolling back") alias, err := f.currentVersionAlias() if err != nil { return err } f.Log.Debugf("current version: %s", *alias.FunctionVersion) if version == *alias.FunctionVersion { return errors.New("Specified version currently deployed.") } f.Log.Infof("rollback to version: %s", version) _, err = f.Service.UpdateAlias(&lambda.UpdateAliasInput{ FunctionName: &f.FunctionName, Name: &f.Alias, FunctionVersion: &version, }) if err != nil { return err } f.Log.WithField("current version", version).Info("function rolled back") return nil }
go
func (f *Function) RollbackVersion(version string) error { f.Log.Info("rolling back") alias, err := f.currentVersionAlias() if err != nil { return err } f.Log.Debugf("current version: %s", *alias.FunctionVersion) if version == *alias.FunctionVersion { return errors.New("Specified version currently deployed.") } f.Log.Infof("rollback to version: %s", version) _, err = f.Service.UpdateAlias(&lambda.UpdateAliasInput{ FunctionName: &f.FunctionName, Name: &f.Alias, FunctionVersion: &version, }) if err != nil { return err } f.Log.WithField("current version", version).Info("function rolled back") return nil }
[ "func", "(", "f", "*", "Function", ")", "RollbackVersion", "(", "version", "string", ")", "error", "{", "f", ".", "Log", ".", "Info", "(", "\"rolling back\"", ")", "\n", "alias", ",", "err", ":=", "f", ".", "currentVersionAlias", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "f", ".", "Log", ".", "Debugf", "(", "\"current version: %s\"", ",", "*", "alias", ".", "FunctionVersion", ")", "\n", "if", "version", "==", "*", "alias", ".", "FunctionVersion", "{", "return", "errors", ".", "New", "(", "\"Specified version currently deployed.\"", ")", "\n", "}", "\n", "f", ".", "Log", ".", "Infof", "(", "\"rollback to version: %s\"", ",", "version", ")", "\n", "_", ",", "err", "=", "f", ".", "Service", ".", "UpdateAlias", "(", "&", "lambda", ".", "UpdateAliasInput", "{", "FunctionName", ":", "&", "f", ".", "FunctionName", ",", "Name", ":", "&", "f", ".", "Alias", ",", "FunctionVersion", ":", "&", "version", ",", "}", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "f", ".", "Log", ".", "WithField", "(", "\"current version\"", ",", "version", ")", ".", "Info", "(", "\"function rolled back\"", ")", "\n", "return", "nil", "\n", "}" ]
// RollbackVersion the function to the specified version.
[ "RollbackVersion", "the", "function", "to", "the", "specified", "version", "." ]
c31f0a78ce189a8328563fa6a6eb97d04ace4284
https://github.com/apex/apex/blob/c31f0a78ce189a8328563fa6a6eb97d04ace4284/function/function.go#L573-L602
train
apex/apex
function/function.go
ZipBytes
func (f *Function) ZipBytes() ([]byte, error) { if f.Zip == "" { f.Log.Debug("building zip") return f.BuildBytes() } f.Log.Debugf("reading zip %q", f.Zip) return ioutil.ReadFile(f.Zip) }
go
func (f *Function) ZipBytes() ([]byte, error) { if f.Zip == "" { f.Log.Debug("building zip") return f.BuildBytes() } f.Log.Debugf("reading zip %q", f.Zip) return ioutil.ReadFile(f.Zip) }
[ "func", "(", "f", "*", "Function", ")", "ZipBytes", "(", ")", "(", "[", "]", "byte", ",", "error", ")", "{", "if", "f", ".", "Zip", "==", "\"\"", "{", "f", ".", "Log", ".", "Debug", "(", "\"building zip\"", ")", "\n", "return", "f", ".", "BuildBytes", "(", ")", "\n", "}", "\n", "f", ".", "Log", ".", "Debugf", "(", "\"reading zip %q\"", ",", "f", ".", "Zip", ")", "\n", "return", "ioutil", ".", "ReadFile", "(", "f", ".", "Zip", ")", "\n", "}" ]
// ZipBytes builds the in-memory zip, or reads // the .Zip from disk if specified.
[ "ZipBytes", "builds", "the", "in", "-", "memory", "zip", "or", "reads", "the", ".", "Zip", "from", "disk", "if", "specified", "." ]
c31f0a78ce189a8328563fa6a6eb97d04ace4284
https://github.com/apex/apex/blob/c31f0a78ce189a8328563fa6a6eb97d04ace4284/function/function.go#L606-L614
train
apex/apex
function/function.go
BuildBytes
func (f *Function) BuildBytes() ([]byte, error) { r, err := f.Build() if err != nil { return nil, err } b, err := ioutil.ReadAll(r) if err != nil { return nil, err } f.Log.Debugf("created build (%s)", humanize.Bytes(uint64(len(b)))) return b, nil }
go
func (f *Function) BuildBytes() ([]byte, error) { r, err := f.Build() if err != nil { return nil, err } b, err := ioutil.ReadAll(r) if err != nil { return nil, err } f.Log.Debugf("created build (%s)", humanize.Bytes(uint64(len(b)))) return b, nil }
[ "func", "(", "f", "*", "Function", ")", "BuildBytes", "(", ")", "(", "[", "]", "byte", ",", "error", ")", "{", "r", ",", "err", ":=", "f", ".", "Build", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "b", ",", "err", ":=", "ioutil", ".", "ReadAll", "(", "r", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "f", ".", "Log", ".", "Debugf", "(", "\"created build (%s)\"", ",", "humanize", ".", "Bytes", "(", "uint64", "(", "len", "(", "b", ")", ")", ")", ")", "\n", "return", "b", ",", "nil", "\n", "}" ]
// BuildBytes returns the generated zip as bytes.
[ "BuildBytes", "returns", "the", "generated", "zip", "as", "bytes", "." ]
c31f0a78ce189a8328563fa6a6eb97d04ace4284
https://github.com/apex/apex/blob/c31f0a78ce189a8328563fa6a6eb97d04ace4284/function/function.go#L617-L630
train
apex/apex
function/function.go
Build
func (f *Function) Build() (io.Reader, error) { f.Log.Debugf("creating build") buf := new(bytes.Buffer) zip := archive.NewZip(buf) if err := f.hookBuild(zip); err != nil { return nil, err } paths, err := utils.LoadFiles(f.Path, f.IgnoreFile) if err != nil { return nil, err } for _, path := range paths { f.Log.WithField("file", path).Debug("add file to zip") fullPath := filepath.Join(f.Path, path) fh, err := os.Open(fullPath) if err != nil { return nil, err } info, err := fh.Stat() if err != nil { return nil, err } if info.IsDir() { // It's a symlink, otherwise it shouldn't be returned by LoadFiles linkPath, err := filepath.EvalSymlinks(fullPath) if err != nil { return nil, err } if err := zip.AddDir(linkPath, path); err != nil { return nil, err } } else { if err := zip.AddFile(path, fh); err != nil { return nil, err } } if err := fh.Close(); err != nil { return nil, err } } if err := zip.Close(); err != nil { return nil, err } return buf, nil }
go
func (f *Function) Build() (io.Reader, error) { f.Log.Debugf("creating build") buf := new(bytes.Buffer) zip := archive.NewZip(buf) if err := f.hookBuild(zip); err != nil { return nil, err } paths, err := utils.LoadFiles(f.Path, f.IgnoreFile) if err != nil { return nil, err } for _, path := range paths { f.Log.WithField("file", path).Debug("add file to zip") fullPath := filepath.Join(f.Path, path) fh, err := os.Open(fullPath) if err != nil { return nil, err } info, err := fh.Stat() if err != nil { return nil, err } if info.IsDir() { // It's a symlink, otherwise it shouldn't be returned by LoadFiles linkPath, err := filepath.EvalSymlinks(fullPath) if err != nil { return nil, err } if err := zip.AddDir(linkPath, path); err != nil { return nil, err } } else { if err := zip.AddFile(path, fh); err != nil { return nil, err } } if err := fh.Close(); err != nil { return nil, err } } if err := zip.Close(); err != nil { return nil, err } return buf, nil }
[ "func", "(", "f", "*", "Function", ")", "Build", "(", ")", "(", "io", ".", "Reader", ",", "error", ")", "{", "f", ".", "Log", ".", "Debugf", "(", "\"creating build\"", ")", "\n", "buf", ":=", "new", "(", "bytes", ".", "Buffer", ")", "\n", "zip", ":=", "archive", ".", "NewZip", "(", "buf", ")", "\n", "if", "err", ":=", "f", ".", "hookBuild", "(", "zip", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "paths", ",", "err", ":=", "utils", ".", "LoadFiles", "(", "f", ".", "Path", ",", "f", ".", "IgnoreFile", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "for", "_", ",", "path", ":=", "range", "paths", "{", "f", ".", "Log", ".", "WithField", "(", "\"file\"", ",", "path", ")", ".", "Debug", "(", "\"add file to zip\"", ")", "\n", "fullPath", ":=", "filepath", ".", "Join", "(", "f", ".", "Path", ",", "path", ")", "\n", "fh", ",", "err", ":=", "os", ".", "Open", "(", "fullPath", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "info", ",", "err", ":=", "fh", ".", "Stat", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "if", "info", ".", "IsDir", "(", ")", "{", "linkPath", ",", "err", ":=", "filepath", ".", "EvalSymlinks", "(", "fullPath", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "if", "err", ":=", "zip", ".", "AddDir", "(", "linkPath", ",", "path", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "}", "else", "{", "if", "err", ":=", "zip", ".", "AddFile", "(", "path", ",", "fh", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "}", "\n", "if", "err", ":=", "fh", ".", "Close", "(", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "}", "\n", "if", "err", ":=", "zip", ".", "Close", "(", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "return", "buf", ",", "nil", "\n", "}" ]
// Build returns the zipped contents of the function.
[ "Build", "returns", "the", "zipped", "contents", "of", "the", "function", "." ]
c31f0a78ce189a8328563fa6a6eb97d04ace4284
https://github.com/apex/apex/blob/c31f0a78ce189a8328563fa6a6eb97d04ace4284/function/function.go#L633-L689
train
apex/apex
function/function.go
GetVersionFromAlias
func (f *Function) GetVersionFromAlias(alias string) (string, error) { var version string = alias aliases, err := f.GetAliases() if err != nil { return version, err } for _, fnAlias := range aliases.Aliases { if strings.Compare(version, *fnAlias.Name) == 0 { version = *fnAlias.FunctionVersion break } } return version, nil }
go
func (f *Function) GetVersionFromAlias(alias string) (string, error) { var version string = alias aliases, err := f.GetAliases() if err != nil { return version, err } for _, fnAlias := range aliases.Aliases { if strings.Compare(version, *fnAlias.Name) == 0 { version = *fnAlias.FunctionVersion break } } return version, nil }
[ "func", "(", "f", "*", "Function", ")", "GetVersionFromAlias", "(", "alias", "string", ")", "(", "string", ",", "error", ")", "{", "var", "version", "string", "=", "alias", "\n", "aliases", ",", "err", ":=", "f", ".", "GetAliases", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "version", ",", "err", "\n", "}", "\n", "for", "_", ",", "fnAlias", ":=", "range", "aliases", ".", "Aliases", "{", "if", "strings", ".", "Compare", "(", "version", ",", "*", "fnAlias", ".", "Name", ")", "==", "0", "{", "version", "=", "*", "fnAlias", ".", "FunctionVersion", "\n", "break", "\n", "}", "\n", "}", "\n", "return", "version", ",", "nil", "\n", "}" ]
// Return function version from alias name, if alias not found, return the input
[ "Return", "function", "version", "from", "alias", "name", "if", "alias", "not", "found", "return", "the", "input" ]
c31f0a78ce189a8328563fa6a6eb97d04ace4284
https://github.com/apex/apex/blob/c31f0a78ce189a8328563fa6a6eb97d04ace4284/function/function.go#L702-L716
train
apex/apex
function/function.go
cleanup
func (f *Function) cleanup() error { versionsToCleanup, err := f.versionsToCleanup() if err != nil { return err } return f.removeVersions(versionsToCleanup) }
go
func (f *Function) cleanup() error { versionsToCleanup, err := f.versionsToCleanup() if err != nil { return err } return f.removeVersions(versionsToCleanup) }
[ "func", "(", "f", "*", "Function", ")", "cleanup", "(", ")", "error", "{", "versionsToCleanup", ",", "err", ":=", "f", ".", "versionsToCleanup", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "return", "f", ".", "removeVersions", "(", "versionsToCleanup", ")", "\n", "}" ]
// cleanup removes any deployed functions beyond the configured `RetainedVersions` value
[ "cleanup", "removes", "any", "deployed", "functions", "beyond", "the", "configured", "RetainedVersions", "value" ]
c31f0a78ce189a8328563fa6a6eb97d04ace4284
https://github.com/apex/apex/blob/c31f0a78ce189a8328563fa6a6eb97d04ace4284/function/function.go#L719-L726
train
apex/apex
function/function.go
versions
func (f *Function) versions() ([]*lambda.FunctionConfiguration, error) { var list []*lambda.FunctionConfiguration request := lambda.ListVersionsByFunctionInput{ FunctionName: &f.FunctionName, } for { page, err := f.Service.ListVersionsByFunction(&request) if err != nil { return nil, err } list = append(list, page.Versions...) if page.NextMarker == nil { break } request.Marker = page.NextMarker } versions := list[1:] // remove $LATEST return versions, nil }
go
func (f *Function) versions() ([]*lambda.FunctionConfiguration, error) { var list []*lambda.FunctionConfiguration request := lambda.ListVersionsByFunctionInput{ FunctionName: &f.FunctionName, } for { page, err := f.Service.ListVersionsByFunction(&request) if err != nil { return nil, err } list = append(list, page.Versions...) if page.NextMarker == nil { break } request.Marker = page.NextMarker } versions := list[1:] // remove $LATEST return versions, nil }
[ "func", "(", "f", "*", "Function", ")", "versions", "(", ")", "(", "[", "]", "*", "lambda", ".", "FunctionConfiguration", ",", "error", ")", "{", "var", "list", "[", "]", "*", "lambda", ".", "FunctionConfiguration", "\n", "request", ":=", "lambda", ".", "ListVersionsByFunctionInput", "{", "FunctionName", ":", "&", "f", ".", "FunctionName", ",", "}", "\n", "for", "{", "page", ",", "err", ":=", "f", ".", "Service", ".", "ListVersionsByFunction", "(", "&", "request", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "list", "=", "append", "(", "list", ",", "page", ".", "Versions", "...", ")", "\n", "if", "page", ".", "NextMarker", "==", "nil", "{", "break", "\n", "}", "\n", "request", ".", "Marker", "=", "page", ".", "NextMarker", "\n", "}", "\n", "versions", ":=", "list", "[", "1", ":", "]", "\n", "return", "versions", ",", "nil", "\n", "}" ]
// versions returns list of all versions deployed to AWS Lambda
[ "versions", "returns", "list", "of", "all", "versions", "deployed", "to", "AWS", "Lambda" ]
c31f0a78ce189a8328563fa6a6eb97d04ace4284
https://github.com/apex/apex/blob/c31f0a78ce189a8328563fa6a6eb97d04ace4284/function/function.go#L729-L753
train
apex/apex
function/function.go
versionsToCleanup
func (f *Function) versionsToCleanup() ([]*lambda.FunctionConfiguration, error) { versions, err := f.versions() if err != nil { return nil, err } if *f.RetainedVersions == 0 { return versions, nil } if len(versions) > *f.RetainedVersions { return versions[:len(versions)-*f.RetainedVersions], nil } return nil, nil }
go
func (f *Function) versionsToCleanup() ([]*lambda.FunctionConfiguration, error) { versions, err := f.versions() if err != nil { return nil, err } if *f.RetainedVersions == 0 { return versions, nil } if len(versions) > *f.RetainedVersions { return versions[:len(versions)-*f.RetainedVersions], nil } return nil, nil }
[ "func", "(", "f", "*", "Function", ")", "versionsToCleanup", "(", ")", "(", "[", "]", "*", "lambda", ".", "FunctionConfiguration", ",", "error", ")", "{", "versions", ",", "err", ":=", "f", ".", "versions", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "if", "*", "f", ".", "RetainedVersions", "==", "0", "{", "return", "versions", ",", "nil", "\n", "}", "\n", "if", "len", "(", "versions", ")", ">", "*", "f", ".", "RetainedVersions", "{", "return", "versions", "[", ":", "len", "(", "versions", ")", "-", "*", "f", ".", "RetainedVersions", "]", ",", "nil", "\n", "}", "\n", "return", "nil", ",", "nil", "\n", "}" ]
// versionsToCleanup returns list of versions to remove after updating function
[ "versionsToCleanup", "returns", "list", "of", "versions", "to", "remove", "after", "updating", "function" ]
c31f0a78ce189a8328563fa6a6eb97d04ace4284
https://github.com/apex/apex/blob/c31f0a78ce189a8328563fa6a6eb97d04ace4284/function/function.go#L756-L771
train
apex/apex
function/function.go
removeVersions
func (f *Function) removeVersions(versions []*lambda.FunctionConfiguration) error { for _, v := range versions { f.Log.Debugf("cleaning up version: %s", *v.Version) _, err := f.Service.DeleteFunction(&lambda.DeleteFunctionInput{ FunctionName: &f.FunctionName, Qualifier: v.Version, }) if err != nil { return err } } return nil }
go
func (f *Function) removeVersions(versions []*lambda.FunctionConfiguration) error { for _, v := range versions { f.Log.Debugf("cleaning up version: %s", *v.Version) _, err := f.Service.DeleteFunction(&lambda.DeleteFunctionInput{ FunctionName: &f.FunctionName, Qualifier: v.Version, }) if err != nil { return err } } return nil }
[ "func", "(", "f", "*", "Function", ")", "removeVersions", "(", "versions", "[", "]", "*", "lambda", ".", "FunctionConfiguration", ")", "error", "{", "for", "_", ",", "v", ":=", "range", "versions", "{", "f", ".", "Log", ".", "Debugf", "(", "\"cleaning up version: %s\"", ",", "*", "v", ".", "Version", ")", "\n", "_", ",", "err", ":=", "f", ".", "Service", ".", "DeleteFunction", "(", "&", "lambda", ".", "DeleteFunctionInput", "{", "FunctionName", ":", "&", "f", ".", "FunctionName", ",", "Qualifier", ":", "v", ".", "Version", ",", "}", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// removeVersions removes specifed function's versions
[ "removeVersions", "removes", "specifed", "function", "s", "versions" ]
c31f0a78ce189a8328563fa6a6eb97d04ace4284
https://github.com/apex/apex/blob/c31f0a78ce189a8328563fa6a6eb97d04ace4284/function/function.go#L774-L789
train
apex/apex
function/function.go
currentVersionAlias
func (f *Function) currentVersionAlias() (*lambda.AliasConfiguration, error) { return f.Service.GetAlias(&lambda.GetAliasInput{ FunctionName: &f.FunctionName, Name: &f.Alias, }) }
go
func (f *Function) currentVersionAlias() (*lambda.AliasConfiguration, error) { return f.Service.GetAlias(&lambda.GetAliasInput{ FunctionName: &f.FunctionName, Name: &f.Alias, }) }
[ "func", "(", "f", "*", "Function", ")", "currentVersionAlias", "(", ")", "(", "*", "lambda", ".", "AliasConfiguration", ",", "error", ")", "{", "return", "f", ".", "Service", ".", "GetAlias", "(", "&", "lambda", ".", "GetAliasInput", "{", "FunctionName", ":", "&", "f", ".", "FunctionName", ",", "Name", ":", "&", "f", ".", "Alias", ",", "}", ")", "\n", "}" ]
// currentVersionAlias returns alias configuration for currently deployed function
[ "currentVersionAlias", "returns", "alias", "configuration", "for", "currently", "deployed", "function" ]
c31f0a78ce189a8328563fa6a6eb97d04ace4284
https://github.com/apex/apex/blob/c31f0a78ce189a8328563fa6a6eb97d04ace4284/function/function.go#L792-L797
train
apex/apex
function/function.go
configChanged
func (f *Function) configChanged(config *lambda.GetFunctionOutput) bool { type diffConfig struct { Description string Memory int64 Timeout int64 Role string Runtime string Handler string VPC vpc.VPC Environment []string KMSKeyArn string DeadLetterConfig lambda.DeadLetterConfig } localConfig := &diffConfig{ Description: f.Description, Memory: f.Memory, Timeout: f.Timeout, Role: f.Role, Runtime: f.Runtime, Handler: f.Handler, KMSKeyArn: f.KMSKeyArn, Environment: environ(f.environment().Variables), VPC: vpc.VPC{ Subnets: f.VPC.Subnets, SecurityGroups: f.VPC.SecurityGroups, }, } if f.DeadLetterARN != "" { localConfig.DeadLetterConfig = lambda.DeadLetterConfig{ TargetArn: &f.DeadLetterARN, } } remoteConfig := &diffConfig{ Description: *config.Configuration.Description, Memory: *config.Configuration.MemorySize, Timeout: *config.Configuration.Timeout, Role: *config.Configuration.Role, Runtime: *config.Configuration.Runtime, Handler: *config.Configuration.Handler, } if config.Configuration.KMSKeyArn != nil { remoteConfig.KMSKeyArn = *config.Configuration.KMSKeyArn } if config.Configuration.Environment != nil { remoteConfig.Environment = environ(config.Configuration.Environment.Variables) } if config.Configuration.DeadLetterConfig != nil { remoteConfig.DeadLetterConfig = lambda.DeadLetterConfig{ TargetArn: config.Configuration.DeadLetterConfig.TargetArn, } } // SDK is inconsistent here. VpcConfig can be nil or empty struct. remoteConfig.VPC = vpc.VPC{Subnets: []string{}, SecurityGroups: []string{}} if config.Configuration.VpcConfig != nil { remoteConfig.VPC = vpc.VPC{ Subnets: aws.StringValueSlice(config.Configuration.VpcConfig.SubnetIds), SecurityGroups: aws.StringValueSlice(config.Configuration.VpcConfig.SecurityGroupIds), } } // don't make any assumptions about the order AWS stores the subnets or security groups sort.StringSlice(remoteConfig.VPC.Subnets).Sort() sort.StringSlice(localConfig.VPC.Subnets).Sort() sort.StringSlice(remoteConfig.VPC.SecurityGroups).Sort() sort.StringSlice(localConfig.VPC.SecurityGroups).Sort() localConfigJSON, _ := json.Marshal(localConfig) remoteConfigJSON, _ := json.Marshal(remoteConfig) return string(localConfigJSON) != string(remoteConfigJSON) }
go
func (f *Function) configChanged(config *lambda.GetFunctionOutput) bool { type diffConfig struct { Description string Memory int64 Timeout int64 Role string Runtime string Handler string VPC vpc.VPC Environment []string KMSKeyArn string DeadLetterConfig lambda.DeadLetterConfig } localConfig := &diffConfig{ Description: f.Description, Memory: f.Memory, Timeout: f.Timeout, Role: f.Role, Runtime: f.Runtime, Handler: f.Handler, KMSKeyArn: f.KMSKeyArn, Environment: environ(f.environment().Variables), VPC: vpc.VPC{ Subnets: f.VPC.Subnets, SecurityGroups: f.VPC.SecurityGroups, }, } if f.DeadLetterARN != "" { localConfig.DeadLetterConfig = lambda.DeadLetterConfig{ TargetArn: &f.DeadLetterARN, } } remoteConfig := &diffConfig{ Description: *config.Configuration.Description, Memory: *config.Configuration.MemorySize, Timeout: *config.Configuration.Timeout, Role: *config.Configuration.Role, Runtime: *config.Configuration.Runtime, Handler: *config.Configuration.Handler, } if config.Configuration.KMSKeyArn != nil { remoteConfig.KMSKeyArn = *config.Configuration.KMSKeyArn } if config.Configuration.Environment != nil { remoteConfig.Environment = environ(config.Configuration.Environment.Variables) } if config.Configuration.DeadLetterConfig != nil { remoteConfig.DeadLetterConfig = lambda.DeadLetterConfig{ TargetArn: config.Configuration.DeadLetterConfig.TargetArn, } } // SDK is inconsistent here. VpcConfig can be nil or empty struct. remoteConfig.VPC = vpc.VPC{Subnets: []string{}, SecurityGroups: []string{}} if config.Configuration.VpcConfig != nil { remoteConfig.VPC = vpc.VPC{ Subnets: aws.StringValueSlice(config.Configuration.VpcConfig.SubnetIds), SecurityGroups: aws.StringValueSlice(config.Configuration.VpcConfig.SecurityGroupIds), } } // don't make any assumptions about the order AWS stores the subnets or security groups sort.StringSlice(remoteConfig.VPC.Subnets).Sort() sort.StringSlice(localConfig.VPC.Subnets).Sort() sort.StringSlice(remoteConfig.VPC.SecurityGroups).Sort() sort.StringSlice(localConfig.VPC.SecurityGroups).Sort() localConfigJSON, _ := json.Marshal(localConfig) remoteConfigJSON, _ := json.Marshal(remoteConfig) return string(localConfigJSON) != string(remoteConfigJSON) }
[ "func", "(", "f", "*", "Function", ")", "configChanged", "(", "config", "*", "lambda", ".", "GetFunctionOutput", ")", "bool", "{", "type", "diffConfig", "struct", "{", "Description", "string", "\n", "Memory", "int64", "\n", "Timeout", "int64", "\n", "Role", "string", "\n", "Runtime", "string", "\n", "Handler", "string", "\n", "VPC", "vpc", ".", "VPC", "\n", "Environment", "[", "]", "string", "\n", "KMSKeyArn", "string", "\n", "DeadLetterConfig", "lambda", ".", "DeadLetterConfig", "\n", "}", "\n", "localConfig", ":=", "&", "diffConfig", "{", "Description", ":", "f", ".", "Description", ",", "Memory", ":", "f", ".", "Memory", ",", "Timeout", ":", "f", ".", "Timeout", ",", "Role", ":", "f", ".", "Role", ",", "Runtime", ":", "f", ".", "Runtime", ",", "Handler", ":", "f", ".", "Handler", ",", "KMSKeyArn", ":", "f", ".", "KMSKeyArn", ",", "Environment", ":", "environ", "(", "f", ".", "environment", "(", ")", ".", "Variables", ")", ",", "VPC", ":", "vpc", ".", "VPC", "{", "Subnets", ":", "f", ".", "VPC", ".", "Subnets", ",", "SecurityGroups", ":", "f", ".", "VPC", ".", "SecurityGroups", ",", "}", ",", "}", "\n", "if", "f", ".", "DeadLetterARN", "!=", "\"\"", "{", "localConfig", ".", "DeadLetterConfig", "=", "lambda", ".", "DeadLetterConfig", "{", "TargetArn", ":", "&", "f", ".", "DeadLetterARN", ",", "}", "\n", "}", "\n", "remoteConfig", ":=", "&", "diffConfig", "{", "Description", ":", "*", "config", ".", "Configuration", ".", "Description", ",", "Memory", ":", "*", "config", ".", "Configuration", ".", "MemorySize", ",", "Timeout", ":", "*", "config", ".", "Configuration", ".", "Timeout", ",", "Role", ":", "*", "config", ".", "Configuration", ".", "Role", ",", "Runtime", ":", "*", "config", ".", "Configuration", ".", "Runtime", ",", "Handler", ":", "*", "config", ".", "Configuration", ".", "Handler", ",", "}", "\n", "if", "config", ".", "Configuration", ".", "KMSKeyArn", "!=", "nil", "{", "remoteConfig", ".", "KMSKeyArn", "=", "*", "config", ".", "Configuration", ".", "KMSKeyArn", "\n", "}", "\n", "if", "config", ".", "Configuration", ".", "Environment", "!=", "nil", "{", "remoteConfig", ".", "Environment", "=", "environ", "(", "config", ".", "Configuration", ".", "Environment", ".", "Variables", ")", "\n", "}", "\n", "if", "config", ".", "Configuration", ".", "DeadLetterConfig", "!=", "nil", "{", "remoteConfig", ".", "DeadLetterConfig", "=", "lambda", ".", "DeadLetterConfig", "{", "TargetArn", ":", "config", ".", "Configuration", ".", "DeadLetterConfig", ".", "TargetArn", ",", "}", "\n", "}", "\n", "remoteConfig", ".", "VPC", "=", "vpc", ".", "VPC", "{", "Subnets", ":", "[", "]", "string", "{", "}", ",", "SecurityGroups", ":", "[", "]", "string", "{", "}", "}", "\n", "if", "config", ".", "Configuration", ".", "VpcConfig", "!=", "nil", "{", "remoteConfig", ".", "VPC", "=", "vpc", ".", "VPC", "{", "Subnets", ":", "aws", ".", "StringValueSlice", "(", "config", ".", "Configuration", ".", "VpcConfig", ".", "SubnetIds", ")", ",", "SecurityGroups", ":", "aws", ".", "StringValueSlice", "(", "config", ".", "Configuration", ".", "VpcConfig", ".", "SecurityGroupIds", ")", ",", "}", "\n", "}", "\n", "sort", ".", "StringSlice", "(", "remoteConfig", ".", "VPC", ".", "Subnets", ")", ".", "Sort", "(", ")", "\n", "sort", ".", "StringSlice", "(", "localConfig", ".", "VPC", ".", "Subnets", ")", ".", "Sort", "(", ")", "\n", "sort", ".", "StringSlice", "(", "remoteConfig", ".", "VPC", ".", "SecurityGroups", ")", ".", "Sort", "(", ")", "\n", "sort", ".", "StringSlice", "(", "localConfig", ".", "VPC", ".", "SecurityGroups", ")", ".", "Sort", "(", ")", "\n", "localConfigJSON", ",", "_", ":=", "json", ".", "Marshal", "(", "localConfig", ")", "\n", "remoteConfigJSON", ",", "_", ":=", "json", ".", "Marshal", "(", "remoteConfig", ")", "\n", "return", "string", "(", "localConfigJSON", ")", "!=", "string", "(", "remoteConfigJSON", ")", "\n", "}" ]
// configChanged checks if function configuration differs from configuration stored in AWS Lambda
[ "configChanged", "checks", "if", "function", "configuration", "differs", "from", "configuration", "stored", "in", "AWS", "Lambda" ]
c31f0a78ce189a8328563fa6a6eb97d04ace4284
https://github.com/apex/apex/blob/c31f0a78ce189a8328563fa6a6eb97d04ace4284/function/function.go#L800-L876
train
apex/apex
function/function.go
hookOpen
func (f *Function) hookOpen() error { for _, name := range f.Plugins { if p, ok := plugins[name].(Opener); ok { if err := p.Open(f); err != nil { return err } } } return nil }
go
func (f *Function) hookOpen() error { for _, name := range f.Plugins { if p, ok := plugins[name].(Opener); ok { if err := p.Open(f); err != nil { return err } } } return nil }
[ "func", "(", "f", "*", "Function", ")", "hookOpen", "(", ")", "error", "{", "for", "_", ",", "name", ":=", "range", "f", ".", "Plugins", "{", "if", "p", ",", "ok", ":=", "plugins", "[", "name", "]", ".", "(", "Opener", ")", ";", "ok", "{", "if", "err", ":=", "p", ".", "Open", "(", "f", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "}", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// hookOpen calls Openers.
[ "hookOpen", "calls", "Openers", "." ]
c31f0a78ce189a8328563fa6a6eb97d04ace4284
https://github.com/apex/apex/blob/c31f0a78ce189a8328563fa6a6eb97d04ace4284/function/function.go#L879-L888
train
apex/apex
function/function.go
hookBuild
func (f *Function) hookBuild(zip *archive.Zip) error { for _, name := range f.Plugins { if p, ok := plugins[name].(Builder); ok { if err := p.Build(f, zip); err != nil { return err } } } return nil }
go
func (f *Function) hookBuild(zip *archive.Zip) error { for _, name := range f.Plugins { if p, ok := plugins[name].(Builder); ok { if err := p.Build(f, zip); err != nil { return err } } } return nil }
[ "func", "(", "f", "*", "Function", ")", "hookBuild", "(", "zip", "*", "archive", ".", "Zip", ")", "error", "{", "for", "_", ",", "name", ":=", "range", "f", ".", "Plugins", "{", "if", "p", ",", "ok", ":=", "plugins", "[", "name", "]", ".", "(", "Builder", ")", ";", "ok", "{", "if", "err", ":=", "p", ".", "Build", "(", "f", ",", "zip", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "}", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// hookBuild calls Builders.
[ "hookBuild", "calls", "Builders", "." ]
c31f0a78ce189a8328563fa6a6eb97d04ace4284
https://github.com/apex/apex/blob/c31f0a78ce189a8328563fa6a6eb97d04ace4284/function/function.go#L891-L900
train
apex/apex
function/function.go
hookClean
func (f *Function) hookClean() error { for _, name := range f.Plugins { if p, ok := plugins[name].(Cleaner); ok { if err := p.Clean(f); err != nil { return err } } } return nil }
go
func (f *Function) hookClean() error { for _, name := range f.Plugins { if p, ok := plugins[name].(Cleaner); ok { if err := p.Clean(f); err != nil { return err } } } return nil }
[ "func", "(", "f", "*", "Function", ")", "hookClean", "(", ")", "error", "{", "for", "_", ",", "name", ":=", "range", "f", ".", "Plugins", "{", "if", "p", ",", "ok", ":=", "plugins", "[", "name", "]", ".", "(", "Cleaner", ")", ";", "ok", "{", "if", "err", ":=", "p", ".", "Clean", "(", "f", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "}", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// hookClean calls Cleaners.
[ "hookClean", "calls", "Cleaners", "." ]
c31f0a78ce189a8328563fa6a6eb97d04ace4284
https://github.com/apex/apex/blob/c31f0a78ce189a8328563fa6a6eb97d04ace4284/function/function.go#L903-L912
train
apex/apex
function/function.go
hookDeploy
func (f *Function) hookDeploy() error { for _, name := range f.Plugins { if p, ok := plugins[name].(Deployer); ok { if err := p.Deploy(f); err != nil { return err } } } return nil }
go
func (f *Function) hookDeploy() error { for _, name := range f.Plugins { if p, ok := plugins[name].(Deployer); ok { if err := p.Deploy(f); err != nil { return err } } } return nil }
[ "func", "(", "f", "*", "Function", ")", "hookDeploy", "(", ")", "error", "{", "for", "_", ",", "name", ":=", "range", "f", ".", "Plugins", "{", "if", "p", ",", "ok", ":=", "plugins", "[", "name", "]", ".", "(", "Deployer", ")", ";", "ok", "{", "if", "err", ":=", "p", ".", "Deploy", "(", "f", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "}", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// hookDeploy calls Deployers.
[ "hookDeploy", "calls", "Deployers", "." ]
c31f0a78ce189a8328563fa6a6eb97d04ace4284
https://github.com/apex/apex/blob/c31f0a78ce189a8328563fa6a6eb97d04ace4284/function/function.go#L915-L924
train
apex/apex
function/function.go
environment
func (f *Function) environment() *lambda.Environment { env := make(map[string]*string) if !f.Edge { for k, v := range f.Environment { env[k] = aws.String(v) } } return &lambda.Environment{Variables: env} }
go
func (f *Function) environment() *lambda.Environment { env := make(map[string]*string) if !f.Edge { for k, v := range f.Environment { env[k] = aws.String(v) } } return &lambda.Environment{Variables: env} }
[ "func", "(", "f", "*", "Function", ")", "environment", "(", ")", "*", "lambda", ".", "Environment", "{", "env", ":=", "make", "(", "map", "[", "string", "]", "*", "string", ")", "\n", "if", "!", "f", ".", "Edge", "{", "for", "k", ",", "v", ":=", "range", "f", ".", "Environment", "{", "env", "[", "k", "]", "=", "aws", ".", "String", "(", "v", ")", "\n", "}", "\n", "}", "\n", "return", "&", "lambda", ".", "Environment", "{", "Variables", ":", "env", "}", "\n", "}" ]
// environment for lambda calls.
[ "environment", "for", "lambda", "calls", "." ]
c31f0a78ce189a8328563fa6a6eb97d04ace4284
https://github.com/apex/apex/blob/c31f0a78ce189a8328563fa6a6eb97d04ace4284/function/function.go#L927-L935
train
apex/apex
function/function.go
environ
func environ(env map[string]*string) []string { var keys []string var pairs []string for k := range env { keys = append(keys, k) } sort.Strings(keys) for _, k := range keys { pairs = append(pairs, fmt.Sprintf("%s=%s", k, *env[k])) } return pairs }
go
func environ(env map[string]*string) []string { var keys []string var pairs []string for k := range env { keys = append(keys, k) } sort.Strings(keys) for _, k := range keys { pairs = append(pairs, fmt.Sprintf("%s=%s", k, *env[k])) } return pairs }
[ "func", "environ", "(", "env", "map", "[", "string", "]", "*", "string", ")", "[", "]", "string", "{", "var", "keys", "[", "]", "string", "\n", "var", "pairs", "[", "]", "string", "\n", "for", "k", ":=", "range", "env", "{", "keys", "=", "append", "(", "keys", ",", "k", ")", "\n", "}", "\n", "sort", ".", "Strings", "(", "keys", ")", "\n", "for", "_", ",", "k", ":=", "range", "keys", "{", "pairs", "=", "append", "(", "pairs", ",", "fmt", ".", "Sprintf", "(", "\"%s=%s\"", ",", "k", ",", "*", "env", "[", "k", "]", ")", ")", "\n", "}", "\n", "return", "pairs", "\n", "}" ]
// environment sorted and joined.
[ "environment", "sorted", "and", "joined", "." ]
c31f0a78ce189a8328563fa6a6eb97d04ace4284
https://github.com/apex/apex/blob/c31f0a78ce189a8328563fa6a6eb97d04ace4284/function/function.go#L938-L953
train
apex/apex
function/function.go
AWSConfig
func (f *Function) AWSConfig() *aws.Config { region := f.Config.Region if f.Config.Edge { region = "us-east-1" } if len(region) > 0 { return aws.NewConfig().WithRegion(region) } return nil }
go
func (f *Function) AWSConfig() *aws.Config { region := f.Config.Region if f.Config.Edge { region = "us-east-1" } if len(region) > 0 { return aws.NewConfig().WithRegion(region) } return nil }
[ "func", "(", "f", "*", "Function", ")", "AWSConfig", "(", ")", "*", "aws", ".", "Config", "{", "region", ":=", "f", ".", "Config", ".", "Region", "\n", "if", "f", ".", "Config", ".", "Edge", "{", "region", "=", "\"us-east-1\"", "\n", "}", "\n", "if", "len", "(", "region", ")", ">", "0", "{", "return", "aws", ".", "NewConfig", "(", ")", ".", "WithRegion", "(", "region", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// AWSConfig returns AWS configuration if function has specified region.
[ "AWSConfig", "returns", "AWS", "configuration", "if", "function", "has", "specified", "region", "." ]
c31f0a78ce189a8328563fa6a6eb97d04ace4284
https://github.com/apex/apex/blob/c31f0a78ce189a8328563fa6a6eb97d04ace4284/function/function.go#L956-L966
train
apex/apex
docs/docs.go
Reader
func Reader() io.Reader { var in bytes.Buffer for _, page := range pages { in.WriteString(fmt.Sprintf("\n# %s\n", page.Name)) in.Write(MustAsset(page.File)) } md := markdown.New(markdown.XHTMLOutput(true), markdown.Nofollow(true)) v := &renderer{} s := v.visit(md.Parse(in.Bytes())) return strings.NewReader(s) }
go
func Reader() io.Reader { var in bytes.Buffer for _, page := range pages { in.WriteString(fmt.Sprintf("\n# %s\n", page.Name)) in.Write(MustAsset(page.File)) } md := markdown.New(markdown.XHTMLOutput(true), markdown.Nofollow(true)) v := &renderer{} s := v.visit(md.Parse(in.Bytes())) return strings.NewReader(s) }
[ "func", "Reader", "(", ")", "io", ".", "Reader", "{", "var", "in", "bytes", ".", "Buffer", "\n", "for", "_", ",", "page", ":=", "range", "pages", "{", "in", ".", "WriteString", "(", "fmt", ".", "Sprintf", "(", "\"\\n# %s\\n\"", ",", "\\n", ")", ")", "\n", "\\n", "\n", "}", "\n", "page", ".", "Name", "\n", "in", ".", "Write", "(", "MustAsset", "(", "page", ".", "File", ")", ")", "\n", "md", ":=", "markdown", ".", "New", "(", "markdown", ".", "XHTMLOutput", "(", "true", ")", ",", "markdown", ".", "Nofollow", "(", "true", ")", ")", "\n", "v", ":=", "&", "renderer", "{", "}", "\n", "}" ]
// Reader returns all documentation as a single page.
[ "Reader", "returns", "all", "documentation", "as", "a", "single", "page", "." ]
c31f0a78ce189a8328563fa6a6eb97d04ace4284
https://github.com/apex/apex/blob/c31f0a78ce189a8328563fa6a6eb97d04ace4284/docs/docs.go#L52-L64
train
apex/apex
docs/docs.go
indent
func indent(s string, n int) string { i := strings.Repeat(" ", n) return i + strings.Replace(s, "\n", "\n"+i, -1) }
go
func indent(s string, n int) string { i := strings.Repeat(" ", n) return i + strings.Replace(s, "\n", "\n"+i, -1) }
[ "func", "indent", "(", "s", "string", ",", "n", "int", ")", "string", "{", "i", ":=", "strings", ".", "Repeat", "(", "\" \"", ",", "n", ")", "\n", "return", "i", "+", "strings", ".", "Replace", "(", "s", ",", "\"\\n\"", ",", "\\n", ",", "\"\\n\"", "+", "\\n", ")", "\n", "}" ]
// indent string N times.
[ "indent", "string", "N", "times", "." ]
c31f0a78ce189a8328563fa6a6eb97d04ace4284
https://github.com/apex/apex/blob/c31f0a78ce189a8328563fa6a6eb97d04ace4284/docs/docs.go#L67-L70
train
apex/apex
docs/docs.go
visit
func (r *renderer) visit(tokens []markdown.Token) (s string) { for _, t := range tokens { s += r.visitToken(t) } return }
go
func (r *renderer) visit(tokens []markdown.Token) (s string) { for _, t := range tokens { s += r.visitToken(t) } return }
[ "func", "(", "r", "*", "renderer", ")", "visit", "(", "tokens", "[", "]", "markdown", ".", "Token", ")", "(", "s", "string", ")", "{", "for", "_", ",", "t", ":=", "range", "tokens", "{", "s", "+=", "r", ".", "visitToken", "(", "t", ")", "\n", "}", "\n", "return", "\n", "}" ]
// visit `tokens`.
[ "visit", "tokens", "." ]
c31f0a78ce189a8328563fa6a6eb97d04ace4284
https://github.com/apex/apex/blob/c31f0a78ce189a8328563fa6a6eb97d04ace4284/docs/docs.go#L80-L85
train
apex/apex
docs/docs.go
visitToken
func (r *renderer) visitToken(t markdown.Token) string { switch t.(type) { case *markdown.ParagraphOpen: r.inParagraph = true return "" case *markdown.ParagraphClose: r.inParagraph = false return "\n" case *markdown.CodeBlock: return fmt.Sprintf("\n%s\n", indent(t.(*markdown.CodeBlock).Content, 2)) case *markdown.Fence: return fmt.Sprintf("\n%s\n", indent(t.(*markdown.Fence).Content, 2)) case *markdown.HeadingOpen: n := t.(*markdown.HeadingOpen).HLevel return fmt.Sprintf("\n %s \033[%dm", strings.Repeat("#", n), colors.Blue) case *markdown.HeadingClose: return "\n\033[0m\n" case *markdown.StrongOpen: return "\033[1m" case *markdown.StrongClose: return "\033[0m" case *markdown.BulletListOpen: r.inList = true return "\n" case *markdown.BulletListClose: r.inList = false return "\n" case *markdown.ListItemOpen: return " - " case *markdown.LinkOpen: r.inLink = t.(*markdown.LinkOpen).Href return "" case *markdown.CodeInline: s := t.(*markdown.CodeInline).Content return fmt.Sprintf("\033[%dm%s\033[0m", colors.Gray, s) case *markdown.Text: s := t.(*markdown.Text).Content if r.inLink != "" { s = fmt.Sprintf("%s (%s)", s, r.inLink) r.inLink = "" } return s case *markdown.Inline: s := r.visit(t.(*markdown.Inline).Children) if r.inParagraph && !r.inList { s = indent(wordwrap.WrapString(s, 75), 1) } return s default: return "" } }
go
func (r *renderer) visitToken(t markdown.Token) string { switch t.(type) { case *markdown.ParagraphOpen: r.inParagraph = true return "" case *markdown.ParagraphClose: r.inParagraph = false return "\n" case *markdown.CodeBlock: return fmt.Sprintf("\n%s\n", indent(t.(*markdown.CodeBlock).Content, 2)) case *markdown.Fence: return fmt.Sprintf("\n%s\n", indent(t.(*markdown.Fence).Content, 2)) case *markdown.HeadingOpen: n := t.(*markdown.HeadingOpen).HLevel return fmt.Sprintf("\n %s \033[%dm", strings.Repeat("#", n), colors.Blue) case *markdown.HeadingClose: return "\n\033[0m\n" case *markdown.StrongOpen: return "\033[1m" case *markdown.StrongClose: return "\033[0m" case *markdown.BulletListOpen: r.inList = true return "\n" case *markdown.BulletListClose: r.inList = false return "\n" case *markdown.ListItemOpen: return " - " case *markdown.LinkOpen: r.inLink = t.(*markdown.LinkOpen).Href return "" case *markdown.CodeInline: s := t.(*markdown.CodeInline).Content return fmt.Sprintf("\033[%dm%s\033[0m", colors.Gray, s) case *markdown.Text: s := t.(*markdown.Text).Content if r.inLink != "" { s = fmt.Sprintf("%s (%s)", s, r.inLink) r.inLink = "" } return s case *markdown.Inline: s := r.visit(t.(*markdown.Inline).Children) if r.inParagraph && !r.inList { s = indent(wordwrap.WrapString(s, 75), 1) } return s default: return "" } }
[ "func", "(", "r", "*", "renderer", ")", "visitToken", "(", "t", "markdown", ".", "Token", ")", "string", "{", "switch", "t", ".", "(", "type", ")", "{", "case", "*", "markdown", ".", "ParagraphOpen", ":", "r", ".", "inParagraph", "=", "true", "\n", "return", "\"\"", "\n", "case", "*", "markdown", ".", "ParagraphClose", ":", "r", ".", "inParagraph", "=", "false", "\n", "return", "\"\\n\"", "\n", "\\n", "case", "*", "markdown", ".", "CodeBlock", ":", "return", "fmt", ".", "Sprintf", "(", "\"\\n%s\\n\"", ",", "\\n", ")", "\n", "\\n", "indent", "(", "t", ".", "(", "*", "markdown", ".", "CodeBlock", ")", ".", "Content", ",", "2", ")", "case", "*", "markdown", ".", "Fence", ":", "return", "fmt", ".", "Sprintf", "(", "\"\\n%s\\n\"", ",", "\\n", ")", "\n", "\\n", "indent", "(", "t", ".", "(", "*", "markdown", ".", "Fence", ")", ".", "Content", ",", "2", ")", "case", "*", "markdown", ".", "HeadingOpen", ":", "n", ":=", "t", ".", "(", "*", "markdown", ".", "HeadingOpen", ")", ".", "HLevel", "\n", "return", "fmt", ".", "Sprintf", "(", "\"\\n %s \\033[%dm\"", ",", "\\n", ",", "\\033", ")", "\n", "strings", ".", "Repeat", "(", "\"#\"", ",", "n", ")", "colors", ".", "Blue", "case", "*", "markdown", ".", "HeadingClose", ":", "return", "\"\\n\\033[0m\\n\"", "\n", "\\n", "\\033", "\\n", "}", "\n", "}" ]
// vistToken `t`.
[ "vistToken", "t", "." ]
c31f0a78ce189a8328563fa6a6eb97d04ace4284
https://github.com/apex/apex/blob/c31f0a78ce189a8328563fa6a6eb97d04ace4284/docs/docs.go#L88-L143
train
apex/apex
plugins/python/python.go
Open
func (p *Plugin) Open(fn *function.Function) error { if !strings.HasPrefix(fn.Runtime, "python") { return nil } // Support "python" for backwards compat. if fn.Runtime == "python" { fn.Runtime = "python2.7" } if fn.Handler == "" { fn.Handler = "main.handle" } return nil }
go
func (p *Plugin) Open(fn *function.Function) error { if !strings.HasPrefix(fn.Runtime, "python") { return nil } // Support "python" for backwards compat. if fn.Runtime == "python" { fn.Runtime = "python2.7" } if fn.Handler == "" { fn.Handler = "main.handle" } return nil }
[ "func", "(", "p", "*", "Plugin", ")", "Open", "(", "fn", "*", "function", ".", "Function", ")", "error", "{", "if", "!", "strings", ".", "HasPrefix", "(", "fn", ".", "Runtime", ",", "\"python\"", ")", "{", "return", "nil", "\n", "}", "\n", "if", "fn", ".", "Runtime", "==", "\"python\"", "{", "fn", ".", "Runtime", "=", "\"python2.7\"", "\n", "}", "\n", "if", "fn", ".", "Handler", "==", "\"\"", "{", "fn", ".", "Handler", "=", "\"main.handle\"", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// Open adds python defaults.
[ "Open", "adds", "python", "defaults", "." ]
c31f0a78ce189a8328563fa6a6eb97d04ace4284
https://github.com/apex/apex/blob/c31f0a78ce189a8328563fa6a6eb97d04ace4284/plugins/python/python.go#L21-L36
train
apex/apex
cmd/apex/invoke/invoke.go
preRun
func preRun(c *cobra.Command, args []string) error { if len(args) < 1 { return errors.New("Missing name argument") } name = args[0] return nil }
go
func preRun(c *cobra.Command, args []string) error { if len(args) < 1 { return errors.New("Missing name argument") } name = args[0] return nil }
[ "func", "preRun", "(", "c", "*", "cobra", ".", "Command", ",", "args", "[", "]", "string", ")", "error", "{", "if", "len", "(", "args", ")", "<", "1", "{", "return", "errors", ".", "New", "(", "\"Missing name argument\"", ")", "\n", "}", "\n", "name", "=", "args", "[", "0", "]", "\n", "return", "nil", "\n", "}" ]
// PreRun errors if the name argument is missing.
[ "PreRun", "errors", "if", "the", "name", "argument", "is", "missing", "." ]
c31f0a78ce189a8328563fa6a6eb97d04ace4284
https://github.com/apex/apex/blob/c31f0a78ce189a8328563fa6a6eb97d04ace4284/cmd/apex/invoke/invoke.go#L54-L61
train