id
int32
0
167k
repo
stringlengths
5
54
path
stringlengths
4
155
func_name
stringlengths
1
118
original_string
stringlengths
52
85.5k
language
stringclasses
1 value
code
stringlengths
52
85.5k
code_tokens
listlengths
21
1.41k
docstring
stringlengths
6
2.61k
docstring_tokens
listlengths
3
215
sha
stringlengths
40
40
url
stringlengths
85
252
20,700
araddon/qlbridge
exec/source.go
NewSource
func NewSource(ctx *plan.Context, p *plan.Source) (*Source, error) { if p.Stmt == nil { return nil, fmt.Errorf("must have from for Source") } if p.Conn == nil { return nil, fmt.Errorf("Must have existing connection on Plan") } scanner, hasScanner := p.Conn.(schema.ConnScanner) // Some sources require context so we seed it here if sourceContext, needsContext := p.Conn.(RequiresContext); needsContext { sourceContext.SetContext(ctx) } if !hasScanner { e, hasSourceExec := p.Conn.(ExecutorSource) if hasSourceExec { s := &Source{ TaskBase: NewTaskBase(ctx), ExecSource: e, p: p, } return s, nil } u.Warnf("source %T does not implement datasource.Scanner", p.Conn) return nil, fmt.Errorf("%T Must Implement Scanner for %q", p.Conn, p.Stmt.String()) } s := &Source{ TaskBase: NewTaskBase(ctx), Scanner: scanner, p: p, } return s, nil }
go
func NewSource(ctx *plan.Context, p *plan.Source) (*Source, error) { if p.Stmt == nil { return nil, fmt.Errorf("must have from for Source") } if p.Conn == nil { return nil, fmt.Errorf("Must have existing connection on Plan") } scanner, hasScanner := p.Conn.(schema.ConnScanner) // Some sources require context so we seed it here if sourceContext, needsContext := p.Conn.(RequiresContext); needsContext { sourceContext.SetContext(ctx) } if !hasScanner { e, hasSourceExec := p.Conn.(ExecutorSource) if hasSourceExec { s := &Source{ TaskBase: NewTaskBase(ctx), ExecSource: e, p: p, } return s, nil } u.Warnf("source %T does not implement datasource.Scanner", p.Conn) return nil, fmt.Errorf("%T Must Implement Scanner for %q", p.Conn, p.Stmt.String()) } s := &Source{ TaskBase: NewTaskBase(ctx), Scanner: scanner, p: p, } return s, nil }
[ "func", "NewSource", "(", "ctx", "*", "plan", ".", "Context", ",", "p", "*", "plan", ".", "Source", ")", "(", "*", "Source", ",", "error", ")", "{", "if", "p", ".", "Stmt", "==", "nil", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n", "if", "p", ".", "Conn", "==", "nil", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n\n", "scanner", ",", "hasScanner", ":=", "p", ".", "Conn", ".", "(", "schema", ".", "ConnScanner", ")", "\n\n", "// Some sources require context so we seed it here", "if", "sourceContext", ",", "needsContext", ":=", "p", ".", "Conn", ".", "(", "RequiresContext", ")", ";", "needsContext", "{", "sourceContext", ".", "SetContext", "(", "ctx", ")", "\n", "}", "\n\n", "if", "!", "hasScanner", "{", "e", ",", "hasSourceExec", ":=", "p", ".", "Conn", ".", "(", "ExecutorSource", ")", "\n", "if", "hasSourceExec", "{", "s", ":=", "&", "Source", "{", "TaskBase", ":", "NewTaskBase", "(", "ctx", ")", ",", "ExecSource", ":", "e", ",", "p", ":", "p", ",", "}", "\n", "return", "s", ",", "nil", "\n", "}", "\n", "u", ".", "Warnf", "(", "\"", "\"", ",", "p", ".", "Conn", ")", "\n", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "p", ".", "Conn", ",", "p", ".", "Stmt", ".", "String", "(", ")", ")", "\n", "}", "\n", "s", ":=", "&", "Source", "{", "TaskBase", ":", "NewTaskBase", "(", "ctx", ")", ",", "Scanner", ":", "scanner", ",", "p", ":", "p", ",", "}", "\n", "return", "s", ",", "nil", "\n", "}" ]
// NewSource create a scanner to read from data source
[ "NewSource", "create", "a", "scanner", "to", "read", "from", "data", "source" ]
23bb6a4e8c9e82ba86952b8a1469ccff1bb296ac
https://github.com/araddon/qlbridge/blob/23bb6a4e8c9e82ba86952b8a1469ccff1bb296ac/exec/source.go#L49-L84
20,701
araddon/qlbridge
exec/results.go
NewResultExecWriter
func NewResultExecWriter(ctx *plan.Context) *ResultExecWriter { m := &ResultExecWriter{ TaskBase: NewTaskBase(ctx), } m.Handler = func(ctx *plan.Context, msg schema.Message) bool { switch mt := msg.(type) { case *datasource.SqlDriverMessage: if len(mt.Vals) > 1 { m.lastInsertID = mt.Vals[0].(int64) m.rowsAffected = mt.Vals[1].(int64) } case nil: u.Warnf("got nil") // Signal to quit return false default: u.Errorf("could not convert to message reader: %T", msg) } return true } return m }
go
func NewResultExecWriter(ctx *plan.Context) *ResultExecWriter { m := &ResultExecWriter{ TaskBase: NewTaskBase(ctx), } m.Handler = func(ctx *plan.Context, msg schema.Message) bool { switch mt := msg.(type) { case *datasource.SqlDriverMessage: if len(mt.Vals) > 1 { m.lastInsertID = mt.Vals[0].(int64) m.rowsAffected = mt.Vals[1].(int64) } case nil: u.Warnf("got nil") // Signal to quit return false default: u.Errorf("could not convert to message reader: %T", msg) } return true } return m }
[ "func", "NewResultExecWriter", "(", "ctx", "*", "plan", ".", "Context", ")", "*", "ResultExecWriter", "{", "m", ":=", "&", "ResultExecWriter", "{", "TaskBase", ":", "NewTaskBase", "(", "ctx", ")", ",", "}", "\n", "m", ".", "Handler", "=", "func", "(", "ctx", "*", "plan", ".", "Context", ",", "msg", "schema", ".", "Message", ")", "bool", "{", "switch", "mt", ":=", "msg", ".", "(", "type", ")", "{", "case", "*", "datasource", ".", "SqlDriverMessage", ":", "if", "len", "(", "mt", ".", "Vals", ")", ">", "1", "{", "m", ".", "lastInsertID", "=", "mt", ".", "Vals", "[", "0", "]", ".", "(", "int64", ")", "\n", "m", ".", "rowsAffected", "=", "mt", ".", "Vals", "[", "1", "]", ".", "(", "int64", ")", "\n", "}", "\n", "case", "nil", ":", "u", ".", "Warnf", "(", "\"", "\"", ")", "\n", "// Signal to quit", "return", "false", "\n\n", "default", ":", "u", ".", "Errorf", "(", "\"", "\"", ",", "msg", ")", "\n", "}", "\n\n", "return", "true", "\n", "}", "\n", "return", "m", "\n", "}" ]
// NewResultExecWriter a result writer for exect task
[ "NewResultExecWriter", "a", "result", "writer", "for", "exect", "task" ]
23bb6a4e8c9e82ba86952b8a1469ccff1bb296ac
https://github.com/araddon/qlbridge/blob/23bb6a4e8c9e82ba86952b8a1469ccff1bb296ac/exec/results.go#L55-L78
20,702
araddon/qlbridge
exec/results.go
NewResultWriter
func NewResultWriter(ctx *plan.Context) *ResultWriter { m := &ResultWriter{ TaskBase: NewTaskBase(ctx), } m.Handler = resultWrite(m) return m }
go
func NewResultWriter(ctx *plan.Context) *ResultWriter { m := &ResultWriter{ TaskBase: NewTaskBase(ctx), } m.Handler = resultWrite(m) return m }
[ "func", "NewResultWriter", "(", "ctx", "*", "plan", ".", "Context", ")", "*", "ResultWriter", "{", "m", ":=", "&", "ResultWriter", "{", "TaskBase", ":", "NewTaskBase", "(", "ctx", ")", ",", "}", "\n", "m", ".", "Handler", "=", "resultWrite", "(", "m", ")", "\n", "return", "m", "\n", "}" ]
// NewResultWriter for a plan
[ "NewResultWriter", "for", "a", "plan" ]
23bb6a4e8c9e82ba86952b8a1469ccff1bb296ac
https://github.com/araddon/qlbridge/blob/23bb6a4e8c9e82ba86952b8a1469ccff1bb296ac/exec/results.go#L81-L87
20,703
araddon/qlbridge
exec/results.go
NewResultRows
func NewResultRows(ctx *plan.Context, cols []string) *ResultWriter { stepper := NewTaskStepper(ctx) m := &ResultWriter{ TaskBase: stepper.TaskBase, cols: cols, } return m }
go
func NewResultRows(ctx *plan.Context, cols []string) *ResultWriter { stepper := NewTaskStepper(ctx) m := &ResultWriter{ TaskBase: stepper.TaskBase, cols: cols, } return m }
[ "func", "NewResultRows", "(", "ctx", "*", "plan", ".", "Context", ",", "cols", "[", "]", "string", ")", "*", "ResultWriter", "{", "stepper", ":=", "NewTaskStepper", "(", "ctx", ")", "\n", "m", ":=", "&", "ResultWriter", "{", "TaskBase", ":", "stepper", ".", "TaskBase", ",", "cols", ":", "cols", ",", "}", "\n", "return", "m", "\n", "}" ]
// NewResultRows a resultwriter
[ "NewResultRows", "a", "resultwriter" ]
23bb6a4e8c9e82ba86952b8a1469ccff1bb296ac
https://github.com/araddon/qlbridge/blob/23bb6a4e8c9e82ba86952b8a1469ccff1bb296ac/exec/results.go#L90-L97
20,704
araddon/qlbridge
exec/results.go
NewResultBuffer
func NewResultBuffer(ctx *plan.Context, writeTo *[]schema.Message) *ResultBuffer { m := &ResultBuffer{ TaskBase: NewTaskBase(ctx), } m.Handler = func(ctx *plan.Context, msg schema.Message) bool { *writeTo = append(*writeTo, msg) //u.Infof("write to msgs: %v", len(*writeTo)) return true } return m }
go
func NewResultBuffer(ctx *plan.Context, writeTo *[]schema.Message) *ResultBuffer { m := &ResultBuffer{ TaskBase: NewTaskBase(ctx), } m.Handler = func(ctx *plan.Context, msg schema.Message) bool { *writeTo = append(*writeTo, msg) //u.Infof("write to msgs: %v", len(*writeTo)) return true } return m }
[ "func", "NewResultBuffer", "(", "ctx", "*", "plan", ".", "Context", ",", "writeTo", "*", "[", "]", "schema", ".", "Message", ")", "*", "ResultBuffer", "{", "m", ":=", "&", "ResultBuffer", "{", "TaskBase", ":", "NewTaskBase", "(", "ctx", ")", ",", "}", "\n", "m", ".", "Handler", "=", "func", "(", "ctx", "*", "plan", ".", "Context", ",", "msg", "schema", ".", "Message", ")", "bool", "{", "*", "writeTo", "=", "append", "(", "*", "writeTo", ",", "msg", ")", "\n", "//u.Infof(\"write to msgs: %v\", len(*writeTo))", "return", "true", "\n", "}", "\n", "return", "m", "\n", "}" ]
// NewResultBuffer create a result buffer to write temp tasks into results.
[ "NewResultBuffer", "create", "a", "result", "buffer", "to", "write", "temp", "tasks", "into", "results", "." ]
23bb6a4e8c9e82ba86952b8a1469ccff1bb296ac
https://github.com/araddon/qlbridge/blob/23bb6a4e8c9e82ba86952b8a1469ccff1bb296ac/exec/results.go#L100-L110
20,705
araddon/qlbridge
exec/results.go
Result
func (m *ResultExecWriter) Result() driver.Result { return &qlbResult{m.lastInsertID, m.rowsAffected, m.err} }
go
func (m *ResultExecWriter) Result() driver.Result { return &qlbResult{m.lastInsertID, m.rowsAffected, m.err} }
[ "func", "(", "m", "*", "ResultExecWriter", ")", "Result", "(", ")", "driver", ".", "Result", "{", "return", "&", "qlbResult", "{", "m", ".", "lastInsertID", ",", "m", ".", "rowsAffected", ",", "m", ".", "err", "}", "\n", "}" ]
// Result of exec task
[ "Result", "of", "exec", "task" ]
23bb6a4e8c9e82ba86952b8a1469ccff1bb296ac
https://github.com/araddon/qlbridge/blob/23bb6a4e8c9e82ba86952b8a1469ccff1bb296ac/exec/results.go#L113-L115
20,706
araddon/qlbridge
datasource/files/scanner_json.go
NewJsonHandlerTables
func NewJsonHandlerTables(lh datasource.FileLineHandler, tables []string) FileHandler { return &jsonHandlerTables{ FileHandler: &jsonHandler{lh}, tables: tables, } }
go
func NewJsonHandlerTables(lh datasource.FileLineHandler, tables []string) FileHandler { return &jsonHandlerTables{ FileHandler: &jsonHandler{lh}, tables: tables, } }
[ "func", "NewJsonHandlerTables", "(", "lh", "datasource", ".", "FileLineHandler", ",", "tables", "[", "]", "string", ")", "FileHandler", "{", "return", "&", "jsonHandlerTables", "{", "FileHandler", ":", "&", "jsonHandler", "{", "lh", "}", ",", "tables", ":", "tables", ",", "}", "\n", "}" ]
// NewJsonHandler creates a json file handler for paging new-line // delimited rows of json file
[ "NewJsonHandler", "creates", "a", "json", "file", "handler", "for", "paging", "new", "-", "line", "delimited", "rows", "of", "json", "file" ]
23bb6a4e8c9e82ba86952b8a1469ccff1bb296ac
https://github.com/araddon/qlbridge/blob/23bb6a4e8c9e82ba86952b8a1469ccff1bb296ac/datasource/files/scanner_json.go#L39-L44
20,707
araddon/qlbridge
generators/elasticsearch/gentypes/gen.go
Numeric
func (f *FieldType) Numeric() bool { if f.Type == value.NumberType || f.Type == value.IntType { return true } // If a nested field with numeric values it's numeric if f.Nested() { switch f.Type { case value.MapIntType, value.MapNumberType: return true } } // Nothing else is numeric return false }
go
func (f *FieldType) Numeric() bool { if f.Type == value.NumberType || f.Type == value.IntType { return true } // If a nested field with numeric values it's numeric if f.Nested() { switch f.Type { case value.MapIntType, value.MapNumberType: return true } } // Nothing else is numeric return false }
[ "func", "(", "f", "*", "FieldType", ")", "Numeric", "(", ")", "bool", "{", "if", "f", ".", "Type", "==", "value", ".", "NumberType", "||", "f", ".", "Type", "==", "value", ".", "IntType", "{", "return", "true", "\n", "}", "\n\n", "// If a nested field with numeric values it's numeric", "if", "f", ".", "Nested", "(", ")", "{", "switch", "f", ".", "Type", "{", "case", "value", ".", "MapIntType", ",", "value", ".", "MapNumberType", ":", "return", "true", "\n", "}", "\n", "}", "\n\n", "// Nothing else is numeric", "return", "false", "\n", "}" ]
// Numeric returns true if field type has numeric values.
[ "Numeric", "returns", "true", "if", "field", "type", "has", "numeric", "values", "." ]
23bb6a4e8c9e82ba86952b8a1469ccff1bb296ac
https://github.com/araddon/qlbridge/blob/23bb6a4e8c9e82ba86952b8a1469ccff1bb296ac/generators/elasticsearch/gentypes/gen.go#L68-L83
20,708
araddon/qlbridge
exec/sqldriver.go
Exec
func (m *qlbConn) Exec(query string, args []driver.Value) (driver.Result, error) { stmt := &qlbStmt{conn: m, query: query} return stmt.Exec(args) }
go
func (m *qlbConn) Exec(query string, args []driver.Value) (driver.Result, error) { stmt := &qlbStmt{conn: m, query: query} return stmt.Exec(args) }
[ "func", "(", "m", "*", "qlbConn", ")", "Exec", "(", "query", "string", ",", "args", "[", "]", "driver", ".", "Value", ")", "(", "driver", ".", "Result", ",", "error", ")", "{", "stmt", ":=", "&", "qlbStmt", "{", "conn", ":", "m", ",", "query", ":", "query", "}", "\n", "return", "stmt", ".", "Exec", "(", "args", ")", "\n", "}" ]
// Exec may return ErrSkip. // // Execer implementation. To be used for queries that do not return any rows // such as Create Index, Insert, Upset, Delete etc
[ "Exec", "may", "return", "ErrSkip", ".", "Execer", "implementation", ".", "To", "be", "used", "for", "queries", "that", "do", "not", "return", "any", "rows", "such", "as", "Create", "Index", "Insert", "Upset", "Delete", "etc" ]
23bb6a4e8c9e82ba86952b8a1469ccff1bb296ac
https://github.com/araddon/qlbridge/blob/23bb6a4e8c9e82ba86952b8a1469ccff1bb296ac/exec/sqldriver.go#L115-L118
20,709
araddon/qlbridge
exec/sqldriver.go
Query
func (m *qlbConn) Query(query string, args []driver.Value) (driver.Rows, error) { stmt := &qlbStmt{conn: m, query: query} return stmt.Query(args) }
go
func (m *qlbConn) Query(query string, args []driver.Value) (driver.Rows, error) { stmt := &qlbStmt{conn: m, query: query} return stmt.Query(args) }
[ "func", "(", "m", "*", "qlbConn", ")", "Query", "(", "query", "string", ",", "args", "[", "]", "driver", ".", "Value", ")", "(", "driver", ".", "Rows", ",", "error", ")", "{", "stmt", ":=", "&", "qlbStmt", "{", "conn", ":", "m", ",", "query", ":", "query", "}", "\n", "return", "stmt", ".", "Query", "(", "args", ")", "\n", "}" ]
// Queryer implementation // Query may return ErrSkip //
[ "Queryer", "implementation", "Query", "may", "return", "ErrSkip" ]
23bb6a4e8c9e82ba86952b8a1469ccff1bb296ac
https://github.com/araddon/qlbridge/blob/23bb6a4e8c9e82ba86952b8a1469ccff1bb296ac/exec/sqldriver.go#L123-L126
20,710
araddon/qlbridge
exec/sqldriver.go
Close
func (m *qlbStmt) Close() error { if m.job != nil { m.job.Close() } return nil }
go
func (m *qlbStmt) Close() error { if m.job != nil { m.job.Close() } return nil }
[ "func", "(", "m", "*", "qlbStmt", ")", "Close", "(", ")", "error", "{", "if", "m", ".", "job", "!=", "nil", "{", "m", ".", "job", ".", "Close", "(", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// Close closes the statement. // // As of Go 1.1, a Stmt will not be closed if it's in use // by any queries.
[ "Close", "closes", "the", "statement", ".", "As", "of", "Go", "1", ".", "1", "a", "Stmt", "will", "not", "be", "closed", "if", "it", "s", "in", "use", "by", "any", "queries", "." ]
23bb6a4e8c9e82ba86952b8a1469ccff1bb296ac
https://github.com/araddon/qlbridge/blob/23bb6a4e8c9e82ba86952b8a1469ccff1bb296ac/exec/sqldriver.go#L174-L179
20,711
araddon/qlbridge
exec/sqldriver.go
Exec
func (m *qlbStmt) Exec(args []driver.Value) (driver.Result, error) { var err error if len(args) > 0 { m.query, err = queryArgsConvert(m.query, args) if err != nil { return nil, err } } // Create a Job, which is Dag of Tasks that Run() ctx := plan.NewContext(m.query) ctx.Schema = m.conn.schema job, err := BuildSqlJob(ctx) if err != nil { return nil, err } m.job = job resultWriter := NewResultExecWriter(ctx) job.RootTask.Add(resultWriter) job.Setup() //u.Infof("in qlbdriver.Exec about to run") err = job.Run() //u.Debugf("After qlb driver.Run() in Exec()") if err != nil { u.Errorf("error on Query.Run(): %v", err) //resultWriter.ErrChan() <- err //job.Close() } return resultWriter.Result(), nil }
go
func (m *qlbStmt) Exec(args []driver.Value) (driver.Result, error) { var err error if len(args) > 0 { m.query, err = queryArgsConvert(m.query, args) if err != nil { return nil, err } } // Create a Job, which is Dag of Tasks that Run() ctx := plan.NewContext(m.query) ctx.Schema = m.conn.schema job, err := BuildSqlJob(ctx) if err != nil { return nil, err } m.job = job resultWriter := NewResultExecWriter(ctx) job.RootTask.Add(resultWriter) job.Setup() //u.Infof("in qlbdriver.Exec about to run") err = job.Run() //u.Debugf("After qlb driver.Run() in Exec()") if err != nil { u.Errorf("error on Query.Run(): %v", err) //resultWriter.ErrChan() <- err //job.Close() } return resultWriter.Result(), nil }
[ "func", "(", "m", "*", "qlbStmt", ")", "Exec", "(", "args", "[", "]", "driver", ".", "Value", ")", "(", "driver", ".", "Result", ",", "error", ")", "{", "var", "err", "error", "\n", "if", "len", "(", "args", ")", ">", "0", "{", "m", ".", "query", ",", "err", "=", "queryArgsConvert", "(", "m", ".", "query", ",", "args", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "}", "\n\n", "// Create a Job, which is Dag of Tasks that Run()", "ctx", ":=", "plan", ".", "NewContext", "(", "m", ".", "query", ")", "\n", "ctx", ".", "Schema", "=", "m", ".", "conn", ".", "schema", "\n", "job", ",", "err", ":=", "BuildSqlJob", "(", "ctx", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "m", ".", "job", "=", "job", "\n\n", "resultWriter", ":=", "NewResultExecWriter", "(", "ctx", ")", "\n", "job", ".", "RootTask", ".", "Add", "(", "resultWriter", ")", "\n\n", "job", ".", "Setup", "(", ")", "\n", "//u.Infof(\"in qlbdriver.Exec about to run\")", "err", "=", "job", ".", "Run", "(", ")", "\n", "//u.Debugf(\"After qlb driver.Run() in Exec()\")", "if", "err", "!=", "nil", "{", "u", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "//resultWriter.ErrChan() <- err", "//job.Close()", "}", "\n", "return", "resultWriter", ".", "Result", "(", ")", ",", "nil", "\n", "}" ]
// Exec executes a query that doesn't return rows, such // as an INSERT, UPDATE, DELETE
[ "Exec", "executes", "a", "query", "that", "doesn", "t", "return", "rows", "such", "as", "an", "INSERT", "UPDATE", "DELETE" ]
23bb6a4e8c9e82ba86952b8a1469ccff1bb296ac
https://github.com/araddon/qlbridge/blob/23bb6a4e8c9e82ba86952b8a1469ccff1bb296ac/exec/sqldriver.go#L194-L225
20,712
araddon/qlbridge
exec/sqldriver.go
Query
func (m *qlbStmt) Query(args []driver.Value) (driver.Rows, error) { var err error if len(args) > 0 { m.query, err = queryArgsConvert(m.query, args) if err != nil { return nil, err } } u.Debugf("query: %v", m.query) // Create a Job, which is Dag of Tasks that Run() ctx := plan.NewContext(m.query) ctx.Schema = m.conn.schema job, err := BuildSqlJob(ctx) if err != nil { u.Warnf("return error? %v", err) return nil, err } m.job = job // The only type of stmt that makes sense for Query is SELECT // and we need list of columns that requires casing sqlSelect, ok := job.Ctx.Stmt.(*rel.SqlSelect) if !ok { u.Warnf("ctx? %v", job.Ctx) return nil, fmt.Errorf("We could not recognize that as a select query: %T", job.Ctx.Stmt) } // Prepare a result writer, we manually append this task to end // of job? resultWriter := NewResultRows(ctx, sqlSelect.Columns.AliasedFieldNames()) job.RootTask.Add(resultWriter) job.Setup() // TODO: this can't run in parallel-buffered mode? // how to open in go-routine and still be able to send error to rows? go func() { //u.Debugf("Start Job.Run") err = job.Run() //u.Debugf("After job.Run()") if err != nil { u.Errorf("error on Query.Run(): %v", err) //resultWriter.ErrChan() <- err //job.Close() } job.Close() //u.Debugf("exiting Background Query") }() return resultWriter, nil }
go
func (m *qlbStmt) Query(args []driver.Value) (driver.Rows, error) { var err error if len(args) > 0 { m.query, err = queryArgsConvert(m.query, args) if err != nil { return nil, err } } u.Debugf("query: %v", m.query) // Create a Job, which is Dag of Tasks that Run() ctx := plan.NewContext(m.query) ctx.Schema = m.conn.schema job, err := BuildSqlJob(ctx) if err != nil { u.Warnf("return error? %v", err) return nil, err } m.job = job // The only type of stmt that makes sense for Query is SELECT // and we need list of columns that requires casing sqlSelect, ok := job.Ctx.Stmt.(*rel.SqlSelect) if !ok { u.Warnf("ctx? %v", job.Ctx) return nil, fmt.Errorf("We could not recognize that as a select query: %T", job.Ctx.Stmt) } // Prepare a result writer, we manually append this task to end // of job? resultWriter := NewResultRows(ctx, sqlSelect.Columns.AliasedFieldNames()) job.RootTask.Add(resultWriter) job.Setup() // TODO: this can't run in parallel-buffered mode? // how to open in go-routine and still be able to send error to rows? go func() { //u.Debugf("Start Job.Run") err = job.Run() //u.Debugf("After job.Run()") if err != nil { u.Errorf("error on Query.Run(): %v", err) //resultWriter.ErrChan() <- err //job.Close() } job.Close() //u.Debugf("exiting Background Query") }() return resultWriter, nil }
[ "func", "(", "m", "*", "qlbStmt", ")", "Query", "(", "args", "[", "]", "driver", ".", "Value", ")", "(", "driver", ".", "Rows", ",", "error", ")", "{", "var", "err", "error", "\n", "if", "len", "(", "args", ")", ">", "0", "{", "m", ".", "query", ",", "err", "=", "queryArgsConvert", "(", "m", ".", "query", ",", "args", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "}", "\n", "u", ".", "Debugf", "(", "\"", "\"", ",", "m", ".", "query", ")", "\n\n", "// Create a Job, which is Dag of Tasks that Run()", "ctx", ":=", "plan", ".", "NewContext", "(", "m", ".", "query", ")", "\n", "ctx", ".", "Schema", "=", "m", ".", "conn", ".", "schema", "\n", "job", ",", "err", ":=", "BuildSqlJob", "(", "ctx", ")", "\n", "if", "err", "!=", "nil", "{", "u", ".", "Warnf", "(", "\"", "\"", ",", "err", ")", "\n", "return", "nil", ",", "err", "\n", "}", "\n", "m", ".", "job", "=", "job", "\n\n", "// The only type of stmt that makes sense for Query is SELECT", "// and we need list of columns that requires casing", "sqlSelect", ",", "ok", ":=", "job", ".", "Ctx", ".", "Stmt", ".", "(", "*", "rel", ".", "SqlSelect", ")", "\n", "if", "!", "ok", "{", "u", ".", "Warnf", "(", "\"", "\"", ",", "job", ".", "Ctx", ")", "\n", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "job", ".", "Ctx", ".", "Stmt", ")", "\n", "}", "\n\n", "// Prepare a result writer, we manually append this task to end", "// of job?", "resultWriter", ":=", "NewResultRows", "(", "ctx", ",", "sqlSelect", ".", "Columns", ".", "AliasedFieldNames", "(", ")", ")", "\n\n", "job", ".", "RootTask", ".", "Add", "(", "resultWriter", ")", "\n\n", "job", ".", "Setup", "(", ")", "\n\n", "// TODO: this can't run in parallel-buffered mode?", "// how to open in go-routine and still be able to send error to rows?", "go", "func", "(", ")", "{", "//u.Debugf(\"Start Job.Run\")", "err", "=", "job", ".", "Run", "(", ")", "\n", "//u.Debugf(\"After job.Run()\")", "if", "err", "!=", "nil", "{", "u", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "//resultWriter.ErrChan() <- err", "//job.Close()", "}", "\n", "job", ".", "Close", "(", ")", "\n", "//u.Debugf(\"exiting Background Query\")", "}", "(", ")", "\n\n", "return", "resultWriter", ",", "nil", "\n", "}" ]
// Query executes a query that may return rows, such as a SELECT
[ "Query", "executes", "a", "query", "that", "may", "return", "rows", "such", "as", "a", "SELECT" ]
23bb6a4e8c9e82ba86952b8a1469ccff1bb296ac
https://github.com/araddon/qlbridge/blob/23bb6a4e8c9e82ba86952b8a1469ccff1bb296ac/exec/sqldriver.go#L228-L280
20,713
progrium/go-basher
basher.go
Application
func Application( funcs map[string]func([]string), scripts []string, loader func(string) ([]byte, error), copyEnv bool) { bashDir, err := homedir.Expand("~/.basher") if err != nil { log.Fatal(err, "1") } bashPath := bashDir + "/bash" if _, err := os.Stat(bashPath); os.IsNotExist(err) { err = RestoreAsset(bashDir, "bash") if err != nil { log.Fatal(err, "1") } } ApplicationWithPath(funcs, scripts, loader, copyEnv, bashPath) }
go
func Application( funcs map[string]func([]string), scripts []string, loader func(string) ([]byte, error), copyEnv bool) { bashDir, err := homedir.Expand("~/.basher") if err != nil { log.Fatal(err, "1") } bashPath := bashDir + "/bash" if _, err := os.Stat(bashPath); os.IsNotExist(err) { err = RestoreAsset(bashDir, "bash") if err != nil { log.Fatal(err, "1") } } ApplicationWithPath(funcs, scripts, loader, copyEnv, bashPath) }
[ "func", "Application", "(", "funcs", "map", "[", "string", "]", "func", "(", "[", "]", "string", ")", ",", "scripts", "[", "]", "string", ",", "loader", "func", "(", "string", ")", "(", "[", "]", "byte", ",", "error", ")", ",", "copyEnv", "bool", ")", "{", "bashDir", ",", "err", ":=", "homedir", ".", "Expand", "(", "\"", "\"", ")", "\n", "if", "err", "!=", "nil", "{", "log", ".", "Fatal", "(", "err", ",", "\"", "\"", ")", "\n", "}", "\n\n", "bashPath", ":=", "bashDir", "+", "\"", "\"", "\n", "if", "_", ",", "err", ":=", "os", ".", "Stat", "(", "bashPath", ")", ";", "os", ".", "IsNotExist", "(", "err", ")", "{", "err", "=", "RestoreAsset", "(", "bashDir", ",", "\"", "\"", ")", "\n", "if", "err", "!=", "nil", "{", "log", ".", "Fatal", "(", "err", ",", "\"", "\"", ")", "\n", "}", "\n", "}", "\n\n", "ApplicationWithPath", "(", "funcs", ",", "scripts", ",", "loader", ",", "copyEnv", ",", "bashPath", ")", "\n", "}" ]
// Application sets up a common entrypoint for a Bash application that // uses exported Go functions. It uses the DEBUG environment variable // to set debug on the Context, and SHELL for the Bash binary if it // includes the string "bash". You can pass a loader function to use // for the sourced files, and a boolean for whether or not the // environment should be copied into the Context process.
[ "Application", "sets", "up", "a", "common", "entrypoint", "for", "a", "Bash", "application", "that", "uses", "exported", "Go", "functions", ".", "It", "uses", "the", "DEBUG", "environment", "variable", "to", "set", "debug", "on", "the", "Context", "and", "SHELL", "for", "the", "Bash", "binary", "if", "it", "includes", "the", "string", "bash", ".", "You", "can", "pass", "a", "loader", "function", "to", "use", "for", "the", "sourced", "files", "and", "a", "boolean", "for", "whether", "or", "not", "the", "environment", "should", "be", "copied", "into", "the", "Context", "process", "." ]
b674c80834b00079887df7847b9892f013c8bb54
https://github.com/progrium/go-basher/blob/b674c80834b00079887df7847b9892f013c8bb54/basher.go#L39-L59
20,714
progrium/go-basher
basher.go
ApplicationWithPath
func ApplicationWithPath( funcs map[string]func([]string), scripts []string, loader func(string) ([]byte, error), copyEnv bool, bashPath string) { bash, err := NewContext(bashPath, os.Getenv("DEBUG") != "") if err != nil { log.Fatal(err) } for name, fn := range funcs { bash.ExportFunc(name, fn) } if bash.HandleFuncs(os.Args) { os.Exit(0) } for _, script := range scripts { bash.Source(script, loader) } if copyEnv { bash.CopyEnv() } status, err := bash.Run("main", os.Args[1:]) if err != nil { log.Fatal(err) } os.Exit(status) }
go
func ApplicationWithPath( funcs map[string]func([]string), scripts []string, loader func(string) ([]byte, error), copyEnv bool, bashPath string) { bash, err := NewContext(bashPath, os.Getenv("DEBUG") != "") if err != nil { log.Fatal(err) } for name, fn := range funcs { bash.ExportFunc(name, fn) } if bash.HandleFuncs(os.Args) { os.Exit(0) } for _, script := range scripts { bash.Source(script, loader) } if copyEnv { bash.CopyEnv() } status, err := bash.Run("main", os.Args[1:]) if err != nil { log.Fatal(err) } os.Exit(status) }
[ "func", "ApplicationWithPath", "(", "funcs", "map", "[", "string", "]", "func", "(", "[", "]", "string", ")", ",", "scripts", "[", "]", "string", ",", "loader", "func", "(", "string", ")", "(", "[", "]", "byte", ",", "error", ")", ",", "copyEnv", "bool", ",", "bashPath", "string", ")", "{", "bash", ",", "err", ":=", "NewContext", "(", "bashPath", ",", "os", ".", "Getenv", "(", "\"", "\"", ")", "!=", "\"", "\"", ")", "\n", "if", "err", "!=", "nil", "{", "log", ".", "Fatal", "(", "err", ")", "\n", "}", "\n", "for", "name", ",", "fn", ":=", "range", "funcs", "{", "bash", ".", "ExportFunc", "(", "name", ",", "fn", ")", "\n", "}", "\n", "if", "bash", ".", "HandleFuncs", "(", "os", ".", "Args", ")", "{", "os", ".", "Exit", "(", "0", ")", "\n", "}", "\n\n", "for", "_", ",", "script", ":=", "range", "scripts", "{", "bash", ".", "Source", "(", "script", ",", "loader", ")", "\n", "}", "\n", "if", "copyEnv", "{", "bash", ".", "CopyEnv", "(", ")", "\n", "}", "\n", "status", ",", "err", ":=", "bash", ".", "Run", "(", "\"", "\"", ",", "os", ".", "Args", "[", "1", ":", "]", ")", "\n", "if", "err", "!=", "nil", "{", "log", ".", "Fatal", "(", "err", ")", "\n", "}", "\n", "os", ".", "Exit", "(", "status", ")", "\n", "}" ]
// ApplicationWithPath functions as Application does while also // allowing the developer to modify the specified bashPath.
[ "ApplicationWithPath", "functions", "as", "Application", "does", "while", "also", "allowing", "the", "developer", "to", "modify", "the", "specified", "bashPath", "." ]
b674c80834b00079887df7847b9892f013c8bb54
https://github.com/progrium/go-basher/blob/b674c80834b00079887df7847b9892f013c8bb54/basher.go#L63-L92
20,715
progrium/go-basher
basher.go
NewContext
func NewContext(bashpath string, debug bool) (*Context, error) { executable, err := osext.Executable() if err != nil { return nil, err } return &Context{ Debug: debug, BashPath: bashpath, SelfPath: executable, Stdin: os.Stdin, Stdout: os.Stdout, Stderr: os.Stderr, scripts: make([][]byte, 0), vars: make([]string, 0), funcs: make(map[string]func([]string)), }, nil }
go
func NewContext(bashpath string, debug bool) (*Context, error) { executable, err := osext.Executable() if err != nil { return nil, err } return &Context{ Debug: debug, BashPath: bashpath, SelfPath: executable, Stdin: os.Stdin, Stdout: os.Stdout, Stderr: os.Stderr, scripts: make([][]byte, 0), vars: make([]string, 0), funcs: make(map[string]func([]string)), }, nil }
[ "func", "NewContext", "(", "bashpath", "string", ",", "debug", "bool", ")", "(", "*", "Context", ",", "error", ")", "{", "executable", ",", "err", ":=", "osext", ".", "Executable", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "return", "&", "Context", "{", "Debug", ":", "debug", ",", "BashPath", ":", "bashpath", ",", "SelfPath", ":", "executable", ",", "Stdin", ":", "os", ".", "Stdin", ",", "Stdout", ":", "os", ".", "Stdout", ",", "Stderr", ":", "os", ".", "Stderr", ",", "scripts", ":", "make", "(", "[", "]", "[", "]", "byte", ",", "0", ")", ",", "vars", ":", "make", "(", "[", "]", "string", ",", "0", ")", ",", "funcs", ":", "make", "(", "map", "[", "string", "]", "func", "(", "[", "]", "string", ")", ")", ",", "}", ",", "nil", "\n", "}" ]
// Creates and initializes a new Context that will use the given Bash executable. // The debug mode will leave the produced temporary BASH_ENV file for inspection.
[ "Creates", "and", "initializes", "a", "new", "Context", "that", "will", "use", "the", "given", "Bash", "executable", ".", "The", "debug", "mode", "will", "leave", "the", "produced", "temporary", "BASH_ENV", "file", "for", "inspection", "." ]
b674c80834b00079887df7847b9892f013c8bb54
https://github.com/progrium/go-basher/blob/b674c80834b00079887df7847b9892f013c8bb54/basher.go#L127-L143
20,716
progrium/go-basher
basher.go
CopyEnv
func (c *Context) CopyEnv() { c.Lock() defer c.Unlock() c.vars = append(c.vars, os.Environ()...) }
go
func (c *Context) CopyEnv() { c.Lock() defer c.Unlock() c.vars = append(c.vars, os.Environ()...) }
[ "func", "(", "c", "*", "Context", ")", "CopyEnv", "(", ")", "{", "c", ".", "Lock", "(", ")", "\n", "defer", "c", ".", "Unlock", "(", ")", "\n", "c", ".", "vars", "=", "append", "(", "c", ".", "vars", ",", "os", ".", "Environ", "(", ")", "...", ")", "\n", "}" ]
// Copies the current environment variables into the Context
[ "Copies", "the", "current", "environment", "variables", "into", "the", "Context" ]
b674c80834b00079887df7847b9892f013c8bb54
https://github.com/progrium/go-basher/blob/b674c80834b00079887df7847b9892f013c8bb54/basher.go#L146-L150
20,717
progrium/go-basher
basher.go
Source
func (c *Context) Source(filepath string, loader func(string) ([]byte, error)) error { if loader == nil { loader = ioutil.ReadFile } data, err := loader(filepath) if err != nil { return err } c.Lock() defer c.Unlock() c.scripts = append(c.scripts, data) return nil }
go
func (c *Context) Source(filepath string, loader func(string) ([]byte, error)) error { if loader == nil { loader = ioutil.ReadFile } data, err := loader(filepath) if err != nil { return err } c.Lock() defer c.Unlock() c.scripts = append(c.scripts, data) return nil }
[ "func", "(", "c", "*", "Context", ")", "Source", "(", "filepath", "string", ",", "loader", "func", "(", "string", ")", "(", "[", "]", "byte", ",", "error", ")", ")", "error", "{", "if", "loader", "==", "nil", "{", "loader", "=", "ioutil", ".", "ReadFile", "\n", "}", "\n", "data", ",", "err", ":=", "loader", "(", "filepath", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "c", ".", "Lock", "(", ")", "\n", "defer", "c", ".", "Unlock", "(", ")", "\n", "c", ".", "scripts", "=", "append", "(", "c", ".", "scripts", ",", "data", ")", "\n", "return", "nil", "\n", "}" ]
// Source adds a shell script to the Context environment. The loader argument can be nil // which means it will use ioutil.Readfile and load from disk, but it exists so you // can use the Asset function produced by go-bindata when including script files in // your Go binary. Calls to Source adds files to the environment in order.
[ "Source", "adds", "a", "shell", "script", "to", "the", "Context", "environment", ".", "The", "loader", "argument", "can", "be", "nil", "which", "means", "it", "will", "use", "ioutil", ".", "Readfile", "and", "load", "from", "disk", "but", "it", "exists", "so", "you", "can", "use", "the", "Asset", "function", "produced", "by", "go", "-", "bindata", "when", "including", "script", "files", "in", "your", "Go", "binary", ".", "Calls", "to", "Source", "adds", "files", "to", "the", "environment", "in", "order", "." ]
b674c80834b00079887df7847b9892f013c8bb54
https://github.com/progrium/go-basher/blob/b674c80834b00079887df7847b9892f013c8bb54/basher.go#L156-L168
20,718
progrium/go-basher
basher.go
Export
func (c *Context) Export(name string, value string) { c.Lock() defer c.Unlock() c.vars = append(c.vars, name+"="+value) }
go
func (c *Context) Export(name string, value string) { c.Lock() defer c.Unlock() c.vars = append(c.vars, name+"="+value) }
[ "func", "(", "c", "*", "Context", ")", "Export", "(", "name", "string", ",", "value", "string", ")", "{", "c", ".", "Lock", "(", ")", "\n", "defer", "c", ".", "Unlock", "(", ")", "\n", "c", ".", "vars", "=", "append", "(", "c", ".", "vars", ",", "name", "+", "\"", "\"", "+", "value", ")", "\n", "}" ]
// Export adds an environment variable to the Context
[ "Export", "adds", "an", "environment", "variable", "to", "the", "Context" ]
b674c80834b00079887df7847b9892f013c8bb54
https://github.com/progrium/go-basher/blob/b674c80834b00079887df7847b9892f013c8bb54/basher.go#L171-L175
20,719
progrium/go-basher
basher.go
ExportFunc
func (c *Context) ExportFunc(name string, fn func([]string)) { c.Lock() defer c.Unlock() c.funcs[name] = fn }
go
func (c *Context) ExportFunc(name string, fn func([]string)) { c.Lock() defer c.Unlock() c.funcs[name] = fn }
[ "func", "(", "c", "*", "Context", ")", "ExportFunc", "(", "name", "string", ",", "fn", "func", "(", "[", "]", "string", ")", ")", "{", "c", ".", "Lock", "(", ")", "\n", "defer", "c", ".", "Unlock", "(", ")", "\n", "c", ".", "funcs", "[", "name", "]", "=", "fn", "\n", "}" ]
// Registers a function with the Context that will produce a Bash function in the environment // that calls back into your executable triggering the function defined as fn.
[ "Registers", "a", "function", "with", "the", "Context", "that", "will", "produce", "a", "Bash", "function", "in", "the", "environment", "that", "calls", "back", "into", "your", "executable", "triggering", "the", "function", "defined", "as", "fn", "." ]
b674c80834b00079887df7847b9892f013c8bb54
https://github.com/progrium/go-basher/blob/b674c80834b00079887df7847b9892f013c8bb54/basher.go#L179-L183
20,720
progrium/go-basher
basher.go
HandleFuncs
func (c *Context) HandleFuncs(args []string) bool { for i, arg := range args { if arg == ":::" && len(args) > i+1 { c.Lock() defer c.Unlock() for cmd := range c.funcs { if cmd == args[i+1] { c.funcs[cmd](args[i+2:]) return true } } return false } } return false }
go
func (c *Context) HandleFuncs(args []string) bool { for i, arg := range args { if arg == ":::" && len(args) > i+1 { c.Lock() defer c.Unlock() for cmd := range c.funcs { if cmd == args[i+1] { c.funcs[cmd](args[i+2:]) return true } } return false } } return false }
[ "func", "(", "c", "*", "Context", ")", "HandleFuncs", "(", "args", "[", "]", "string", ")", "bool", "{", "for", "i", ",", "arg", ":=", "range", "args", "{", "if", "arg", "==", "\"", "\"", "&&", "len", "(", "args", ")", ">", "i", "+", "1", "{", "c", ".", "Lock", "(", ")", "\n", "defer", "c", ".", "Unlock", "(", ")", "\n", "for", "cmd", ":=", "range", "c", ".", "funcs", "{", "if", "cmd", "==", "args", "[", "i", "+", "1", "]", "{", "c", ".", "funcs", "[", "cmd", "]", "(", "args", "[", "i", "+", "2", ":", "]", ")", "\n", "return", "true", "\n", "}", "\n", "}", "\n", "return", "false", "\n", "}", "\n", "}", "\n", "return", "false", "\n", "}" ]
// Expects your os.Args to parse and handle any callbacks to Go functions registered with // ExportFunc. You normally call this at the beginning of your program. If a registered // function is found and handled, HandleFuncs will exit with the appropriate exit code for you.
[ "Expects", "your", "os", ".", "Args", "to", "parse", "and", "handle", "any", "callbacks", "to", "Go", "functions", "registered", "with", "ExportFunc", ".", "You", "normally", "call", "this", "at", "the", "beginning", "of", "your", "program", ".", "If", "a", "registered", "function", "is", "found", "and", "handled", "HandleFuncs", "will", "exit", "with", "the", "appropriate", "exit", "code", "for", "you", "." ]
b674c80834b00079887df7847b9892f013c8bb54
https://github.com/progrium/go-basher/blob/b674c80834b00079887df7847b9892f013c8bb54/basher.go#L188-L203
20,721
progrium/go-basher
bash_linux.go
MustAsset
func MustAsset(name string) []byte { a, err := Asset(name) if (err != nil) { panic("asset: Asset(" + name + "): " + err.Error()) } return a }
go
func MustAsset(name string) []byte { a, err := Asset(name) if (err != nil) { panic("asset: Asset(" + name + "): " + err.Error()) } return a }
[ "func", "MustAsset", "(", "name", "string", ")", "[", "]", "byte", "{", "a", ",", "err", ":=", "Asset", "(", "name", ")", "\n", "if", "(", "err", "!=", "nil", ")", "{", "panic", "(", "\"", "\"", "+", "name", "+", "\"", "\"", "+", "err", ".", "Error", "(", ")", ")", "\n", "}", "\n\n", "return", "a", "\n", "}" ]
// MustAsset is like Asset but panics when Asset would return an error. // It simplifies safe initialization of global variables.
[ "MustAsset", "is", "like", "Asset", "but", "panics", "when", "Asset", "would", "return", "an", "error", ".", "It", "simplifies", "safe", "initialization", "of", "global", "variables", "." ]
b674c80834b00079887df7847b9892f013c8bb54
https://github.com/progrium/go-basher/blob/b674c80834b00079887df7847b9892f013c8bb54/bash_linux.go#L103-L110
20,722
keybase/go-keychain
macos_1.10.go
createTrustedApplication
func createTrustedApplication(trustedApplication string) (C.CFTypeRef, error) { var trustedApplicationCStr *C.char if trustedApplication != "" { trustedApplicationCStr = C.CString(trustedApplication) defer C.free(unsafe.Pointer(trustedApplicationCStr)) } var trustedApplicationRef C.SecTrustedApplicationRef errCode := C.SecTrustedApplicationCreateFromPath(trustedApplicationCStr, &trustedApplicationRef) err := checkError(errCode) if err != nil { return 0, err } return C.CFTypeRef(trustedApplicationRef), nil }
go
func createTrustedApplication(trustedApplication string) (C.CFTypeRef, error) { var trustedApplicationCStr *C.char if trustedApplication != "" { trustedApplicationCStr = C.CString(trustedApplication) defer C.free(unsafe.Pointer(trustedApplicationCStr)) } var trustedApplicationRef C.SecTrustedApplicationRef errCode := C.SecTrustedApplicationCreateFromPath(trustedApplicationCStr, &trustedApplicationRef) err := checkError(errCode) if err != nil { return 0, err } return C.CFTypeRef(trustedApplicationRef), nil }
[ "func", "createTrustedApplication", "(", "trustedApplication", "string", ")", "(", "C", ".", "CFTypeRef", ",", "error", ")", "{", "var", "trustedApplicationCStr", "*", "C", ".", "char", "\n", "if", "trustedApplication", "!=", "\"", "\"", "{", "trustedApplicationCStr", "=", "C", ".", "CString", "(", "trustedApplication", ")", "\n", "defer", "C", ".", "free", "(", "unsafe", ".", "Pointer", "(", "trustedApplicationCStr", ")", ")", "\n", "}", "\n\n", "var", "trustedApplicationRef", "C", ".", "SecTrustedApplicationRef", "\n", "errCode", ":=", "C", ".", "SecTrustedApplicationCreateFromPath", "(", "trustedApplicationCStr", ",", "&", "trustedApplicationRef", ")", "\n", "err", ":=", "checkError", "(", "errCode", ")", "\n", "if", "err", "!=", "nil", "{", "return", "0", ",", "err", "\n", "}", "\n\n", "return", "C", ".", "CFTypeRef", "(", "trustedApplicationRef", ")", ",", "nil", "\n", "}" ]
// createTrustedApplication creates a SecTrustedApplicationRef as a CFTypeRef. // The returned SecTrustedApplicationRef, if non-nil, must be released via CFRelease.
[ "createTrustedApplication", "creates", "a", "SecTrustedApplicationRef", "as", "a", "CFTypeRef", ".", "The", "returned", "SecTrustedApplicationRef", "if", "non", "-", "nil", "must", "be", "released", "via", "CFRelease", "." ]
8441f7257eb146425dca61e269cdb931987e6455
https://github.com/keybase/go-keychain/blob/8441f7257eb146425dca61e269cdb931987e6455/macos_1.10.go#L81-L96
20,723
keybase/go-keychain
macos_1.10.go
Convert
func (a Access) Convert() (C.CFTypeRef, error) { return createAccess(a.Label, a.TrustedApplications) }
go
func (a Access) Convert() (C.CFTypeRef, error) { return createAccess(a.Label, a.TrustedApplications) }
[ "func", "(", "a", "Access", ")", "Convert", "(", ")", "(", "C", ".", "CFTypeRef", ",", "error", ")", "{", "return", "createAccess", "(", "a", ".", "Label", ",", "a", ".", "TrustedApplications", ")", "\n", "}" ]
// Convert converts Access to CFTypeRef. // The returned CFTypeRef, if non-nil, must be released via CFRelease.
[ "Convert", "converts", "Access", "to", "CFTypeRef", ".", "The", "returned", "CFTypeRef", "if", "non", "-", "nil", "must", "be", "released", "via", "CFRelease", "." ]
8441f7257eb146425dca61e269cdb931987e6455
https://github.com/keybase/go-keychain/blob/8441f7257eb146425dca61e269cdb931987e6455/macos_1.10.go#L106-L108
20,724
keybase/go-keychain
macos_1.10.go
SetAccess
func (k *Item) SetAccess(a *Access) { if a != nil { k.attr[AccessKey] = a } else { delete(k.attr, AccessKey) } }
go
func (k *Item) SetAccess(a *Access) { if a != nil { k.attr[AccessKey] = a } else { delete(k.attr, AccessKey) } }
[ "func", "(", "k", "*", "Item", ")", "SetAccess", "(", "a", "*", "Access", ")", "{", "if", "a", "!=", "nil", "{", "k", ".", "attr", "[", "AccessKey", "]", "=", "a", "\n", "}", "else", "{", "delete", "(", "k", ".", "attr", ",", "AccessKey", ")", "\n", "}", "\n", "}" ]
// SetAccess sets Access on Item
[ "SetAccess", "sets", "Access", "on", "Item" ]
8441f7257eb146425dca61e269cdb931987e6455
https://github.com/keybase/go-keychain/blob/8441f7257eb146425dca61e269cdb931987e6455/macos_1.10.go#L111-L117
20,725
keybase/go-keychain
macos_1.10.go
DeleteItemRef
func DeleteItemRef(ref C.CFTypeRef) error { errCode := C.SecKeychainItemDelete(C.SecKeychainItemRef(ref)) return checkError(errCode) }
go
func DeleteItemRef(ref C.CFTypeRef) error { errCode := C.SecKeychainItemDelete(C.SecKeychainItemRef(ref)) return checkError(errCode) }
[ "func", "DeleteItemRef", "(", "ref", "C", ".", "CFTypeRef", ")", "error", "{", "errCode", ":=", "C", ".", "SecKeychainItemDelete", "(", "C", ".", "SecKeychainItemRef", "(", "ref", ")", ")", "\n", "return", "checkError", "(", "errCode", ")", "\n", "}" ]
// DeleteItemRef deletes a keychain item reference.
[ "DeleteItemRef", "deletes", "a", "keychain", "item", "reference", "." ]
8441f7257eb146425dca61e269cdb931987e6455
https://github.com/keybase/go-keychain/blob/8441f7257eb146425dca61e269cdb931987e6455/macos_1.10.go#L120-L123
20,726
keybase/go-keychain
macos_1.10.go
NewKeychain
func NewKeychain(path string, password string) (Keychain, error) { return newKeychain(path, password, false) }
go
func NewKeychain(path string, password string) (Keychain, error) { return newKeychain(path, password, false) }
[ "func", "NewKeychain", "(", "path", "string", ",", "password", "string", ")", "(", "Keychain", ",", "error", ")", "{", "return", "newKeychain", "(", "path", ",", "password", ",", "false", ")", "\n", "}" ]
// NewKeychain creates a new keychain file with a password
[ "NewKeychain", "creates", "a", "new", "keychain", "file", "with", "a", "password" ]
8441f7257eb146425dca61e269cdb931987e6455
https://github.com/keybase/go-keychain/blob/8441f7257eb146425dca61e269cdb931987e6455/macos_1.10.go#L138-L140
20,727
keybase/go-keychain
macos_1.10.go
Status
func (kc Keychain) Status() error { // returns no error even if it doesn't exist kref, err := openKeychainRef(kc.path) if err != nil { return err } defer C.CFRelease(C.CFTypeRef(kref)) var status C.SecKeychainStatus return checkError(C.SecKeychainGetStatus(kref, &status)) }
go
func (kc Keychain) Status() error { // returns no error even if it doesn't exist kref, err := openKeychainRef(kc.path) if err != nil { return err } defer C.CFRelease(C.CFTypeRef(kref)) var status C.SecKeychainStatus return checkError(C.SecKeychainGetStatus(kref, &status)) }
[ "func", "(", "kc", "Keychain", ")", "Status", "(", ")", "error", "{", "// returns no error even if it doesn't exist", "kref", ",", "err", ":=", "openKeychainRef", "(", "kc", ".", "path", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "defer", "C", ".", "CFRelease", "(", "C", ".", "CFTypeRef", "(", "kref", ")", ")", "\n\n", "var", "status", "C", ".", "SecKeychainStatus", "\n", "return", "checkError", "(", "C", ".", "SecKeychainGetStatus", "(", "kref", ",", "&", "status", ")", ")", "\n", "}" ]
// Status returns the status of the keychain
[ "Status", "returns", "the", "status", "of", "the", "keychain" ]
8441f7257eb146425dca61e269cdb931987e6455
https://github.com/keybase/go-keychain/blob/8441f7257eb146425dca61e269cdb931987e6455/macos_1.10.go#L182-L192
20,728
keybase/go-keychain
macos_1.10.go
openKeychainRef
func openKeychainRef(path string) (C.SecKeychainRef, error) { pathName := C.CString(path) defer C.free(unsafe.Pointer(pathName)) var kref C.SecKeychainRef if err := checkError(C.SecKeychainOpen(pathName, &kref)); err != nil { return 0, err } return kref, nil }
go
func openKeychainRef(path string) (C.SecKeychainRef, error) { pathName := C.CString(path) defer C.free(unsafe.Pointer(pathName)) var kref C.SecKeychainRef if err := checkError(C.SecKeychainOpen(pathName, &kref)); err != nil { return 0, err } return kref, nil }
[ "func", "openKeychainRef", "(", "path", "string", ")", "(", "C", ".", "SecKeychainRef", ",", "error", ")", "{", "pathName", ":=", "C", ".", "CString", "(", "path", ")", "\n", "defer", "C", ".", "free", "(", "unsafe", ".", "Pointer", "(", "pathName", ")", ")", "\n\n", "var", "kref", "C", ".", "SecKeychainRef", "\n", "if", "err", ":=", "checkError", "(", "C", ".", "SecKeychainOpen", "(", "pathName", ",", "&", "kref", ")", ")", ";", "err", "!=", "nil", "{", "return", "0", ",", "err", "\n", "}", "\n\n", "return", "kref", ",", "nil", "\n", "}" ]
// The returned SecKeychainRef, if non-nil, must be released via CFRelease.
[ "The", "returned", "SecKeychainRef", "if", "non", "-", "nil", "must", "be", "released", "via", "CFRelease", "." ]
8441f7257eb146425dca61e269cdb931987e6455
https://github.com/keybase/go-keychain/blob/8441f7257eb146425dca61e269cdb931987e6455/macos_1.10.go#L195-L205
20,729
keybase/go-keychain
macos_1.10.go
UnlockAtPath
func UnlockAtPath(path string, password string) error { kref, err := openKeychainRef(path) defer Release(C.CFTypeRef(kref)) if err != nil { return err } passwordRef := C.CString(password) defer C.free(unsafe.Pointer(passwordRef)) return checkError(C.SecKeychainUnlock(kref, C.UInt32(len(password)), unsafe.Pointer(passwordRef), C.Boolean(1))) }
go
func UnlockAtPath(path string, password string) error { kref, err := openKeychainRef(path) defer Release(C.CFTypeRef(kref)) if err != nil { return err } passwordRef := C.CString(password) defer C.free(unsafe.Pointer(passwordRef)) return checkError(C.SecKeychainUnlock(kref, C.UInt32(len(password)), unsafe.Pointer(passwordRef), C.Boolean(1))) }
[ "func", "UnlockAtPath", "(", "path", "string", ",", "password", "string", ")", "error", "{", "kref", ",", "err", ":=", "openKeychainRef", "(", "path", ")", "\n", "defer", "Release", "(", "C", ".", "CFTypeRef", "(", "kref", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "passwordRef", ":=", "C", ".", "CString", "(", "password", ")", "\n", "defer", "C", ".", "free", "(", "unsafe", ".", "Pointer", "(", "passwordRef", ")", ")", "\n", "return", "checkError", "(", "C", ".", "SecKeychainUnlock", "(", "kref", ",", "C", ".", "UInt32", "(", "len", "(", "password", ")", ")", ",", "unsafe", ".", "Pointer", "(", "passwordRef", ")", ",", "C", ".", "Boolean", "(", "1", ")", ")", ")", "\n", "}" ]
// UnlockAtPath unlocks keychain at path
[ "UnlockAtPath", "unlocks", "keychain", "at", "path" ]
8441f7257eb146425dca61e269cdb931987e6455
https://github.com/keybase/go-keychain/blob/8441f7257eb146425dca61e269cdb931987e6455/macos_1.10.go#L208-L217
20,730
keybase/go-keychain
macos_1.10.go
LockAtPath
func LockAtPath(path string) error { kref, err := openKeychainRef(path) defer Release(C.CFTypeRef(kref)) if err != nil { return err } return checkError(C.SecKeychainLock(kref)) }
go
func LockAtPath(path string) error { kref, err := openKeychainRef(path) defer Release(C.CFTypeRef(kref)) if err != nil { return err } return checkError(C.SecKeychainLock(kref)) }
[ "func", "LockAtPath", "(", "path", "string", ")", "error", "{", "kref", ",", "err", ":=", "openKeychainRef", "(", "path", ")", "\n", "defer", "Release", "(", "C", ".", "CFTypeRef", "(", "kref", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "return", "checkError", "(", "C", ".", "SecKeychainLock", "(", "kref", ")", ")", "\n", "}" ]
// LockAtPath locks keychain at path
[ "LockAtPath", "locks", "keychain", "at", "path" ]
8441f7257eb146425dca61e269cdb931987e6455
https://github.com/keybase/go-keychain/blob/8441f7257eb146425dca61e269cdb931987e6455/macos_1.10.go#L220-L227
20,731
keybase/go-keychain
macos_1.10.go
Convert
func (kc Keychain) Convert() (C.CFTypeRef, error) { keyRef, err := openKeychainRef(kc.path) return C.CFTypeRef(keyRef), err }
go
func (kc Keychain) Convert() (C.CFTypeRef, error) { keyRef, err := openKeychainRef(kc.path) return C.CFTypeRef(keyRef), err }
[ "func", "(", "kc", "Keychain", ")", "Convert", "(", ")", "(", "C", ".", "CFTypeRef", ",", "error", ")", "{", "keyRef", ",", "err", ":=", "openKeychainRef", "(", "kc", ".", "path", ")", "\n", "return", "C", ".", "CFTypeRef", "(", "keyRef", ")", ",", "err", "\n", "}" ]
// Convert Keychain to CFTypeRef. // The returned CFTypeRef, if non-nil, must be released via CFRelease.
[ "Convert", "Keychain", "to", "CFTypeRef", ".", "The", "returned", "CFTypeRef", "if", "non", "-", "nil", "must", "be", "released", "via", "CFRelease", "." ]
8441f7257eb146425dca61e269cdb931987e6455
https://github.com/keybase/go-keychain/blob/8441f7257eb146425dca61e269cdb931987e6455/macos_1.10.go#L236-L239
20,732
keybase/go-keychain
macos_1.10.go
Convert
func (ka keychainArray) Convert() (C.CFTypeRef, error) { var refs = make([]C.CFTypeRef, len(ka)) var err error for idx, kc := range ka { if refs[idx], err = kc.Convert(); err != nil { // If we error trying to convert lets release any we converted before for _, ref := range refs { if ref != 0 { Release(ref) } } return 0, err } } return C.CFTypeRef(ArrayToCFArray(refs)), nil }
go
func (ka keychainArray) Convert() (C.CFTypeRef, error) { var refs = make([]C.CFTypeRef, len(ka)) var err error for idx, kc := range ka { if refs[idx], err = kc.Convert(); err != nil { // If we error trying to convert lets release any we converted before for _, ref := range refs { if ref != 0 { Release(ref) } } return 0, err } } return C.CFTypeRef(ArrayToCFArray(refs)), nil }
[ "func", "(", "ka", "keychainArray", ")", "Convert", "(", ")", "(", "C", ".", "CFTypeRef", ",", "error", ")", "{", "var", "refs", "=", "make", "(", "[", "]", "C", ".", "CFTypeRef", ",", "len", "(", "ka", ")", ")", "\n", "var", "err", "error", "\n\n", "for", "idx", ",", "kc", ":=", "range", "ka", "{", "if", "refs", "[", "idx", "]", ",", "err", "=", "kc", ".", "Convert", "(", ")", ";", "err", "!=", "nil", "{", "// If we error trying to convert lets release any we converted before", "for", "_", ",", "ref", ":=", "range", "refs", "{", "if", "ref", "!=", "0", "{", "Release", "(", "ref", ")", "\n", "}", "\n", "}", "\n", "return", "0", ",", "err", "\n", "}", "\n", "}", "\n\n", "return", "C", ".", "CFTypeRef", "(", "ArrayToCFArray", "(", "refs", ")", ")", ",", "nil", "\n", "}" ]
// Convert the keychainArray to a CFTypeRef. // The returned CFTypeRef, if non-nil, must be released via CFRelease.
[ "Convert", "the", "keychainArray", "to", "a", "CFTypeRef", ".", "The", "returned", "CFTypeRef", "if", "non", "-", "nil", "must", "be", "released", "via", "CFRelease", "." ]
8441f7257eb146425dca61e269cdb931987e6455
https://github.com/keybase/go-keychain/blob/8441f7257eb146425dca61e269cdb931987e6455/macos_1.10.go#L245-L262
20,733
keybase/go-keychain
macos_1.10.go
SetMatchSearchList
func (k *Item) SetMatchSearchList(karr ...Keychain) { k.attr[MatchSearchListKey] = keychainArray(karr) }
go
func (k *Item) SetMatchSearchList(karr ...Keychain) { k.attr[MatchSearchListKey] = keychainArray(karr) }
[ "func", "(", "k", "*", "Item", ")", "SetMatchSearchList", "(", "karr", "...", "Keychain", ")", "{", "k", ".", "attr", "[", "MatchSearchListKey", "]", "=", "keychainArray", "(", "karr", ")", "\n", "}" ]
// SetMatchSearchList sets match type on keychains
[ "SetMatchSearchList", "sets", "match", "type", "on", "keychains" ]
8441f7257eb146425dca61e269cdb931987e6455
https://github.com/keybase/go-keychain/blob/8441f7257eb146425dca61e269cdb931987e6455/macos_1.10.go#L265-L267
20,734
keybase/go-keychain
bind/bind.go
AddGenericPassword
func AddGenericPassword(service string, account string, label string, password string, accessGroup string) error { item := keychain.NewGenericPassword(service, account, label, []byte(password), accessGroup) return keychain.AddItem(item) }
go
func AddGenericPassword(service string, account string, label string, password string, accessGroup string) error { item := keychain.NewGenericPassword(service, account, label, []byte(password), accessGroup) return keychain.AddItem(item) }
[ "func", "AddGenericPassword", "(", "service", "string", ",", "account", "string", ",", "label", "string", ",", "password", "string", ",", "accessGroup", "string", ")", "error", "{", "item", ":=", "keychain", ".", "NewGenericPassword", "(", "service", ",", "account", ",", "label", ",", "[", "]", "byte", "(", "password", ")", ",", "accessGroup", ")", "\n", "return", "keychain", ".", "AddItem", "(", "item", ")", "\n", "}" ]
// AddGenericPassword adds generic password
[ "AddGenericPassword", "adds", "generic", "password" ]
8441f7257eb146425dca61e269cdb931987e6455
https://github.com/keybase/go-keychain/blob/8441f7257eb146425dca61e269cdb931987e6455/bind/bind.go#L18-L21
20,735
keybase/go-keychain
bind/bind.go
DeleteGenericPassword
func DeleteGenericPassword(service string, account string, accessGroup string) error { item := keychain.NewItem() item.SetSecClass(keychain.SecClassGenericPassword) item.SetService(service) item.SetAccount(account) item.SetAccessGroup(accessGroup) return keychain.DeleteItem(item) }
go
func DeleteGenericPassword(service string, account string, accessGroup string) error { item := keychain.NewItem() item.SetSecClass(keychain.SecClassGenericPassword) item.SetService(service) item.SetAccount(account) item.SetAccessGroup(accessGroup) return keychain.DeleteItem(item) }
[ "func", "DeleteGenericPassword", "(", "service", "string", ",", "account", "string", ",", "accessGroup", "string", ")", "error", "{", "item", ":=", "keychain", ".", "NewItem", "(", ")", "\n", "item", ".", "SetSecClass", "(", "keychain", ".", "SecClassGenericPassword", ")", "\n", "item", ".", "SetService", "(", "service", ")", "\n", "item", ".", "SetAccount", "(", "account", ")", "\n", "item", ".", "SetAccessGroup", "(", "accessGroup", ")", "\n", "return", "keychain", ".", "DeleteItem", "(", "item", ")", "\n", "}" ]
// DeleteGenericPassword deletes generic password
[ "DeleteGenericPassword", "deletes", "generic", "password" ]
8441f7257eb146425dca61e269cdb931987e6455
https://github.com/keybase/go-keychain/blob/8441f7257eb146425dca61e269cdb931987e6455/bind/bind.go#L24-L31
20,736
keybase/go-keychain
secretservice/secretservice.go
PromptAndWait
func (s *SecretService) PromptAndWait(prompt dbus.ObjectPath) (paths *dbus.Variant, err error) { if prompt == NullPrompt { return nil, nil } call := s.Obj(prompt).Call("org.freedesktop.Secret.Prompt.Prompt", NilFlags, "Keyring Prompt") if call.Err != nil { return nil, errors.Wrap(err, "failed to prompt") } for { var result PromptCompletedResult select { case signal := <-s.signalCh: if signal.Name != "org.freedesktop.Secret.Prompt.Completed" { continue } err = dbus.Store(signal.Body, &result.Dismissed, &result.Paths) if err != nil { return nil, errors.Wrap(err, "failed to unmarshal prompt result") } if result.Dismissed { return nil, PromptDismissedError{errors.New("prompt dismissed")} } return &result.Paths, nil case <-time.After(30 * time.Second): return nil, errors.New("prompt timed out") } } }
go
func (s *SecretService) PromptAndWait(prompt dbus.ObjectPath) (paths *dbus.Variant, err error) { if prompt == NullPrompt { return nil, nil } call := s.Obj(prompt).Call("org.freedesktop.Secret.Prompt.Prompt", NilFlags, "Keyring Prompt") if call.Err != nil { return nil, errors.Wrap(err, "failed to prompt") } for { var result PromptCompletedResult select { case signal := <-s.signalCh: if signal.Name != "org.freedesktop.Secret.Prompt.Completed" { continue } err = dbus.Store(signal.Body, &result.Dismissed, &result.Paths) if err != nil { return nil, errors.Wrap(err, "failed to unmarshal prompt result") } if result.Dismissed { return nil, PromptDismissedError{errors.New("prompt dismissed")} } return &result.Paths, nil case <-time.After(30 * time.Second): return nil, errors.New("prompt timed out") } } }
[ "func", "(", "s", "*", "SecretService", ")", "PromptAndWait", "(", "prompt", "dbus", ".", "ObjectPath", ")", "(", "paths", "*", "dbus", ".", "Variant", ",", "err", "error", ")", "{", "if", "prompt", "==", "NullPrompt", "{", "return", "nil", ",", "nil", "\n", "}", "\n", "call", ":=", "s", ".", "Obj", "(", "prompt", ")", ".", "Call", "(", "\"", "\"", ",", "NilFlags", ",", "\"", "\"", ")", "\n", "if", "call", ".", "Err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Wrap", "(", "err", ",", "\"", "\"", ")", "\n", "}", "\n", "for", "{", "var", "result", "PromptCompletedResult", "\n", "select", "{", "case", "signal", ":=", "<-", "s", ".", "signalCh", ":", "if", "signal", ".", "Name", "!=", "\"", "\"", "{", "continue", "\n", "}", "\n", "err", "=", "dbus", ".", "Store", "(", "signal", ".", "Body", ",", "&", "result", ".", "Dismissed", ",", "&", "result", ".", "Paths", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Wrap", "(", "err", ",", "\"", "\"", ")", "\n", "}", "\n", "if", "result", ".", "Dismissed", "{", "return", "nil", ",", "PromptDismissedError", "{", "errors", ".", "New", "(", "\"", "\"", ")", "}", "\n", "}", "\n", "return", "&", "result", ".", "Paths", ",", "nil", "\n", "case", "<-", "time", ".", "After", "(", "30", "*", "time", ".", "Second", ")", ":", "return", "nil", ",", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n", "}", "\n", "}" ]
// PromptAndWait is NOT thread-safe.
[ "PromptAndWait", "is", "NOT", "thread", "-", "safe", "." ]
8441f7257eb146425dca61e269cdb931987e6455
https://github.com/keybase/go-keychain/blob/8441f7257eb146425dca61e269cdb931987e6455/secretservice/secretservice.go#L266-L293
20,737
keybase/go-keychain
datetime.go
CFDateToTime
func CFDateToTime(d C.CFDateRef) time.Time { abs := C.CFDateGetAbsoluteTime(d) s, ns := absoluteTimeToUnix(abs) return time.Unix(s, ns) }
go
func CFDateToTime(d C.CFDateRef) time.Time { abs := C.CFDateGetAbsoluteTime(d) s, ns := absoluteTimeToUnix(abs) return time.Unix(s, ns) }
[ "func", "CFDateToTime", "(", "d", "C", ".", "CFDateRef", ")", "time", ".", "Time", "{", "abs", ":=", "C", ".", "CFDateGetAbsoluteTime", "(", "d", ")", "\n", "s", ",", "ns", ":=", "absoluteTimeToUnix", "(", "abs", ")", "\n", "return", "time", ".", "Unix", "(", "s", ",", "ns", ")", "\n", "}" ]
// CFDateToTime will convert the given CFDateRef to a time.Time.
[ "CFDateToTime", "will", "convert", "the", "given", "CFDateRef", "to", "a", "time", ".", "Time", "." ]
8441f7257eb146425dca61e269cdb931987e6455
https://github.com/keybase/go-keychain/blob/8441f7257eb146425dca61e269cdb931987e6455/datetime.go#L67-L71
20,738
keybase/go-keychain
corefoundation_1.10.go
CFDataToBytes
func CFDataToBytes(cfData C.CFDataRef) ([]byte, error) { return C.GoBytes(unsafe.Pointer(C.CFDataGetBytePtr(cfData)), C.int(C.CFDataGetLength(cfData))), nil }
go
func CFDataToBytes(cfData C.CFDataRef) ([]byte, error) { return C.GoBytes(unsafe.Pointer(C.CFDataGetBytePtr(cfData)), C.int(C.CFDataGetLength(cfData))), nil }
[ "func", "CFDataToBytes", "(", "cfData", "C", ".", "CFDataRef", ")", "(", "[", "]", "byte", ",", "error", ")", "{", "return", "C", ".", "GoBytes", "(", "unsafe", ".", "Pointer", "(", "C", ".", "CFDataGetBytePtr", "(", "cfData", ")", ")", ",", "C", ".", "int", "(", "C", ".", "CFDataGetLength", "(", "cfData", ")", ")", ")", ",", "nil", "\n", "}" ]
// CFDataToBytes converts CFData to bytes.
[ "CFDataToBytes", "converts", "CFData", "to", "bytes", "." ]
8441f7257eb146425dca61e269cdb931987e6455
https://github.com/keybase/go-keychain/blob/8441f7257eb146425dca61e269cdb931987e6455/corefoundation_1.10.go#L63-L65
20,739
keybase/go-keychain
corefoundation_1.10.go
CFStringToString
func CFStringToString(s C.CFStringRef) string { p := C.CFStringGetCStringPtr(s, C.kCFStringEncodingUTF8) if p != nil { return C.GoString(p) } length := C.CFStringGetLength(s) if length == 0 { return "" } maxBufLen := C.CFStringGetMaximumSizeForEncoding(length, C.kCFStringEncodingUTF8) if maxBufLen == 0 { return "" } buf := make([]byte, maxBufLen) var usedBufLen C.CFIndex _ = C.CFStringGetBytes(s, C.CFRange{0, length}, C.kCFStringEncodingUTF8, C.UInt8(0), C.false, (*C.UInt8)(&buf[0]), maxBufLen, &usedBufLen) return string(buf[:usedBufLen]) }
go
func CFStringToString(s C.CFStringRef) string { p := C.CFStringGetCStringPtr(s, C.kCFStringEncodingUTF8) if p != nil { return C.GoString(p) } length := C.CFStringGetLength(s) if length == 0 { return "" } maxBufLen := C.CFStringGetMaximumSizeForEncoding(length, C.kCFStringEncodingUTF8) if maxBufLen == 0 { return "" } buf := make([]byte, maxBufLen) var usedBufLen C.CFIndex _ = C.CFStringGetBytes(s, C.CFRange{0, length}, C.kCFStringEncodingUTF8, C.UInt8(0), C.false, (*C.UInt8)(&buf[0]), maxBufLen, &usedBufLen) return string(buf[:usedBufLen]) }
[ "func", "CFStringToString", "(", "s", "C", ".", "CFStringRef", ")", "string", "{", "p", ":=", "C", ".", "CFStringGetCStringPtr", "(", "s", ",", "C", ".", "kCFStringEncodingUTF8", ")", "\n", "if", "p", "!=", "nil", "{", "return", "C", ".", "GoString", "(", "p", ")", "\n", "}", "\n", "length", ":=", "C", ".", "CFStringGetLength", "(", "s", ")", "\n", "if", "length", "==", "0", "{", "return", "\"", "\"", "\n", "}", "\n", "maxBufLen", ":=", "C", ".", "CFStringGetMaximumSizeForEncoding", "(", "length", ",", "C", ".", "kCFStringEncodingUTF8", ")", "\n", "if", "maxBufLen", "==", "0", "{", "return", "\"", "\"", "\n", "}", "\n", "buf", ":=", "make", "(", "[", "]", "byte", ",", "maxBufLen", ")", "\n", "var", "usedBufLen", "C", ".", "CFIndex", "\n", "_", "=", "C", ".", "CFStringGetBytes", "(", "s", ",", "C", ".", "CFRange", "{", "0", ",", "length", "}", ",", "C", ".", "kCFStringEncodingUTF8", ",", "C", ".", "UInt8", "(", "0", ")", ",", "C", ".", "false", ",", "(", "*", "C", ".", "UInt8", ")", "(", "&", "buf", "[", "0", "]", ")", ",", "maxBufLen", ",", "&", "usedBufLen", ")", "\n", "return", "string", "(", "buf", "[", ":", "usedBufLen", "]", ")", "\n", "}" ]
// CFStringToString converts a CFStringRef to a string.
[ "CFStringToString", "converts", "a", "CFStringRef", "to", "a", "string", "." ]
8441f7257eb146425dca61e269cdb931987e6455
https://github.com/keybase/go-keychain/blob/8441f7257eb146425dca61e269cdb931987e6455/corefoundation_1.10.go#L122-L139
20,740
keybase/go-keychain
corefoundation_1.10.go
CFTypeDescription
func CFTypeDescription(ref C.CFTypeRef) string { typeID := C.CFGetTypeID(ref) typeDesc := C.CFCopyTypeIDDescription(typeID) defer Release(C.CFTypeRef(typeDesc)) return CFStringToString(typeDesc) }
go
func CFTypeDescription(ref C.CFTypeRef) string { typeID := C.CFGetTypeID(ref) typeDesc := C.CFCopyTypeIDDescription(typeID) defer Release(C.CFTypeRef(typeDesc)) return CFStringToString(typeDesc) }
[ "func", "CFTypeDescription", "(", "ref", "C", ".", "CFTypeRef", ")", "string", "{", "typeID", ":=", "C", ".", "CFGetTypeID", "(", "ref", ")", "\n", "typeDesc", ":=", "C", ".", "CFCopyTypeIDDescription", "(", "typeID", ")", "\n", "defer", "Release", "(", "C", ".", "CFTypeRef", "(", "typeDesc", ")", ")", "\n", "return", "CFStringToString", "(", "typeDesc", ")", "\n", "}" ]
// CFTypeDescription returns type string for CFTypeRef.
[ "CFTypeDescription", "returns", "type", "string", "for", "CFTypeRef", "." ]
8441f7257eb146425dca61e269cdb931987e6455
https://github.com/keybase/go-keychain/blob/8441f7257eb146425dca61e269cdb931987e6455/corefoundation_1.10.go#L226-L231
20,741
keybase/go-keychain
corefoundation_1.10.go
Convert
func Convert(ref C.CFTypeRef) (interface{}, error) { typeID := C.CFGetTypeID(ref) if typeID == C.CFStringGetTypeID() { return CFStringToString(C.CFStringRef(ref)), nil } else if typeID == C.CFDictionaryGetTypeID() { return ConvertCFDictionary(C.CFDictionaryRef(ref)) } else if typeID == C.CFArrayGetTypeID() { arr := CFArrayToArray(C.CFArrayRef(ref)) results := make([]interface{}, 0, len(arr)) for _, ref := range arr { v, err := Convert(ref) if err != nil { return nil, err } results = append(results, v) return results, nil } } else if typeID == C.CFDataGetTypeID() { b, err := CFDataToBytes(C.CFDataRef(ref)) if err != nil { return nil, err } return b, nil } else if typeID == C.CFNumberGetTypeID() { return CFNumberToInterface(C.CFNumberRef(ref)), nil } else if typeID == C.CFBooleanGetTypeID() { if C.CFBooleanGetValue(C.CFBooleanRef(ref)) != 0 { return true, nil } return false, nil } return nil, fmt.Errorf("Invalid type: %s", CFTypeDescription(ref)) }
go
func Convert(ref C.CFTypeRef) (interface{}, error) { typeID := C.CFGetTypeID(ref) if typeID == C.CFStringGetTypeID() { return CFStringToString(C.CFStringRef(ref)), nil } else if typeID == C.CFDictionaryGetTypeID() { return ConvertCFDictionary(C.CFDictionaryRef(ref)) } else if typeID == C.CFArrayGetTypeID() { arr := CFArrayToArray(C.CFArrayRef(ref)) results := make([]interface{}, 0, len(arr)) for _, ref := range arr { v, err := Convert(ref) if err != nil { return nil, err } results = append(results, v) return results, nil } } else if typeID == C.CFDataGetTypeID() { b, err := CFDataToBytes(C.CFDataRef(ref)) if err != nil { return nil, err } return b, nil } else if typeID == C.CFNumberGetTypeID() { return CFNumberToInterface(C.CFNumberRef(ref)), nil } else if typeID == C.CFBooleanGetTypeID() { if C.CFBooleanGetValue(C.CFBooleanRef(ref)) != 0 { return true, nil } return false, nil } return nil, fmt.Errorf("Invalid type: %s", CFTypeDescription(ref)) }
[ "func", "Convert", "(", "ref", "C", ".", "CFTypeRef", ")", "(", "interface", "{", "}", ",", "error", ")", "{", "typeID", ":=", "C", ".", "CFGetTypeID", "(", "ref", ")", "\n", "if", "typeID", "==", "C", ".", "CFStringGetTypeID", "(", ")", "{", "return", "CFStringToString", "(", "C", ".", "CFStringRef", "(", "ref", ")", ")", ",", "nil", "\n", "}", "else", "if", "typeID", "==", "C", ".", "CFDictionaryGetTypeID", "(", ")", "{", "return", "ConvertCFDictionary", "(", "C", ".", "CFDictionaryRef", "(", "ref", ")", ")", "\n", "}", "else", "if", "typeID", "==", "C", ".", "CFArrayGetTypeID", "(", ")", "{", "arr", ":=", "CFArrayToArray", "(", "C", ".", "CFArrayRef", "(", "ref", ")", ")", "\n", "results", ":=", "make", "(", "[", "]", "interface", "{", "}", ",", "0", ",", "len", "(", "arr", ")", ")", "\n", "for", "_", ",", "ref", ":=", "range", "arr", "{", "v", ",", "err", ":=", "Convert", "(", "ref", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "results", "=", "append", "(", "results", ",", "v", ")", "\n", "return", "results", ",", "nil", "\n", "}", "\n", "}", "else", "if", "typeID", "==", "C", ".", "CFDataGetTypeID", "(", ")", "{", "b", ",", "err", ":=", "CFDataToBytes", "(", "C", ".", "CFDataRef", "(", "ref", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "return", "b", ",", "nil", "\n", "}", "else", "if", "typeID", "==", "C", ".", "CFNumberGetTypeID", "(", ")", "{", "return", "CFNumberToInterface", "(", "C", ".", "CFNumberRef", "(", "ref", ")", ")", ",", "nil", "\n", "}", "else", "if", "typeID", "==", "C", ".", "CFBooleanGetTypeID", "(", ")", "{", "if", "C", ".", "CFBooleanGetValue", "(", "C", ".", "CFBooleanRef", "(", "ref", ")", ")", "!=", "0", "{", "return", "true", ",", "nil", "\n", "}", "\n", "return", "false", ",", "nil", "\n", "}", "\n\n", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "CFTypeDescription", "(", "ref", ")", ")", "\n", "}" ]
// Convert converts a CFTypeRef to a go instance.
[ "Convert", "converts", "a", "CFTypeRef", "to", "a", "go", "instance", "." ]
8441f7257eb146425dca61e269cdb931987e6455
https://github.com/keybase/go-keychain/blob/8441f7257eb146425dca61e269cdb931987e6455/corefoundation_1.10.go#L234-L267
20,742
keybase/go-keychain
util.go
RandBytes
func RandBytes(length int) ([]byte, error) { buf := make([]byte, length) if _, err := randRead(buf); err != nil { return nil, err } return buf, nil }
go
func RandBytes(length int) ([]byte, error) { buf := make([]byte, length) if _, err := randRead(buf); err != nil { return nil, err } return buf, nil }
[ "func", "RandBytes", "(", "length", "int", ")", "(", "[", "]", "byte", ",", "error", ")", "{", "buf", ":=", "make", "(", "[", "]", "byte", ",", "length", ")", "\n", "if", "_", ",", "err", ":=", "randRead", "(", "buf", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "return", "buf", ",", "nil", "\n", "}" ]
// RandBytes returns random bytes of length
[ "RandBytes", "returns", "random", "bytes", "of", "length" ]
8441f7257eb146425dca61e269cdb931987e6455
https://github.com/keybase/go-keychain/blob/8441f7257eb146425dca61e269cdb931987e6455/util.go#L25-L31
20,743
keybase/go-keychain
corefoundation_pre1.10.go
CFDictionaryToMap
func CFDictionaryToMap(cfDict C.CFDictionaryRef) (m map[C.CFTypeRef]uintptr) { count := C.CFDictionaryGetCount(cfDict) if count > 0 { keys := make([]C.CFTypeRef, count) values := make([]C.CFTypeRef, count) C.CFDictionaryGetKeysAndValues(cfDict, (*unsafe.Pointer)(&keys[0]), (*unsafe.Pointer)(&values[0])) m = make(map[C.CFTypeRef]uintptr, count) for i := C.CFIndex(0); i < count; i++ { k := keys[i] v := values[i] m[k] = uintptr(v) } } return }
go
func CFDictionaryToMap(cfDict C.CFDictionaryRef) (m map[C.CFTypeRef]uintptr) { count := C.CFDictionaryGetCount(cfDict) if count > 0 { keys := make([]C.CFTypeRef, count) values := make([]C.CFTypeRef, count) C.CFDictionaryGetKeysAndValues(cfDict, (*unsafe.Pointer)(&keys[0]), (*unsafe.Pointer)(&values[0])) m = make(map[C.CFTypeRef]uintptr, count) for i := C.CFIndex(0); i < count; i++ { k := keys[i] v := values[i] m[k] = uintptr(v) } } return }
[ "func", "CFDictionaryToMap", "(", "cfDict", "C", ".", "CFDictionaryRef", ")", "(", "m", "map", "[", "C", ".", "CFTypeRef", "]", "uintptr", ")", "{", "count", ":=", "C", ".", "CFDictionaryGetCount", "(", "cfDict", ")", "\n", "if", "count", ">", "0", "{", "keys", ":=", "make", "(", "[", "]", "C", ".", "CFTypeRef", ",", "count", ")", "\n", "values", ":=", "make", "(", "[", "]", "C", ".", "CFTypeRef", ",", "count", ")", "\n", "C", ".", "CFDictionaryGetKeysAndValues", "(", "cfDict", ",", "(", "*", "unsafe", ".", "Pointer", ")", "(", "&", "keys", "[", "0", "]", ")", ",", "(", "*", "unsafe", ".", "Pointer", ")", "(", "&", "values", "[", "0", "]", ")", ")", "\n", "m", "=", "make", "(", "map", "[", "C", ".", "CFTypeRef", "]", "uintptr", ",", "count", ")", "\n", "for", "i", ":=", "C", ".", "CFIndex", "(", "0", ")", ";", "i", "<", "count", ";", "i", "++", "{", "k", ":=", "keys", "[", "i", "]", "\n", "v", ":=", "values", "[", "i", "]", "\n", "m", "[", "k", "]", "=", "uintptr", "(", "v", ")", "\n", "}", "\n", "}", "\n", "return", "\n", "}" ]
// CFDictionaryToMap converts CFDictionaryRef to a map.
[ "CFDictionaryToMap", "converts", "CFDictionaryRef", "to", "a", "map", "." ]
8441f7257eb146425dca61e269cdb931987e6455
https://github.com/keybase/go-keychain/blob/8441f7257eb146425dca61e269cdb931987e6455/corefoundation_pre1.10.go#L72-L86
20,744
keybase/go-keychain
corefoundation_pre1.10.go
CFArrayToArray
func CFArrayToArray(cfArray C.CFArrayRef) (a []C.CFTypeRef) { count := C.CFArrayGetCount(cfArray) if count > 0 { a = make([]C.CFTypeRef, count) C.CFArrayGetValues(cfArray, C.CFRange{0, count}, (*unsafe.Pointer)(&a[0])) } return }
go
func CFArrayToArray(cfArray C.CFArrayRef) (a []C.CFTypeRef) { count := C.CFArrayGetCount(cfArray) if count > 0 { a = make([]C.CFTypeRef, count) C.CFArrayGetValues(cfArray, C.CFRange{0, count}, (*unsafe.Pointer)(&a[0])) } return }
[ "func", "CFArrayToArray", "(", "cfArray", "C", ".", "CFArrayRef", ")", "(", "a", "[", "]", "C", ".", "CFTypeRef", ")", "{", "count", ":=", "C", ".", "CFArrayGetCount", "(", "cfArray", ")", "\n", "if", "count", ">", "0", "{", "a", "=", "make", "(", "[", "]", "C", ".", "CFTypeRef", ",", "count", ")", "\n", "C", ".", "CFArrayGetValues", "(", "cfArray", ",", "C", ".", "CFRange", "{", "0", ",", "count", "}", ",", "(", "*", "unsafe", ".", "Pointer", ")", "(", "&", "a", "[", "0", "]", ")", ")", "\n", "}", "\n", "return", "\n", "}" ]
// CFArrayToArray converts a CFArrayRef to an array of CFTypes.
[ "CFArrayToArray", "converts", "a", "CFArrayRef", "to", "an", "array", "of", "CFTypes", "." ]
8441f7257eb146425dca61e269cdb931987e6455
https://github.com/keybase/go-keychain/blob/8441f7257eb146425dca61e269cdb931987e6455/corefoundation_pre1.10.go#L142-L149
20,745
keybase/go-keychain
keychain_1.10.go
SetSecClass
func (k *Item) SetSecClass(sc SecClass) { k.attr[SecClassKey] = secClassTypeRef[sc] }
go
func (k *Item) SetSecClass(sc SecClass) { k.attr[SecClassKey] = secClassTypeRef[sc] }
[ "func", "(", "k", "*", "Item", ")", "SetSecClass", "(", "sc", "SecClass", ")", "{", "k", ".", "attr", "[", "SecClassKey", "]", "=", "secClassTypeRef", "[", "sc", "]", "\n", "}" ]
// SetSecClass sets the security class
[ "SetSecClass", "sets", "the", "security", "class" ]
8441f7257eb146425dca61e269cdb931987e6455
https://github.com/keybase/go-keychain/blob/8441f7257eb146425dca61e269cdb931987e6455/keychain_1.10.go#L211-L213
20,746
keybase/go-keychain
keychain_1.10.go
SetString
func (k *Item) SetString(key string, s string) { if s != "" { k.attr[key] = s } else { delete(k.attr, key) } }
go
func (k *Item) SetString(key string, s string) { if s != "" { k.attr[key] = s } else { delete(k.attr, key) } }
[ "func", "(", "k", "*", "Item", ")", "SetString", "(", "key", "string", ",", "s", "string", ")", "{", "if", "s", "!=", "\"", "\"", "{", "k", ".", "attr", "[", "key", "]", "=", "s", "\n", "}", "else", "{", "delete", "(", "k", ".", "attr", ",", "key", ")", "\n", "}", "\n", "}" ]
// SetString sets a string attibute for a string key
[ "SetString", "sets", "a", "string", "attibute", "for", "a", "string", "key" ]
8441f7257eb146425dca61e269cdb931987e6455
https://github.com/keybase/go-keychain/blob/8441f7257eb146425dca61e269cdb931987e6455/keychain_1.10.go#L216-L222
20,747
keybase/go-keychain
keychain_1.10.go
SetData
func (k *Item) SetData(b []byte) { if b != nil { k.attr[DataKey] = b } else { delete(k.attr, DataKey) } }
go
func (k *Item) SetData(b []byte) { if b != nil { k.attr[DataKey] = b } else { delete(k.attr, DataKey) } }
[ "func", "(", "k", "*", "Item", ")", "SetData", "(", "b", "[", "]", "byte", ")", "{", "if", "b", "!=", "nil", "{", "k", ".", "attr", "[", "DataKey", "]", "=", "b", "\n", "}", "else", "{", "delete", "(", "k", ".", "attr", ",", "DataKey", ")", "\n", "}", "\n", "}" ]
// SetData sets the data attribute
[ "SetData", "sets", "the", "data", "attribute" ]
8441f7257eb146425dca61e269cdb931987e6455
https://github.com/keybase/go-keychain/blob/8441f7257eb146425dca61e269cdb931987e6455/keychain_1.10.go#L245-L251
20,748
keybase/go-keychain
keychain_1.10.go
SetSynchronizable
func (k *Item) SetSynchronizable(sync Synchronizable) { if sync != SynchronizableDefault { k.attr[SynchronizableKey] = syncTypeRef[sync] } else { delete(k.attr, SynchronizableKey) } }
go
func (k *Item) SetSynchronizable(sync Synchronizable) { if sync != SynchronizableDefault { k.attr[SynchronizableKey] = syncTypeRef[sync] } else { delete(k.attr, SynchronizableKey) } }
[ "func", "(", "k", "*", "Item", ")", "SetSynchronizable", "(", "sync", "Synchronizable", ")", "{", "if", "sync", "!=", "SynchronizableDefault", "{", "k", ".", "attr", "[", "SynchronizableKey", "]", "=", "syncTypeRef", "[", "sync", "]", "\n", "}", "else", "{", "delete", "(", "k", ".", "attr", ",", "SynchronizableKey", ")", "\n", "}", "\n", "}" ]
// SetSynchronizable sets the synchronizable attribute
[ "SetSynchronizable", "sets", "the", "synchronizable", "attribute" ]
8441f7257eb146425dca61e269cdb931987e6455
https://github.com/keybase/go-keychain/blob/8441f7257eb146425dca61e269cdb931987e6455/keychain_1.10.go#L259-L265
20,749
keybase/go-keychain
keychain_1.10.go
SetAccessible
func (k *Item) SetAccessible(accessible Accessible) { if accessible != AccessibleDefault { k.attr[AccessibleKey] = accessibleTypeRef[accessible] } else { delete(k.attr, AccessibleKey) } }
go
func (k *Item) SetAccessible(accessible Accessible) { if accessible != AccessibleDefault { k.attr[AccessibleKey] = accessibleTypeRef[accessible] } else { delete(k.attr, AccessibleKey) } }
[ "func", "(", "k", "*", "Item", ")", "SetAccessible", "(", "accessible", "Accessible", ")", "{", "if", "accessible", "!=", "AccessibleDefault", "{", "k", ".", "attr", "[", "AccessibleKey", "]", "=", "accessibleTypeRef", "[", "accessible", "]", "\n", "}", "else", "{", "delete", "(", "k", ".", "attr", ",", "AccessibleKey", ")", "\n", "}", "\n", "}" ]
// SetAccessible sets the accessible attribute
[ "SetAccessible", "sets", "the", "accessible", "attribute" ]
8441f7257eb146425dca61e269cdb931987e6455
https://github.com/keybase/go-keychain/blob/8441f7257eb146425dca61e269cdb931987e6455/keychain_1.10.go#L268-L274
20,750
keybase/go-keychain
keychain_1.10.go
SetMatchLimit
func (k *Item) SetMatchLimit(matchLimit MatchLimit) { if matchLimit != MatchLimitDefault { k.attr[MatchLimitKey] = matchTypeRef[matchLimit] } else { delete(k.attr, MatchLimitKey) } }
go
func (k *Item) SetMatchLimit(matchLimit MatchLimit) { if matchLimit != MatchLimitDefault { k.attr[MatchLimitKey] = matchTypeRef[matchLimit] } else { delete(k.attr, MatchLimitKey) } }
[ "func", "(", "k", "*", "Item", ")", "SetMatchLimit", "(", "matchLimit", "MatchLimit", ")", "{", "if", "matchLimit", "!=", "MatchLimitDefault", "{", "k", ".", "attr", "[", "MatchLimitKey", "]", "=", "matchTypeRef", "[", "matchLimit", "]", "\n", "}", "else", "{", "delete", "(", "k", ".", "attr", ",", "MatchLimitKey", ")", "\n", "}", "\n", "}" ]
// SetMatchLimit sets the match limit
[ "SetMatchLimit", "sets", "the", "match", "limit" ]
8441f7257eb146425dca61e269cdb931987e6455
https://github.com/keybase/go-keychain/blob/8441f7257eb146425dca61e269cdb931987e6455/keychain_1.10.go#L277-L283
20,751
keybase/go-keychain
keychain_1.10.go
NewGenericPassword
func NewGenericPassword(service string, account string, label string, data []byte, accessGroup string) Item { item := NewItem() item.SetSecClass(SecClassGenericPassword) item.SetService(service) item.SetAccount(account) item.SetLabel(label) item.SetData(data) item.SetAccessGroup(accessGroup) return item }
go
func NewGenericPassword(service string, account string, label string, data []byte, accessGroup string) Item { item := NewItem() item.SetSecClass(SecClassGenericPassword) item.SetService(service) item.SetAccount(account) item.SetLabel(label) item.SetData(data) item.SetAccessGroup(accessGroup) return item }
[ "func", "NewGenericPassword", "(", "service", "string", ",", "account", "string", ",", "label", "string", ",", "data", "[", "]", "byte", ",", "accessGroup", "string", ")", "Item", "{", "item", ":=", "NewItem", "(", ")", "\n", "item", ".", "SetSecClass", "(", "SecClassGenericPassword", ")", "\n", "item", ".", "SetService", "(", "service", ")", "\n", "item", ".", "SetAccount", "(", "account", ")", "\n", "item", ".", "SetLabel", "(", "label", ")", "\n", "item", ".", "SetData", "(", "data", ")", "\n", "item", ".", "SetAccessGroup", "(", "accessGroup", ")", "\n", "return", "item", "\n", "}" ]
// NewGenericPassword creates a generic password item with the default keychain. This is a convenience method.
[ "NewGenericPassword", "creates", "a", "generic", "password", "item", "with", "the", "default", "keychain", ".", "This", "is", "a", "convenience", "method", "." ]
8441f7257eb146425dca61e269cdb931987e6455
https://github.com/keybase/go-keychain/blob/8441f7257eb146425dca61e269cdb931987e6455/keychain_1.10.go#L306-L315
20,752
keybase/go-keychain
keychain_1.10.go
AddItem
func AddItem(item Item) error { cfDict, err := ConvertMapToCFDictionary(item.attr) if err != nil { return err } defer Release(C.CFTypeRef(cfDict)) errCode := C.SecItemAdd(cfDict, nil) err = checkError(errCode) return err }
go
func AddItem(item Item) error { cfDict, err := ConvertMapToCFDictionary(item.attr) if err != nil { return err } defer Release(C.CFTypeRef(cfDict)) errCode := C.SecItemAdd(cfDict, nil) err = checkError(errCode) return err }
[ "func", "AddItem", "(", "item", "Item", ")", "error", "{", "cfDict", ",", "err", ":=", "ConvertMapToCFDictionary", "(", "item", ".", "attr", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "defer", "Release", "(", "C", ".", "CFTypeRef", "(", "cfDict", ")", ")", "\n\n", "errCode", ":=", "C", ".", "SecItemAdd", "(", "cfDict", ",", "nil", ")", "\n", "err", "=", "checkError", "(", "errCode", ")", "\n", "return", "err", "\n", "}" ]
// AddItem adds a Item to a Keychain
[ "AddItem", "adds", "a", "Item", "to", "a", "Keychain" ]
8441f7257eb146425dca61e269cdb931987e6455
https://github.com/keybase/go-keychain/blob/8441f7257eb146425dca61e269cdb931987e6455/keychain_1.10.go#L318-L328
20,753
keybase/go-keychain
keychain_1.10.go
UpdateItem
func UpdateItem(queryItem Item, updateItem Item) error { cfDict, err := ConvertMapToCFDictionary(queryItem.attr) if err != nil { return err } defer Release(C.CFTypeRef(cfDict)) cfDictUpdate, err := ConvertMapToCFDictionary(updateItem.attr) if err != nil { return err } defer Release(C.CFTypeRef(cfDictUpdate)) errCode := C.SecItemUpdate(cfDict, cfDictUpdate) err = checkError(errCode) return err }
go
func UpdateItem(queryItem Item, updateItem Item) error { cfDict, err := ConvertMapToCFDictionary(queryItem.attr) if err != nil { return err } defer Release(C.CFTypeRef(cfDict)) cfDictUpdate, err := ConvertMapToCFDictionary(updateItem.attr) if err != nil { return err } defer Release(C.CFTypeRef(cfDictUpdate)) errCode := C.SecItemUpdate(cfDict, cfDictUpdate) err = checkError(errCode) return err }
[ "func", "UpdateItem", "(", "queryItem", "Item", ",", "updateItem", "Item", ")", "error", "{", "cfDict", ",", "err", ":=", "ConvertMapToCFDictionary", "(", "queryItem", ".", "attr", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "defer", "Release", "(", "C", ".", "CFTypeRef", "(", "cfDict", ")", ")", "\n", "cfDictUpdate", ",", "err", ":=", "ConvertMapToCFDictionary", "(", "updateItem", ".", "attr", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "defer", "Release", "(", "C", ".", "CFTypeRef", "(", "cfDictUpdate", ")", ")", "\n", "errCode", ":=", "C", ".", "SecItemUpdate", "(", "cfDict", ",", "cfDictUpdate", ")", "\n", "err", "=", "checkError", "(", "errCode", ")", "\n", "return", "err", "\n", "}" ]
// UpdateItem updates the queryItem with the parameters from updateItem
[ "UpdateItem", "updates", "the", "queryItem", "with", "the", "parameters", "from", "updateItem" ]
8441f7257eb146425dca61e269cdb931987e6455
https://github.com/keybase/go-keychain/blob/8441f7257eb146425dca61e269cdb931987e6455/keychain_1.10.go#L331-L345
20,754
keybase/go-keychain
keychain_1.10.go
DeleteGenericPasswordItem
func DeleteGenericPasswordItem(service string, account string) error { item := NewItem() item.SetSecClass(SecClassGenericPassword) item.SetService(service) item.SetAccount(account) return DeleteItem(item) }
go
func DeleteGenericPasswordItem(service string, account string) error { item := NewItem() item.SetSecClass(SecClassGenericPassword) item.SetService(service) item.SetAccount(account) return DeleteItem(item) }
[ "func", "DeleteGenericPasswordItem", "(", "service", "string", ",", "account", "string", ")", "error", "{", "item", ":=", "NewItem", "(", ")", "\n", "item", ".", "SetSecClass", "(", "SecClassGenericPassword", ")", "\n", "item", ".", "SetService", "(", "service", ")", "\n", "item", ".", "SetAccount", "(", "account", ")", "\n", "return", "DeleteItem", "(", "item", ")", "\n", "}" ]
// DeleteGenericPasswordItem removes a generic password item.
[ "DeleteGenericPasswordItem", "removes", "a", "generic", "password", "item", "." ]
8441f7257eb146425dca61e269cdb931987e6455
https://github.com/keybase/go-keychain/blob/8441f7257eb146425dca61e269cdb931987e6455/keychain_1.10.go#L465-L471
20,755
keybase/go-keychain
keychain_1.10.go
DeleteItem
func DeleteItem(item Item) error { cfDict, err := ConvertMapToCFDictionary(item.attr) if err != nil { return err } defer Release(C.CFTypeRef(cfDict)) errCode := C.SecItemDelete(cfDict) return checkError(errCode) }
go
func DeleteItem(item Item) error { cfDict, err := ConvertMapToCFDictionary(item.attr) if err != nil { return err } defer Release(C.CFTypeRef(cfDict)) errCode := C.SecItemDelete(cfDict) return checkError(errCode) }
[ "func", "DeleteItem", "(", "item", "Item", ")", "error", "{", "cfDict", ",", "err", ":=", "ConvertMapToCFDictionary", "(", "item", ".", "attr", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "defer", "Release", "(", "C", ".", "CFTypeRef", "(", "cfDict", ")", ")", "\n\n", "errCode", ":=", "C", ".", "SecItemDelete", "(", "cfDict", ")", "\n", "return", "checkError", "(", "errCode", ")", "\n", "}" ]
// DeleteItem removes a Item
[ "DeleteItem", "removes", "a", "Item" ]
8441f7257eb146425dca61e269cdb931987e6455
https://github.com/keybase/go-keychain/blob/8441f7257eb146425dca61e269cdb931987e6455/keychain_1.10.go#L474-L483
20,756
keybase/go-keychain
keychain_1.10.go
GetGenericPasswordAccounts
func GetGenericPasswordAccounts(service string) ([]string, error) { query := NewItem() query.SetSecClass(SecClassGenericPassword) query.SetService(service) query.SetMatchLimit(MatchLimitAll) query.SetReturnAttributes(true) results, err := QueryItem(query) if err != nil { return nil, err } accounts := make([]string, 0, len(results)) for _, r := range results { accounts = append(accounts, r.Account) } return accounts, nil }
go
func GetGenericPasswordAccounts(service string) ([]string, error) { query := NewItem() query.SetSecClass(SecClassGenericPassword) query.SetService(service) query.SetMatchLimit(MatchLimitAll) query.SetReturnAttributes(true) results, err := QueryItem(query) if err != nil { return nil, err } accounts := make([]string, 0, len(results)) for _, r := range results { accounts = append(accounts, r.Account) } return accounts, nil }
[ "func", "GetGenericPasswordAccounts", "(", "service", "string", ")", "(", "[", "]", "string", ",", "error", ")", "{", "query", ":=", "NewItem", "(", ")", "\n", "query", ".", "SetSecClass", "(", "SecClassGenericPassword", ")", "\n", "query", ".", "SetService", "(", "service", ")", "\n", "query", ".", "SetMatchLimit", "(", "MatchLimitAll", ")", "\n", "query", ".", "SetReturnAttributes", "(", "true", ")", "\n", "results", ",", "err", ":=", "QueryItem", "(", "query", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "accounts", ":=", "make", "(", "[", "]", "string", ",", "0", ",", "len", "(", "results", ")", ")", "\n", "for", "_", ",", "r", ":=", "range", "results", "{", "accounts", "=", "append", "(", "accounts", ",", "r", ".", "Account", ")", "\n", "}", "\n\n", "return", "accounts", ",", "nil", "\n", "}" ]
// GetGenericPasswordAccounts returns generic password accounts for service. This is a convenience method.
[ "GetGenericPasswordAccounts", "returns", "generic", "password", "accounts", "for", "service", ".", "This", "is", "a", "convenience", "method", "." ]
8441f7257eb146425dca61e269cdb931987e6455
https://github.com/keybase/go-keychain/blob/8441f7257eb146425dca61e269cdb931987e6455/keychain_1.10.go#L491-L508
20,757
keybase/go-keychain
keychain_1.10.go
GetGenericPassword
func GetGenericPassword(service string, account string, label string, accessGroup string) ([]byte, error) { query := NewItem() query.SetSecClass(SecClassGenericPassword) query.SetService(service) query.SetAccount(account) query.SetLabel(label) query.SetAccessGroup(accessGroup) query.SetMatchLimit(MatchLimitOne) query.SetReturnData(true) results, err := QueryItem(query) if err != nil { return nil, err } if len(results) > 1 { return nil, fmt.Errorf("Too many results") } if len(results) == 1 { return results[0].Data, nil } return nil, nil }
go
func GetGenericPassword(service string, account string, label string, accessGroup string) ([]byte, error) { query := NewItem() query.SetSecClass(SecClassGenericPassword) query.SetService(service) query.SetAccount(account) query.SetLabel(label) query.SetAccessGroup(accessGroup) query.SetMatchLimit(MatchLimitOne) query.SetReturnData(true) results, err := QueryItem(query) if err != nil { return nil, err } if len(results) > 1 { return nil, fmt.Errorf("Too many results") } if len(results) == 1 { return results[0].Data, nil } return nil, nil }
[ "func", "GetGenericPassword", "(", "service", "string", ",", "account", "string", ",", "label", "string", ",", "accessGroup", "string", ")", "(", "[", "]", "byte", ",", "error", ")", "{", "query", ":=", "NewItem", "(", ")", "\n", "query", ".", "SetSecClass", "(", "SecClassGenericPassword", ")", "\n", "query", ".", "SetService", "(", "service", ")", "\n", "query", ".", "SetAccount", "(", "account", ")", "\n", "query", ".", "SetLabel", "(", "label", ")", "\n", "query", ".", "SetAccessGroup", "(", "accessGroup", ")", "\n", "query", ".", "SetMatchLimit", "(", "MatchLimitOne", ")", "\n", "query", ".", "SetReturnData", "(", "true", ")", "\n", "results", ",", "err", ":=", "QueryItem", "(", "query", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "if", "len", "(", "results", ")", ">", "1", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n", "if", "len", "(", "results", ")", "==", "1", "{", "return", "results", "[", "0", "]", ".", "Data", ",", "nil", "\n", "}", "\n", "return", "nil", ",", "nil", "\n", "}" ]
// GetGenericPassword returns password data for service and account. This is a convenience method. // If item is not found returns nil, nil.
[ "GetGenericPassword", "returns", "password", "data", "for", "service", "and", "account", ".", "This", "is", "a", "convenience", "method", ".", "If", "item", "is", "not", "found", "returns", "nil", "nil", "." ]
8441f7257eb146425dca61e269cdb931987e6455
https://github.com/keybase/go-keychain/blob/8441f7257eb146425dca61e269cdb931987e6455/keychain_1.10.go#L512-L532
20,758
keybase/go-keychain
macos_pre1.10.go
createAccess
func createAccess(label string, trustedApplications []string) (C.CFTypeRef, error) { var err error var labelRef C.CFStringRef if labelRef, err = StringToCFString(label); err != nil { return nil, err } defer C.CFRelease(C.CFTypeRef(labelRef)) var trustedApplicationsArray C.CFArrayRef if trustedApplications != nil { if len(trustedApplications) > 0 { // Always prepend with empty string which signifies that we // include a NULL application, which means ourselves. trustedApplications = append([]string{""}, trustedApplications...) } var trustedApplicationsRefs []C.CFTypeRef for _, trustedApplication := range trustedApplications { trustedApplicationRef, createErr := createTrustedApplication(trustedApplication) if createErr != nil { return nil, createErr } defer C.CFRelease(C.CFTypeRef(trustedApplicationRef)) trustedApplicationsRefs = append(trustedApplicationsRefs, trustedApplicationRef) } trustedApplicationsArray = ArrayToCFArray(trustedApplicationsRefs) defer C.CFRelease(C.CFTypeRef(trustedApplicationsArray)) } var access C.SecAccessRef errCode := C.SecAccessCreate(labelRef, trustedApplicationsArray, &access) err = checkError(errCode) if err != nil { return nil, err } return C.CFTypeRef(access), nil }
go
func createAccess(label string, trustedApplications []string) (C.CFTypeRef, error) { var err error var labelRef C.CFStringRef if labelRef, err = StringToCFString(label); err != nil { return nil, err } defer C.CFRelease(C.CFTypeRef(labelRef)) var trustedApplicationsArray C.CFArrayRef if trustedApplications != nil { if len(trustedApplications) > 0 { // Always prepend with empty string which signifies that we // include a NULL application, which means ourselves. trustedApplications = append([]string{""}, trustedApplications...) } var trustedApplicationsRefs []C.CFTypeRef for _, trustedApplication := range trustedApplications { trustedApplicationRef, createErr := createTrustedApplication(trustedApplication) if createErr != nil { return nil, createErr } defer C.CFRelease(C.CFTypeRef(trustedApplicationRef)) trustedApplicationsRefs = append(trustedApplicationsRefs, trustedApplicationRef) } trustedApplicationsArray = ArrayToCFArray(trustedApplicationsRefs) defer C.CFRelease(C.CFTypeRef(trustedApplicationsArray)) } var access C.SecAccessRef errCode := C.SecAccessCreate(labelRef, trustedApplicationsArray, &access) err = checkError(errCode) if err != nil { return nil, err } return C.CFTypeRef(access), nil }
[ "func", "createAccess", "(", "label", "string", ",", "trustedApplications", "[", "]", "string", ")", "(", "C", ".", "CFTypeRef", ",", "error", ")", "{", "var", "err", "error", "\n", "var", "labelRef", "C", ".", "CFStringRef", "\n", "if", "labelRef", ",", "err", "=", "StringToCFString", "(", "label", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "defer", "C", ".", "CFRelease", "(", "C", ".", "CFTypeRef", "(", "labelRef", ")", ")", "\n\n", "var", "trustedApplicationsArray", "C", ".", "CFArrayRef", "\n", "if", "trustedApplications", "!=", "nil", "{", "if", "len", "(", "trustedApplications", ")", ">", "0", "{", "// Always prepend with empty string which signifies that we", "// include a NULL application, which means ourselves.", "trustedApplications", "=", "append", "(", "[", "]", "string", "{", "\"", "\"", "}", ",", "trustedApplications", "...", ")", "\n", "}", "\n\n", "var", "trustedApplicationsRefs", "[", "]", "C", ".", "CFTypeRef", "\n", "for", "_", ",", "trustedApplication", ":=", "range", "trustedApplications", "{", "trustedApplicationRef", ",", "createErr", ":=", "createTrustedApplication", "(", "trustedApplication", ")", "\n", "if", "createErr", "!=", "nil", "{", "return", "nil", ",", "createErr", "\n", "}", "\n", "defer", "C", ".", "CFRelease", "(", "C", ".", "CFTypeRef", "(", "trustedApplicationRef", ")", ")", "\n", "trustedApplicationsRefs", "=", "append", "(", "trustedApplicationsRefs", ",", "trustedApplicationRef", ")", "\n", "}", "\n\n", "trustedApplicationsArray", "=", "ArrayToCFArray", "(", "trustedApplicationsRefs", ")", "\n", "defer", "C", ".", "CFRelease", "(", "C", ".", "CFTypeRef", "(", "trustedApplicationsArray", ")", ")", "\n", "}", "\n\n", "var", "access", "C", ".", "SecAccessRef", "\n", "errCode", ":=", "C", ".", "SecAccessCreate", "(", "labelRef", ",", "trustedApplicationsArray", ",", "&", "access", ")", "\n", "err", "=", "checkError", "(", "errCode", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "return", "C", ".", "CFTypeRef", "(", "access", ")", ",", "nil", "\n", "}" ]
// createAccess creates a SecAccessRef as CFTypeRef. // The returned SecAccessRef, if non-nil, must be released via CFRelease.
[ "createAccess", "creates", "a", "SecAccessRef", "as", "CFTypeRef", ".", "The", "returned", "SecAccessRef", "if", "non", "-", "nil", "must", "be", "released", "via", "CFRelease", "." ]
8441f7257eb146425dca61e269cdb931987e6455
https://github.com/keybase/go-keychain/blob/8441f7257eb146425dca61e269cdb931987e6455/macos_pre1.10.go#L41-L79
20,759
keybase/go-keychain
keychain_pre1.10.go
QueryItemRef
func QueryItemRef(item Item) (C.CFTypeRef, error) { cfDict, err := ConvertMapToCFDictionary(item.attr) if err != nil { return nil, err } defer Release(C.CFTypeRef(cfDict)) var resultsRef C.CFTypeRef errCode := C.SecItemCopyMatching(cfDict, &resultsRef) if Error(errCode) == ErrorItemNotFound { return nil, nil } err = checkError(errCode) if err != nil { return nil, err } return resultsRef, nil }
go
func QueryItemRef(item Item) (C.CFTypeRef, error) { cfDict, err := ConvertMapToCFDictionary(item.attr) if err != nil { return nil, err } defer Release(C.CFTypeRef(cfDict)) var resultsRef C.CFTypeRef errCode := C.SecItemCopyMatching(cfDict, &resultsRef) if Error(errCode) == ErrorItemNotFound { return nil, nil } err = checkError(errCode) if err != nil { return nil, err } return resultsRef, nil }
[ "func", "QueryItemRef", "(", "item", "Item", ")", "(", "C", ".", "CFTypeRef", ",", "error", ")", "{", "cfDict", ",", "err", ":=", "ConvertMapToCFDictionary", "(", "item", ".", "attr", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "defer", "Release", "(", "C", ".", "CFTypeRef", "(", "cfDict", ")", ")", "\n\n", "var", "resultsRef", "C", ".", "CFTypeRef", "\n", "errCode", ":=", "C", ".", "SecItemCopyMatching", "(", "cfDict", ",", "&", "resultsRef", ")", "\n", "if", "Error", "(", "errCode", ")", "==", "ErrorItemNotFound", "{", "return", "nil", ",", "nil", "\n", "}", "\n", "err", "=", "checkError", "(", "errCode", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "return", "resultsRef", ",", "nil", "\n", "}" ]
// QueryItemRef returns query result as CFTypeRef. You must release it when you are done.
[ "QueryItemRef", "returns", "query", "result", "as", "CFTypeRef", ".", "You", "must", "release", "it", "when", "you", "are", "done", "." ]
8441f7257eb146425dca61e269cdb931987e6455
https://github.com/keybase/go-keychain/blob/8441f7257eb146425dca61e269cdb931987e6455/keychain_pre1.10.go#L389-L406
20,760
keybase/go-keychain
keychain_pre1.10.go
QueryItem
func QueryItem(item Item) ([]QueryResult, error) { resultsRef, err := QueryItemRef(item) if err != nil { return nil, err } if resultsRef == nil { return nil, nil } defer Release(resultsRef) results := make([]QueryResult, 0, 1) typeID := C.CFGetTypeID(resultsRef) if typeID == C.CFArrayGetTypeID() { arr := CFArrayToArray(C.CFArrayRef(resultsRef)) for _, ref := range arr { elementTypeID := C.CFGetTypeID(ref) if elementTypeID == C.CFDictionaryGetTypeID() { item, err := convertResult(C.CFDictionaryRef(ref)) if err != nil { return nil, err } results = append(results, *item) } else { return nil, fmt.Errorf("invalid result type (If you SetReturnRef(true) you should use QueryItemRef directly)") } } } else if typeID == C.CFDictionaryGetTypeID() { item, err := convertResult(C.CFDictionaryRef(resultsRef)) if err != nil { return nil, err } results = append(results, *item) } else if typeID == C.CFDataGetTypeID() { b, err := CFDataToBytes(C.CFDataRef(resultsRef)) if err != nil { return nil, err } item := QueryResult{Data: b} results = append(results, item) } else { return nil, fmt.Errorf("Invalid result type: %s", CFTypeDescription(resultsRef)) } return results, nil }
go
func QueryItem(item Item) ([]QueryResult, error) { resultsRef, err := QueryItemRef(item) if err != nil { return nil, err } if resultsRef == nil { return nil, nil } defer Release(resultsRef) results := make([]QueryResult, 0, 1) typeID := C.CFGetTypeID(resultsRef) if typeID == C.CFArrayGetTypeID() { arr := CFArrayToArray(C.CFArrayRef(resultsRef)) for _, ref := range arr { elementTypeID := C.CFGetTypeID(ref) if elementTypeID == C.CFDictionaryGetTypeID() { item, err := convertResult(C.CFDictionaryRef(ref)) if err != nil { return nil, err } results = append(results, *item) } else { return nil, fmt.Errorf("invalid result type (If you SetReturnRef(true) you should use QueryItemRef directly)") } } } else if typeID == C.CFDictionaryGetTypeID() { item, err := convertResult(C.CFDictionaryRef(resultsRef)) if err != nil { return nil, err } results = append(results, *item) } else if typeID == C.CFDataGetTypeID() { b, err := CFDataToBytes(C.CFDataRef(resultsRef)) if err != nil { return nil, err } item := QueryResult{Data: b} results = append(results, item) } else { return nil, fmt.Errorf("Invalid result type: %s", CFTypeDescription(resultsRef)) } return results, nil }
[ "func", "QueryItem", "(", "item", "Item", ")", "(", "[", "]", "QueryResult", ",", "error", ")", "{", "resultsRef", ",", "err", ":=", "QueryItemRef", "(", "item", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "if", "resultsRef", "==", "nil", "{", "return", "nil", ",", "nil", "\n", "}", "\n", "defer", "Release", "(", "resultsRef", ")", "\n\n", "results", ":=", "make", "(", "[", "]", "QueryResult", ",", "0", ",", "1", ")", "\n\n", "typeID", ":=", "C", ".", "CFGetTypeID", "(", "resultsRef", ")", "\n", "if", "typeID", "==", "C", ".", "CFArrayGetTypeID", "(", ")", "{", "arr", ":=", "CFArrayToArray", "(", "C", ".", "CFArrayRef", "(", "resultsRef", ")", ")", "\n", "for", "_", ",", "ref", ":=", "range", "arr", "{", "elementTypeID", ":=", "C", ".", "CFGetTypeID", "(", "ref", ")", "\n", "if", "elementTypeID", "==", "C", ".", "CFDictionaryGetTypeID", "(", ")", "{", "item", ",", "err", ":=", "convertResult", "(", "C", ".", "CFDictionaryRef", "(", "ref", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "results", "=", "append", "(", "results", ",", "*", "item", ")", "\n", "}", "else", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n", "}", "\n", "}", "else", "if", "typeID", "==", "C", ".", "CFDictionaryGetTypeID", "(", ")", "{", "item", ",", "err", ":=", "convertResult", "(", "C", ".", "CFDictionaryRef", "(", "resultsRef", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "results", "=", "append", "(", "results", ",", "*", "item", ")", "\n", "}", "else", "if", "typeID", "==", "C", ".", "CFDataGetTypeID", "(", ")", "{", "b", ",", "err", ":=", "CFDataToBytes", "(", "C", ".", "CFDataRef", "(", "resultsRef", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "item", ":=", "QueryResult", "{", "Data", ":", "b", "}", "\n", "results", "=", "append", "(", "results", ",", "item", ")", "\n", "}", "else", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "CFTypeDescription", "(", "resultsRef", ")", ")", "\n", "}", "\n\n", "return", "results", ",", "nil", "\n", "}" ]
// QueryItem returns a list of query results.
[ "QueryItem", "returns", "a", "list", "of", "query", "results", "." ]
8441f7257eb146425dca61e269cdb931987e6455
https://github.com/keybase/go-keychain/blob/8441f7257eb146425dca61e269cdb931987e6455/keychain_pre1.10.go#L409-L454
20,761
hashicorp/net-rpc-msgpackrpc
msgpackrpc.go
NewClientCodec
func NewClientCodec(conn io.ReadWriteCloser) rpc.ClientCodec { return NewCodec(true, true, conn) }
go
func NewClientCodec(conn io.ReadWriteCloser) rpc.ClientCodec { return NewCodec(true, true, conn) }
[ "func", "NewClientCodec", "(", "conn", "io", ".", "ReadWriteCloser", ")", "rpc", ".", "ClientCodec", "{", "return", "NewCodec", "(", "true", ",", "true", ",", "conn", ")", "\n", "}" ]
// NewClientCodec returns a new rpc.ClientCodec using MessagePack-RPC on conn.
[ "NewClientCodec", "returns", "a", "new", "rpc", ".", "ClientCodec", "using", "MessagePack", "-", "RPC", "on", "conn", "." ]
a14192a58a694c123d8fe5481d4a4727d6ae82f3
https://github.com/hashicorp/net-rpc-msgpackrpc/blob/a14192a58a694c123d8fe5481d4a4727d6ae82f3/msgpackrpc.go#L28-L30
20,762
hashicorp/net-rpc-msgpackrpc
msgpackrpc.go
NewServerCodec
func NewServerCodec(conn io.ReadWriteCloser) rpc.ServerCodec { return NewCodec(true, true, conn) }
go
func NewServerCodec(conn io.ReadWriteCloser) rpc.ServerCodec { return NewCodec(true, true, conn) }
[ "func", "NewServerCodec", "(", "conn", "io", ".", "ReadWriteCloser", ")", "rpc", ".", "ServerCodec", "{", "return", "NewCodec", "(", "true", ",", "true", ",", "conn", ")", "\n", "}" ]
// NewServerCodec returns a new rpc.ServerCodec using MessagePack-RPC on conn.
[ "NewServerCodec", "returns", "a", "new", "rpc", ".", "ServerCodec", "using", "MessagePack", "-", "RPC", "on", "conn", "." ]
a14192a58a694c123d8fe5481d4a4727d6ae82f3
https://github.com/hashicorp/net-rpc-msgpackrpc/blob/a14192a58a694c123d8fe5481d4a4727d6ae82f3/msgpackrpc.go#L33-L35
20,763
hashicorp/net-rpc-msgpackrpc
codec.go
NewCodec
func NewCodec(bufReads, bufWrites bool, conn io.ReadWriteCloser) *MsgpackCodec { return NewCodecFromHandle(bufReads, bufWrites, conn, msgpackHandle) }
go
func NewCodec(bufReads, bufWrites bool, conn io.ReadWriteCloser) *MsgpackCodec { return NewCodecFromHandle(bufReads, bufWrites, conn, msgpackHandle) }
[ "func", "NewCodec", "(", "bufReads", ",", "bufWrites", "bool", ",", "conn", "io", ".", "ReadWriteCloser", ")", "*", "MsgpackCodec", "{", "return", "NewCodecFromHandle", "(", "bufReads", ",", "bufWrites", ",", "conn", ",", "msgpackHandle", ")", "\n", "}" ]
// NewCodec returns a MsgpackCodec that can be used as either a Client or Server // rpc Codec using a default handle. It also provides controls for enabling and // disabling buffering for both reads and writes.
[ "NewCodec", "returns", "a", "MsgpackCodec", "that", "can", "be", "used", "as", "either", "a", "Client", "or", "Server", "rpc", "Codec", "using", "a", "default", "handle", ".", "It", "also", "provides", "controls", "for", "enabling", "and", "disabling", "buffering", "for", "both", "reads", "and", "writes", "." ]
a14192a58a694c123d8fe5481d4a4727d6ae82f3
https://github.com/hashicorp/net-rpc-msgpackrpc/blob/a14192a58a694c123d8fe5481d4a4727d6ae82f3/codec.go#L32-L34
20,764
hashicorp/net-rpc-msgpackrpc
codec.go
NewCodecFromHandle
func NewCodecFromHandle(bufReads, bufWrites bool, conn io.ReadWriteCloser, h *codec.MsgpackHandle) *MsgpackCodec { cc := &MsgpackCodec{ conn: conn, } if bufReads { cc.bufR = bufio.NewReader(conn) cc.dec = codec.NewDecoder(cc.bufR, h) } else { cc.dec = codec.NewDecoder(cc.conn, h) } if bufWrites { cc.bufW = bufio.NewWriter(conn) cc.enc = codec.NewEncoder(cc.bufW, h) } else { cc.enc = codec.NewEncoder(cc.conn, h) } return cc }
go
func NewCodecFromHandle(bufReads, bufWrites bool, conn io.ReadWriteCloser, h *codec.MsgpackHandle) *MsgpackCodec { cc := &MsgpackCodec{ conn: conn, } if bufReads { cc.bufR = bufio.NewReader(conn) cc.dec = codec.NewDecoder(cc.bufR, h) } else { cc.dec = codec.NewDecoder(cc.conn, h) } if bufWrites { cc.bufW = bufio.NewWriter(conn) cc.enc = codec.NewEncoder(cc.bufW, h) } else { cc.enc = codec.NewEncoder(cc.conn, h) } return cc }
[ "func", "NewCodecFromHandle", "(", "bufReads", ",", "bufWrites", "bool", ",", "conn", "io", ".", "ReadWriteCloser", ",", "h", "*", "codec", ".", "MsgpackHandle", ")", "*", "MsgpackCodec", "{", "cc", ":=", "&", "MsgpackCodec", "{", "conn", ":", "conn", ",", "}", "\n", "if", "bufReads", "{", "cc", ".", "bufR", "=", "bufio", ".", "NewReader", "(", "conn", ")", "\n", "cc", ".", "dec", "=", "codec", ".", "NewDecoder", "(", "cc", ".", "bufR", ",", "h", ")", "\n", "}", "else", "{", "cc", ".", "dec", "=", "codec", ".", "NewDecoder", "(", "cc", ".", "conn", ",", "h", ")", "\n", "}", "\n", "if", "bufWrites", "{", "cc", ".", "bufW", "=", "bufio", ".", "NewWriter", "(", "conn", ")", "\n", "cc", ".", "enc", "=", "codec", ".", "NewEncoder", "(", "cc", ".", "bufW", ",", "h", ")", "\n", "}", "else", "{", "cc", ".", "enc", "=", "codec", ".", "NewEncoder", "(", "cc", ".", "conn", ",", "h", ")", "\n", "}", "\n", "return", "cc", "\n", "}" ]
// NewCodecFromHandle returns a MsgpackCodec that can be used as either a Client // or Server rpc Codec using the passed handle. It also provides controls for // enabling and disabling buffering for both reads and writes.
[ "NewCodecFromHandle", "returns", "a", "MsgpackCodec", "that", "can", "be", "used", "as", "either", "a", "Client", "or", "Server", "rpc", "Codec", "using", "the", "passed", "handle", ".", "It", "also", "provides", "controls", "for", "enabling", "and", "disabling", "buffering", "for", "both", "reads", "and", "writes", "." ]
a14192a58a694c123d8fe5481d4a4727d6ae82f3
https://github.com/hashicorp/net-rpc-msgpackrpc/blob/a14192a58a694c123d8fe5481d4a4727d6ae82f3/codec.go#L39-L57
20,765
googleapis/gax-go
v2/header.go
XGoogHeader
func XGoogHeader(keyval ...string) string { if len(keyval) == 0 { return "" } if len(keyval)%2 != 0 { panic("gax.Header: odd argument count") } var buf bytes.Buffer for i := 0; i < len(keyval); i += 2 { buf.WriteByte(' ') buf.WriteString(keyval[i]) buf.WriteByte('/') buf.WriteString(keyval[i+1]) } return buf.String()[1:] }
go
func XGoogHeader(keyval ...string) string { if len(keyval) == 0 { return "" } if len(keyval)%2 != 0 { panic("gax.Header: odd argument count") } var buf bytes.Buffer for i := 0; i < len(keyval); i += 2 { buf.WriteByte(' ') buf.WriteString(keyval[i]) buf.WriteByte('/') buf.WriteString(keyval[i+1]) } return buf.String()[1:] }
[ "func", "XGoogHeader", "(", "keyval", "...", "string", ")", "string", "{", "if", "len", "(", "keyval", ")", "==", "0", "{", "return", "\"", "\"", "\n", "}", "\n", "if", "len", "(", "keyval", ")", "%", "2", "!=", "0", "{", "panic", "(", "\"", "\"", ")", "\n", "}", "\n", "var", "buf", "bytes", ".", "Buffer", "\n", "for", "i", ":=", "0", ";", "i", "<", "len", "(", "keyval", ")", ";", "i", "+=", "2", "{", "buf", ".", "WriteByte", "(", "' '", ")", "\n", "buf", ".", "WriteString", "(", "keyval", "[", "i", "]", ")", "\n", "buf", ".", "WriteByte", "(", "'/'", ")", "\n", "buf", ".", "WriteString", "(", "keyval", "[", "i", "+", "1", "]", ")", "\n", "}", "\n", "return", "buf", ".", "String", "(", ")", "[", "1", ":", "]", "\n", "}" ]
// XGoogHeader is for use by the Google Cloud Libraries only. // // XGoogHeader formats key-value pairs. // The resulting string is suitable for x-goog-api-client header.
[ "XGoogHeader", "is", "for", "use", "by", "the", "Google", "Cloud", "Libraries", "only", ".", "XGoogHeader", "formats", "key", "-", "value", "pairs", ".", "The", "resulting", "string", "is", "suitable", "for", "x", "-", "goog", "-", "api", "-", "client", "header", "." ]
9e334198cafcf7b281a9673424d7b1c3a02ebd50
https://github.com/googleapis/gax-go/blob/9e334198cafcf7b281a9673424d7b1c3a02ebd50/v2/header.go#L38-L53
20,766
googleapis/gax-go
v2/invoke.go
invoke
func invoke(ctx context.Context, call APICall, settings CallSettings, sp sleeper) error { var retryer Retryer for { err := call(ctx, settings) if err == nil { return nil } if settings.Retry == nil { return err } // Never retry permanent certificate errors. (e.x. if ca-certificates // are not installed). We should only make very few, targeted // exceptions: many (other) status=Unavailable should be retried, such // as if there's a network hiccup, or the internet goes out for a // minute. This is also why here we are doing string parsing instead of // simply making Unavailable a non-retried code elsewhere. if strings.Contains(err.Error(), "x509: certificate signed by unknown authority") { return err } if retryer == nil { if r := settings.Retry(); r != nil { retryer = r } else { return err } } if d, ok := retryer.Retry(err); !ok { return err } else if err = sp(ctx, d); err != nil { return err } } }
go
func invoke(ctx context.Context, call APICall, settings CallSettings, sp sleeper) error { var retryer Retryer for { err := call(ctx, settings) if err == nil { return nil } if settings.Retry == nil { return err } // Never retry permanent certificate errors. (e.x. if ca-certificates // are not installed). We should only make very few, targeted // exceptions: many (other) status=Unavailable should be retried, such // as if there's a network hiccup, or the internet goes out for a // minute. This is also why here we are doing string parsing instead of // simply making Unavailable a non-retried code elsewhere. if strings.Contains(err.Error(), "x509: certificate signed by unknown authority") { return err } if retryer == nil { if r := settings.Retry(); r != nil { retryer = r } else { return err } } if d, ok := retryer.Retry(err); !ok { return err } else if err = sp(ctx, d); err != nil { return err } } }
[ "func", "invoke", "(", "ctx", "context", ".", "Context", ",", "call", "APICall", ",", "settings", "CallSettings", ",", "sp", "sleeper", ")", "error", "{", "var", "retryer", "Retryer", "\n", "for", "{", "err", ":=", "call", "(", "ctx", ",", "settings", ")", "\n", "if", "err", "==", "nil", "{", "return", "nil", "\n", "}", "\n", "if", "settings", ".", "Retry", "==", "nil", "{", "return", "err", "\n", "}", "\n", "// Never retry permanent certificate errors. (e.x. if ca-certificates", "// are not installed). We should only make very few, targeted", "// exceptions: many (other) status=Unavailable should be retried, such", "// as if there's a network hiccup, or the internet goes out for a", "// minute. This is also why here we are doing string parsing instead of", "// simply making Unavailable a non-retried code elsewhere.", "if", "strings", ".", "Contains", "(", "err", ".", "Error", "(", ")", ",", "\"", "\"", ")", "{", "return", "err", "\n", "}", "\n", "if", "retryer", "==", "nil", "{", "if", "r", ":=", "settings", ".", "Retry", "(", ")", ";", "r", "!=", "nil", "{", "retryer", "=", "r", "\n", "}", "else", "{", "return", "err", "\n", "}", "\n", "}", "\n", "if", "d", ",", "ok", ":=", "retryer", ".", "Retry", "(", "err", ")", ";", "!", "ok", "{", "return", "err", "\n", "}", "else", "if", "err", "=", "sp", "(", "ctx", ",", "d", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "}", "\n", "}" ]
// invoke implements Invoke, taking an additional sleeper argument for testing.
[ "invoke", "implements", "Invoke", "taking", "an", "additional", "sleeper", "argument", "for", "testing", "." ]
9e334198cafcf7b281a9673424d7b1c3a02ebd50
https://github.com/googleapis/gax-go/blob/9e334198cafcf7b281a9673424d7b1c3a02ebd50/v2/invoke.go#L67-L99
20,767
googleapis/gax-go
v2/call_option.go
Pause
func (bo *Backoff) Pause() time.Duration { if bo.Initial == 0 { bo.Initial = time.Second } if bo.cur == 0 { bo.cur = bo.Initial } if bo.Max == 0 { bo.Max = 30 * time.Second } if bo.Multiplier < 1 { bo.Multiplier = 2 } // Select a duration between 1ns and the current max. It might seem // counterintuitive to have so much jitter, but // https://www.awsarchitectureblog.com/2015/03/backoff.html argues that // that is the best strategy. d := time.Duration(1 + rand.Int63n(int64(bo.cur))) bo.cur = time.Duration(float64(bo.cur) * bo.Multiplier) if bo.cur > bo.Max { bo.cur = bo.Max } return d }
go
func (bo *Backoff) Pause() time.Duration { if bo.Initial == 0 { bo.Initial = time.Second } if bo.cur == 0 { bo.cur = bo.Initial } if bo.Max == 0 { bo.Max = 30 * time.Second } if bo.Multiplier < 1 { bo.Multiplier = 2 } // Select a duration between 1ns and the current max. It might seem // counterintuitive to have so much jitter, but // https://www.awsarchitectureblog.com/2015/03/backoff.html argues that // that is the best strategy. d := time.Duration(1 + rand.Int63n(int64(bo.cur))) bo.cur = time.Duration(float64(bo.cur) * bo.Multiplier) if bo.cur > bo.Max { bo.cur = bo.Max } return d }
[ "func", "(", "bo", "*", "Backoff", ")", "Pause", "(", ")", "time", ".", "Duration", "{", "if", "bo", ".", "Initial", "==", "0", "{", "bo", ".", "Initial", "=", "time", ".", "Second", "\n", "}", "\n", "if", "bo", ".", "cur", "==", "0", "{", "bo", ".", "cur", "=", "bo", ".", "Initial", "\n", "}", "\n", "if", "bo", ".", "Max", "==", "0", "{", "bo", ".", "Max", "=", "30", "*", "time", ".", "Second", "\n", "}", "\n", "if", "bo", ".", "Multiplier", "<", "1", "{", "bo", ".", "Multiplier", "=", "2", "\n", "}", "\n", "// Select a duration between 1ns and the current max. It might seem", "// counterintuitive to have so much jitter, but", "// https://www.awsarchitectureblog.com/2015/03/backoff.html argues that", "// that is the best strategy.", "d", ":=", "time", ".", "Duration", "(", "1", "+", "rand", ".", "Int63n", "(", "int64", "(", "bo", ".", "cur", ")", ")", ")", "\n", "bo", ".", "cur", "=", "time", ".", "Duration", "(", "float64", "(", "bo", ".", "cur", ")", "*", "bo", ".", "Multiplier", ")", "\n", "if", "bo", ".", "cur", ">", "bo", ".", "Max", "{", "bo", ".", "cur", "=", "bo", ".", "Max", "\n", "}", "\n", "return", "d", "\n", "}" ]
// Pause returns the next time.Duration that the caller should use to backoff.
[ "Pause", "returns", "the", "next", "time", ".", "Duration", "that", "the", "caller", "should", "use", "to", "backoff", "." ]
9e334198cafcf7b281a9673424d7b1c3a02ebd50
https://github.com/googleapis/gax-go/blob/9e334198cafcf7b281a9673424d7b1c3a02ebd50/v2/call_option.go#L117-L140
20,768
googleapis/gax-go
v2/call_option.go
WithGRPCOptions
func WithGRPCOptions(opt ...grpc.CallOption) CallOption { return grpcOpt(append([]grpc.CallOption(nil), opt...)) }
go
func WithGRPCOptions(opt ...grpc.CallOption) CallOption { return grpcOpt(append([]grpc.CallOption(nil), opt...)) }
[ "func", "WithGRPCOptions", "(", "opt", "...", "grpc", ".", "CallOption", ")", "CallOption", "{", "return", "grpcOpt", "(", "append", "(", "[", "]", "grpc", ".", "CallOption", "(", "nil", ")", ",", "opt", "...", ")", ")", "\n", "}" ]
// WithGRPCOptions allows passing gRPC call options during client creation.
[ "WithGRPCOptions", "allows", "passing", "gRPC", "call", "options", "during", "client", "creation", "." ]
9e334198cafcf7b281a9673424d7b1c3a02ebd50
https://github.com/googleapis/gax-go/blob/9e334198cafcf7b281a9673424d7b1c3a02ebd50/v2/call_option.go#L149-L151
20,769
bsm/redis-lock
lock.go
Run
func Run(client RedisClient, key string, opts *Options, handler func()) error { locker, err := Obtain(client, key, opts) if err != nil { return err } sem := make(chan struct{}) go func() { handler() close(sem) }() select { case <-sem: return locker.Unlock() case <-time.After(locker.opts.LockTimeout): return ErrLockDurationExceeded } }
go
func Run(client RedisClient, key string, opts *Options, handler func()) error { locker, err := Obtain(client, key, opts) if err != nil { return err } sem := make(chan struct{}) go func() { handler() close(sem) }() select { case <-sem: return locker.Unlock() case <-time.After(locker.opts.LockTimeout): return ErrLockDurationExceeded } }
[ "func", "Run", "(", "client", "RedisClient", ",", "key", "string", ",", "opts", "*", "Options", ",", "handler", "func", "(", ")", ")", "error", "{", "locker", ",", "err", ":=", "Obtain", "(", "client", ",", "key", ",", "opts", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "sem", ":=", "make", "(", "chan", "struct", "{", "}", ")", "\n", "go", "func", "(", ")", "{", "handler", "(", ")", "\n", "close", "(", "sem", ")", "\n", "}", "(", ")", "\n\n", "select", "{", "case", "<-", "sem", ":", "return", "locker", ".", "Unlock", "(", ")", "\n", "case", "<-", "time", ".", "After", "(", "locker", ".", "opts", ".", "LockTimeout", ")", ":", "return", "ErrLockDurationExceeded", "\n", "}", "\n", "}" ]
// Run runs a callback handler with a Redis lock. It may return ErrLockNotObtained // if a lock was not successfully acquired.
[ "Run", "runs", "a", "callback", "handler", "with", "a", "Redis", "lock", ".", "It", "may", "return", "ErrLockNotObtained", "if", "a", "lock", "was", "not", "successfully", "acquired", "." ]
a411a6dd9badb340368e4e97ad9de11ea0e63811
https://github.com/bsm/redis-lock/blob/a411a6dd9badb340368e4e97ad9de11ea0e63811/lock.go#L49-L67
20,770
bsm/redis-lock
lock.go
New
func New(client RedisClient, key string, opts *Options) *Locker { var o Options if opts != nil { o = *opts } o.normalize() return &Locker{client: client, key: key, opts: o} }
go
func New(client RedisClient, key string, opts *Options) *Locker { var o Options if opts != nil { o = *opts } o.normalize() return &Locker{client: client, key: key, opts: o} }
[ "func", "New", "(", "client", "RedisClient", ",", "key", "string", ",", "opts", "*", "Options", ")", "*", "Locker", "{", "var", "o", "Options", "\n", "if", "opts", "!=", "nil", "{", "o", "=", "*", "opts", "\n", "}", "\n", "o", ".", "normalize", "(", ")", "\n\n", "return", "&", "Locker", "{", "client", ":", "client", ",", "key", ":", "key", ",", "opts", ":", "o", "}", "\n", "}" ]
// New creates a new distributed locker on a given key.
[ "New", "creates", "a", "new", "distributed", "locker", "on", "a", "given", "key", "." ]
a411a6dd9badb340368e4e97ad9de11ea0e63811
https://github.com/bsm/redis-lock/blob/a411a6dd9badb340368e4e97ad9de11ea0e63811/lock.go#L82-L90
20,771
bsm/redis-lock
lock.go
IsLocked
func (l *Locker) IsLocked() bool { l.mutex.Lock() locked := l.token != "" l.mutex.Unlock() return locked }
go
func (l *Locker) IsLocked() bool { l.mutex.Lock() locked := l.token != "" l.mutex.Unlock() return locked }
[ "func", "(", "l", "*", "Locker", ")", "IsLocked", "(", ")", "bool", "{", "l", ".", "mutex", ".", "Lock", "(", ")", "\n", "locked", ":=", "l", ".", "token", "!=", "\"", "\"", "\n", "l", ".", "mutex", ".", "Unlock", "(", ")", "\n\n", "return", "locked", "\n", "}" ]
// IsLocked returns true if a lock is still being held.
[ "IsLocked", "returns", "true", "if", "a", "lock", "is", "still", "being", "held", "." ]
a411a6dd9badb340368e4e97ad9de11ea0e63811
https://github.com/bsm/redis-lock/blob/a411a6dd9badb340368e4e97ad9de11ea0e63811/lock.go#L93-L99
20,772
bsm/redis-lock
lock.go
LockWithContext
func (l *Locker) LockWithContext(ctx context.Context) (bool, error) { l.mutex.Lock() defer l.mutex.Unlock() if l.token != "" { return l.refresh(ctx) } return l.create(ctx) }
go
func (l *Locker) LockWithContext(ctx context.Context) (bool, error) { l.mutex.Lock() defer l.mutex.Unlock() if l.token != "" { return l.refresh(ctx) } return l.create(ctx) }
[ "func", "(", "l", "*", "Locker", ")", "LockWithContext", "(", "ctx", "context", ".", "Context", ")", "(", "bool", ",", "error", ")", "{", "l", ".", "mutex", ".", "Lock", "(", ")", "\n", "defer", "l", ".", "mutex", ".", "Unlock", "(", ")", "\n\n", "if", "l", ".", "token", "!=", "\"", "\"", "{", "return", "l", ".", "refresh", "(", "ctx", ")", "\n", "}", "\n", "return", "l", ".", "create", "(", "ctx", ")", "\n", "}" ]
// LockWithContext is like Lock but allows to pass an additional context which allows cancelling // lock attempts prematurely.
[ "LockWithContext", "is", "like", "Lock", "but", "allows", "to", "pass", "an", "additional", "context", "which", "allows", "cancelling", "lock", "attempts", "prematurely", "." ]
a411a6dd9badb340368e4e97ad9de11ea0e63811
https://github.com/bsm/redis-lock/blob/a411a6dd9badb340368e4e97ad9de11ea0e63811/lock.go#L108-L116
20,773
bsm/redis-lock
lock.go
Unlock
func (l *Locker) Unlock() error { l.mutex.Lock() err := l.release() l.mutex.Unlock() return err }
go
func (l *Locker) Unlock() error { l.mutex.Lock() err := l.release() l.mutex.Unlock() return err }
[ "func", "(", "l", "*", "Locker", ")", "Unlock", "(", ")", "error", "{", "l", ".", "mutex", ".", "Lock", "(", ")", "\n", "err", ":=", "l", ".", "release", "(", ")", "\n", "l", ".", "mutex", ".", "Unlock", "(", ")", "\n\n", "return", "err", "\n", "}" ]
// Unlock releases the lock
[ "Unlock", "releases", "the", "lock" ]
a411a6dd9badb340368e4e97ad9de11ea0e63811
https://github.com/bsm/redis-lock/blob/a411a6dd9badb340368e4e97ad9de11ea0e63811/lock.go#L119-L125
20,774
satyrius/gonx
entry.go
Field
func (entry *Entry) Field(name string) (value string, err error) { value, ok := entry.fields[name] if !ok { err = fmt.Errorf("field '%v' does not found in record %+v", name, *entry) } return }
go
func (entry *Entry) Field(name string) (value string, err error) { value, ok := entry.fields[name] if !ok { err = fmt.Errorf("field '%v' does not found in record %+v", name, *entry) } return }
[ "func", "(", "entry", "*", "Entry", ")", "Field", "(", "name", "string", ")", "(", "value", "string", ",", "err", "error", ")", "{", "value", ",", "ok", ":=", "entry", ".", "fields", "[", "name", "]", "\n", "if", "!", "ok", "{", "err", "=", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "name", ",", "*", "entry", ")", "\n", "}", "\n", "return", "\n", "}" ]
// Field returns an entry field value by name or empty string and error if it // does not exist.
[ "Field", "returns", "an", "entry", "field", "value", "by", "name", "or", "empty", "string", "and", "error", "if", "it", "does", "not", "exist", "." ]
d96bd26e3b2c9d8b84b4694d858bb70b5e904d63
https://github.com/satyrius/gonx/blob/d96bd26e3b2c9d8b84b4694d858bb70b5e904d63/entry.go#L35-L41
20,775
satyrius/gonx
entry.go
FloatField
func (entry *Entry) FloatField(name string) (value float64, err error) { tmp, err := entry.Field(name) if err == nil { value, err = strconv.ParseFloat(tmp, 64) } return }
go
func (entry *Entry) FloatField(name string) (value float64, err error) { tmp, err := entry.Field(name) if err == nil { value, err = strconv.ParseFloat(tmp, 64) } return }
[ "func", "(", "entry", "*", "Entry", ")", "FloatField", "(", "name", "string", ")", "(", "value", "float64", ",", "err", "error", ")", "{", "tmp", ",", "err", ":=", "entry", ".", "Field", "(", "name", ")", "\n", "if", "err", "==", "nil", "{", "value", ",", "err", "=", "strconv", ".", "ParseFloat", "(", "tmp", ",", "64", ")", "\n", "}", "\n", "return", "\n", "}" ]
// FloatField returns an entry field value as float64. Return nil if field does not exist // and conversion error if cannot cast a type.
[ "FloatField", "returns", "an", "entry", "field", "value", "as", "float64", ".", "Return", "nil", "if", "field", "does", "not", "exist", "and", "conversion", "error", "if", "cannot", "cast", "a", "type", "." ]
d96bd26e3b2c9d8b84b4694d858bb70b5e904d63
https://github.com/satyrius/gonx/blob/d96bd26e3b2c9d8b84b4694d858bb70b5e904d63/entry.go#L45-L51
20,776
satyrius/gonx
entry.go
SetField
func (entry *Entry) SetField(name string, value string) { entry.fields[name] = value }
go
func (entry *Entry) SetField(name string, value string) { entry.fields[name] = value }
[ "func", "(", "entry", "*", "Entry", ")", "SetField", "(", "name", "string", ",", "value", "string", ")", "{", "entry", ".", "fields", "[", "name", "]", "=", "value", "\n", "}" ]
// SetField sets the value of a field
[ "SetField", "sets", "the", "value", "of", "a", "field" ]
d96bd26e3b2c9d8b84b4694d858bb70b5e904d63
https://github.com/satyrius/gonx/blob/d96bd26e3b2c9d8b84b4694d858bb70b5e904d63/entry.go#L54-L56
20,777
satyrius/gonx
entry.go
SetFloatField
func (entry *Entry) SetFloatField(name string, value float64) { entry.SetField(name, strconv.FormatFloat(value, 'f', 2, 64)) }
go
func (entry *Entry) SetFloatField(name string, value float64) { entry.SetField(name, strconv.FormatFloat(value, 'f', 2, 64)) }
[ "func", "(", "entry", "*", "Entry", ")", "SetFloatField", "(", "name", "string", ",", "value", "float64", ")", "{", "entry", ".", "SetField", "(", "name", ",", "strconv", ".", "FormatFloat", "(", "value", ",", "'f'", ",", "2", ",", "64", ")", ")", "\n", "}" ]
// SetFloatField is a Float field value setter. It accepts float64, but still store it as a // string in the same fields map. The precision is 2, its enough for log // parsing task
[ "SetFloatField", "is", "a", "Float", "field", "value", "setter", ".", "It", "accepts", "float64", "but", "still", "store", "it", "as", "a", "string", "in", "the", "same", "fields", "map", ".", "The", "precision", "is", "2", "its", "enough", "for", "log", "parsing", "task" ]
d96bd26e3b2c9d8b84b4694d858bb70b5e904d63
https://github.com/satyrius/gonx/blob/d96bd26e3b2c9d8b84b4694d858bb70b5e904d63/entry.go#L61-L63
20,778
satyrius/gonx
entry.go
SetUintField
func (entry *Entry) SetUintField(name string, value uint64) { entry.SetField(name, strconv.FormatUint(uint64(value), 10)) }
go
func (entry *Entry) SetUintField(name string, value uint64) { entry.SetField(name, strconv.FormatUint(uint64(value), 10)) }
[ "func", "(", "entry", "*", "Entry", ")", "SetUintField", "(", "name", "string", ",", "value", "uint64", ")", "{", "entry", ".", "SetField", "(", "name", ",", "strconv", ".", "FormatUint", "(", "uint64", "(", "value", ")", ",", "10", ")", ")", "\n", "}" ]
// SetUintField is a Integer field value setter. It accepts float64, but still store it as a // string in the same fields map.
[ "SetUintField", "is", "a", "Integer", "field", "value", "setter", ".", "It", "accepts", "float64", "but", "still", "store", "it", "as", "a", "string", "in", "the", "same", "fields", "map", "." ]
d96bd26e3b2c9d8b84b4694d858bb70b5e904d63
https://github.com/satyrius/gonx/blob/d96bd26e3b2c9d8b84b4694d858bb70b5e904d63/entry.go#L67-L69
20,779
satyrius/gonx
entry.go
Merge
func (entry *Entry) Merge(merge *Entry) { for name, value := range merge.fields { entry.SetField(name, value) } }
go
func (entry *Entry) Merge(merge *Entry) { for name, value := range merge.fields { entry.SetField(name, value) } }
[ "func", "(", "entry", "*", "Entry", ")", "Merge", "(", "merge", "*", "Entry", ")", "{", "for", "name", ",", "value", ":=", "range", "merge", ".", "fields", "{", "entry", ".", "SetField", "(", "name", ",", "value", ")", "\n", "}", "\n", "}" ]
// Merge two entries by updating values for master entry with given.
[ "Merge", "two", "entries", "by", "updating", "values", "for", "master", "entry", "with", "given", "." ]
d96bd26e3b2c9d8b84b4694d858bb70b5e904d63
https://github.com/satyrius/gonx/blob/d96bd26e3b2c9d8b84b4694d858bb70b5e904d63/entry.go#L72-L76
20,780
satyrius/gonx
entry.go
FieldsHash
func (entry *Entry) FieldsHash(fields []string) string { var key []string for _, name := range fields { value, err := entry.Field(name) if err != nil { value = "NULL" } key = append(key, fmt.Sprintf("'%v'=%v", name, value)) } return strings.Join(key, ";") }
go
func (entry *Entry) FieldsHash(fields []string) string { var key []string for _, name := range fields { value, err := entry.Field(name) if err != nil { value = "NULL" } key = append(key, fmt.Sprintf("'%v'=%v", name, value)) } return strings.Join(key, ";") }
[ "func", "(", "entry", "*", "Entry", ")", "FieldsHash", "(", "fields", "[", "]", "string", ")", "string", "{", "var", "key", "[", "]", "string", "\n", "for", "_", ",", "name", ":=", "range", "fields", "{", "value", ",", "err", ":=", "entry", ".", "Field", "(", "name", ")", "\n", "if", "err", "!=", "nil", "{", "value", "=", "\"", "\"", "\n", "}", "\n", "key", "=", "append", "(", "key", ",", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "name", ",", "value", ")", ")", "\n", "}", "\n", "return", "strings", ".", "Join", "(", "key", ",", "\"", "\"", ")", "\n", "}" ]
// FieldsHash returns a hash of all fields
[ "FieldsHash", "returns", "a", "hash", "of", "all", "fields" ]
d96bd26e3b2c9d8b84b4694d858bb70b5e904d63
https://github.com/satyrius/gonx/blob/d96bd26e3b2c9d8b84b4694d858bb70b5e904d63/entry.go#L79-L89
20,781
satyrius/gonx
entry.go
Partial
func (entry *Entry) Partial(fields []string) *Entry { partial := NewEmptyEntry() for _, name := range fields { value, _ := entry.Field(name) partial.SetField(name, value) } return partial }
go
func (entry *Entry) Partial(fields []string) *Entry { partial := NewEmptyEntry() for _, name := range fields { value, _ := entry.Field(name) partial.SetField(name, value) } return partial }
[ "func", "(", "entry", "*", "Entry", ")", "Partial", "(", "fields", "[", "]", "string", ")", "*", "Entry", "{", "partial", ":=", "NewEmptyEntry", "(", ")", "\n", "for", "_", ",", "name", ":=", "range", "fields", "{", "value", ",", "_", ":=", "entry", ".", "Field", "(", "name", ")", "\n", "partial", ".", "SetField", "(", "name", ",", "value", ")", "\n", "}", "\n", "return", "partial", "\n", "}" ]
// Partial returns a partial field entry with the specified fields
[ "Partial", "returns", "a", "partial", "field", "entry", "with", "the", "specified", "fields" ]
d96bd26e3b2c9d8b84b4694d858bb70b5e904d63
https://github.com/satyrius/gonx/blob/d96bd26e3b2c9d8b84b4694d858bb70b5e904d63/entry.go#L92-L99
20,782
satyrius/gonx
reader.go
NewReader
func NewReader(logFile io.Reader, format string) *Reader { return NewParserReader(logFile, NewParser(format)) }
go
func NewReader(logFile io.Reader, format string) *Reader { return NewParserReader(logFile, NewParser(format)) }
[ "func", "NewReader", "(", "logFile", "io", ".", "Reader", ",", "format", "string", ")", "*", "Reader", "{", "return", "NewParserReader", "(", "logFile", ",", "NewParser", "(", "format", ")", ")", "\n", "}" ]
// NewReader creates a reader for a custom log format.
[ "NewReader", "creates", "a", "reader", "for", "a", "custom", "log", "format", "." ]
d96bd26e3b2c9d8b84b4694d858bb70b5e904d63
https://github.com/satyrius/gonx/blob/d96bd26e3b2c9d8b84b4694d858bb70b5e904d63/reader.go#L15-L17
20,783
satyrius/gonx
reader.go
NewParserReader
func NewParserReader(logFile io.Reader, parser StringParser) *Reader { return &Reader{ file: logFile, parser: parser, } }
go
func NewParserReader(logFile io.Reader, parser StringParser) *Reader { return &Reader{ file: logFile, parser: parser, } }
[ "func", "NewParserReader", "(", "logFile", "io", ".", "Reader", ",", "parser", "StringParser", ")", "*", "Reader", "{", "return", "&", "Reader", "{", "file", ":", "logFile", ",", "parser", ":", "parser", ",", "}", "\n", "}" ]
// NewParserReader creates a reader with the given parser
[ "NewParserReader", "creates", "a", "reader", "with", "the", "given", "parser" ]
d96bd26e3b2c9d8b84b4694d858bb70b5e904d63
https://github.com/satyrius/gonx/blob/d96bd26e3b2c9d8b84b4694d858bb70b5e904d63/reader.go#L20-L25
20,784
satyrius/gonx
reader.go
NewNginxReader
func NewNginxReader(logFile io.Reader, nginxConf io.Reader, formatName string) (reader *Reader, err error) { parser, err := NewNginxParser(nginxConf, formatName) if err != nil { return nil, err } reader = &Reader{ file: logFile, parser: parser, } return }
go
func NewNginxReader(logFile io.Reader, nginxConf io.Reader, formatName string) (reader *Reader, err error) { parser, err := NewNginxParser(nginxConf, formatName) if err != nil { return nil, err } reader = &Reader{ file: logFile, parser: parser, } return }
[ "func", "NewNginxReader", "(", "logFile", "io", ".", "Reader", ",", "nginxConf", "io", ".", "Reader", ",", "formatName", "string", ")", "(", "reader", "*", "Reader", ",", "err", "error", ")", "{", "parser", ",", "err", ":=", "NewNginxParser", "(", "nginxConf", ",", "formatName", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "reader", "=", "&", "Reader", "{", "file", ":", "logFile", ",", "parser", ":", "parser", ",", "}", "\n", "return", "\n", "}" ]
// NewNginxReader creates a reader for the nginx log format. Nginx config parser will be used // to get particular format from the conf file.
[ "NewNginxReader", "creates", "a", "reader", "for", "the", "nginx", "log", "format", ".", "Nginx", "config", "parser", "will", "be", "used", "to", "get", "particular", "format", "from", "the", "conf", "file", "." ]
d96bd26e3b2c9d8b84b4694d858bb70b5e904d63
https://github.com/satyrius/gonx/blob/d96bd26e3b2c9d8b84b4694d858bb70b5e904d63/reader.go#L29-L39
20,785
satyrius/gonx
reader.go
Read
func (r *Reader) Read() (entry *Entry, err error) { if r.entries == nil { r.entries = MapReduce(r.file, r.parser, new(ReadAll)) } entry, ok := <-r.entries if !ok { err = io.EOF } return }
go
func (r *Reader) Read() (entry *Entry, err error) { if r.entries == nil { r.entries = MapReduce(r.file, r.parser, new(ReadAll)) } entry, ok := <-r.entries if !ok { err = io.EOF } return }
[ "func", "(", "r", "*", "Reader", ")", "Read", "(", ")", "(", "entry", "*", "Entry", ",", "err", "error", ")", "{", "if", "r", ".", "entries", "==", "nil", "{", "r", ".", "entries", "=", "MapReduce", "(", "r", ".", "file", ",", "r", ".", "parser", ",", "new", "(", "ReadAll", ")", ")", "\n", "}", "\n", "entry", ",", "ok", ":=", "<-", "r", ".", "entries", "\n", "if", "!", "ok", "{", "err", "=", "io", ".", "EOF", "\n", "}", "\n", "return", "\n", "}" ]
// Read next parsed Entry from the log file. Return EOF if there are no Entries to read.
[ "Read", "next", "parsed", "Entry", "from", "the", "log", "file", ".", "Return", "EOF", "if", "there", "are", "no", "Entries", "to", "read", "." ]
d96bd26e3b2c9d8b84b4694d858bb70b5e904d63
https://github.com/satyrius/gonx/blob/d96bd26e3b2c9d8b84b4694d858bb70b5e904d63/reader.go#L42-L51
20,786
satyrius/gonx
parser.go
NewParser
func NewParser(format string) *Parser { // First split up multiple concatenated fields with placeholder placeholder := " _PLACEHOLDER___ " preparedFormat := format concatenatedRe := regexp.MustCompile(`[A-Za-z0-9_]\$[A-Za-z0-9_]`) for concatenatedRe.MatchString(preparedFormat) { preparedFormat = regexp.MustCompile(`([A-Za-z0-9_])\$([A-Za-z0-9_]+)(\\?([^$\\A-Za-z0-9_]))`).ReplaceAllString( preparedFormat, fmt.Sprintf("${1}${3}%s$$${2}${3}", placeholder), ) } // Second replace each fileds to regexp grouping quotedFormat := regexp.QuoteMeta(preparedFormat + " ") re := regexp.MustCompile(`\\\$([A-Za-z0-9_]+)(?:\\\$[A-Za-z0-9_])*(\\?([^$\\A-Za-z0-9_]))`).ReplaceAllString( quotedFormat, "(?P<$1>[^$3]*)$2") // Finally remove placeholder re = regexp.MustCompile(fmt.Sprintf(".%s", placeholder)).ReplaceAllString(re, "") return &Parser{format, regexp.MustCompile(fmt.Sprintf("^%v", strings.Trim(re, " ")))} }
go
func NewParser(format string) *Parser { // First split up multiple concatenated fields with placeholder placeholder := " _PLACEHOLDER___ " preparedFormat := format concatenatedRe := regexp.MustCompile(`[A-Za-z0-9_]\$[A-Za-z0-9_]`) for concatenatedRe.MatchString(preparedFormat) { preparedFormat = regexp.MustCompile(`([A-Za-z0-9_])\$([A-Za-z0-9_]+)(\\?([^$\\A-Za-z0-9_]))`).ReplaceAllString( preparedFormat, fmt.Sprintf("${1}${3}%s$$${2}${3}", placeholder), ) } // Second replace each fileds to regexp grouping quotedFormat := regexp.QuoteMeta(preparedFormat + " ") re := regexp.MustCompile(`\\\$([A-Za-z0-9_]+)(?:\\\$[A-Za-z0-9_])*(\\?([^$\\A-Za-z0-9_]))`).ReplaceAllString( quotedFormat, "(?P<$1>[^$3]*)$2") // Finally remove placeholder re = regexp.MustCompile(fmt.Sprintf(".%s", placeholder)).ReplaceAllString(re, "") return &Parser{format, regexp.MustCompile(fmt.Sprintf("^%v", strings.Trim(re, " ")))} }
[ "func", "NewParser", "(", "format", "string", ")", "*", "Parser", "{", "// First split up multiple concatenated fields with placeholder", "placeholder", ":=", "\"", "\"", "\n", "preparedFormat", ":=", "format", "\n", "concatenatedRe", ":=", "regexp", ".", "MustCompile", "(", "`[A-Za-z0-9_]\\$[A-Za-z0-9_]`", ")", "\n", "for", "concatenatedRe", ".", "MatchString", "(", "preparedFormat", ")", "{", "preparedFormat", "=", "regexp", ".", "MustCompile", "(", "`([A-Za-z0-9_])\\$([A-Za-z0-9_]+)(\\\\?([^$\\\\A-Za-z0-9_]))`", ")", ".", "ReplaceAllString", "(", "preparedFormat", ",", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "placeholder", ")", ",", ")", "\n", "}", "\n\n", "// Second replace each fileds to regexp grouping", "quotedFormat", ":=", "regexp", ".", "QuoteMeta", "(", "preparedFormat", "+", "\"", "\"", ")", "\n", "re", ":=", "regexp", ".", "MustCompile", "(", "`\\\\\\$([A-Za-z0-9_]+)(?:\\\\\\$[A-Za-z0-9_])*(\\\\?([^$\\\\A-Za-z0-9_]))`", ")", ".", "ReplaceAllString", "(", "quotedFormat", ",", "\"", "\"", ")", "\n\n", "// Finally remove placeholder", "re", "=", "regexp", ".", "MustCompile", "(", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "placeholder", ")", ")", ".", "ReplaceAllString", "(", "re", ",", "\"", "\"", ")", "\n", "return", "&", "Parser", "{", "format", ",", "regexp", ".", "MustCompile", "(", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "strings", ".", "Trim", "(", "re", ",", "\"", "\"", ")", ")", ")", "}", "\n", "}" ]
// NewParser returns a new Parser, use given log format to create its internal // strings parsing regexp.
[ "NewParser", "returns", "a", "new", "Parser", "use", "given", "log", "format", "to", "create", "its", "internal", "strings", "parsing", "regexp", "." ]
d96bd26e3b2c9d8b84b4694d858bb70b5e904d63
https://github.com/satyrius/gonx/blob/d96bd26e3b2c9d8b84b4694d858bb70b5e904d63/parser.go#L24-L43
20,787
satyrius/gonx
parser.go
ParseString
func (parser *Parser) ParseString(line string) (entry *Entry, err error) { re := parser.regexp fields := re.FindStringSubmatch(line) if fields == nil { err = fmt.Errorf("access log line '%v' does not match given format '%v'", line, re) return } // Iterate over subexp foung and fill the map record entry = NewEmptyEntry() for i, name := range re.SubexpNames() { if i == 0 { continue } entry.SetField(name, fields[i]) } return }
go
func (parser *Parser) ParseString(line string) (entry *Entry, err error) { re := parser.regexp fields := re.FindStringSubmatch(line) if fields == nil { err = fmt.Errorf("access log line '%v' does not match given format '%v'", line, re) return } // Iterate over subexp foung and fill the map record entry = NewEmptyEntry() for i, name := range re.SubexpNames() { if i == 0 { continue } entry.SetField(name, fields[i]) } return }
[ "func", "(", "parser", "*", "Parser", ")", "ParseString", "(", "line", "string", ")", "(", "entry", "*", "Entry", ",", "err", "error", ")", "{", "re", ":=", "parser", ".", "regexp", "\n", "fields", ":=", "re", ".", "FindStringSubmatch", "(", "line", ")", "\n", "if", "fields", "==", "nil", "{", "err", "=", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "line", ",", "re", ")", "\n", "return", "\n", "}", "\n\n", "// Iterate over subexp foung and fill the map record", "entry", "=", "NewEmptyEntry", "(", ")", "\n", "for", "i", ",", "name", ":=", "range", "re", ".", "SubexpNames", "(", ")", "{", "if", "i", "==", "0", "{", "continue", "\n", "}", "\n", "entry", ".", "SetField", "(", "name", ",", "fields", "[", "i", "]", ")", "\n", "}", "\n", "return", "\n", "}" ]
// ParseString parses a log file line using internal format regexp. If a line // does not match the given format an error will be returned.
[ "ParseString", "parses", "a", "log", "file", "line", "using", "internal", "format", "regexp", ".", "If", "a", "line", "does", "not", "match", "the", "given", "format", "an", "error", "will", "be", "returned", "." ]
d96bd26e3b2c9d8b84b4694d858bb70b5e904d63
https://github.com/satyrius/gonx/blob/d96bd26e3b2c9d8b84b4694d858bb70b5e904d63/parser.go#L47-L64
20,788
satyrius/gonx
parser.go
NewNginxParser
func NewNginxParser(conf io.Reader, name string) (parser *Parser, err error) { scanner := bufio.NewScanner(conf) re := regexp.MustCompile(fmt.Sprintf(`^\s*log_format\s+%v\s+(.+)\s*$`, name)) found := false var format string for scanner.Scan() { var line string if !found { // Find a log_format definition line = scanner.Text() formatDef := re.FindStringSubmatch(line) if formatDef == nil { continue } found = true line = formatDef[1] } else { line = scanner.Text() } // Look for a definition end re = regexp.MustCompile(`^\s*(.*?)\s*(;|$)`) lineSplit := re.FindStringSubmatch(line) if l := len(lineSplit[1]); l > 2 { format += lineSplit[1][1 : l-1] } if lineSplit[2] == ";" { break } } if !found { err = fmt.Errorf("`log_format %v` not found in given config", name) } else { err = scanner.Err() } parser = NewParser(format) return }
go
func NewNginxParser(conf io.Reader, name string) (parser *Parser, err error) { scanner := bufio.NewScanner(conf) re := regexp.MustCompile(fmt.Sprintf(`^\s*log_format\s+%v\s+(.+)\s*$`, name)) found := false var format string for scanner.Scan() { var line string if !found { // Find a log_format definition line = scanner.Text() formatDef := re.FindStringSubmatch(line) if formatDef == nil { continue } found = true line = formatDef[1] } else { line = scanner.Text() } // Look for a definition end re = regexp.MustCompile(`^\s*(.*?)\s*(;|$)`) lineSplit := re.FindStringSubmatch(line) if l := len(lineSplit[1]); l > 2 { format += lineSplit[1][1 : l-1] } if lineSplit[2] == ";" { break } } if !found { err = fmt.Errorf("`log_format %v` not found in given config", name) } else { err = scanner.Err() } parser = NewParser(format) return }
[ "func", "NewNginxParser", "(", "conf", "io", ".", "Reader", ",", "name", "string", ")", "(", "parser", "*", "Parser", ",", "err", "error", ")", "{", "scanner", ":=", "bufio", ".", "NewScanner", "(", "conf", ")", "\n", "re", ":=", "regexp", ".", "MustCompile", "(", "fmt", ".", "Sprintf", "(", "`^\\s*log_format\\s+%v\\s+(.+)\\s*$`", ",", "name", ")", ")", "\n", "found", ":=", "false", "\n", "var", "format", "string", "\n", "for", "scanner", ".", "Scan", "(", ")", "{", "var", "line", "string", "\n", "if", "!", "found", "{", "// Find a log_format definition", "line", "=", "scanner", ".", "Text", "(", ")", "\n", "formatDef", ":=", "re", ".", "FindStringSubmatch", "(", "line", ")", "\n", "if", "formatDef", "==", "nil", "{", "continue", "\n", "}", "\n", "found", "=", "true", "\n", "line", "=", "formatDef", "[", "1", "]", "\n", "}", "else", "{", "line", "=", "scanner", ".", "Text", "(", ")", "\n", "}", "\n", "// Look for a definition end", "re", "=", "regexp", ".", "MustCompile", "(", "`^\\s*(.*?)\\s*(;|$)`", ")", "\n", "lineSplit", ":=", "re", ".", "FindStringSubmatch", "(", "line", ")", "\n", "if", "l", ":=", "len", "(", "lineSplit", "[", "1", "]", ")", ";", "l", ">", "2", "{", "format", "+=", "lineSplit", "[", "1", "]", "[", "1", ":", "l", "-", "1", "]", "\n", "}", "\n", "if", "lineSplit", "[", "2", "]", "==", "\"", "\"", "{", "break", "\n", "}", "\n", "}", "\n", "if", "!", "found", "{", "err", "=", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "name", ")", "\n", "}", "else", "{", "err", "=", "scanner", ".", "Err", "(", ")", "\n", "}", "\n", "parser", "=", "NewParser", "(", "format", ")", "\n", "return", "\n", "}" ]
// NewNginxParser parses the nginx conf file to find log_format with the given // name and returns a parser for this format. It returns an error if cannot find // the given log format.
[ "NewNginxParser", "parses", "the", "nginx", "conf", "file", "to", "find", "log_format", "with", "the", "given", "name", "and", "returns", "a", "parser", "for", "this", "format", ".", "It", "returns", "an", "error", "if", "cannot", "find", "the", "given", "log", "format", "." ]
d96bd26e3b2c9d8b84b4694d858bb70b5e904d63
https://github.com/satyrius/gonx/blob/d96bd26e3b2c9d8b84b4694d858bb70b5e904d63/parser.go#L69-L105
20,789
satyrius/gonx
mapreduce.go
MapReduce
func MapReduce(file io.Reader, parser StringParser, reducer Reducer) chan *Entry { // Input file lines. This channel is unbuffered to publish // next line to handle only when previous is taken by mapper. var lines = make(chan string) // Host thread to spawn new mappers var entries = make(chan *Entry, 10) go func(topLoad int) { // Create semafore channel with capacity equal to the output channel // capacity. Use it to control mapper goroutines spawn. var sem = make(chan bool, topLoad) for i := 0; i < topLoad; i++ { // Ready to go! sem <- true } var wg sync.WaitGroup for { // Wait until semaphore becomes available and run a mapper if !<-sem { // Stop the host loop if false received from semaphore break } wg.Add(1) go func() { defer wg.Done() // Take next file line to map. Check is channel closed. line, ok := <-lines // Return immediately if lines channel is closed if !ok { // Send false to semaphore channel to indicate that job's done sem <- false return } entry, err := parser.ParseString(line) if err == nil { // Write result Entry to the output channel. This will // block goroutine runtime until channel is free to // accept new item. entries <- entry } else { handleError(err) } // Increment semaphore to allow new mapper workers to spawn sem <- true }() } // Wait for all mappers to complete, then send a quit signal wg.Wait() close(entries) }(cap(entries)) // Run reducer routine. var output = make(chan *Entry) go reducer.Reduce(entries, output) go func() { reader := bufio.NewReader(file) line, err := readLine(reader) for err == nil { // Read next line from the file and feed mapper routines. lines <- line line, err = readLine(reader) } close(lines) if err != nil && err != io.EOF { handleError(err) } }() return output }
go
func MapReduce(file io.Reader, parser StringParser, reducer Reducer) chan *Entry { // Input file lines. This channel is unbuffered to publish // next line to handle only when previous is taken by mapper. var lines = make(chan string) // Host thread to spawn new mappers var entries = make(chan *Entry, 10) go func(topLoad int) { // Create semafore channel with capacity equal to the output channel // capacity. Use it to control mapper goroutines spawn. var sem = make(chan bool, topLoad) for i := 0; i < topLoad; i++ { // Ready to go! sem <- true } var wg sync.WaitGroup for { // Wait until semaphore becomes available and run a mapper if !<-sem { // Stop the host loop if false received from semaphore break } wg.Add(1) go func() { defer wg.Done() // Take next file line to map. Check is channel closed. line, ok := <-lines // Return immediately if lines channel is closed if !ok { // Send false to semaphore channel to indicate that job's done sem <- false return } entry, err := parser.ParseString(line) if err == nil { // Write result Entry to the output channel. This will // block goroutine runtime until channel is free to // accept new item. entries <- entry } else { handleError(err) } // Increment semaphore to allow new mapper workers to spawn sem <- true }() } // Wait for all mappers to complete, then send a quit signal wg.Wait() close(entries) }(cap(entries)) // Run reducer routine. var output = make(chan *Entry) go reducer.Reduce(entries, output) go func() { reader := bufio.NewReader(file) line, err := readLine(reader) for err == nil { // Read next line from the file and feed mapper routines. lines <- line line, err = readLine(reader) } close(lines) if err != nil && err != io.EOF { handleError(err) } }() return output }
[ "func", "MapReduce", "(", "file", "io", ".", "Reader", ",", "parser", "StringParser", ",", "reducer", "Reducer", ")", "chan", "*", "Entry", "{", "// Input file lines. This channel is unbuffered to publish", "// next line to handle only when previous is taken by mapper.", "var", "lines", "=", "make", "(", "chan", "string", ")", "\n\n", "// Host thread to spawn new mappers", "var", "entries", "=", "make", "(", "chan", "*", "Entry", ",", "10", ")", "\n", "go", "func", "(", "topLoad", "int", ")", "{", "// Create semafore channel with capacity equal to the output channel", "// capacity. Use it to control mapper goroutines spawn.", "var", "sem", "=", "make", "(", "chan", "bool", ",", "topLoad", ")", "\n", "for", "i", ":=", "0", ";", "i", "<", "topLoad", ";", "i", "++", "{", "// Ready to go!", "sem", "<-", "true", "\n", "}", "\n\n", "var", "wg", "sync", ".", "WaitGroup", "\n", "for", "{", "// Wait until semaphore becomes available and run a mapper", "if", "!", "<-", "sem", "{", "// Stop the host loop if false received from semaphore", "break", "\n", "}", "\n", "wg", ".", "Add", "(", "1", ")", "\n", "go", "func", "(", ")", "{", "defer", "wg", ".", "Done", "(", ")", "\n", "// Take next file line to map. Check is channel closed.", "line", ",", "ok", ":=", "<-", "lines", "\n", "// Return immediately if lines channel is closed", "if", "!", "ok", "{", "// Send false to semaphore channel to indicate that job's done", "sem", "<-", "false", "\n", "return", "\n", "}", "\n", "entry", ",", "err", ":=", "parser", ".", "ParseString", "(", "line", ")", "\n", "if", "err", "==", "nil", "{", "// Write result Entry to the output channel. This will", "// block goroutine runtime until channel is free to", "// accept new item.", "entries", "<-", "entry", "\n", "}", "else", "{", "handleError", "(", "err", ")", "\n", "}", "\n", "// Increment semaphore to allow new mapper workers to spawn", "sem", "<-", "true", "\n", "}", "(", ")", "\n", "}", "\n", "// Wait for all mappers to complete, then send a quit signal", "wg", ".", "Wait", "(", ")", "\n", "close", "(", "entries", ")", "\n", "}", "(", "cap", "(", "entries", ")", ")", "\n\n", "// Run reducer routine.", "var", "output", "=", "make", "(", "chan", "*", "Entry", ")", "\n", "go", "reducer", ".", "Reduce", "(", "entries", ",", "output", ")", "\n\n", "go", "func", "(", ")", "{", "reader", ":=", "bufio", ".", "NewReader", "(", "file", ")", "\n", "line", ",", "err", ":=", "readLine", "(", "reader", ")", "\n", "for", "err", "==", "nil", "{", "// Read next line from the file and feed mapper routines.", "lines", "<-", "line", "\n", "line", ",", "err", "=", "readLine", "(", "reader", ")", "\n", "}", "\n", "close", "(", "lines", ")", "\n\n", "if", "err", "!=", "nil", "&&", "err", "!=", "io", ".", "EOF", "{", "handleError", "(", "err", ")", "\n", "}", "\n", "}", "(", ")", "\n\n", "return", "output", "\n", "}" ]
// MapReduce iterates over given file and map each it's line into Entry record using // parser and apply reducer to the Entries channel. Execution terminates // when result will be readed from reducer's output channel, but the mapper // works and fills input Entries channel until all lines will be read from // the fiven file.
[ "MapReduce", "iterates", "over", "given", "file", "and", "map", "each", "it", "s", "line", "into", "Entry", "record", "using", "parser", "and", "apply", "reducer", "to", "the", "Entries", "channel", ".", "Execution", "terminates", "when", "result", "will", "be", "readed", "from", "reducer", "s", "output", "channel", "but", "the", "mapper", "works", "and", "fills", "input", "Entries", "channel", "until", "all", "lines", "will", "be", "read", "from", "the", "fiven", "file", "." ]
d96bd26e3b2c9d8b84b4694d858bb70b5e904d63
https://github.com/satyrius/gonx/blob/d96bd26e3b2c9d8b84b4694d858bb70b5e904d63/mapreduce.go#L19-L91
20,790
satyrius/gonx
filter.go
Filter
func (i *Datetime) Filter(entry *Entry) (validEntry *Entry) { val, err := entry.Field(i.Field) if err != nil { // TODO handle error return } t, err := time.Parse(i.Format, val) if err != nil { // TODO handle error return } if i.withinBounds(t) { validEntry = entry } return }
go
func (i *Datetime) Filter(entry *Entry) (validEntry *Entry) { val, err := entry.Field(i.Field) if err != nil { // TODO handle error return } t, err := time.Parse(i.Format, val) if err != nil { // TODO handle error return } if i.withinBounds(t) { validEntry = entry } return }
[ "func", "(", "i", "*", "Datetime", ")", "Filter", "(", "entry", "*", "Entry", ")", "(", "validEntry", "*", "Entry", ")", "{", "val", ",", "err", ":=", "entry", ".", "Field", "(", "i", ".", "Field", ")", "\n", "if", "err", "!=", "nil", "{", "// TODO handle error", "return", "\n", "}", "\n", "t", ",", "err", ":=", "time", ".", "Parse", "(", "i", ".", "Format", ",", "val", ")", "\n", "if", "err", "!=", "nil", "{", "// TODO handle error", "return", "\n", "}", "\n", "if", "i", ".", "withinBounds", "(", "t", ")", "{", "validEntry", "=", "entry", "\n", "}", "\n", "return", "\n", "}" ]
// Filter checks a field value to be in desired datetime range.
[ "Filter", "checks", "a", "field", "value", "to", "be", "in", "desired", "datetime", "range", "." ]
d96bd26e3b2c9d8b84b4694d858bb70b5e904d63
https://github.com/satyrius/gonx/blob/d96bd26e3b2c9d8b84b4694d858bb70b5e904d63/filter.go#L24-L39
20,791
satyrius/gonx
filter.go
Reduce
func (i *Datetime) Reduce(input chan *Entry, output chan *Entry) { for entry := range input { if valid := i.Filter(entry); valid != nil { output <- valid } } close(output) }
go
func (i *Datetime) Reduce(input chan *Entry, output chan *Entry) { for entry := range input { if valid := i.Filter(entry); valid != nil { output <- valid } } close(output) }
[ "func", "(", "i", "*", "Datetime", ")", "Reduce", "(", "input", "chan", "*", "Entry", ",", "output", "chan", "*", "Entry", ")", "{", "for", "entry", ":=", "range", "input", "{", "if", "valid", ":=", "i", ".", "Filter", "(", "entry", ")", ";", "valid", "!=", "nil", "{", "output", "<-", "valid", "\n", "}", "\n", "}", "\n", "close", "(", "output", ")", "\n", "}" ]
// Reduce implements the Reducer interface. Go through input and apply Filter.
[ "Reduce", "implements", "the", "Reducer", "interface", ".", "Go", "through", "input", "and", "apply", "Filter", "." ]
d96bd26e3b2c9d8b84b4694d858bb70b5e904d63
https://github.com/satyrius/gonx/blob/d96bd26e3b2c9d8b84b4694d858bb70b5e904d63/filter.go#L42-L49
20,792
satyrius/gonx
reducer.go
Reduce
func (r *ReadAll) Reduce(input chan *Entry, output chan *Entry) { for entry := range input { output <- entry } close(output) }
go
func (r *ReadAll) Reduce(input chan *Entry, output chan *Entry) { for entry := range input { output <- entry } close(output) }
[ "func", "(", "r", "*", "ReadAll", ")", "Reduce", "(", "input", "chan", "*", "Entry", ",", "output", "chan", "*", "Entry", ")", "{", "for", "entry", ":=", "range", "input", "{", "output", "<-", "entry", "\n", "}", "\n", "close", "(", "output", ")", "\n", "}" ]
// Reduce redirects input Entries channel directly to the output without any // modifications. It is useful when you want jast to read file fast // using asynchronous with mapper routines.
[ "Reduce", "redirects", "input", "Entries", "channel", "directly", "to", "the", "output", "without", "any", "modifications", ".", "It", "is", "useful", "when", "you", "want", "jast", "to", "read", "file", "fast", "using", "asynchronous", "with", "mapper", "routines", "." ]
d96bd26e3b2c9d8b84b4694d858bb70b5e904d63
https://github.com/satyrius/gonx/blob/d96bd26e3b2c9d8b84b4694d858bb70b5e904d63/reducer.go#L22-L27
20,793
satyrius/gonx
reducer.go
Reduce
func (r *Count) Reduce(input chan *Entry, output chan *Entry) { var count uint64 for { _, ok := <-input if !ok { break } count++ } entry := NewEmptyEntry() entry.SetUintField("count", count) output <- entry close(output) }
go
func (r *Count) Reduce(input chan *Entry, output chan *Entry) { var count uint64 for { _, ok := <-input if !ok { break } count++ } entry := NewEmptyEntry() entry.SetUintField("count", count) output <- entry close(output) }
[ "func", "(", "r", "*", "Count", ")", "Reduce", "(", "input", "chan", "*", "Entry", ",", "output", "chan", "*", "Entry", ")", "{", "var", "count", "uint64", "\n", "for", "{", "_", ",", "ok", ":=", "<-", "input", "\n", "if", "!", "ok", "{", "break", "\n", "}", "\n", "count", "++", "\n", "}", "\n", "entry", ":=", "NewEmptyEntry", "(", ")", "\n", "entry", ".", "SetUintField", "(", "\"", "\"", ",", "count", ")", "\n", "output", "<-", "entry", "\n", "close", "(", "output", ")", "\n", "}" ]
// Reduce simply counts entries and write a sum to the output channel
[ "Reduce", "simply", "counts", "entries", "and", "write", "a", "sum", "to", "the", "output", "channel" ]
d96bd26e3b2c9d8b84b4694d858bb70b5e904d63
https://github.com/satyrius/gonx/blob/d96bd26e3b2c9d8b84b4694d858bb70b5e904d63/reducer.go#L34-L47
20,794
satyrius/gonx
reducer.go
Reduce
func (r *Sum) Reduce(input chan *Entry, output chan *Entry) { sum := make(map[string]float64) for entry := range input { for _, name := range r.Fields { val, err := entry.FloatField(name) if err == nil { sum[name] += val } } } entry := NewEmptyEntry() for name, val := range sum { entry.SetFloatField(name, val) } output <- entry close(output) }
go
func (r *Sum) Reduce(input chan *Entry, output chan *Entry) { sum := make(map[string]float64) for entry := range input { for _, name := range r.Fields { val, err := entry.FloatField(name) if err == nil { sum[name] += val } } } entry := NewEmptyEntry() for name, val := range sum { entry.SetFloatField(name, val) } output <- entry close(output) }
[ "func", "(", "r", "*", "Sum", ")", "Reduce", "(", "input", "chan", "*", "Entry", ",", "output", "chan", "*", "Entry", ")", "{", "sum", ":=", "make", "(", "map", "[", "string", "]", "float64", ")", "\n", "for", "entry", ":=", "range", "input", "{", "for", "_", ",", "name", ":=", "range", "r", ".", "Fields", "{", "val", ",", "err", ":=", "entry", ".", "FloatField", "(", "name", ")", "\n", "if", "err", "==", "nil", "{", "sum", "[", "name", "]", "+=", "val", "\n", "}", "\n", "}", "\n", "}", "\n", "entry", ":=", "NewEmptyEntry", "(", ")", "\n", "for", "name", ",", "val", ":=", "range", "sum", "{", "entry", ".", "SetFloatField", "(", "name", ",", "val", ")", "\n", "}", "\n", "output", "<-", "entry", "\n", "close", "(", "output", ")", "\n", "}" ]
// Reduce summarizes given Entry fields and return a map with result for each field.
[ "Reduce", "summarizes", "given", "Entry", "fields", "and", "return", "a", "map", "with", "result", "for", "each", "field", "." ]
d96bd26e3b2c9d8b84b4694d858bb70b5e904d63
https://github.com/satyrius/gonx/blob/d96bd26e3b2c9d8b84b4694d858bb70b5e904d63/reducer.go#L55-L71
20,795
satyrius/gonx
reducer.go
NewChain
func NewChain(reducers ...Reducer) *Chain { chain := new(Chain) for _, r := range reducers { if f, ok := interface{}(r).(Filter); ok { chain.filters = append(chain.filters, f) } else { chain.reducers = append(chain.reducers, r) } } return chain }
go
func NewChain(reducers ...Reducer) *Chain { chain := new(Chain) for _, r := range reducers { if f, ok := interface{}(r).(Filter); ok { chain.filters = append(chain.filters, f) } else { chain.reducers = append(chain.reducers, r) } } return chain }
[ "func", "NewChain", "(", "reducers", "...", "Reducer", ")", "*", "Chain", "{", "chain", ":=", "new", "(", "Chain", ")", "\n", "for", "_", ",", "r", ":=", "range", "reducers", "{", "if", "f", ",", "ok", ":=", "interface", "{", "}", "(", "r", ")", ".", "(", "Filter", ")", ";", "ok", "{", "chain", ".", "filters", "=", "append", "(", "chain", ".", "filters", ",", "f", ")", "\n", "}", "else", "{", "chain", ".", "reducers", "=", "append", "(", "chain", ".", "reducers", ",", "r", ")", "\n", "}", "\n", "}", "\n", "return", "chain", "\n", "}" ]
// NewChain creates a new chain of Reducers
[ "NewChain", "creates", "a", "new", "chain", "of", "Reducers" ]
d96bd26e3b2c9d8b84b4694d858bb70b5e904d63
https://github.com/satyrius/gonx/blob/d96bd26e3b2c9d8b84b4694d858bb70b5e904d63/reducer.go#L107-L117
20,796
satyrius/gonx
reducer.go
Reduce
func (r *Chain) Reduce(input chan *Entry, output chan *Entry) { // Make input and output channel for each reducer subInput := make([]chan *Entry, len(r.reducers)) subOutput := make([]chan *Entry, len(r.reducers)) for i, reducer := range r.reducers { subInput[i] = make(chan *Entry, cap(input)) subOutput[i] = make(chan *Entry, cap(output)) go reducer.Reduce(subInput[i], subOutput[i]) } // Read reducer master input channel for entry := range input { for _, f := range r.filters { entry = f.Filter(entry) if entry == nil { break } } // Publish input entry for each sub-reducers to process if entry != nil { for _, sub := range subInput { sub <- entry } } } for _, ch := range subInput { close(ch) } // Merge all results entry := NewEmptyEntry() for _, result := range subOutput { entry.Merge(<-result) } output <- entry close(output) }
go
func (r *Chain) Reduce(input chan *Entry, output chan *Entry) { // Make input and output channel for each reducer subInput := make([]chan *Entry, len(r.reducers)) subOutput := make([]chan *Entry, len(r.reducers)) for i, reducer := range r.reducers { subInput[i] = make(chan *Entry, cap(input)) subOutput[i] = make(chan *Entry, cap(output)) go reducer.Reduce(subInput[i], subOutput[i]) } // Read reducer master input channel for entry := range input { for _, f := range r.filters { entry = f.Filter(entry) if entry == nil { break } } // Publish input entry for each sub-reducers to process if entry != nil { for _, sub := range subInput { sub <- entry } } } for _, ch := range subInput { close(ch) } // Merge all results entry := NewEmptyEntry() for _, result := range subOutput { entry.Merge(<-result) } output <- entry close(output) }
[ "func", "(", "r", "*", "Chain", ")", "Reduce", "(", "input", "chan", "*", "Entry", ",", "output", "chan", "*", "Entry", ")", "{", "// Make input and output channel for each reducer", "subInput", ":=", "make", "(", "[", "]", "chan", "*", "Entry", ",", "len", "(", "r", ".", "reducers", ")", ")", "\n", "subOutput", ":=", "make", "(", "[", "]", "chan", "*", "Entry", ",", "len", "(", "r", ".", "reducers", ")", ")", "\n", "for", "i", ",", "reducer", ":=", "range", "r", ".", "reducers", "{", "subInput", "[", "i", "]", "=", "make", "(", "chan", "*", "Entry", ",", "cap", "(", "input", ")", ")", "\n", "subOutput", "[", "i", "]", "=", "make", "(", "chan", "*", "Entry", ",", "cap", "(", "output", ")", ")", "\n", "go", "reducer", ".", "Reduce", "(", "subInput", "[", "i", "]", ",", "subOutput", "[", "i", "]", ")", "\n", "}", "\n\n", "// Read reducer master input channel", "for", "entry", ":=", "range", "input", "{", "for", "_", ",", "f", ":=", "range", "r", ".", "filters", "{", "entry", "=", "f", ".", "Filter", "(", "entry", ")", "\n", "if", "entry", "==", "nil", "{", "break", "\n", "}", "\n", "}", "\n", "// Publish input entry for each sub-reducers to process", "if", "entry", "!=", "nil", "{", "for", "_", ",", "sub", ":=", "range", "subInput", "{", "sub", "<-", "entry", "\n", "}", "\n", "}", "\n", "}", "\n", "for", "_", ",", "ch", ":=", "range", "subInput", "{", "close", "(", "ch", ")", "\n", "}", "\n\n", "// Merge all results", "entry", ":=", "NewEmptyEntry", "(", ")", "\n", "for", "_", ",", "result", ":=", "range", "subOutput", "{", "entry", ".", "Merge", "(", "<-", "result", ")", "\n", "}", "\n\n", "output", "<-", "entry", "\n", "close", "(", "output", ")", "\n", "}" ]
// Reduce applies a chain of reducers to the input channel of entries and merge results
[ "Reduce", "applies", "a", "chain", "of", "reducers", "to", "the", "input", "channel", "of", "entries", "and", "merge", "results" ]
d96bd26e3b2c9d8b84b4694d858bb70b5e904d63
https://github.com/satyrius/gonx/blob/d96bd26e3b2c9d8b84b4694d858bb70b5e904d63/reducer.go#L120-L157
20,797
satyrius/gonx
reducer.go
NewGroupBy
func NewGroupBy(fields []string, reducers ...Reducer) *GroupBy { return &GroupBy{ Fields: fields, reducers: reducers, } }
go
func NewGroupBy(fields []string, reducers ...Reducer) *GroupBy { return &GroupBy{ Fields: fields, reducers: reducers, } }
[ "func", "NewGroupBy", "(", "fields", "[", "]", "string", ",", "reducers", "...", "Reducer", ")", "*", "GroupBy", "{", "return", "&", "GroupBy", "{", "Fields", ":", "fields", ",", "reducers", ":", "reducers", ",", "}", "\n", "}" ]
// NewGroupBy creates a new GroupBy Reducer
[ "NewGroupBy", "creates", "a", "new", "GroupBy", "Reducer" ]
d96bd26e3b2c9d8b84b4694d858bb70b5e904d63
https://github.com/satyrius/gonx/blob/d96bd26e3b2c9d8b84b4694d858bb70b5e904d63/reducer.go#L167-L172
20,798
satyrius/gonx
reducer.go
Reduce
func (r *GroupBy) Reduce(input chan *Entry, output chan *Entry) { subInput := make(map[string]chan *Entry) subOutput := make(map[string]chan *Entry) // Read reducer master input channel and create discinct input chanel // for each entry key we group by for entry := range input { key := entry.FieldsHash(r.Fields) if _, ok := subInput[key]; !ok { subInput[key] = make(chan *Entry, cap(input)) subOutput[key] = make(chan *Entry, cap(output)+1) subOutput[key] <- entry.Partial(r.Fields) go NewChain(r.reducers...).Reduce(subInput[key], subOutput[key]) } subInput[key] <- entry } for _, ch := range subInput { close(ch) } for _, ch := range subOutput { entry := <-ch entry.Merge(<-ch) output <- entry } close(output) }
go
func (r *GroupBy) Reduce(input chan *Entry, output chan *Entry) { subInput := make(map[string]chan *Entry) subOutput := make(map[string]chan *Entry) // Read reducer master input channel and create discinct input chanel // for each entry key we group by for entry := range input { key := entry.FieldsHash(r.Fields) if _, ok := subInput[key]; !ok { subInput[key] = make(chan *Entry, cap(input)) subOutput[key] = make(chan *Entry, cap(output)+1) subOutput[key] <- entry.Partial(r.Fields) go NewChain(r.reducers...).Reduce(subInput[key], subOutput[key]) } subInput[key] <- entry } for _, ch := range subInput { close(ch) } for _, ch := range subOutput { entry := <-ch entry.Merge(<-ch) output <- entry } close(output) }
[ "func", "(", "r", "*", "GroupBy", ")", "Reduce", "(", "input", "chan", "*", "Entry", ",", "output", "chan", "*", "Entry", ")", "{", "subInput", ":=", "make", "(", "map", "[", "string", "]", "chan", "*", "Entry", ")", "\n", "subOutput", ":=", "make", "(", "map", "[", "string", "]", "chan", "*", "Entry", ")", "\n\n", "// Read reducer master input channel and create discinct input chanel", "// for each entry key we group by", "for", "entry", ":=", "range", "input", "{", "key", ":=", "entry", ".", "FieldsHash", "(", "r", ".", "Fields", ")", "\n", "if", "_", ",", "ok", ":=", "subInput", "[", "key", "]", ";", "!", "ok", "{", "subInput", "[", "key", "]", "=", "make", "(", "chan", "*", "Entry", ",", "cap", "(", "input", ")", ")", "\n", "subOutput", "[", "key", "]", "=", "make", "(", "chan", "*", "Entry", ",", "cap", "(", "output", ")", "+", "1", ")", "\n", "subOutput", "[", "key", "]", "<-", "entry", ".", "Partial", "(", "r", ".", "Fields", ")", "\n", "go", "NewChain", "(", "r", ".", "reducers", "...", ")", ".", "Reduce", "(", "subInput", "[", "key", "]", ",", "subOutput", "[", "key", "]", ")", "\n", "}", "\n", "subInput", "[", "key", "]", "<-", "entry", "\n", "}", "\n", "for", "_", ",", "ch", ":=", "range", "subInput", "{", "close", "(", "ch", ")", "\n", "}", "\n", "for", "_", ",", "ch", ":=", "range", "subOutput", "{", "entry", ":=", "<-", "ch", "\n", "entry", ".", "Merge", "(", "<-", "ch", ")", "\n", "output", "<-", "entry", "\n", "}", "\n", "close", "(", "output", ")", "\n", "}" ]
// Reduce applies related reducers and group data by Fields.
[ "Reduce", "applies", "related", "reducers", "and", "group", "data", "by", "Fields", "." ]
d96bd26e3b2c9d8b84b4694d858bb70b5e904d63
https://github.com/satyrius/gonx/blob/d96bd26e3b2c9d8b84b4694d858bb70b5e904d63/reducer.go#L175-L200
20,799
go-gl/mathgl
mgl32/vecn.go
destroy
func (vn *VecN) destroy() { if vn == nil || vn.vec == nil { return } if shouldPool { returnToPool(vn.vec) } vn.vec = nil }
go
func (vn *VecN) destroy() { if vn == nil || vn.vec == nil { return } if shouldPool { returnToPool(vn.vec) } vn.vec = nil }
[ "func", "(", "vn", "*", "VecN", ")", "destroy", "(", ")", "{", "if", "vn", "==", "nil", "||", "vn", ".", "vec", "==", "nil", "{", "return", "\n", "}", "\n\n", "if", "shouldPool", "{", "returnToPool", "(", "vn", ".", "vec", ")", "\n", "}", "\n", "vn", ".", "vec", "=", "nil", "\n", "}" ]
// Sends the allocated memory through the callback if it exists
[ "Sends", "the", "allocated", "memory", "through", "the", "callback", "if", "it", "exists" ]
c4601bc793c7a480dab005cf969aab0d7a7fb07d
https://github.com/go-gl/mathgl/blob/c4601bc793c7a480dab005cf969aab0d7a7fb07d/mgl32/vecn.go#L72-L81