repo
stringlengths
5
54
path
stringlengths
4
155
func_name
stringlengths
1
118
original_string
stringlengths
52
85.5k
language
stringclasses
1 value
code
stringlengths
52
85.5k
code_tokens
list
docstring
stringlengths
6
2.61k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
85
252
partition
stringclasses
1 value
golang/geo
s2/shapeutil.go
newRangeIterator
func newRangeIterator(index *ShapeIndex) *rangeIterator { r := &rangeIterator{ it: index.Iterator(), } r.refresh() return r }
go
func newRangeIterator(index *ShapeIndex) *rangeIterator { r := &rangeIterator{ it: index.Iterator(), } r.refresh() return r }
[ "func", "newRangeIterator", "(", "index", "*", "ShapeIndex", ")", "*", "rangeIterator", "{", "r", ":=", "&", "rangeIterator", "{", "it", ":", "index", ".", "Iterator", "(", ")", ",", "}", "\n", "r", ".", "refresh", "(", ")", "\n", "return", "r", "\n"...
// newRangeIterator creates a new rangeIterator positioned at the first cell of the given index.
[ "newRangeIterator", "creates", "a", "new", "rangeIterator", "positioned", "at", "the", "first", "cell", "of", "the", "given", "index", "." ]
476085157cff9aaeef4d4f124649436542d4114a
https://github.com/golang/geo/blob/476085157cff9aaeef4d4f124649436542d4114a/s2/shapeutil.go#L45-L51
train
golang/geo
s2/shapeutil.go
seekTo
func (r *rangeIterator) seekTo(target *rangeIterator) { r.it.seek(target.rangeMin) // If the current cell does not overlap target, it is possible that the // previous cell is the one we are looking for. This can only happen when // the previous cell contains target but has a smaller CellID. if r.it.Done() || r.it.CellID().RangeMin() > target.rangeMax { if r.it.Prev() && r.it.CellID().RangeMax() < target.cellID() { r.it.Next() } } r.refresh() }
go
func (r *rangeIterator) seekTo(target *rangeIterator) { r.it.seek(target.rangeMin) // If the current cell does not overlap target, it is possible that the // previous cell is the one we are looking for. This can only happen when // the previous cell contains target but has a smaller CellID. if r.it.Done() || r.it.CellID().RangeMin() > target.rangeMax { if r.it.Prev() && r.it.CellID().RangeMax() < target.cellID() { r.it.Next() } } r.refresh() }
[ "func", "(", "r", "*", "rangeIterator", ")", "seekTo", "(", "target", "*", "rangeIterator", ")", "{", "r", ".", "it", ".", "seek", "(", "target", ".", "rangeMin", ")", "\n", "// If the current cell does not overlap target, it is possible that the", "// previous cell...
// seekTo positions the iterator at the first cell that overlaps or follows // the current range minimum of the target iterator, i.e. such that its // rangeMax >= target.rangeMin.
[ "seekTo", "positions", "the", "iterator", "at", "the", "first", "cell", "that", "overlaps", "or", "follows", "the", "current", "range", "minimum", "of", "the", "target", "iterator", "i", ".", "e", ".", "such", "that", "its", "rangeMax", ">", "=", "target",...
476085157cff9aaeef4d4f124649436542d4114a
https://github.com/golang/geo/blob/476085157cff9aaeef4d4f124649436542d4114a/s2/shapeutil.go#L61-L72
train
golang/geo
s2/shapeutil.go
seekBeyond
func (r *rangeIterator) seekBeyond(target *rangeIterator) { r.it.seek(target.rangeMax.Next()) if !r.it.Done() && r.it.CellID().RangeMin() <= target.rangeMax { r.it.Next() } r.refresh() }
go
func (r *rangeIterator) seekBeyond(target *rangeIterator) { r.it.seek(target.rangeMax.Next()) if !r.it.Done() && r.it.CellID().RangeMin() <= target.rangeMax { r.it.Next() } r.refresh() }
[ "func", "(", "r", "*", "rangeIterator", ")", "seekBeyond", "(", "target", "*", "rangeIterator", ")", "{", "r", ".", "it", ".", "seek", "(", "target", ".", "rangeMax", ".", "Next", "(", ")", ")", "\n", "if", "!", "r", ".", "it", ".", "Done", "(", ...
// seekBeyond positions the iterator at the first cell that follows the current // range minimum of the target iterator. i.e. the first cell such that its // rangeMin > target.rangeMax.
[ "seekBeyond", "positions", "the", "iterator", "at", "the", "first", "cell", "that", "follows", "the", "current", "range", "minimum", "of", "the", "target", "iterator", ".", "i", ".", "e", ".", "the", "first", "cell", "such", "that", "its", "rangeMin", ">",...
476085157cff9aaeef4d4f124649436542d4114a
https://github.com/golang/geo/blob/476085157cff9aaeef4d4f124649436542d4114a/s2/shapeutil.go#L77-L83
train
golang/geo
s2/shapeutil.go
refresh
func (r *rangeIterator) refresh() { r.rangeMin = r.cellID().RangeMin() r.rangeMax = r.cellID().RangeMax() }
go
func (r *rangeIterator) refresh() { r.rangeMin = r.cellID().RangeMin() r.rangeMax = r.cellID().RangeMax() }
[ "func", "(", "r", "*", "rangeIterator", ")", "refresh", "(", ")", "{", "r", ".", "rangeMin", "=", "r", ".", "cellID", "(", ")", ".", "RangeMin", "(", ")", "\n", "r", ".", "rangeMax", "=", "r", ".", "cellID", "(", ")", ".", "RangeMax", "(", ")",...
// refresh updates the iterators min and max values.
[ "refresh", "updates", "the", "iterators", "min", "and", "max", "values", "." ]
476085157cff9aaeef4d4f124649436542d4114a
https://github.com/golang/geo/blob/476085157cff9aaeef4d4f124649436542d4114a/s2/shapeutil.go#L86-L89
train
golang/geo
s2/shapeutil.go
referencePointAtVertex
func referencePointAtVertex(shape Shape, vTest Point) (ReferencePoint, bool) { var ref ReferencePoint // Let P be an unbalanced vertex. Vertex P is defined to be inside the // region if the region contains a particular direction vector starting from // P, namely the direction p.Ortho(). This can be calculated using // ContainsVertexQuery. containsQuery := NewContainsVertexQuery(vTest) n := shape.NumEdges() for e := 0; e < n; e++ { edge := shape.Edge(e) if edge.V0 == vTest { containsQuery.AddEdge(edge.V1, 1) } if edge.V1 == vTest { containsQuery.AddEdge(edge.V0, -1) } } containsSign := containsQuery.ContainsVertex() if containsSign == 0 { return ref, false // There are no unmatched edges incident to this vertex. } ref.Point = vTest ref.Contained = containsSign > 0 return ref, true }
go
func referencePointAtVertex(shape Shape, vTest Point) (ReferencePoint, bool) { var ref ReferencePoint // Let P be an unbalanced vertex. Vertex P is defined to be inside the // region if the region contains a particular direction vector starting from // P, namely the direction p.Ortho(). This can be calculated using // ContainsVertexQuery. containsQuery := NewContainsVertexQuery(vTest) n := shape.NumEdges() for e := 0; e < n; e++ { edge := shape.Edge(e) if edge.V0 == vTest { containsQuery.AddEdge(edge.V1, 1) } if edge.V1 == vTest { containsQuery.AddEdge(edge.V0, -1) } } containsSign := containsQuery.ContainsVertex() if containsSign == 0 { return ref, false // There are no unmatched edges incident to this vertex. } ref.Point = vTest ref.Contained = containsSign > 0 return ref, true }
[ "func", "referencePointAtVertex", "(", "shape", "Shape", ",", "vTest", "Point", ")", "(", "ReferencePoint", ",", "bool", ")", "{", "var", "ref", "ReferencePoint", "\n\n", "// Let P be an unbalanced vertex. Vertex P is defined to be inside the", "// region if the region contai...
// referencePointAtVertex reports whether the given vertex is unbalanced, and // returns a ReferencePoint indicating if the point is contained. // Otherwise returns false.
[ "referencePointAtVertex", "reports", "whether", "the", "given", "vertex", "is", "unbalanced", "and", "returns", "a", "ReferencePoint", "indicating", "if", "the", "point", "is", "contained", ".", "Otherwise", "returns", "false", "." ]
476085157cff9aaeef4d4f124649436542d4114a
https://github.com/golang/geo/blob/476085157cff9aaeef4d4f124649436542d4114a/s2/shapeutil.go#L174-L201
train
golang/geo
s2/contains_vertex_query.go
NewContainsVertexQuery
func NewContainsVertexQuery(target Point) *ContainsVertexQuery { return &ContainsVertexQuery{ target: target, edgeMap: make(map[Point]int), } }
go
func NewContainsVertexQuery(target Point) *ContainsVertexQuery { return &ContainsVertexQuery{ target: target, edgeMap: make(map[Point]int), } }
[ "func", "NewContainsVertexQuery", "(", "target", "Point", ")", "*", "ContainsVertexQuery", "{", "return", "&", "ContainsVertexQuery", "{", "target", ":", "target", ",", "edgeMap", ":", "make", "(", "map", "[", "Point", "]", "int", ")", ",", "}", "\n", "}" ...
// NewContainsVertexQuery returns a new query for the given vertex whose // containment will be determined.
[ "NewContainsVertexQuery", "returns", "a", "new", "query", "for", "the", "given", "vertex", "whose", "containment", "will", "be", "determined", "." ]
476085157cff9aaeef4d4f124649436542d4114a
https://github.com/golang/geo/blob/476085157cff9aaeef4d4f124649436542d4114a/s2/contains_vertex_query.go#L31-L36
train
golang/geo
s2/contains_vertex_query.go
ContainsVertex
func (q *ContainsVertexQuery) ContainsVertex() int { // Find the unmatched edge that is immediately clockwise from Ortho(P). referenceDir := Point{q.target.Ortho()} bestPoint := referenceDir bestDir := 0 for k, v := range q.edgeMap { if v == 0 { continue // This is a "matched" edge. } if OrderedCCW(referenceDir, bestPoint, k, q.target) { bestPoint = k bestDir = v } } return bestDir }
go
func (q *ContainsVertexQuery) ContainsVertex() int { // Find the unmatched edge that is immediately clockwise from Ortho(P). referenceDir := Point{q.target.Ortho()} bestPoint := referenceDir bestDir := 0 for k, v := range q.edgeMap { if v == 0 { continue // This is a "matched" edge. } if OrderedCCW(referenceDir, bestPoint, k, q.target) { bestPoint = k bestDir = v } } return bestDir }
[ "func", "(", "q", "*", "ContainsVertexQuery", ")", "ContainsVertex", "(", ")", "int", "{", "// Find the unmatched edge that is immediately clockwise from Ortho(P).", "referenceDir", ":=", "Point", "{", "q", ".", "target", ".", "Ortho", "(", ")", "}", "\n\n", "bestPo...
// ContainsVertex reports a +1 if the target vertex is contained, -1 if it is // not contained, and 0 if the incident edges consisted of matched sibling pairs.
[ "ContainsVertex", "reports", "a", "+", "1", "if", "the", "target", "vertex", "is", "contained", "-", "1", "if", "it", "is", "not", "contained", "and", "0", "if", "the", "incident", "edges", "consisted", "of", "matched", "sibling", "pairs", "." ]
476085157cff9aaeef4d4f124649436542d4114a
https://github.com/golang/geo/blob/476085157cff9aaeef4d4f124649436542d4114a/s2/contains_vertex_query.go#L46-L63
train
docopt/docopt.go
examples/config_file/config_file.go
merge
func merge(mapA, mapB map[string]interface{}) map[string]interface{} { result := make(map[string]interface{}) for k, v := range mapA { result[k] = v } for k, v := range mapB { if _, ok := result[k]; !ok || result[k] == nil || result[k] == false { result[k] = v } } return result }
go
func merge(mapA, mapB map[string]interface{}) map[string]interface{} { result := make(map[string]interface{}) for k, v := range mapA { result[k] = v } for k, v := range mapB { if _, ok := result[k]; !ok || result[k] == nil || result[k] == false { result[k] = v } } return result }
[ "func", "merge", "(", "mapA", ",", "mapB", "map", "[", "string", "]", "interface", "{", "}", ")", "map", "[", "string", "]", "interface", "{", "}", "{", "result", ":=", "make", "(", "map", "[", "string", "]", "interface", "{", "}", ")", "\n", "fo...
// merge combines two maps. // truthiness takes priority over falsiness // mapA takes priority over mapB
[ "merge", "combines", "two", "maps", ".", "truthiness", "takes", "priority", "over", "falsiness", "mapA", "takes", "priority", "over", "mapB" ]
ee0de3bc6815ee19d4a46c7eb90f829db0e014b1
https://github.com/docopt/docopt.go/blob/ee0de3bc6815ee19d4a46c7eb90f829db0e014b1/examples/config_file/config_file.go#L47-L58
train
docopt/docopt.go
opts.go
guessUntaggedField
func guessUntaggedField(key string) string { switch { case strings.HasPrefix(key, "--") && len(key[2:]) > 1: return titleCaseDashes(key[2:]) case strings.HasPrefix(key, "-") && len(key[1:]) == 1: return titleCaseDashes(key[1:]) case strings.HasPrefix(key, "<") && strings.HasSuffix(key, ">"): key = key[1 : len(key)-1] } return strings.Title(strings.ToLower(key)) }
go
func guessUntaggedField(key string) string { switch { case strings.HasPrefix(key, "--") && len(key[2:]) > 1: return titleCaseDashes(key[2:]) case strings.HasPrefix(key, "-") && len(key[1:]) == 1: return titleCaseDashes(key[1:]) case strings.HasPrefix(key, "<") && strings.HasSuffix(key, ">"): key = key[1 : len(key)-1] } return strings.Title(strings.ToLower(key)) }
[ "func", "guessUntaggedField", "(", "key", "string", ")", "string", "{", "switch", "{", "case", "strings", ".", "HasPrefix", "(", "key", ",", "\"", "\"", ")", "&&", "len", "(", "key", "[", "2", ":", "]", ")", ">", "1", ":", "return", "titleCaseDashes"...
// Best guess which field.Name in a struct to assign for an option key.
[ "Best", "guess", "which", "field", ".", "Name", "in", "a", "struct", "to", "assign", "for", "an", "option", "key", "." ]
ee0de3bc6815ee19d4a46c7eb90f829db0e014b1
https://github.com/docopt/docopt.go/blob/ee0de3bc6815ee19d4a46c7eb90f829db0e014b1/opts.go#L254-L264
train
docopt/docopt.go
token.go
isStringUppercase
func isStringUppercase(s string) bool { if strings.ToUpper(s) != s { return false } for _, c := range []rune(s) { if unicode.IsUpper(c) { return true } } return false }
go
func isStringUppercase(s string) bool { if strings.ToUpper(s) != s { return false } for _, c := range []rune(s) { if unicode.IsUpper(c) { return true } } return false }
[ "func", "isStringUppercase", "(", "s", "string", ")", "bool", "{", "if", "strings", ".", "ToUpper", "(", "s", ")", "!=", "s", "{", "return", "false", "\n", "}", "\n", "for", "_", ",", "c", ":=", "range", "[", "]", "rune", "(", "s", ")", "{", "i...
// returns true if all cased characters in the string are uppercase // and there are there is at least one cased charcter
[ "returns", "true", "if", "all", "cased", "characters", "in", "the", "string", "are", "uppercase", "and", "there", "are", "there", "is", "at", "least", "one", "cased", "charcter" ]
ee0de3bc6815ee19d4a46c7eb90f829db0e014b1
https://github.com/docopt/docopt.go/blob/ee0de3bc6815ee19d4a46c7eb90f829db0e014b1/token.go#L116-L126
train
rubenv/sql-migrate
sqlparse/sqlparse.go
endsWithSemicolon
func endsWithSemicolon(line string) bool { prev := "" scanner := bufio.NewScanner(strings.NewReader(line)) scanner.Split(bufio.ScanWords) for scanner.Scan() { word := scanner.Text() if strings.HasPrefix(word, "--") { break } prev = word } return strings.HasSuffix(prev, ";") }
go
func endsWithSemicolon(line string) bool { prev := "" scanner := bufio.NewScanner(strings.NewReader(line)) scanner.Split(bufio.ScanWords) for scanner.Scan() { word := scanner.Text() if strings.HasPrefix(word, "--") { break } prev = word } return strings.HasSuffix(prev, ";") }
[ "func", "endsWithSemicolon", "(", "line", "string", ")", "bool", "{", "prev", ":=", "\"", "\"", "\n", "scanner", ":=", "bufio", ".", "NewScanner", "(", "strings", ".", "NewReader", "(", "line", ")", ")", "\n", "scanner", ".", "Split", "(", "bufio", "."...
// Checks the line to see if the line has a statement-ending semicolon // or if the line contains a double-dash comment.
[ "Checks", "the", "line", "to", "see", "if", "the", "line", "has", "a", "statement", "-", "ending", "semicolon", "or", "if", "the", "line", "contains", "a", "double", "-", "dash", "comment", "." ]
54bad0a9b051368ffec9cd2b869789c2b8eaea35
https://github.com/rubenv/sql-migrate/blob/54bad0a9b051368ffec9cd2b869789c2b8eaea35/sqlparse/sqlparse.go#L47-L62
train
rubenv/sql-migrate
migrate.go
Exec
func Exec(db *sql.DB, dialect string, m MigrationSource, dir MigrationDirection) (int, error) { return ExecMax(db, dialect, m, dir, 0) }
go
func Exec(db *sql.DB, dialect string, m MigrationSource, dir MigrationDirection) (int, error) { return ExecMax(db, dialect, m, dir, 0) }
[ "func", "Exec", "(", "db", "*", "sql", ".", "DB", ",", "dialect", "string", ",", "m", "MigrationSource", ",", "dir", "MigrationDirection", ")", "(", "int", ",", "error", ")", "{", "return", "ExecMax", "(", "db", ",", "dialect", ",", "m", ",", "dir", ...
// Execute a set of migrations // // Returns the number of applied migrations.
[ "Execute", "a", "set", "of", "migrations", "Returns", "the", "number", "of", "applied", "migrations", "." ]
54bad0a9b051368ffec9cd2b869789c2b8eaea35
https://github.com/rubenv/sql-migrate/blob/54bad0a9b051368ffec9cd2b869789c2b8eaea35/migrate.go#L365-L367
train
rubenv/sql-migrate
migrate.go
PlanMigration
func PlanMigration(db *sql.DB, dialect string, m MigrationSource, dir MigrationDirection, max int) ([]*PlannedMigration, *gorp.DbMap, error) { dbMap, err := getMigrationDbMap(db, dialect) if err != nil { return nil, nil, err } migrations, err := m.FindMigrations() if err != nil { return nil, nil, err } var migrationRecords []MigrationRecord _, err = dbMap.Select(&migrationRecords, fmt.Sprintf("SELECT * FROM %s", dbMap.Dialect.QuotedTableForQuery(schemaName, tableName))) if err != nil { return nil, nil, err } // Sort migrations that have been run by Id. var existingMigrations []*Migration for _, migrationRecord := range migrationRecords { existingMigrations = append(existingMigrations, &Migration{ Id: migrationRecord.Id, }) } sort.Sort(byId(existingMigrations)) // Make sure all migrations in the database are among the found migrations which // are to be applied. migrationsSearch := make(map[string]struct{}) for _, migration := range migrations { migrationsSearch[migration.Id] = struct{}{} } for _, existingMigration := range existingMigrations { if _, ok := migrationsSearch[existingMigration.Id]; !ok { return nil, nil, newPlanError(existingMigration, "unknown migration in database") } } // Get last migration that was run record := &Migration{} if len(existingMigrations) > 0 { record = existingMigrations[len(existingMigrations)-1] } result := make([]*PlannedMigration, 0) // Add missing migrations up to the last run migration. // This can happen for example when merges happened. if len(existingMigrations) > 0 { result = append(result, ToCatchup(migrations, existingMigrations, record)...) } // Figure out which migrations to apply toApply := ToApply(migrations, record.Id, dir) toApplyCount := len(toApply) if max > 0 && max < toApplyCount { toApplyCount = max } for _, v := range toApply[0:toApplyCount] { if dir == Up { result = append(result, &PlannedMigration{ Migration: v, Queries: v.Up, DisableTransaction: v.DisableTransactionUp, }) } else if dir == Down { result = append(result, &PlannedMigration{ Migration: v, Queries: v.Down, DisableTransaction: v.DisableTransactionDown, }) } } return result, dbMap, nil }
go
func PlanMigration(db *sql.DB, dialect string, m MigrationSource, dir MigrationDirection, max int) ([]*PlannedMigration, *gorp.DbMap, error) { dbMap, err := getMigrationDbMap(db, dialect) if err != nil { return nil, nil, err } migrations, err := m.FindMigrations() if err != nil { return nil, nil, err } var migrationRecords []MigrationRecord _, err = dbMap.Select(&migrationRecords, fmt.Sprintf("SELECT * FROM %s", dbMap.Dialect.QuotedTableForQuery(schemaName, tableName))) if err != nil { return nil, nil, err } // Sort migrations that have been run by Id. var existingMigrations []*Migration for _, migrationRecord := range migrationRecords { existingMigrations = append(existingMigrations, &Migration{ Id: migrationRecord.Id, }) } sort.Sort(byId(existingMigrations)) // Make sure all migrations in the database are among the found migrations which // are to be applied. migrationsSearch := make(map[string]struct{}) for _, migration := range migrations { migrationsSearch[migration.Id] = struct{}{} } for _, existingMigration := range existingMigrations { if _, ok := migrationsSearch[existingMigration.Id]; !ok { return nil, nil, newPlanError(existingMigration, "unknown migration in database") } } // Get last migration that was run record := &Migration{} if len(existingMigrations) > 0 { record = existingMigrations[len(existingMigrations)-1] } result := make([]*PlannedMigration, 0) // Add missing migrations up to the last run migration. // This can happen for example when merges happened. if len(existingMigrations) > 0 { result = append(result, ToCatchup(migrations, existingMigrations, record)...) } // Figure out which migrations to apply toApply := ToApply(migrations, record.Id, dir) toApplyCount := len(toApply) if max > 0 && max < toApplyCount { toApplyCount = max } for _, v := range toApply[0:toApplyCount] { if dir == Up { result = append(result, &PlannedMigration{ Migration: v, Queries: v.Up, DisableTransaction: v.DisableTransactionUp, }) } else if dir == Down { result = append(result, &PlannedMigration{ Migration: v, Queries: v.Down, DisableTransaction: v.DisableTransactionDown, }) } } return result, dbMap, nil }
[ "func", "PlanMigration", "(", "db", "*", "sql", ".", "DB", ",", "dialect", "string", ",", "m", "MigrationSource", ",", "dir", "MigrationDirection", ",", "max", "int", ")", "(", "[", "]", "*", "PlannedMigration", ",", "*", "gorp", ".", "DbMap", ",", "er...
// Plan a migration.
[ "Plan", "a", "migration", "." ]
54bad0a9b051368ffec9cd2b869789c2b8eaea35
https://github.com/rubenv/sql-migrate/blob/54bad0a9b051368ffec9cd2b869789c2b8eaea35/migrate.go#L445-L521
train
rubenv/sql-migrate
migrate.go
SkipMax
func SkipMax(db *sql.DB, dialect string, m MigrationSource, dir MigrationDirection, max int) (int, error) { migrations, dbMap, err := PlanMigration(db, dialect, m, dir, max) if err != nil { return 0, err } // Skip migrations applied := 0 for _, migration := range migrations { var executor SqlExecutor if migration.DisableTransaction { executor = dbMap } else { executor, err = dbMap.Begin() if err != nil { return applied, newTxError(migration, err) } } err = executor.Insert(&MigrationRecord{ Id: migration.Id, AppliedAt: time.Now(), }) if err != nil { if trans, ok := executor.(*gorp.Transaction); ok { _ = trans.Rollback() } return applied, newTxError(migration, err) } if trans, ok := executor.(*gorp.Transaction); ok { if err := trans.Commit(); err != nil { return applied, newTxError(migration, err) } } applied++ } return applied, nil }
go
func SkipMax(db *sql.DB, dialect string, m MigrationSource, dir MigrationDirection, max int) (int, error) { migrations, dbMap, err := PlanMigration(db, dialect, m, dir, max) if err != nil { return 0, err } // Skip migrations applied := 0 for _, migration := range migrations { var executor SqlExecutor if migration.DisableTransaction { executor = dbMap } else { executor, err = dbMap.Begin() if err != nil { return applied, newTxError(migration, err) } } err = executor.Insert(&MigrationRecord{ Id: migration.Id, AppliedAt: time.Now(), }) if err != nil { if trans, ok := executor.(*gorp.Transaction); ok { _ = trans.Rollback() } return applied, newTxError(migration, err) } if trans, ok := executor.(*gorp.Transaction); ok { if err := trans.Commit(); err != nil { return applied, newTxError(migration, err) } } applied++ } return applied, nil }
[ "func", "SkipMax", "(", "db", "*", "sql", ".", "DB", ",", "dialect", "string", ",", "m", "MigrationSource", ",", "dir", "MigrationDirection", ",", "max", "int", ")", "(", "int", ",", "error", ")", "{", "migrations", ",", "dbMap", ",", "err", ":=", "P...
// Skip a set of migrations // // Will skip at most `max` migrations. Pass 0 for no limit. // // Returns the number of skipped migrations.
[ "Skip", "a", "set", "of", "migrations", "Will", "skip", "at", "most", "max", "migrations", ".", "Pass", "0", "for", "no", "limit", ".", "Returns", "the", "number", "of", "skipped", "migrations", "." ]
54bad0a9b051368ffec9cd2b869789c2b8eaea35
https://github.com/rubenv/sql-migrate/blob/54bad0a9b051368ffec9cd2b869789c2b8eaea35/migrate.go#L528-L570
train
rubenv/sql-migrate
migrate.go
ToApply
func ToApply(migrations []*Migration, current string, direction MigrationDirection) []*Migration { var index = -1 if current != "" { for index < len(migrations)-1 { index++ if migrations[index].Id == current { break } } } if direction == Up { return migrations[index+1:] } else if direction == Down { if index == -1 { return []*Migration{} } // Add in reverse order toApply := make([]*Migration, index+1) for i := 0; i < index+1; i++ { toApply[index-i] = migrations[i] } return toApply } panic("Not possible") }
go
func ToApply(migrations []*Migration, current string, direction MigrationDirection) []*Migration { var index = -1 if current != "" { for index < len(migrations)-1 { index++ if migrations[index].Id == current { break } } } if direction == Up { return migrations[index+1:] } else if direction == Down { if index == -1 { return []*Migration{} } // Add in reverse order toApply := make([]*Migration, index+1) for i := 0; i < index+1; i++ { toApply[index-i] = migrations[i] } return toApply } panic("Not possible") }
[ "func", "ToApply", "(", "migrations", "[", "]", "*", "Migration", ",", "current", "string", ",", "direction", "MigrationDirection", ")", "[", "]", "*", "Migration", "{", "var", "index", "=", "-", "1", "\n", "if", "current", "!=", "\"", "\"", "{", "for"...
// Filter a slice of migrations into ones that should be applied.
[ "Filter", "a", "slice", "of", "migrations", "into", "ones", "that", "should", "be", "applied", "." ]
54bad0a9b051368ffec9cd2b869789c2b8eaea35
https://github.com/rubenv/sql-migrate/blob/54bad0a9b051368ffec9cd2b869789c2b8eaea35/migrate.go#L573-L600
train
cheekybits/genny
examples/queue/queue_generic.go
Enq
func (q *GenericQueue) Enq(obj Generic) *GenericQueue { q.items = append(q.items, obj) return q }
go
func (q *GenericQueue) Enq(obj Generic) *GenericQueue { q.items = append(q.items, obj) return q }
[ "func", "(", "q", "*", "GenericQueue", ")", "Enq", "(", "obj", "Generic", ")", "*", "GenericQueue", "{", "q", ".", "items", "=", "append", "(", "q", ".", "items", ",", "obj", ")", "\n", "return", "q", "\n", "}" ]
// Enq adds an item to the queue.
[ "Enq", "adds", "an", "item", "to", "the", "queue", "." ]
d2cf3cdd35ce0d789056c4bc02a4d6349c947caf
https://github.com/cheekybits/genny/blob/d2cf3cdd35ce0d789056c4bc02a4d6349c947caf/examples/queue/queue_generic.go#L18-L21
train
cheekybits/genny
examples/queue/queue_generic.go
Deq
func (q *GenericQueue) Deq() Generic { obj := q.items[0] q.items = q.items[1:] return obj }
go
func (q *GenericQueue) Deq() Generic { obj := q.items[0] q.items = q.items[1:] return obj }
[ "func", "(", "q", "*", "GenericQueue", ")", "Deq", "(", ")", "Generic", "{", "obj", ":=", "q", ".", "items", "[", "0", "]", "\n", "q", ".", "items", "=", "q", ".", "items", "[", "1", ":", "]", "\n", "return", "obj", "\n", "}" ]
// Deq removes and returns the next item in the queue.
[ "Deq", "removes", "and", "returns", "the", "next", "item", "in", "the", "queue", "." ]
d2cf3cdd35ce0d789056c4bc02a4d6349c947caf
https://github.com/cheekybits/genny/blob/d2cf3cdd35ce0d789056c4bc02a4d6349c947caf/examples/queue/queue_generic.go#L24-L28
train
cheekybits/genny
parse/parse.go
subTypeIntoLine
func subTypeIntoLine(line, typeTemplate, specificType string) string { src := []byte(line) var s scanner.Scanner fset := token.NewFileSet() file := fset.AddFile("", fset.Base(), len(src)) s.Init(file, src, nil, scanner.ScanComments) output := "" for { _, tok, lit := s.Scan() if tok == token.EOF { break } else if tok == token.COMMENT { subbed := subTypeIntoComment(lit, typeTemplate, specificType) output = output + subbed + " " } else if tok.IsLiteral() { subbed := subIntoLiteral(lit, typeTemplate, specificType) output = output + subbed + " " } else { output = output + tok.String() + " " } } return output }
go
func subTypeIntoLine(line, typeTemplate, specificType string) string { src := []byte(line) var s scanner.Scanner fset := token.NewFileSet() file := fset.AddFile("", fset.Base(), len(src)) s.Init(file, src, nil, scanner.ScanComments) output := "" for { _, tok, lit := s.Scan() if tok == token.EOF { break } else if tok == token.COMMENT { subbed := subTypeIntoComment(lit, typeTemplate, specificType) output = output + subbed + " " } else if tok.IsLiteral() { subbed := subIntoLiteral(lit, typeTemplate, specificType) output = output + subbed + " " } else { output = output + tok.String() + " " } } return output }
[ "func", "subTypeIntoLine", "(", "line", ",", "typeTemplate", ",", "specificType", "string", ")", "string", "{", "src", ":=", "[", "]", "byte", "(", "line", ")", "\n", "var", "s", "scanner", ".", "Scanner", "\n", "fset", ":=", "token", ".", "NewFileSet", ...
// Does the heavy lifting of taking a line of our code and // sbustituting a type into there for our generic type
[ "Does", "the", "heavy", "lifting", "of", "taking", "a", "line", "of", "our", "code", "and", "sbustituting", "a", "type", "into", "there", "for", "our", "generic", "type" ]
d2cf3cdd35ce0d789056c4bc02a4d6349c947caf
https://github.com/cheekybits/genny/blob/d2cf3cdd35ce0d789056c4bc02a4d6349c947caf/parse/parse.go#L67-L89
train
cheekybits/genny
parse/parse.go
wordify
func wordify(s string, exported bool) string { s = strings.TrimRight(s, "{}") s = strings.TrimLeft(s, "*&") s = strings.Replace(s, ".", "", -1) if !exported { return s } return strings.ToUpper(string(s[0])) + s[1:] }
go
func wordify(s string, exported bool) string { s = strings.TrimRight(s, "{}") s = strings.TrimLeft(s, "*&") s = strings.Replace(s, ".", "", -1) if !exported { return s } return strings.ToUpper(string(s[0])) + s[1:] }
[ "func", "wordify", "(", "s", "string", ",", "exported", "bool", ")", "string", "{", "s", "=", "strings", ".", "TrimRight", "(", "s", ",", "\"", "\"", ")", "\n", "s", "=", "strings", ".", "TrimLeft", "(", "s", ",", "\"", "\"", ")", "\n", "s", "=...
// wordify turns a type into a nice word for function and type // names etc.
[ "wordify", "turns", "a", "type", "into", "a", "nice", "word", "for", "function", "and", "type", "names", "etc", "." ]
d2cf3cdd35ce0d789056c4bc02a4d6349c947caf
https://github.com/cheekybits/genny/blob/d2cf3cdd35ce0d789056c4bc02a4d6349c947caf/parse/parse.go#L263-L271
train
cheekybits/genny
out/lazy_file.go
Close
func (lw *LazyFile) Close() error { if lw.file != nil { return lw.file.Close() } return nil }
go
func (lw *LazyFile) Close() error { if lw.file != nil { return lw.file.Close() } return nil }
[ "func", "(", "lw", "*", "LazyFile", ")", "Close", "(", ")", "error", "{", "if", "lw", ".", "file", "!=", "nil", "{", "return", "lw", ".", "file", ".", "Close", "(", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// Close closes the file if it is created. Returns nil if no file is created.
[ "Close", "closes", "the", "file", "if", "it", "is", "created", ".", "Returns", "nil", "if", "no", "file", "is", "created", "." ]
d2cf3cdd35ce0d789056c4bc02a4d6349c947caf
https://github.com/cheekybits/genny/blob/d2cf3cdd35ce0d789056c4bc02a4d6349c947caf/out/lazy_file.go#L18-L23
train
cheekybits/genny
out/lazy_file.go
Write
func (lw *LazyFile) Write(p []byte) (int, error) { if lw.file == nil { err := os.MkdirAll(path.Dir(lw.FileName), 0755) if err != nil { return 0, err } lw.file, err = os.Create(lw.FileName) if err != nil { return 0, err } } return lw.file.Write(p) }
go
func (lw *LazyFile) Write(p []byte) (int, error) { if lw.file == nil { err := os.MkdirAll(path.Dir(lw.FileName), 0755) if err != nil { return 0, err } lw.file, err = os.Create(lw.FileName) if err != nil { return 0, err } } return lw.file.Write(p) }
[ "func", "(", "lw", "*", "LazyFile", ")", "Write", "(", "p", "[", "]", "byte", ")", "(", "int", ",", "error", ")", "{", "if", "lw", ".", "file", "==", "nil", "{", "err", ":=", "os", ".", "MkdirAll", "(", "path", ".", "Dir", "(", "lw", ".", "...
// Write writes to the specified file and creates the file first time it is called.
[ "Write", "writes", "to", "the", "specified", "file", "and", "creates", "the", "file", "first", "time", "it", "is", "called", "." ]
d2cf3cdd35ce0d789056c4bc02a4d6349c947caf
https://github.com/cheekybits/genny/blob/d2cf3cdd35ce0d789056c4bc02a4d6349c947caf/out/lazy_file.go#L26-L38
train
cheekybits/genny
main.go
gen
func gen(filename, pkgName string, in io.ReadSeeker, typesets []map[string]string, out io.Writer) error { var output []byte var err error output, err = parse.Generics(filename, pkgName, in, typesets) if err != nil { return err } out.Write(output) return nil }
go
func gen(filename, pkgName string, in io.ReadSeeker, typesets []map[string]string, out io.Writer) error { var output []byte var err error output, err = parse.Generics(filename, pkgName, in, typesets) if err != nil { return err } out.Write(output) return nil }
[ "func", "gen", "(", "filename", ",", "pkgName", "string", ",", "in", "io", ".", "ReadSeeker", ",", "typesets", "[", "]", "map", "[", "string", "]", "string", ",", "out", "io", ".", "Writer", ")", "error", "{", "var", "output", "[", "]", "byte", "\n...
// gen performs the generic generation.
[ "gen", "performs", "the", "generic", "generation", "." ]
d2cf3cdd35ce0d789056c4bc02a4d6349c947caf
https://github.com/cheekybits/genny/blob/d2cf3cdd35ce0d789056c4bc02a4d6349c947caf/main.go#L142-L154
train
machinebox/graphql
graphql.go
NewClient
func NewClient(endpoint string, opts ...ClientOption) *Client { c := &Client{ endpoint: endpoint, Log: func(string) {}, } for _, optionFunc := range opts { optionFunc(c) } if c.httpClient == nil { c.httpClient = http.DefaultClient } return c }
go
func NewClient(endpoint string, opts ...ClientOption) *Client { c := &Client{ endpoint: endpoint, Log: func(string) {}, } for _, optionFunc := range opts { optionFunc(c) } if c.httpClient == nil { c.httpClient = http.DefaultClient } return c }
[ "func", "NewClient", "(", "endpoint", "string", ",", "opts", "...", "ClientOption", ")", "*", "Client", "{", "c", ":=", "&", "Client", "{", "endpoint", ":", "endpoint", ",", "Log", ":", "func", "(", "string", ")", "{", "}", ",", "}", "\n", "for", "...
// NewClient makes a new Client capable of making GraphQL requests.
[ "NewClient", "makes", "a", "new", "Client", "capable", "of", "making", "GraphQL", "requests", "." ]
3a92531802258604bd12793465c2e28bc4b2fc85
https://github.com/machinebox/graphql/blob/3a92531802258604bd12793465c2e28bc4b2fc85/graphql.go#L61-L73
train
machinebox/graphql
graphql.go
Run
func (c *Client) Run(ctx context.Context, req *Request, resp interface{}) error { select { case <-ctx.Done(): return ctx.Err() default: } if len(req.files) > 0 && !c.useMultipartForm { return errors.New("cannot send files with PostFields option") } if c.useMultipartForm { return c.runWithPostFields(ctx, req, resp) } return c.runWithJSON(ctx, req, resp) }
go
func (c *Client) Run(ctx context.Context, req *Request, resp interface{}) error { select { case <-ctx.Done(): return ctx.Err() default: } if len(req.files) > 0 && !c.useMultipartForm { return errors.New("cannot send files with PostFields option") } if c.useMultipartForm { return c.runWithPostFields(ctx, req, resp) } return c.runWithJSON(ctx, req, resp) }
[ "func", "(", "c", "*", "Client", ")", "Run", "(", "ctx", "context", ".", "Context", ",", "req", "*", "Request", ",", "resp", "interface", "{", "}", ")", "error", "{", "select", "{", "case", "<-", "ctx", ".", "Done", "(", ")", ":", "return", "ctx"...
// Run executes the query and unmarshals the response from the data field // into the response object. // Pass in a nil response object to skip response parsing. // If the request fails or the server returns an error, the first error // will be returned.
[ "Run", "executes", "the", "query", "and", "unmarshals", "the", "response", "from", "the", "data", "field", "into", "the", "response", "object", ".", "Pass", "in", "a", "nil", "response", "object", "to", "skip", "response", "parsing", ".", "If", "the", "req...
3a92531802258604bd12793465c2e28bc4b2fc85
https://github.com/machinebox/graphql/blob/3a92531802258604bd12793465c2e28bc4b2fc85/graphql.go#L84-L97
train
machinebox/graphql
graphql.go
NewRequest
func NewRequest(q string) *Request { req := &Request{ q: q, Header: make(map[string][]string), } return req }
go
func NewRequest(q string) *Request { req := &Request{ q: q, Header: make(map[string][]string), } return req }
[ "func", "NewRequest", "(", "q", "string", ")", "*", "Request", "{", "req", ":=", "&", "Request", "{", "q", ":", "q", ",", "Header", ":", "make", "(", "map", "[", "string", "]", "[", "]", "string", ")", ",", "}", "\n", "return", "req", "\n", "}"...
// NewRequest makes a new Request with the specified string.
[ "NewRequest", "makes", "a", "new", "Request", "with", "the", "specified", "string", "." ]
3a92531802258604bd12793465c2e28bc4b2fc85
https://github.com/machinebox/graphql/blob/3a92531802258604bd12793465c2e28bc4b2fc85/graphql.go#L277-L283
train
machinebox/graphql
graphql.go
Var
func (req *Request) Var(key string, value interface{}) { if req.vars == nil { req.vars = make(map[string]interface{}) } req.vars[key] = value }
go
func (req *Request) Var(key string, value interface{}) { if req.vars == nil { req.vars = make(map[string]interface{}) } req.vars[key] = value }
[ "func", "(", "req", "*", "Request", ")", "Var", "(", "key", "string", ",", "value", "interface", "{", "}", ")", "{", "if", "req", ".", "vars", "==", "nil", "{", "req", ".", "vars", "=", "make", "(", "map", "[", "string", "]", "interface", "{", ...
// Var sets a variable.
[ "Var", "sets", "a", "variable", "." ]
3a92531802258604bd12793465c2e28bc4b2fc85
https://github.com/machinebox/graphql/blob/3a92531802258604bd12793465c2e28bc4b2fc85/graphql.go#L286-L291
train
machinebox/graphql
graphql.go
File
func (req *Request) File(fieldname, filename string, r io.Reader) { req.files = append(req.files, File{ Field: fieldname, Name: filename, R: r, }) }
go
func (req *Request) File(fieldname, filename string, r io.Reader) { req.files = append(req.files, File{ Field: fieldname, Name: filename, R: r, }) }
[ "func", "(", "req", "*", "Request", ")", "File", "(", "fieldname", ",", "filename", "string", ",", "r", "io", ".", "Reader", ")", "{", "req", ".", "files", "=", "append", "(", "req", ".", "files", ",", "File", "{", "Field", ":", "fieldname", ",", ...
// File sets a file to upload. // Files are only supported with a Client that was created with // the UseMultipartForm option.
[ "File", "sets", "a", "file", "to", "upload", ".", "Files", "are", "only", "supported", "with", "a", "Client", "that", "was", "created", "with", "the", "UseMultipartForm", "option", "." ]
3a92531802258604bd12793465c2e28bc4b2fc85
https://github.com/machinebox/graphql/blob/3a92531802258604bd12793465c2e28bc4b2fc85/graphql.go#L311-L317
train
cenkalti/backoff
context.go
WithContext
func WithContext(b BackOff, ctx context.Context) BackOffContext { if ctx == nil { panic("nil context") } if b, ok := b.(*backOffContext); ok { return &backOffContext{ BackOff: b.BackOff, ctx: ctx, } } return &backOffContext{ BackOff: b, ctx: ctx, } }
go
func WithContext(b BackOff, ctx context.Context) BackOffContext { if ctx == nil { panic("nil context") } if b, ok := b.(*backOffContext); ok { return &backOffContext{ BackOff: b.BackOff, ctx: ctx, } } return &backOffContext{ BackOff: b, ctx: ctx, } }
[ "func", "WithContext", "(", "b", "BackOff", ",", "ctx", "context", ".", "Context", ")", "BackOffContext", "{", "if", "ctx", "==", "nil", "{", "panic", "(", "\"", "\"", ")", "\n", "}", "\n\n", "if", "b", ",", "ok", ":=", "b", ".", "(", "*", "backO...
// WithContext returns a BackOffContext with context ctx // // ctx must not be nil
[ "WithContext", "returns", "a", "BackOffContext", "with", "context", "ctx", "ctx", "must", "not", "be", "nil" ]
1e4cf3da559842a91afcb6ea6141451e6c30c618
https://github.com/cenkalti/backoff/blob/1e4cf3da559842a91afcb6ea6141451e6c30c618/context.go#L23-L39
train
sideshow/apns2
notification.go
MarshalJSON
func (n *Notification) MarshalJSON() ([]byte, error) { switch n.Payload.(type) { case string: return []byte(n.Payload.(string)), nil case []byte: return n.Payload.([]byte), nil default: return json.Marshal(n.Payload) } }
go
func (n *Notification) MarshalJSON() ([]byte, error) { switch n.Payload.(type) { case string: return []byte(n.Payload.(string)), nil case []byte: return n.Payload.([]byte), nil default: return json.Marshal(n.Payload) } }
[ "func", "(", "n", "*", "Notification", ")", "MarshalJSON", "(", ")", "(", "[", "]", "byte", ",", "error", ")", "{", "switch", "n", ".", "Payload", ".", "(", "type", ")", "{", "case", "string", ":", "return", "[", "]", "byte", "(", "n", ".", "Pa...
// MarshalJSON converts the notification payload to JSON.
[ "MarshalJSON", "converts", "the", "notification", "payload", "to", "JSON", "." ]
d5157a5e6ef01fe1b953450a7a8a1bbe77e865c2
https://github.com/sideshow/apns2/blob/d5157a5e6ef01fe1b953450a7a8a1bbe77e865c2/notification.go#L71-L80
train
sideshow/apns2
token/token.go
GenerateIfExpired
func (t *Token) GenerateIfExpired() { t.Lock() defer t.Unlock() if t.Expired() { t.Generate() } }
go
func (t *Token) GenerateIfExpired() { t.Lock() defer t.Unlock() if t.Expired() { t.Generate() } }
[ "func", "(", "t", "*", "Token", ")", "GenerateIfExpired", "(", ")", "{", "t", ".", "Lock", "(", ")", "\n", "defer", "t", ".", "Unlock", "(", ")", "\n", "if", "t", ".", "Expired", "(", ")", "{", "t", ".", "Generate", "(", ")", "\n", "}", "\n",...
// GenerateIfExpired checks to see if the token is about to expire and // generates a new token.
[ "GenerateIfExpired", "checks", "to", "see", "if", "the", "token", "is", "about", "to", "expire", "and", "generates", "a", "new", "token", "." ]
d5157a5e6ef01fe1b953450a7a8a1bbe77e865c2
https://github.com/sideshow/apns2/blob/d5157a5e6ef01fe1b953450a7a8a1bbe77e865c2/token/token.go#L71-L77
train
sideshow/apns2
token/token.go
Expired
func (t *Token) Expired() bool { return time.Now().Unix() >= (t.IssuedAt + TokenTimeout) }
go
func (t *Token) Expired() bool { return time.Now().Unix() >= (t.IssuedAt + TokenTimeout) }
[ "func", "(", "t", "*", "Token", ")", "Expired", "(", ")", "bool", "{", "return", "time", ".", "Now", "(", ")", ".", "Unix", "(", ")", ">=", "(", "t", ".", "IssuedAt", "+", "TokenTimeout", ")", "\n", "}" ]
// Expired checks to see if the token has expired.
[ "Expired", "checks", "to", "see", "if", "the", "token", "has", "expired", "." ]
d5157a5e6ef01fe1b953450a7a8a1bbe77e865c2
https://github.com/sideshow/apns2/blob/d5157a5e6ef01fe1b953450a7a8a1bbe77e865c2/token/token.go#L80-L82
train
sideshow/apns2
token/token.go
Generate
func (t *Token) Generate() (bool, error) { if t.AuthKey == nil { return false, ErrAuthKeyNil } issuedAt := time.Now().Unix() jwtToken := &jwt.Token{ Header: map[string]interface{}{ "alg": "ES256", "kid": t.KeyID, }, Claims: jwt.MapClaims{ "iss": t.TeamID, "iat": issuedAt, }, Method: jwt.SigningMethodES256, } bearer, err := jwtToken.SignedString(t.AuthKey) if err != nil { return false, err } t.IssuedAt = issuedAt t.Bearer = bearer return true, nil }
go
func (t *Token) Generate() (bool, error) { if t.AuthKey == nil { return false, ErrAuthKeyNil } issuedAt := time.Now().Unix() jwtToken := &jwt.Token{ Header: map[string]interface{}{ "alg": "ES256", "kid": t.KeyID, }, Claims: jwt.MapClaims{ "iss": t.TeamID, "iat": issuedAt, }, Method: jwt.SigningMethodES256, } bearer, err := jwtToken.SignedString(t.AuthKey) if err != nil { return false, err } t.IssuedAt = issuedAt t.Bearer = bearer return true, nil }
[ "func", "(", "t", "*", "Token", ")", "Generate", "(", ")", "(", "bool", ",", "error", ")", "{", "if", "t", ".", "AuthKey", "==", "nil", "{", "return", "false", ",", "ErrAuthKeyNil", "\n", "}", "\n", "issuedAt", ":=", "time", ".", "Now", "(", ")",...
// Generate creates a new token.
[ "Generate", "creates", "a", "new", "token", "." ]
d5157a5e6ef01fe1b953450a7a8a1bbe77e865c2
https://github.com/sideshow/apns2/blob/d5157a5e6ef01fe1b953450a7a8a1bbe77e865c2/token/token.go#L85-L108
train
sideshow/apns2
client.go
Push
func (c *Client) Push(n *Notification) (*Response, error) { return c.PushWithContext(nil, n) }
go
func (c *Client) Push(n *Notification) (*Response, error) { return c.PushWithContext(nil, n) }
[ "func", "(", "c", "*", "Client", ")", "Push", "(", "n", "*", "Notification", ")", "(", "*", "Response", ",", "error", ")", "{", "return", "c", ".", "PushWithContext", "(", "nil", ",", "n", ")", "\n", "}" ]
// Push sends a Notification to the APNs gateway. If the underlying http.Client // is not currently connected, this method will attempt to reconnect // transparently before sending the notification. It will return a Response // indicating whether the notification was accepted or rejected by the APNs // gateway, or an error if something goes wrong. // // Use PushWithContext if you need better cancellation and timeout control.
[ "Push", "sends", "a", "Notification", "to", "the", "APNs", "gateway", ".", "If", "the", "underlying", "http", ".", "Client", "is", "not", "currently", "connected", "this", "method", "will", "attempt", "to", "reconnect", "transparently", "before", "sending", "t...
d5157a5e6ef01fe1b953450a7a8a1bbe77e865c2
https://github.com/sideshow/apns2/blob/d5157a5e6ef01fe1b953450a7a8a1bbe77e865c2/client.go#L137-L139
train
sideshow/apns2
client.go
PushWithContext
func (c *Client) PushWithContext(ctx Context, n *Notification) (*Response, error) { payload, err := json.Marshal(n) if err != nil { return nil, err } url := fmt.Sprintf("%v/3/device/%v", c.Host, n.DeviceToken) req, _ := http.NewRequest("POST", url, bytes.NewBuffer(payload)) if c.Token != nil { c.setTokenHeader(req) } setHeaders(req, n) httpRes, err := c.requestWithContext(ctx, req) if err != nil { return nil, err } defer httpRes.Body.Close() response := &Response{} response.StatusCode = httpRes.StatusCode response.ApnsID = httpRes.Header.Get("apns-id") decoder := json.NewDecoder(httpRes.Body) if err := decoder.Decode(&response); err != nil && err != io.EOF { return &Response{}, err } return response, nil }
go
func (c *Client) PushWithContext(ctx Context, n *Notification) (*Response, error) { payload, err := json.Marshal(n) if err != nil { return nil, err } url := fmt.Sprintf("%v/3/device/%v", c.Host, n.DeviceToken) req, _ := http.NewRequest("POST", url, bytes.NewBuffer(payload)) if c.Token != nil { c.setTokenHeader(req) } setHeaders(req, n) httpRes, err := c.requestWithContext(ctx, req) if err != nil { return nil, err } defer httpRes.Body.Close() response := &Response{} response.StatusCode = httpRes.StatusCode response.ApnsID = httpRes.Header.Get("apns-id") decoder := json.NewDecoder(httpRes.Body) if err := decoder.Decode(&response); err != nil && err != io.EOF { return &Response{}, err } return response, nil }
[ "func", "(", "c", "*", "Client", ")", "PushWithContext", "(", "ctx", "Context", ",", "n", "*", "Notification", ")", "(", "*", "Response", ",", "error", ")", "{", "payload", ",", "err", ":=", "json", ".", "Marshal", "(", "n", ")", "\n", "if", "err",...
// PushWithContext sends a Notification to the APNs gateway. Context carries a // deadline and a cancellation signal and allows you to close long running // requests when the context timeout is exceeded. Context can be nil, for // backwards compatibility. // // If the underlying http.Client is not currently connected, this method will // attempt to reconnect transparently before sending the notification. It will // return a Response indicating whether the notification was accepted or // rejected by the APNs gateway, or an error if something goes wrong.
[ "PushWithContext", "sends", "a", "Notification", "to", "the", "APNs", "gateway", ".", "Context", "carries", "a", "deadline", "and", "a", "cancellation", "signal", "and", "allows", "you", "to", "close", "long", "running", "requests", "when", "the", "context", "...
d5157a5e6ef01fe1b953450a7a8a1bbe77e865c2
https://github.com/sideshow/apns2/blob/d5157a5e6ef01fe1b953450a7a8a1bbe77e865c2/client.go#L150-L180
train
sideshow/apns2
client_manager.go
NewClientManager
func NewClientManager() *ClientManager { manager := &ClientManager{ MaxSize: 64, MaxAge: 10 * time.Minute, Factory: NewClient, } manager.initInternals() return manager }
go
func NewClientManager() *ClientManager { manager := &ClientManager{ MaxSize: 64, MaxAge: 10 * time.Minute, Factory: NewClient, } manager.initInternals() return manager }
[ "func", "NewClientManager", "(", ")", "*", "ClientManager", "{", "manager", ":=", "&", "ClientManager", "{", "MaxSize", ":", "64", ",", "MaxAge", ":", "10", "*", "time", ".", "Minute", ",", "Factory", ":", "NewClient", ",", "}", "\n\n", "manager", ".", ...
// NewClientManager returns a new ClientManager for prolonged, concurrent usage // of multiple APNs clients. ClientManager is flexible enough to work best for // your use case. When a client is not found in the manager, Get will return // the result of calling Factory, which can be a Client or nil. // // Having multiple clients per certificate in the manager is not allowed. // // By default, MaxSize is 64, MaxAge is 10 minutes, and Factory always returns // a Client with default options.
[ "NewClientManager", "returns", "a", "new", "ClientManager", "for", "prolonged", "concurrent", "usage", "of", "multiple", "APNs", "clients", ".", "ClientManager", "is", "flexible", "enough", "to", "work", "best", "for", "your", "use", "case", ".", "When", "a", ...
d5157a5e6ef01fe1b953450a7a8a1bbe77e865c2
https://github.com/sideshow/apns2/blob/d5157a5e6ef01fe1b953450a7a8a1bbe77e865c2/client_manager.go#L49-L59
train
sideshow/apns2
client_manager.go
Add
func (m *ClientManager) Add(client *Client) { m.initInternals() m.mu.Lock() defer m.mu.Unlock() key := cacheKey(client.Certificate) now := time.Now() if ele, hit := m.cache[key]; hit { item := ele.Value.(*managerItem) item.client = client item.lastUsed = now m.ll.MoveToFront(ele) return } ele := m.ll.PushFront(&managerItem{key, client, now}) m.cache[key] = ele if m.MaxSize != 0 && m.ll.Len() > m.MaxSize { m.mu.Unlock() m.removeOldest() m.mu.Lock() } }
go
func (m *ClientManager) Add(client *Client) { m.initInternals() m.mu.Lock() defer m.mu.Unlock() key := cacheKey(client.Certificate) now := time.Now() if ele, hit := m.cache[key]; hit { item := ele.Value.(*managerItem) item.client = client item.lastUsed = now m.ll.MoveToFront(ele) return } ele := m.ll.PushFront(&managerItem{key, client, now}) m.cache[key] = ele if m.MaxSize != 0 && m.ll.Len() > m.MaxSize { m.mu.Unlock() m.removeOldest() m.mu.Lock() } }
[ "func", "(", "m", "*", "ClientManager", ")", "Add", "(", "client", "*", "Client", ")", "{", "m", ".", "initInternals", "(", ")", "\n", "m", ".", "mu", ".", "Lock", "(", ")", "\n", "defer", "m", ".", "mu", ".", "Unlock", "(", ")", "\n\n", "key",...
// Add adds a Client to the manager. You can use this to individually configure // Clients in the manager.
[ "Add", "adds", "a", "Client", "to", "the", "manager", ".", "You", "can", "use", "this", "to", "individually", "configure", "Clients", "in", "the", "manager", "." ]
d5157a5e6ef01fe1b953450a7a8a1bbe77e865c2
https://github.com/sideshow/apns2/blob/d5157a5e6ef01fe1b953450a7a8a1bbe77e865c2/client_manager.go#L63-L84
train
sideshow/apns2
client_manager.go
Get
func (m *ClientManager) Get(certificate tls.Certificate) *Client { m.initInternals() m.mu.Lock() defer m.mu.Unlock() key := cacheKey(certificate) now := time.Now() if ele, hit := m.cache[key]; hit { item := ele.Value.(*managerItem) if m.MaxAge != 0 && item.lastUsed.Before(now.Add(-m.MaxAge)) { c := m.Factory(certificate) if c == nil { return nil } item.client = c } item.lastUsed = now m.ll.MoveToFront(ele) return item.client } c := m.Factory(certificate) if c == nil { return nil } m.mu.Unlock() m.Add(c) m.mu.Lock() return c }
go
func (m *ClientManager) Get(certificate tls.Certificate) *Client { m.initInternals() m.mu.Lock() defer m.mu.Unlock() key := cacheKey(certificate) now := time.Now() if ele, hit := m.cache[key]; hit { item := ele.Value.(*managerItem) if m.MaxAge != 0 && item.lastUsed.Before(now.Add(-m.MaxAge)) { c := m.Factory(certificate) if c == nil { return nil } item.client = c } item.lastUsed = now m.ll.MoveToFront(ele) return item.client } c := m.Factory(certificate) if c == nil { return nil } m.mu.Unlock() m.Add(c) m.mu.Lock() return c }
[ "func", "(", "m", "*", "ClientManager", ")", "Get", "(", "certificate", "tls", ".", "Certificate", ")", "*", "Client", "{", "m", ".", "initInternals", "(", ")", "\n", "m", ".", "mu", ".", "Lock", "(", ")", "\n", "defer", "m", ".", "mu", ".", "Unl...
// Get gets a Client from the manager. If a Client is not found in the manager // or if a Client has remained in the manager longer than MaxAge, Get will call // the ClientManager's Factory function, store the result in the manager if // non-nil, and return it.
[ "Get", "gets", "a", "Client", "from", "the", "manager", ".", "If", "a", "Client", "is", "not", "found", "in", "the", "manager", "or", "if", "a", "Client", "has", "remained", "in", "the", "manager", "longer", "than", "MaxAge", "Get", "will", "call", "th...
d5157a5e6ef01fe1b953450a7a8a1bbe77e865c2
https://github.com/sideshow/apns2/blob/d5157a5e6ef01fe1b953450a7a8a1bbe77e865c2/client_manager.go#L90-L119
train
sideshow/apns2
client_manager.go
Len
func (m *ClientManager) Len() int { if m.cache == nil { return 0 } m.mu.Lock() defer m.mu.Unlock() return m.ll.Len() }
go
func (m *ClientManager) Len() int { if m.cache == nil { return 0 } m.mu.Lock() defer m.mu.Unlock() return m.ll.Len() }
[ "func", "(", "m", "*", "ClientManager", ")", "Len", "(", ")", "int", "{", "if", "m", ".", "cache", "==", "nil", "{", "return", "0", "\n", "}", "\n", "m", ".", "mu", ".", "Lock", "(", ")", "\n", "defer", "m", ".", "mu", ".", "Unlock", "(", "...
// Len returns the current size of the ClientManager.
[ "Len", "returns", "the", "current", "size", "of", "the", "ClientManager", "." ]
d5157a5e6ef01fe1b953450a7a8a1bbe77e865c2
https://github.com/sideshow/apns2/blob/d5157a5e6ef01fe1b953450a7a8a1bbe77e865c2/client_manager.go#L122-L129
train
google/zoekt
gitindex/submodule.go
ParseGitModules
func ParseGitModules(content []byte) (map[string]*SubmoduleEntry, error) { dec := config.NewDecoder(bytes.NewBuffer(content)) cfg := &config.Config{} if err := dec.Decode(cfg); err != nil { return nil, err } result := map[string]*SubmoduleEntry{} for _, s := range cfg.Sections { if s.Name != "submodule" { continue } for _, ss := range s.Subsections { name := ss.Name e := &SubmoduleEntry{} for _, o := range ss.Options { switch o.Key { case "branch": e.Branch = o.Value case "path": e.Path = o.Value case "url": e.URL = o.Value } } result[name] = e } } return result, nil }
go
func ParseGitModules(content []byte) (map[string]*SubmoduleEntry, error) { dec := config.NewDecoder(bytes.NewBuffer(content)) cfg := &config.Config{} if err := dec.Decode(cfg); err != nil { return nil, err } result := map[string]*SubmoduleEntry{} for _, s := range cfg.Sections { if s.Name != "submodule" { continue } for _, ss := range s.Subsections { name := ss.Name e := &SubmoduleEntry{} for _, o := range ss.Options { switch o.Key { case "branch": e.Branch = o.Value case "path": e.Path = o.Value case "url": e.URL = o.Value } } result[name] = e } } return result, nil }
[ "func", "ParseGitModules", "(", "content", "[", "]", "byte", ")", "(", "map", "[", "string", "]", "*", "SubmoduleEntry", ",", "error", ")", "{", "dec", ":=", "config", ".", "NewDecoder", "(", "bytes", ".", "NewBuffer", "(", "content", ")", ")", "\n", ...
// ParseGitModules parses the contents of a .gitmodules file.
[ "ParseGitModules", "parses", "the", "contents", "of", "a", ".", "gitmodules", "file", "." ]
3493be98f11f3ca46cdb973a968f09f7cacc645d
https://github.com/google/zoekt/blob/3493be98f11f3ca46cdb973a968f09f7cacc645d/gitindex/submodule.go#L31-L64
train
google/zoekt
bits.go
caseFoldingEqualsRunes
func caseFoldingEqualsRunes(lower, mixed []byte) (int, bool) { matchTotal := 0 for len(lower) > 0 && len(mixed) > 0 { lr, lsz := utf8.DecodeRune(lower) lower = lower[lsz:] mr, msz := utf8.DecodeRune(mixed) mixed = mixed[msz:] matchTotal += msz if lr != unicode.ToLower(mr) { return 0, false } } return matchTotal, len(lower) == 0 }
go
func caseFoldingEqualsRunes(lower, mixed []byte) (int, bool) { matchTotal := 0 for len(lower) > 0 && len(mixed) > 0 { lr, lsz := utf8.DecodeRune(lower) lower = lower[lsz:] mr, msz := utf8.DecodeRune(mixed) mixed = mixed[msz:] matchTotal += msz if lr != unicode.ToLower(mr) { return 0, false } } return matchTotal, len(lower) == 0 }
[ "func", "caseFoldingEqualsRunes", "(", "lower", ",", "mixed", "[", "]", "byte", ")", "(", "int", ",", "bool", ")", "{", "matchTotal", ":=", "0", "\n", "for", "len", "(", "lower", ")", ">", "0", "&&", "len", "(", "mixed", ")", ">", "0", "{", "lr",...
// compare 'lower' and 'mixed', where lower is the needle. 'mixed' may // be larger than 'lower'. Returns whether there was a match, and if // yes, the byte size of the match.
[ "compare", "lower", "and", "mixed", "where", "lower", "is", "the", "needle", ".", "mixed", "may", "be", "larger", "than", "lower", ".", "Returns", "whether", "there", "was", "a", "match", "and", "if", "yes", "the", "byte", "size", "of", "the", "match", ...
3493be98f11f3ca46cdb973a968f09f7cacc645d
https://github.com/google/zoekt/blob/3493be98f11f3ca46cdb973a968f09f7cacc645d/bits.go#L59-L75
train
google/zoekt
query/parse.go
parseStringLiteral
func parseStringLiteral(in []byte) (lit []byte, n int, err error) { left := in[1:] found := false loop: for len(left) > 0 { c := left[0] left = left[1:] switch c { case '"': found = true break loop case '\\': // TODO - other escape sequences. if len(left) == 0 { return nil, 0, fmt.Errorf("query: missing char after \\") } c = left[0] left = left[1:] lit = append(lit, c) default: lit = append(lit, c) } } if !found { return nil, 0, fmt.Errorf("query: unterminated quoted string") } return lit, len(in) - len(left), nil }
go
func parseStringLiteral(in []byte) (lit []byte, n int, err error) { left := in[1:] found := false loop: for len(left) > 0 { c := left[0] left = left[1:] switch c { case '"': found = true break loop case '\\': // TODO - other escape sequences. if len(left) == 0 { return nil, 0, fmt.Errorf("query: missing char after \\") } c = left[0] left = left[1:] lit = append(lit, c) default: lit = append(lit, c) } } if !found { return nil, 0, fmt.Errorf("query: unterminated quoted string") } return lit, len(in) - len(left), nil }
[ "func", "parseStringLiteral", "(", "in", "[", "]", "byte", ")", "(", "lit", "[", "]", "byte", ",", "n", "int", ",", "err", "error", ")", "{", "left", ":=", "in", "[", "1", ":", "]", "\n", "found", ":=", "false", "\n\n", "loop", ":", "for", "len...
// parseStringLiteral parses a string literal, consumes the starting // quote too.
[ "parseStringLiteral", "parses", "a", "string", "literal", "consumes", "the", "starting", "quote", "too", "." ]
3493be98f11f3ca46cdb973a968f09f7cacc645d
https://github.com/google/zoekt/blob/3493be98f11f3ca46cdb973a968f09f7cacc645d/query/parse.go#L37-L66
train
google/zoekt
query/parse.go
Parse
func Parse(qStr string) (Q, error) { b := []byte(qStr) qs, _, err := parseExprList(b) if err != nil { return nil, err } q, err := parseOperators(qs) if err != nil { return nil, err } return Simplify(q), nil }
go
func Parse(qStr string) (Q, error) { b := []byte(qStr) qs, _, err := parseExprList(b) if err != nil { return nil, err } q, err := parseOperators(qs) if err != nil { return nil, err } return Simplify(q), nil }
[ "func", "Parse", "(", "qStr", "string", ")", "(", "Q", ",", "error", ")", "{", "b", ":=", "[", "]", "byte", "(", "qStr", ")", "\n\n", "qs", ",", "_", ",", "err", ":=", "parseExprList", "(", "b", ")", "\n", "if", "err", "!=", "nil", "{", "retu...
// Parse parses a string into a query.
[ "Parse", "parses", "a", "string", "into", "a", "query", "." ]
3493be98f11f3ca46cdb973a968f09f7cacc645d
https://github.com/google/zoekt/blob/3493be98f11f3ca46cdb973a968f09f7cacc645d/query/parse.go#L81-L95
train
google/zoekt
query/parse.go
regexpQuery
func regexpQuery(text string, content, file bool) (Q, error) { var expr Q r, err := syntax.Parse(text, syntax.ClassNL|syntax.PerlX|syntax.UnicodeGroups) if err != nil { return nil, err } if r.Op == syntax.OpLiteral { expr = &Substring{ Pattern: string(r.Rune), FileName: file, Content: content, } } else { expr = &Regexp{ Regexp: r, FileName: file, Content: content, } } return expr, nil }
go
func regexpQuery(text string, content, file bool) (Q, error) { var expr Q r, err := syntax.Parse(text, syntax.ClassNL|syntax.PerlX|syntax.UnicodeGroups) if err != nil { return nil, err } if r.Op == syntax.OpLiteral { expr = &Substring{ Pattern: string(r.Rune), FileName: file, Content: content, } } else { expr = &Regexp{ Regexp: r, FileName: file, Content: content, } } return expr, nil }
[ "func", "regexpQuery", "(", "text", "string", ",", "content", ",", "file", "bool", ")", "(", "Q", ",", "error", ")", "{", "var", "expr", "Q", "\n\n", "r", ",", "err", ":=", "syntax", ".", "Parse", "(", "text", ",", "syntax", ".", "ClassNL", "|", ...
// regexpQuery parses an atom into either a regular expression, or a // simple substring atom.
[ "regexpQuery", "parses", "an", "atom", "into", "either", "a", "regular", "expression", "or", "a", "simple", "substring", "atom", "." ]
3493be98f11f3ca46cdb973a968f09f7cacc645d
https://github.com/google/zoekt/blob/3493be98f11f3ca46cdb973a968f09f7cacc645d/query/parse.go#L197-L220
train
google/zoekt
query/parse.go
parseOperators
func parseOperators(in []Q) (Q, error) { top := &Or{} cur := &And{} seenOr := false for _, q := range in { if _, ok := q.(*orOperator); ok { seenOr = true if len(cur.Children) == 0 { return nil, fmt.Errorf("query: OR operator should have operand") } top.Children = append(top.Children, cur) cur = &And{} } else { cur.Children = append(cur.Children, q) } } if seenOr && len(cur.Children) == 0 { return nil, fmt.Errorf("query: OR operator should have operand") } top.Children = append(top.Children, cur) return top, nil }
go
func parseOperators(in []Q) (Q, error) { top := &Or{} cur := &And{} seenOr := false for _, q := range in { if _, ok := q.(*orOperator); ok { seenOr = true if len(cur.Children) == 0 { return nil, fmt.Errorf("query: OR operator should have operand") } top.Children = append(top.Children, cur) cur = &And{} } else { cur.Children = append(cur.Children, q) } } if seenOr && len(cur.Children) == 0 { return nil, fmt.Errorf("query: OR operator should have operand") } top.Children = append(top.Children, cur) return top, nil }
[ "func", "parseOperators", "(", "in", "[", "]", "Q", ")", "(", "Q", ",", "error", ")", "{", "top", ":=", "&", "Or", "{", "}", "\n", "cur", ":=", "&", "And", "{", "}", "\n\n", "seenOr", ":=", "false", "\n", "for", "_", ",", "q", ":=", "range", ...
// parseOperators interprets the orOperator in a list of queries.
[ "parseOperators", "interprets", "the", "orOperator", "in", "a", "list", "of", "queries", "." ]
3493be98f11f3ca46cdb973a968f09f7cacc645d
https://github.com/google/zoekt/blob/3493be98f11f3ca46cdb973a968f09f7cacc645d/query/parse.go#L223-L246
train
google/zoekt
query/parse.go
parseExprList
func parseExprList(in []byte) ([]Q, int, error) { b := in[:] var qs []Q for len(b) > 0 { for len(b) > 0 && isSpace(b[0]) { b = b[1:] } tok, _ := nextToken(b) if tok != nil && tok.Type == tokParenClose { break } else if tok != nil && tok.Type == tokOr { qs = append(qs, &orOperator{}) b = b[len(tok.Input):] continue } q, n, err := parseExpr(b) if err != nil { return nil, 0, err } if q == nil { // eof or a ')' break } qs = append(qs, q) b = b[n:] } setCase := "auto" newQS := qs[:0] for _, q := range qs { if sc, ok := q.(*caseQ); ok { setCase = sc.Flavor } else { newQS = append(newQS, q) } } qs = mapQueryList(newQS, func(q Q) Q { if sc, ok := q.(setCaser); ok { sc.setCase(setCase) } return q }) return qs, len(in) - len(b), nil }
go
func parseExprList(in []byte) ([]Q, int, error) { b := in[:] var qs []Q for len(b) > 0 { for len(b) > 0 && isSpace(b[0]) { b = b[1:] } tok, _ := nextToken(b) if tok != nil && tok.Type == tokParenClose { break } else if tok != nil && tok.Type == tokOr { qs = append(qs, &orOperator{}) b = b[len(tok.Input):] continue } q, n, err := parseExpr(b) if err != nil { return nil, 0, err } if q == nil { // eof or a ')' break } qs = append(qs, q) b = b[n:] } setCase := "auto" newQS := qs[:0] for _, q := range qs { if sc, ok := q.(*caseQ); ok { setCase = sc.Flavor } else { newQS = append(newQS, q) } } qs = mapQueryList(newQS, func(q Q) Q { if sc, ok := q.(setCaser); ok { sc.setCase(setCase) } return q }) return qs, len(in) - len(b), nil }
[ "func", "parseExprList", "(", "in", "[", "]", "byte", ")", "(", "[", "]", "Q", ",", "int", ",", "error", ")", "{", "b", ":=", "in", "[", ":", "]", "\n", "var", "qs", "[", "]", "Q", "\n", "for", "len", "(", "b", ")", ">", "0", "{", "for", ...
// parseExprList parses a list of query expressions. It is the // workhorse of the Parse function.
[ "parseExprList", "parses", "a", "list", "of", "query", "expressions", ".", "It", "is", "the", "workhorse", "of", "the", "Parse", "function", "." ]
3493be98f11f3ca46cdb973a968f09f7cacc645d
https://github.com/google/zoekt/blob/3493be98f11f3ca46cdb973a968f09f7cacc645d/query/parse.go#L250-L295
train
google/zoekt
query/parse.go
nextToken
func nextToken(in []byte) (*token, error) { left := in[:] parenCount := 0 var cur token if len(left) == 0 { return nil, nil } if left[0] == '-' { return &token{ Type: tokNegate, Text: []byte{'-'}, Input: in[:1], }, nil } foundSpace := false loop: for len(left) > 0 { c := left[0] switch c { case '(': parenCount++ cur.Text = append(cur.Text, c) left = left[1:] case ')': if parenCount == 0 { if len(cur.Text) == 0 { cur.Text = []byte{')'} left = left[1:] } break loop } cur.Text = append(cur.Text, c) left = left[1:] parenCount-- case '"': t, n, err := parseStringLiteral(left) if err != nil { return nil, err } cur.Text = append(cur.Text, t...) left = left[n:] case '\\': left = left[1:] if len(left) == 0 { return nil, fmt.Errorf("query: lone \\ at end") } c := left[0] cur.Text = append(cur.Text, '\\', c) left = left[1:] case ' ', '\n', '\t': if parenCount > 0 { foundSpace = true } break loop default: cur.Text = append(cur.Text, c) left = left[1:] } } if len(cur.Text) == 0 { return nil, nil } if foundSpace && cur.Text[0] == '(' { cur.Text = cur.Text[:1] cur.Input = in[:1] } else { cur.Input = in[:len(in)-len(left)] } cur.setType() return &cur, nil }
go
func nextToken(in []byte) (*token, error) { left := in[:] parenCount := 0 var cur token if len(left) == 0 { return nil, nil } if left[0] == '-' { return &token{ Type: tokNegate, Text: []byte{'-'}, Input: in[:1], }, nil } foundSpace := false loop: for len(left) > 0 { c := left[0] switch c { case '(': parenCount++ cur.Text = append(cur.Text, c) left = left[1:] case ')': if parenCount == 0 { if len(cur.Text) == 0 { cur.Text = []byte{')'} left = left[1:] } break loop } cur.Text = append(cur.Text, c) left = left[1:] parenCount-- case '"': t, n, err := parseStringLiteral(left) if err != nil { return nil, err } cur.Text = append(cur.Text, t...) left = left[n:] case '\\': left = left[1:] if len(left) == 0 { return nil, fmt.Errorf("query: lone \\ at end") } c := left[0] cur.Text = append(cur.Text, '\\', c) left = left[1:] case ' ', '\n', '\t': if parenCount > 0 { foundSpace = true } break loop default: cur.Text = append(cur.Text, c) left = left[1:] } } if len(cur.Text) == 0 { return nil, nil } if foundSpace && cur.Text[0] == '(' { cur.Text = cur.Text[:1] cur.Input = in[:1] } else { cur.Input = in[:len(in)-len(left)] } cur.setType() return &cur, nil }
[ "func", "nextToken", "(", "in", "[", "]", "byte", ")", "(", "*", "token", ",", "error", ")", "{", "left", ":=", "in", "[", ":", "]", "\n", "parenCount", ":=", "0", "\n", "var", "cur", "token", "\n", "if", "len", "(", "left", ")", "==", "0", "...
// nextToken returns the next token from the given input.
[ "nextToken", "returns", "the", "next", "token", "from", "the", "given", "input", "." ]
3493be98f11f3ca46cdb973a968f09f7cacc645d
https://github.com/google/zoekt/blob/3493be98f11f3ca46cdb973a968f09f7cacc645d/query/parse.go#L393-L471
train
google/zoekt
gitindex/repocache.go
NewRepoCache
func NewRepoCache(dir string) *RepoCache { return &RepoCache{ baseDir: dir, repos: make(map[string]*git.Repository), } }
go
func NewRepoCache(dir string) *RepoCache { return &RepoCache{ baseDir: dir, repos: make(map[string]*git.Repository), } }
[ "func", "NewRepoCache", "(", "dir", "string", ")", "*", "RepoCache", "{", "return", "&", "RepoCache", "{", "baseDir", ":", "dir", ",", "repos", ":", "make", "(", "map", "[", "string", "]", "*", "git", ".", "Repository", ")", ",", "}", "\n", "}" ]
// NewRepoCache creates a new RepoCache rooted at the given directory.
[ "NewRepoCache", "creates", "a", "new", "RepoCache", "rooted", "at", "the", "given", "directory", "." ]
3493be98f11f3ca46cdb973a968f09f7cacc645d
https://github.com/google/zoekt/blob/3493be98f11f3ca46cdb973a968f09f7cacc645d/gitindex/repocache.go#L37-L42
train
google/zoekt
gitindex/repocache.go
Path
func Path(baseDir string, name string) string { key := repoKeyStr(name) return filepath.Join(baseDir, key) }
go
func Path(baseDir string, name string) string { key := repoKeyStr(name) return filepath.Join(baseDir, key) }
[ "func", "Path", "(", "baseDir", "string", ",", "name", "string", ")", "string", "{", "key", ":=", "repoKeyStr", "(", "name", ")", "\n", "return", "filepath", ".", "Join", "(", "baseDir", ",", "key", ")", "\n", "}" ]
// Path returns the absolute path of the bare repository.
[ "Path", "returns", "the", "absolute", "path", "of", "the", "bare", "repository", "." ]
3493be98f11f3ca46cdb973a968f09f7cacc645d
https://github.com/google/zoekt/blob/3493be98f11f3ca46cdb973a968f09f7cacc645d/gitindex/repocache.go#L56-L59
train
google/zoekt
gitindex/repocache.go
Open
func (rc *RepoCache) Open(u *url.URL) (*git.Repository, error) { dir := rc.Path(u) rc.reposMu.Lock() defer rc.reposMu.Unlock() key := repoKey(u) r := rc.repos[key] if r != nil { return r, nil } repo, err := git.PlainOpen(dir) if err == nil { rc.repos[key] = repo } return repo, err }
go
func (rc *RepoCache) Open(u *url.URL) (*git.Repository, error) { dir := rc.Path(u) rc.reposMu.Lock() defer rc.reposMu.Unlock() key := repoKey(u) r := rc.repos[key] if r != nil { return r, nil } repo, err := git.PlainOpen(dir) if err == nil { rc.repos[key] = repo } return repo, err }
[ "func", "(", "rc", "*", "RepoCache", ")", "Open", "(", "u", "*", "url", ".", "URL", ")", "(", "*", "git", ".", "Repository", ",", "error", ")", "{", "dir", ":=", "rc", ".", "Path", "(", "u", ")", "\n", "rc", ".", "reposMu", ".", "Lock", "(", ...
// Open opens a git repository. The cache retains a pointer to the // repository.
[ "Open", "opens", "a", "git", "repository", ".", "The", "cache", "retains", "a", "pointer", "to", "the", "repository", "." ]
3493be98f11f3ca46cdb973a968f09f7cacc645d
https://github.com/google/zoekt/blob/3493be98f11f3ca46cdb973a968f09f7cacc645d/gitindex/repocache.go#L68-L84
train
google/zoekt
gitindex/repocache.go
ListRepos
func ListRepos(baseDir string, u *url.URL) ([]string, error) { key := filepath.Join(u.Host, u.Path) var paths []string walk := func(path string, info os.FileInfo, err error) error { if err != nil { return err } if !info.IsDir() { return nil } if strings.HasSuffix(path, ".git") && !strings.HasSuffix(path, "/.git") { _, err := git.PlainOpen(path) if err == nil { p, err := filepath.Rel(baseDir, path) if err == nil { paths = append(paths, p) } } return filepath.SkipDir } return nil } if err := filepath.Walk(filepath.Join(baseDir, key), walk); err != nil { return nil, err } return paths, nil }
go
func ListRepos(baseDir string, u *url.URL) ([]string, error) { key := filepath.Join(u.Host, u.Path) var paths []string walk := func(path string, info os.FileInfo, err error) error { if err != nil { return err } if !info.IsDir() { return nil } if strings.HasSuffix(path, ".git") && !strings.HasSuffix(path, "/.git") { _, err := git.PlainOpen(path) if err == nil { p, err := filepath.Rel(baseDir, path) if err == nil { paths = append(paths, p) } } return filepath.SkipDir } return nil } if err := filepath.Walk(filepath.Join(baseDir, key), walk); err != nil { return nil, err } return paths, nil }
[ "func", "ListRepos", "(", "baseDir", "string", ",", "u", "*", "url", ".", "URL", ")", "(", "[", "]", "string", ",", "error", ")", "{", "key", ":=", "filepath", ".", "Join", "(", "u", ".", "Host", ",", "u", ".", "Path", ")", "\n\n", "var", "path...
// ListRepos returns paths to repos on disk that start with the given // URL prefix. The paths are relative to baseDir, and typically // include a ".git" suffix.
[ "ListRepos", "returns", "paths", "to", "repos", "on", "disk", "that", "start", "with", "the", "given", "URL", "prefix", ".", "The", "paths", "are", "relative", "to", "baseDir", "and", "typically", "include", "a", ".", "git", "suffix", "." ]
3493be98f11f3ca46cdb973a968f09f7cacc645d
https://github.com/google/zoekt/blob/3493be98f11f3ca46cdb973a968f09f7cacc645d/gitindex/repocache.go#L89-L117
train
google/zoekt
cmd/zoekt-mirror-gitiles/cgit.go
getCGitRepos
func getCGitRepos(u *url.URL, filter func(string) bool) (map[string]*crawlTarget, error) { c, err := normalizedGet(u) if err != nil { return nil, err } pages := map[string]*crawlTarget{} for _, m := range cgitRepoEntryRE.FindAllSubmatch(c, -1) { nm := strings.TrimSuffix(string(m[1]), ".git") if !filter(nm) { continue } relUrl := string(m[2]) u, err := u.Parse(relUrl) if err != nil { log.Printf("ignoring u.Parse(%q): %v", relUrl, err) continue } pages[nm] = &crawlTarget{ webURL: u.String(), webURLType: "cgit", } } // TODO - parallel? for _, target := range pages { u, _ := url.Parse(target.webURL) c, err := cgitCloneURL(u) if err != nil { log.Printf("ignoring cgitCloneURL(%s): %v", u, c) continue } target.cloneURL = c.String() } return pages, nil }
go
func getCGitRepos(u *url.URL, filter func(string) bool) (map[string]*crawlTarget, error) { c, err := normalizedGet(u) if err != nil { return nil, err } pages := map[string]*crawlTarget{} for _, m := range cgitRepoEntryRE.FindAllSubmatch(c, -1) { nm := strings.TrimSuffix(string(m[1]), ".git") if !filter(nm) { continue } relUrl := string(m[2]) u, err := u.Parse(relUrl) if err != nil { log.Printf("ignoring u.Parse(%q): %v", relUrl, err) continue } pages[nm] = &crawlTarget{ webURL: u.String(), webURLType: "cgit", } } // TODO - parallel? for _, target := range pages { u, _ := url.Parse(target.webURL) c, err := cgitCloneURL(u) if err != nil { log.Printf("ignoring cgitCloneURL(%s): %v", u, c) continue } target.cloneURL = c.String() } return pages, nil }
[ "func", "getCGitRepos", "(", "u", "*", "url", ".", "URL", ",", "filter", "func", "(", "string", ")", "bool", ")", "(", "map", "[", "string", "]", "*", "crawlTarget", ",", "error", ")", "{", "c", ",", "err", ":=", "normalizedGet", "(", "u", ")", "...
// getCGitRepos finds repo names from the CGit index page hosted at // URL `u`.
[ "getCGitRepos", "finds", "repo", "names", "from", "the", "CGit", "index", "page", "hosted", "at", "URL", "u", "." ]
3493be98f11f3ca46cdb973a968f09f7cacc645d
https://github.com/google/zoekt/blob/3493be98f11f3ca46cdb973a968f09f7cacc645d/cmd/zoekt-mirror-gitiles/cgit.go#L54-L93
train
google/zoekt
indexfile_linux.go
NewIndexFile
func NewIndexFile(f *os.File) (IndexFile, error) { defer f.Close() fi, err := f.Stat() if err != nil { return nil, err } sz := fi.Size() if sz >= maxUInt32 { return nil, fmt.Errorf("file %s too large: %d", f.Name(), sz) } r := &mmapedIndexFile{ name: f.Name(), size: uint32(sz), } rounded := (r.size + 4095) &^ 4095 r.data, err = syscall.Mmap(int(f.Fd()), 0, int(rounded), syscall.PROT_READ, syscall.MAP_SHARED) if err != nil { return nil, err } return r, err }
go
func NewIndexFile(f *os.File) (IndexFile, error) { defer f.Close() fi, err := f.Stat() if err != nil { return nil, err } sz := fi.Size() if sz >= maxUInt32 { return nil, fmt.Errorf("file %s too large: %d", f.Name(), sz) } r := &mmapedIndexFile{ name: f.Name(), size: uint32(sz), } rounded := (r.size + 4095) &^ 4095 r.data, err = syscall.Mmap(int(f.Fd()), 0, int(rounded), syscall.PROT_READ, syscall.MAP_SHARED) if err != nil { return nil, err } return r, err }
[ "func", "NewIndexFile", "(", "f", "*", "os", ".", "File", ")", "(", "IndexFile", ",", "error", ")", "{", "defer", "f", ".", "Close", "(", ")", "\n\n", "fi", ",", "err", ":=", "f", ".", "Stat", "(", ")", "\n", "if", "err", "!=", "nil", "{", "r...
// NewIndexFile returns a new index file. The index file takes // ownership of the passed in file, and may close it.
[ "NewIndexFile", "returns", "a", "new", "index", "file", ".", "The", "index", "file", "takes", "ownership", "of", "the", "passed", "in", "file", "and", "may", "close", "it", "." ]
3493be98f11f3ca46cdb973a968f09f7cacc645d
https://github.com/google/zoekt/blob/3493be98f11f3ca46cdb973a968f09f7cacc645d/indexfile_linux.go#L50-L74
train
google/zoekt
gitindex/filter.go
Include
func (f *Filter) Include(name string) bool { if f.inc != nil { if !f.inc.MatchString(name) { return false } } if f.exc != nil { if f.exc.MatchString(name) { return false } } return true }
go
func (f *Filter) Include(name string) bool { if f.inc != nil { if !f.inc.MatchString(name) { return false } } if f.exc != nil { if f.exc.MatchString(name) { return false } } return true }
[ "func", "(", "f", "*", "Filter", ")", "Include", "(", "name", "string", ")", "bool", "{", "if", "f", ".", "inc", "!=", "nil", "{", "if", "!", "f", ".", "inc", ".", "MatchString", "(", "name", ")", "{", "return", "false", "\n", "}", "\n", "}", ...
// Include returns true if the name passes the filter.
[ "Include", "returns", "true", "if", "the", "name", "passes", "the", "filter", "." ]
3493be98f11f3ca46cdb973a968f09f7cacc645d
https://github.com/google/zoekt/blob/3493be98f11f3ca46cdb973a968f09f7cacc645d/gitindex/filter.go#L25-L37
train
google/zoekt
gitindex/filter.go
NewFilter
func NewFilter(includeRegex, excludeRegex string) (*Filter, error) { f := &Filter{} var err error if includeRegex != "" { f.inc, err = regexp.Compile(includeRegex) if err != nil { return nil, err } } if excludeRegex != "" { f.exc, err = regexp.Compile(excludeRegex) if err != nil { return nil, err } } return f, nil }
go
func NewFilter(includeRegex, excludeRegex string) (*Filter, error) { f := &Filter{} var err error if includeRegex != "" { f.inc, err = regexp.Compile(includeRegex) if err != nil { return nil, err } } if excludeRegex != "" { f.exc, err = regexp.Compile(excludeRegex) if err != nil { return nil, err } } return f, nil }
[ "func", "NewFilter", "(", "includeRegex", ",", "excludeRegex", "string", ")", "(", "*", "Filter", ",", "error", ")", "{", "f", ":=", "&", "Filter", "{", "}", "\n", "var", "err", "error", "\n", "if", "includeRegex", "!=", "\"", "\"", "{", "f", ".", ...
// NewFilter creates a new filter.
[ "NewFilter", "creates", "a", "new", "filter", "." ]
3493be98f11f3ca46cdb973a968f09f7cacc645d
https://github.com/google/zoekt/blob/3493be98f11f3ca46cdb973a968f09f7cacc645d/gitindex/filter.go#L40-L58
train
google/zoekt
matchiter.go
matchContent
func (m *candidateMatch) matchContent(content []byte) bool { if m.caseSensitive { comp := bytes.Equal(m.substrBytes, content[m.byteOffset:m.byteOffset+uint32(len(m.substrBytes))]) m.byteMatchSz = uint32(len(m.substrBytes)) return comp } else { // It is tempting to try a simple ASCII based // comparison if possible, but we need more // information. Simple ASCII chars have unicode upper // case variants (the ASCII 'k' has the Kelvin symbol // as upper case variant). We can only degrade to // ASCII if we are sure that both the corpus and the // query is ASCII only sz, ok := caseFoldingEqualsRunes(m.substrLowered, content[m.byteOffset:]) m.byteMatchSz = uint32(sz) return ok } }
go
func (m *candidateMatch) matchContent(content []byte) bool { if m.caseSensitive { comp := bytes.Equal(m.substrBytes, content[m.byteOffset:m.byteOffset+uint32(len(m.substrBytes))]) m.byteMatchSz = uint32(len(m.substrBytes)) return comp } else { // It is tempting to try a simple ASCII based // comparison if possible, but we need more // information. Simple ASCII chars have unicode upper // case variants (the ASCII 'k' has the Kelvin symbol // as upper case variant). We can only degrade to // ASCII if we are sure that both the corpus and the // query is ASCII only sz, ok := caseFoldingEqualsRunes(m.substrLowered, content[m.byteOffset:]) m.byteMatchSz = uint32(sz) return ok } }
[ "func", "(", "m", "*", "candidateMatch", ")", "matchContent", "(", "content", "[", "]", "byte", ")", "bool", "{", "if", "m", ".", "caseSensitive", "{", "comp", ":=", "bytes", ".", "Equal", "(", "m", ".", "substrBytes", ",", "content", "[", "m", ".", ...
// Matches content against the substring, and populates byteMatchSz on success
[ "Matches", "content", "against", "the", "substring", "and", "populates", "byteMatchSz", "on", "success" ]
3493be98f11f3ca46cdb973a968f09f7cacc645d
https://github.com/google/zoekt/blob/3493be98f11f3ca46cdb973a968f09f7cacc645d/matchiter.go#L43-L61
train
google/zoekt
eval.go
gatherBranches
func (d *indexData) gatherBranches(docID uint32, mt matchTree, known map[matchTree]bool) []string { foundBranchQuery := false var branches []string visitMatches(mt, known, func(mt matchTree) { bq, ok := mt.(*branchQueryMatchTree) if ok { foundBranchQuery = true branches = append(branches, d.branchNames[uint(bq.mask)]) } }) if !foundBranchQuery { mask := d.fileBranchMasks[docID] id := uint32(1) for mask != 0 { if mask&0x1 != 0 { branches = append(branches, d.branchNames[uint(id)]) } id <<= 1 mask >>= 1 } } return branches }
go
func (d *indexData) gatherBranches(docID uint32, mt matchTree, known map[matchTree]bool) []string { foundBranchQuery := false var branches []string visitMatches(mt, known, func(mt matchTree) { bq, ok := mt.(*branchQueryMatchTree) if ok { foundBranchQuery = true branches = append(branches, d.branchNames[uint(bq.mask)]) } }) if !foundBranchQuery { mask := d.fileBranchMasks[docID] id := uint32(1) for mask != 0 { if mask&0x1 != 0 { branches = append(branches, d.branchNames[uint(id)]) } id <<= 1 mask >>= 1 } } return branches }
[ "func", "(", "d", "*", "indexData", ")", "gatherBranches", "(", "docID", "uint32", ",", "mt", "matchTree", ",", "known", "map", "[", "matchTree", "]", "bool", ")", "[", "]", "string", "{", "foundBranchQuery", ":=", "false", "\n", "var", "branches", "[", ...
// gatherBranches returns a list of branch names.
[ "gatherBranches", "returns", "a", "list", "of", "branch", "names", "." ]
3493be98f11f3ca46cdb973a968f09f7cacc645d
https://github.com/google/zoekt/blob/3493be98f11f3ca46cdb973a968f09f7cacc645d/eval.go#L366-L391
train
google/zoekt
gitindex/clone.go
CloneRepo
func CloneRepo(destDir, name, cloneURL string, settings map[string]string) (string, error) { parent := filepath.Join(destDir, filepath.Dir(name)) if err := os.MkdirAll(parent, 0755); err != nil { return "", err } repoDest := filepath.Join(parent, filepath.Base(name)+".git") if _, err := os.Lstat(repoDest); err == nil { return "", nil } var keys []string for k := range settings { keys = append(keys, k) } sort.Strings(keys) var config []string for _, k := range keys { if settings[k] != "" { config = append(config, "--config", k+"="+settings[k]) } } cmd := exec.Command( "git", "clone", "--bare", "--verbose", "--progress", // Only fetch branch heads, and ignore note branches. "--config", "remote.origin.fetch=+refs/heads/*:refs/heads/*") cmd.Args = append(cmd.Args, config...) cmd.Args = append(cmd.Args, cloneURL, repoDest) // Prevent prompting cmd.Stdin = &bytes.Buffer{} log.Println("running:", cmd.Args) if err := cmd.Run(); err != nil { return "", err } return repoDest, nil }
go
func CloneRepo(destDir, name, cloneURL string, settings map[string]string) (string, error) { parent := filepath.Join(destDir, filepath.Dir(name)) if err := os.MkdirAll(parent, 0755); err != nil { return "", err } repoDest := filepath.Join(parent, filepath.Base(name)+".git") if _, err := os.Lstat(repoDest); err == nil { return "", nil } var keys []string for k := range settings { keys = append(keys, k) } sort.Strings(keys) var config []string for _, k := range keys { if settings[k] != "" { config = append(config, "--config", k+"="+settings[k]) } } cmd := exec.Command( "git", "clone", "--bare", "--verbose", "--progress", // Only fetch branch heads, and ignore note branches. "--config", "remote.origin.fetch=+refs/heads/*:refs/heads/*") cmd.Args = append(cmd.Args, config...) cmd.Args = append(cmd.Args, cloneURL, repoDest) // Prevent prompting cmd.Stdin = &bytes.Buffer{} log.Println("running:", cmd.Args) if err := cmd.Run(); err != nil { return "", err } return repoDest, nil }
[ "func", "CloneRepo", "(", "destDir", ",", "name", ",", "cloneURL", "string", ",", "settings", "map", "[", "string", "]", "string", ")", "(", "string", ",", "error", ")", "{", "parent", ":=", "filepath", ".", "Join", "(", "destDir", ",", "filepath", "."...
// CloneRepo clones one repository, adding the given config // settings. It returns the bare repo directory. The `name` argument // determines where the repo is stored relative to `destDir`. Returns // the directory of the repository.
[ "CloneRepo", "clones", "one", "repository", "adding", "the", "given", "config", "settings", ".", "It", "returns", "the", "bare", "repo", "directory", ".", "The", "name", "argument", "determines", "where", "the", "repo", "is", "stored", "relative", "to", "destD...
3493be98f11f3ca46cdb973a968f09f7cacc645d
https://github.com/google/zoekt/blob/3493be98f11f3ca46cdb973a968f09f7cacc645d/gitindex/clone.go#L30-L68
train
google/zoekt
build/builder.go
HashOptions
func (o *Options) HashOptions() string { hasher := sha1.New() hasher.Write([]byte(o.CTags)) hasher.Write([]byte(fmt.Sprintf("%t", o.CTagsMustSucceed))) hasher.Write([]byte(fmt.Sprintf("%d", o.SizeMax))) hasher.Write([]byte(fmt.Sprintf("%q", o.LargeFiles))) return fmt.Sprintf("%x", hasher.Sum(nil)) }
go
func (o *Options) HashOptions() string { hasher := sha1.New() hasher.Write([]byte(o.CTags)) hasher.Write([]byte(fmt.Sprintf("%t", o.CTagsMustSucceed))) hasher.Write([]byte(fmt.Sprintf("%d", o.SizeMax))) hasher.Write([]byte(fmt.Sprintf("%q", o.LargeFiles))) return fmt.Sprintf("%x", hasher.Sum(nil)) }
[ "func", "(", "o", "*", "Options", ")", "HashOptions", "(", ")", "string", "{", "hasher", ":=", "sha1", ".", "New", "(", ")", "\n\n", "hasher", ".", "Write", "(", "[", "]", "byte", "(", "o", ".", "CTags", ")", ")", "\n", "hasher", ".", "Write", ...
// HashOptions creates a hash of the options that affect an index.
[ "HashOptions", "creates", "a", "hash", "of", "the", "options", "that", "affect", "an", "index", "." ]
3493be98f11f3ca46cdb973a968f09f7cacc645d
https://github.com/google/zoekt/blob/3493be98f11f3ca46cdb973a968f09f7cacc645d/build/builder.go#L84-L93
train
google/zoekt
build/builder.go
SetDefaults
func (o *Options) SetDefaults() { if o.CTags == "" { ctags, err := exec.LookPath("universal-ctags") if err == nil { o.CTags = ctags } } if o.CTags == "" { ctags, err := exec.LookPath("ctags-exuberant") if err == nil { o.CTags = ctags } } if o.Parallelism == 0 { o.Parallelism = 1 } if o.SizeMax == 0 { o.SizeMax = 128 << 10 } if o.ShardMax == 0 { o.ShardMax = 128 << 20 } if o.RepositoryDescription.Name == "" && o.RepositoryDescription.URL != "" { parsed, _ := url.Parse(o.RepositoryDescription.URL) if parsed != nil { o.RepositoryDescription.Name = filepath.Join(parsed.Host, parsed.Path) } } }
go
func (o *Options) SetDefaults() { if o.CTags == "" { ctags, err := exec.LookPath("universal-ctags") if err == nil { o.CTags = ctags } } if o.CTags == "" { ctags, err := exec.LookPath("ctags-exuberant") if err == nil { o.CTags = ctags } } if o.Parallelism == 0 { o.Parallelism = 1 } if o.SizeMax == 0 { o.SizeMax = 128 << 10 } if o.ShardMax == 0 { o.ShardMax = 128 << 20 } if o.RepositoryDescription.Name == "" && o.RepositoryDescription.URL != "" { parsed, _ := url.Parse(o.RepositoryDescription.URL) if parsed != nil { o.RepositoryDescription.Name = filepath.Join(parsed.Host, parsed.Path) } } }
[ "func", "(", "o", "*", "Options", ")", "SetDefaults", "(", ")", "{", "if", "o", ".", "CTags", "==", "\"", "\"", "{", "ctags", ",", "err", ":=", "exec", ".", "LookPath", "(", "\"", "\"", ")", "\n", "if", "err", "==", "nil", "{", "o", ".", "CTa...
// SetDefaults sets reasonable default options.
[ "SetDefaults", "sets", "reasonable", "default", "options", "." ]
3493be98f11f3ca46cdb973a968f09f7cacc645d
https://github.com/google/zoekt/blob/3493be98f11f3ca46cdb973a968f09f7cacc645d/build/builder.go#L123-L153
train
google/zoekt
build/builder.go
shardName
func (o *Options) shardName(n int) string { abs := url.QueryEscape(o.RepositoryDescription.Name) if len(abs) > 200 { abs = abs[:200] + hashString(abs)[:8] } return filepath.Join(o.IndexDir, fmt.Sprintf("%s_v%d.%05d.zoekt", abs, zoekt.IndexFormatVersion, n)) }
go
func (o *Options) shardName(n int) string { abs := url.QueryEscape(o.RepositoryDescription.Name) if len(abs) > 200 { abs = abs[:200] + hashString(abs)[:8] } return filepath.Join(o.IndexDir, fmt.Sprintf("%s_v%d.%05d.zoekt", abs, zoekt.IndexFormatVersion, n)) }
[ "func", "(", "o", "*", "Options", ")", "shardName", "(", "n", "int", ")", "string", "{", "abs", ":=", "url", ".", "QueryEscape", "(", "o", ".", "RepositoryDescription", ".", "Name", ")", "\n", "if", "len", "(", "abs", ")", ">", "200", "{", "abs", ...
// ShardName returns the name the given index shard.
[ "ShardName", "returns", "the", "name", "the", "given", "index", "shard", "." ]
3493be98f11f3ca46cdb973a968f09f7cacc645d
https://github.com/google/zoekt/blob/3493be98f11f3ca46cdb973a968f09f7cacc645d/build/builder.go#L162-L169
train
google/zoekt
build/builder.go
IndexVersions
func (o *Options) IndexVersions() []zoekt.RepositoryBranch { fn := o.shardName(0) f, err := os.Open(fn) if err != nil { return nil } iFile, err := zoekt.NewIndexFile(f) if err != nil { return nil } defer iFile.Close() repo, index, err := zoekt.ReadMetadata(iFile) if err != nil { return nil } if index.IndexFeatureVersion != zoekt.FeatureVersion { return nil } if repo.IndexOptions != o.HashOptions() { return nil } return repo.Branches }
go
func (o *Options) IndexVersions() []zoekt.RepositoryBranch { fn := o.shardName(0) f, err := os.Open(fn) if err != nil { return nil } iFile, err := zoekt.NewIndexFile(f) if err != nil { return nil } defer iFile.Close() repo, index, err := zoekt.ReadMetadata(iFile) if err != nil { return nil } if index.IndexFeatureVersion != zoekt.FeatureVersion { return nil } if repo.IndexOptions != o.HashOptions() { return nil } return repo.Branches }
[ "func", "(", "o", "*", "Options", ")", "IndexVersions", "(", ")", "[", "]", "zoekt", ".", "RepositoryBranch", "{", "fn", ":=", "o", ".", "shardName", "(", "0", ")", "\n\n", "f", ",", "err", ":=", "os", ".", "Open", "(", "fn", ")", "\n", "if", "...
// IndexVersions returns the versions as present in the index, for // implementing incremental indexing.
[ "IndexVersions", "returns", "the", "versions", "as", "present", "in", "the", "index", "for", "implementing", "incremental", "indexing", "." ]
3493be98f11f3ca46cdb973a968f09f7cacc645d
https://github.com/google/zoekt/blob/3493be98f11f3ca46cdb973a968f09f7cacc645d/build/builder.go#L173-L201
train
google/zoekt
build/builder.go
IgnoreSizeMax
func (o *Options) IgnoreSizeMax(name string) bool { for _, pattern := range o.LargeFiles { pattern = strings.TrimSpace(pattern) m, _ := filepath.Match(pattern, name) if m { return true } } return false }
go
func (o *Options) IgnoreSizeMax(name string) bool { for _, pattern := range o.LargeFiles { pattern = strings.TrimSpace(pattern) m, _ := filepath.Match(pattern, name) if m { return true } } return false }
[ "func", "(", "o", "*", "Options", ")", "IgnoreSizeMax", "(", "name", "string", ")", "bool", "{", "for", "_", ",", "pattern", ":=", "range", "o", ".", "LargeFiles", "{", "pattern", "=", "strings", ".", "TrimSpace", "(", "pattern", ")", "\n", "m", ",",...
// IgnoreSizeMax determines whether the max size should be ignored.
[ "IgnoreSizeMax", "determines", "whether", "the", "max", "size", "should", "be", "ignored", "." ]
3493be98f11f3ca46cdb973a968f09f7cacc645d
https://github.com/google/zoekt/blob/3493be98f11f3ca46cdb973a968f09f7cacc645d/build/builder.go#L204-L214
train
google/zoekt
build/builder.go
NewBuilder
func NewBuilder(opts Options) (*Builder, error) { opts.SetDefaults() if opts.RepositoryDescription.Name == "" { return nil, fmt.Errorf("builder: must set Name") } b := &Builder{ opts: opts, throttle: make(chan int, opts.Parallelism), finishedShards: map[string]string{}, } if b.opts.CTags == "" && b.opts.CTagsMustSucceed { return nil, fmt.Errorf("ctags binary not found, but CTagsMustSucceed set") } if strings.Contains(opts.CTags, "universal-ctags") { parser, err := ctags.NewParser(opts.CTags) if err != nil && opts.CTagsMustSucceed { return nil, fmt.Errorf("ctags.NewParser: %v", err) } b.parser = parser } if _, err := b.newShardBuilder(); err != nil { return nil, err } return b, nil }
go
func NewBuilder(opts Options) (*Builder, error) { opts.SetDefaults() if opts.RepositoryDescription.Name == "" { return nil, fmt.Errorf("builder: must set Name") } b := &Builder{ opts: opts, throttle: make(chan int, opts.Parallelism), finishedShards: map[string]string{}, } if b.opts.CTags == "" && b.opts.CTagsMustSucceed { return nil, fmt.Errorf("ctags binary not found, but CTagsMustSucceed set") } if strings.Contains(opts.CTags, "universal-ctags") { parser, err := ctags.NewParser(opts.CTags) if err != nil && opts.CTagsMustSucceed { return nil, fmt.Errorf("ctags.NewParser: %v", err) } b.parser = parser } if _, err := b.newShardBuilder(); err != nil { return nil, err } return b, nil }
[ "func", "NewBuilder", "(", "opts", "Options", ")", "(", "*", "Builder", ",", "error", ")", "{", "opts", ".", "SetDefaults", "(", ")", "\n", "if", "opts", ".", "RepositoryDescription", ".", "Name", "==", "\"", "\"", "{", "return", "nil", ",", "fmt", "...
// NewBuilder creates a new Builder instance.
[ "NewBuilder", "creates", "a", "new", "Builder", "instance", "." ]
3493be98f11f3ca46cdb973a968f09f7cacc645d
https://github.com/google/zoekt/blob/3493be98f11f3ca46cdb973a968f09f7cacc645d/build/builder.go#L217-L246
train
google/zoekt
build/builder.go
AddFile
func (b *Builder) AddFile(name string, content []byte) error { return b.Add(zoekt.Document{Name: name, Content: content}) }
go
func (b *Builder) AddFile(name string, content []byte) error { return b.Add(zoekt.Document{Name: name, Content: content}) }
[ "func", "(", "b", "*", "Builder", ")", "AddFile", "(", "name", "string", ",", "content", "[", "]", "byte", ")", "error", "{", "return", "b", ".", "Add", "(", "zoekt", ".", "Document", "{", "Name", ":", "name", ",", "Content", ":", "content", "}", ...
// AddFile is a convenience wrapper for the Add method
[ "AddFile", "is", "a", "convenience", "wrapper", "for", "the", "Add", "method" ]
3493be98f11f3ca46cdb973a968f09f7cacc645d
https://github.com/google/zoekt/blob/3493be98f11f3ca46cdb973a968f09f7cacc645d/build/builder.go#L249-L251
train
google/zoekt
build/builder.go
Finish
func (b *Builder) Finish() error { b.flush() b.building.Wait() if b.buildError != nil { for tmp := range b.finishedShards { os.Remove(tmp) } return b.buildError } for tmp, final := range b.finishedShards { if err := os.Rename(tmp, final); err != nil { b.buildError = err } } if b.nextShardNum > 0 { b.deleteRemainingShards() } return b.buildError }
go
func (b *Builder) Finish() error { b.flush() b.building.Wait() if b.buildError != nil { for tmp := range b.finishedShards { os.Remove(tmp) } return b.buildError } for tmp, final := range b.finishedShards { if err := os.Rename(tmp, final); err != nil { b.buildError = err } } if b.nextShardNum > 0 { b.deleteRemainingShards() } return b.buildError }
[ "func", "(", "b", "*", "Builder", ")", "Finish", "(", ")", "error", "{", "b", ".", "flush", "(", ")", "\n", "b", ".", "building", ".", "Wait", "(", ")", "\n\n", "if", "b", ".", "buildError", "!=", "nil", "{", "for", "tmp", ":=", "range", "b", ...
// Finish creates a last shard from the buffered documents, and clears // stale shards from previous runs
[ "Finish", "creates", "a", "last", "shard", "from", "the", "buffered", "documents", "and", "clears", "stale", "shards", "from", "previous", "runs" ]
3493be98f11f3ca46cdb973a968f09f7cacc645d
https://github.com/google/zoekt/blob/3493be98f11f3ca46cdb973a968f09f7cacc645d/build/builder.go#L276-L297
train
google/zoekt
shards/shards.go
NewDirectorySearcher
func NewDirectorySearcher(dir string) (zoekt.Searcher, error) { ss := newShardedSearcher(int64(runtime.NumCPU())) tl := &throttledLoader{ ss: ss, throttle: make(chan struct{}, runtime.NumCPU()), } _, err := NewDirectoryWatcher(dir, tl) if err != nil { return nil, err } return ss, nil }
go
func NewDirectorySearcher(dir string) (zoekt.Searcher, error) { ss := newShardedSearcher(int64(runtime.NumCPU())) tl := &throttledLoader{ ss: ss, throttle: make(chan struct{}, runtime.NumCPU()), } _, err := NewDirectoryWatcher(dir, tl) if err != nil { return nil, err } return ss, nil }
[ "func", "NewDirectorySearcher", "(", "dir", "string", ")", "(", "zoekt", ".", "Searcher", ",", "error", ")", "{", "ss", ":=", "newShardedSearcher", "(", "int64", "(", "runtime", ".", "NumCPU", "(", ")", ")", ")", "\n", "tl", ":=", "&", "throttledLoader",...
// NewDirectorySearcher returns a searcher instance that loads all // shards corresponding to a glob into memory.
[ "NewDirectorySearcher", "returns", "a", "searcher", "instance", "that", "loads", "all", "shards", "corresponding", "to", "a", "glob", "into", "memory", "." ]
3493be98f11f3ca46cdb973a968f09f7cacc645d
https://github.com/google/zoekt/blob/3493be98f11f3ca46cdb973a968f09f7cacc645d/shards/shards.go#L61-L73
train
google/zoekt
shards/shards.go
Close
func (ss *shardedSearcher) Close() { ss.lock(context.Background()) defer ss.unlock() for _, s := range ss.shards { s.Close() } }
go
func (ss *shardedSearcher) Close() { ss.lock(context.Background()) defer ss.unlock() for _, s := range ss.shards { s.Close() } }
[ "func", "(", "ss", "*", "shardedSearcher", ")", "Close", "(", ")", "{", "ss", ".", "lock", "(", "context", ".", "Background", "(", ")", ")", "\n", "defer", "ss", ".", "unlock", "(", ")", "\n", "for", "_", ",", "s", ":=", "range", "ss", ".", "sh...
// Close closes references to open files. It may be called only once.
[ "Close", "closes", "references", "to", "open", "files", ".", "It", "may", "be", "called", "only", "once", "." ]
3493be98f11f3ca46cdb973a968f09f7cacc645d
https://github.com/google/zoekt/blob/3493be98f11f3ca46cdb973a968f09f7cacc645d/shards/shards.go#L102-L108
train
google/zoekt
shards/shards.go
getShards
func (s *shardedSearcher) getShards() []rankedShard { var res []rankedShard for _, sh := range s.shards { res = append(res, sh) } // TODO: precompute this. sort.Slice(res, func(i, j int) bool { return res[i].rank > res[j].rank }) return res }
go
func (s *shardedSearcher) getShards() []rankedShard { var res []rankedShard for _, sh := range s.shards { res = append(res, sh) } // TODO: precompute this. sort.Slice(res, func(i, j int) bool { return res[i].rank > res[j].rank }) return res }
[ "func", "(", "s", "*", "shardedSearcher", ")", "getShards", "(", ")", "[", "]", "rankedShard", "{", "var", "res", "[", "]", "rankedShard", "\n", "for", "_", ",", "sh", ":=", "range", "s", ".", "shards", "{", "res", "=", "append", "(", "res", ",", ...
// getShards returns the currently loaded shards. The shards must be // accessed under a rlock call. The shards are sorted by decreasing // rank.
[ "getShards", "returns", "the", "currently", "loaded", "shards", ".", "The", "shards", "must", "be", "accessed", "under", "a", "rlock", "call", ".", "The", "shards", "are", "sorted", "by", "decreasing", "rank", "." ]
3493be98f11f3ca46cdb973a968f09f7cacc645d
https://github.com/google/zoekt/blob/3493be98f11f3ca46cdb973a968f09f7cacc645d/shards/shards.go#L322-L332
train
google/zoekt
gitindex/index.go
RepoModTime
func RepoModTime(dir string) (time.Time, error) { var last time.Time refDir := filepath.Join(dir, "refs") if _, err := os.Lstat(refDir); err == nil { if err := filepath.Walk(refDir, func(name string, fi os.FileInfo, err error) error { if !fi.IsDir() && last.Before(fi.ModTime()) { last = fi.ModTime() } return nil }); err != nil { return last, err } } // git gc compresses refs into the following file: for _, fn := range []string{"info/refs", "packed-refs"} { if fi, err := os.Lstat(filepath.Join(dir, fn)); err == nil && !fi.IsDir() && last.Before(fi.ModTime()) { last = fi.ModTime() } } return last, nil }
go
func RepoModTime(dir string) (time.Time, error) { var last time.Time refDir := filepath.Join(dir, "refs") if _, err := os.Lstat(refDir); err == nil { if err := filepath.Walk(refDir, func(name string, fi os.FileInfo, err error) error { if !fi.IsDir() && last.Before(fi.ModTime()) { last = fi.ModTime() } return nil }); err != nil { return last, err } } // git gc compresses refs into the following file: for _, fn := range []string{"info/refs", "packed-refs"} { if fi, err := os.Lstat(filepath.Join(dir, fn)); err == nil && !fi.IsDir() && last.Before(fi.ModTime()) { last = fi.ModTime() } } return last, nil }
[ "func", "RepoModTime", "(", "dir", "string", ")", "(", "time", ".", "Time", ",", "error", ")", "{", "var", "last", "time", ".", "Time", "\n", "refDir", ":=", "filepath", ".", "Join", "(", "dir", ",", "\"", "\"", ")", "\n", "if", "_", ",", "err", ...
// RepoModTime returns the time of last fetch of a git repository.
[ "RepoModTime", "returns", "the", "time", "of", "last", "fetch", "of", "a", "git", "repository", "." ]
3493be98f11f3ca46cdb973a968f09f7cacc645d
https://github.com/google/zoekt/blob/3493be98f11f3ca46cdb973a968f09f7cacc645d/gitindex/index.go#L45-L68
train
google/zoekt
gitindex/index.go
setTemplates
func setTemplates(repo *zoekt.Repository, u *url.URL, typ string) error { repo.URL = u.String() switch typ { case "gitiles": /// eg. https://gerrit.googlesource.com/gitiles/+/master/tools/run_dev.sh#20 repo.CommitURLTemplate = u.String() + "/+/{{.Version}}" repo.FileURLTemplate = u.String() + "/+/{{.Version}}/{{.Path}}" repo.LineFragmentTemplate = "#{{.LineNumber}}" case "github": // eg. https://github.com/hanwen/go-fuse/blob/notify/genversion.sh#L10 repo.CommitURLTemplate = u.String() + "/commit/{{.Version}}" repo.FileURLTemplate = u.String() + "/blob/{{.Version}}/{{.Path}}" repo.LineFragmentTemplate = "#L{{.LineNumber}}" case "cgit": // http://git.savannah.gnu.org/cgit/lilypond.git/tree/elisp/lilypond-mode.el?h=dev/philh&id=b2ca0fefe3018477aaca23b6f672c7199ba5238e#n100 repo.CommitURLTemplate = u.String() + "/commit/?id={{.Version}}" repo.FileURLTemplate = u.String() + "/tree/{{.Path}}/?id={{.Version}}" repo.LineFragmentTemplate = "#n{{.LineNumber}}" case "gitweb": // https://gerrit.libreoffice.org/gitweb?p=online.git;a=blob;f=Makefile.am;h=cfcfd7c36fbae10e269653dc57a9b68c92d4c10b;hb=848145503bf7b98ce4a4aa0a858a0d71dd0dbb26#l10 repo.FileURLTemplate = u.String() + ";a=blob;f={{.Path}};hb={{.Version}}" repo.CommitURLTemplate = u.String() + ";a=commit;h={{.Version}}" repo.LineFragmentTemplate = "#l{{.LineNumber}}" case "source.bazel.build": // https://source.bazel.build/bazel/+/57bc201346e61c62a921c1cbf32ad24f185c10c9 // https://source.bazel.build/bazel/+/57bc201346e61c62a921c1cbf32ad24f185c10c9:tools/cpp/BUILD.empty;l=10 repo.CommitURLTemplate = u.String() + "/+/{{.Version}}" repo.FileURLTemplate = u.String() + "/+/{{.Version}}:{{.Path}}" repo.LineFragmentTemplate = ";l={{.LineNumber}}" case "bitbucket-server": // https://<bitbucketserver-host>/projects/<project>/repos/<repo>/commits/5be7ca73b898bf17a08e607918accfdeafe1e0bc // https://<bitbucketserver-host>/projects/<project>/repos/<repo>/browse/<file>?at=5be7ca73b898bf17a08e607918accfdeafe1e0bc repo.CommitURLTemplate = u.String() + "/commits/{{.Version}}" repo.FileURLTemplate = u.String() + "/{{.Path}}?at={{.Version}}" repo.LineFragmentTemplate = "#{{.LineNumber}}" case "gitlab": repo.CommitURLTemplate = u.String() + "/commit/{{.Version}}" repo.FileURLTemplate = u.String() + "/blob/{{.Version}}/{{.Path}}" repo.LineFragmentTemplate = "#L{{.LineNumber}}" default: return fmt.Errorf("URL scheme type %q unknown", typ) } return nil }
go
func setTemplates(repo *zoekt.Repository, u *url.URL, typ string) error { repo.URL = u.String() switch typ { case "gitiles": /// eg. https://gerrit.googlesource.com/gitiles/+/master/tools/run_dev.sh#20 repo.CommitURLTemplate = u.String() + "/+/{{.Version}}" repo.FileURLTemplate = u.String() + "/+/{{.Version}}/{{.Path}}" repo.LineFragmentTemplate = "#{{.LineNumber}}" case "github": // eg. https://github.com/hanwen/go-fuse/blob/notify/genversion.sh#L10 repo.CommitURLTemplate = u.String() + "/commit/{{.Version}}" repo.FileURLTemplate = u.String() + "/blob/{{.Version}}/{{.Path}}" repo.LineFragmentTemplate = "#L{{.LineNumber}}" case "cgit": // http://git.savannah.gnu.org/cgit/lilypond.git/tree/elisp/lilypond-mode.el?h=dev/philh&id=b2ca0fefe3018477aaca23b6f672c7199ba5238e#n100 repo.CommitURLTemplate = u.String() + "/commit/?id={{.Version}}" repo.FileURLTemplate = u.String() + "/tree/{{.Path}}/?id={{.Version}}" repo.LineFragmentTemplate = "#n{{.LineNumber}}" case "gitweb": // https://gerrit.libreoffice.org/gitweb?p=online.git;a=blob;f=Makefile.am;h=cfcfd7c36fbae10e269653dc57a9b68c92d4c10b;hb=848145503bf7b98ce4a4aa0a858a0d71dd0dbb26#l10 repo.FileURLTemplate = u.String() + ";a=blob;f={{.Path}};hb={{.Version}}" repo.CommitURLTemplate = u.String() + ";a=commit;h={{.Version}}" repo.LineFragmentTemplate = "#l{{.LineNumber}}" case "source.bazel.build": // https://source.bazel.build/bazel/+/57bc201346e61c62a921c1cbf32ad24f185c10c9 // https://source.bazel.build/bazel/+/57bc201346e61c62a921c1cbf32ad24f185c10c9:tools/cpp/BUILD.empty;l=10 repo.CommitURLTemplate = u.String() + "/+/{{.Version}}" repo.FileURLTemplate = u.String() + "/+/{{.Version}}:{{.Path}}" repo.LineFragmentTemplate = ";l={{.LineNumber}}" case "bitbucket-server": // https://<bitbucketserver-host>/projects/<project>/repos/<repo>/commits/5be7ca73b898bf17a08e607918accfdeafe1e0bc // https://<bitbucketserver-host>/projects/<project>/repos/<repo>/browse/<file>?at=5be7ca73b898bf17a08e607918accfdeafe1e0bc repo.CommitURLTemplate = u.String() + "/commits/{{.Version}}" repo.FileURLTemplate = u.String() + "/{{.Path}}?at={{.Version}}" repo.LineFragmentTemplate = "#{{.LineNumber}}" case "gitlab": repo.CommitURLTemplate = u.String() + "/commit/{{.Version}}" repo.FileURLTemplate = u.String() + "/blob/{{.Version}}/{{.Path}}" repo.LineFragmentTemplate = "#L{{.LineNumber}}" default: return fmt.Errorf("URL scheme type %q unknown", typ) } return nil }
[ "func", "setTemplates", "(", "repo", "*", "zoekt", ".", "Repository", ",", "u", "*", "url", ".", "URL", ",", "typ", "string", ")", "error", "{", "repo", ".", "URL", "=", "u", ".", "String", "(", ")", "\n", "switch", "typ", "{", "case", "\"", "\""...
// setTemplates fills in URL templates for known git hosting // sites.
[ "setTemplates", "fills", "in", "URL", "templates", "for", "known", "git", "hosting", "sites", "." ]
3493be98f11f3ca46cdb973a968f09f7cacc645d
https://github.com/google/zoekt/blob/3493be98f11f3ca46cdb973a968f09f7cacc645d/gitindex/index.go#L111-L154
train
google/zoekt
gitindex/index.go
getCommit
func getCommit(repo *git.Repository, prefix, ref string) (*object.Commit, error) { sha1, err := repo.ResolveRevision(plumbing.Revision(ref)) // ref might be a branch name (e.g. "master") add branch prefix and try again. if err != nil { sha1, err = repo.ResolveRevision(plumbing.Revision(filepath.Join(prefix, ref))) } if err != nil { return nil, err } commitObj, err := repo.CommitObject(*sha1) if err != nil { return nil, err } return commitObj, nil }
go
func getCommit(repo *git.Repository, prefix, ref string) (*object.Commit, error) { sha1, err := repo.ResolveRevision(plumbing.Revision(ref)) // ref might be a branch name (e.g. "master") add branch prefix and try again. if err != nil { sha1, err = repo.ResolveRevision(plumbing.Revision(filepath.Join(prefix, ref))) } if err != nil { return nil, err } commitObj, err := repo.CommitObject(*sha1) if err != nil { return nil, err } return commitObj, nil }
[ "func", "getCommit", "(", "repo", "*", "git", ".", "Repository", ",", "prefix", ",", "ref", "string", ")", "(", "*", "object", ".", "Commit", ",", "error", ")", "{", "sha1", ",", "err", ":=", "repo", ".", "ResolveRevision", "(", "plumbing", ".", "Rev...
// getCommit returns a tree object for the given reference.
[ "getCommit", "returns", "a", "tree", "object", "for", "the", "given", "reference", "." ]
3493be98f11f3ca46cdb973a968f09f7cacc645d
https://github.com/google/zoekt/blob/3493be98f11f3ca46cdb973a968f09f7cacc645d/gitindex/index.go#L157-L172
train
google/zoekt
gitindex/index.go
SetTemplatesFromOrigin
func SetTemplatesFromOrigin(desc *zoekt.Repository, u *url.URL) error { desc.Name = filepath.Join(u.Host, strings.TrimSuffix(u.Path, ".git")) if strings.HasSuffix(u.Host, ".googlesource.com") { return setTemplates(desc, u, "gitiles") } else if u.Host == "github.com" { u.Path = strings.TrimSuffix(u.Path, ".git") return setTemplates(desc, u, "github") } else { return fmt.Errorf("unknown git hosting site %q", u) } }
go
func SetTemplatesFromOrigin(desc *zoekt.Repository, u *url.URL) error { desc.Name = filepath.Join(u.Host, strings.TrimSuffix(u.Path, ".git")) if strings.HasSuffix(u.Host, ".googlesource.com") { return setTemplates(desc, u, "gitiles") } else if u.Host == "github.com" { u.Path = strings.TrimSuffix(u.Path, ".git") return setTemplates(desc, u, "github") } else { return fmt.Errorf("unknown git hosting site %q", u) } }
[ "func", "SetTemplatesFromOrigin", "(", "desc", "*", "zoekt", ".", "Repository", ",", "u", "*", "url", ".", "URL", ")", "error", "{", "desc", ".", "Name", "=", "filepath", ".", "Join", "(", "u", ".", "Host", ",", "strings", ".", "TrimSuffix", "(", "u"...
// SetTemplates fills in templates based on the origin URL.
[ "SetTemplates", "fills", "in", "templates", "based", "on", "the", "origin", "URL", "." ]
3493be98f11f3ca46cdb973a968f09f7cacc645d
https://github.com/google/zoekt/blob/3493be98f11f3ca46cdb973a968f09f7cacc645d/gitindex/index.go#L273-L284
train
google/zoekt
matchtree.go
prepare
func (t *bruteForceMatchTree) prepare(doc uint32) { t.docID = doc t.firstDone = true }
go
func (t *bruteForceMatchTree) prepare(doc uint32) { t.docID = doc t.firstDone = true }
[ "func", "(", "t", "*", "bruteForceMatchTree", ")", "prepare", "(", "doc", "uint32", ")", "{", "t", ".", "docID", "=", "doc", "\n", "t", ".", "firstDone", "=", "true", "\n", "}" ]
// all prepare methods
[ "all", "prepare", "methods" ]
3493be98f11f3ca46cdb973a968f09f7cacc645d
https://github.com/google/zoekt/blob/3493be98f11f3ca46cdb973a968f09f7cacc645d/matchtree.go#L146-L149
train
google/zoekt
ctags/parse.go
Parse
func Parse(in string) (*Entry, error) { fields := strings.Split(in, "\t") e := Entry{} if len(fields) < 3 { return nil, fmt.Errorf("too few fields: %q", in) } e.Sym = fields[0] e.Path = fields[1] lstr := fields[2] if len(lstr) < 2 { return nil, fmt.Errorf("got %q for linenum field", lstr) } l, err := strconv.ParseInt(lstr[:len(lstr)-2], 10, 64) if err != nil { return nil, err } e.Line = int(l) e.Kind = fields[3] field: for _, f := range fields[3:] { if string(f) == "file:" { e.FileLimited = true } for _, p := range []string{"class", "enum"} { if strings.HasPrefix(f, p+":") { e.Parent = strings.TrimPrefix(f, p+":") e.ParentType = p continue field } } } return &e, nil }
go
func Parse(in string) (*Entry, error) { fields := strings.Split(in, "\t") e := Entry{} if len(fields) < 3 { return nil, fmt.Errorf("too few fields: %q", in) } e.Sym = fields[0] e.Path = fields[1] lstr := fields[2] if len(lstr) < 2 { return nil, fmt.Errorf("got %q for linenum field", lstr) } l, err := strconv.ParseInt(lstr[:len(lstr)-2], 10, 64) if err != nil { return nil, err } e.Line = int(l) e.Kind = fields[3] field: for _, f := range fields[3:] { if string(f) == "file:" { e.FileLimited = true } for _, p := range []string{"class", "enum"} { if strings.HasPrefix(f, p+":") { e.Parent = strings.TrimPrefix(f, p+":") e.ParentType = p continue field } } } return &e, nil }
[ "func", "Parse", "(", "in", "string", ")", "(", "*", "Entry", ",", "error", ")", "{", "fields", ":=", "strings", ".", "Split", "(", "in", ",", "\"", "\\t", "\"", ")", "\n", "e", ":=", "Entry", "{", "}", "\n\n", "if", "len", "(", "fields", ")", ...
// Parse parses a single line of exuberant "ctags -n" output.
[ "Parse", "parses", "a", "single", "line", "of", "exuberant", "ctags", "-", "n", "output", "." ]
3493be98f11f3ca46cdb973a968f09f7cacc645d
https://github.com/google/zoekt/blob/3493be98f11f3ca46cdb973a968f09f7cacc645d/ctags/parse.go#L36-L73
train
google/zoekt
query/query.go
Map
func Map(q Q, f func(q Q) Q) Q { switch s := q.(type) { case *And: q = &And{Children: mapQueryList(s.Children, f)} case *Or: q = &Or{Children: mapQueryList(s.Children, f)} case *Not: q = &Not{Child: Map(s.Child, f)} } return f(q) }
go
func Map(q Q, f func(q Q) Q) Q { switch s := q.(type) { case *And: q = &And{Children: mapQueryList(s.Children, f)} case *Or: q = &Or{Children: mapQueryList(s.Children, f)} case *Not: q = &Not{Child: Map(s.Child, f)} } return f(q) }
[ "func", "Map", "(", "q", "Q", ",", "f", "func", "(", "q", "Q", ")", "Q", ")", "Q", "{", "switch", "s", ":=", "q", ".", "(", "type", ")", "{", "case", "*", "And", ":", "q", "=", "&", "And", "{", "Children", ":", "mapQueryList", "(", "s", "...
// Map runs f over the q.
[ "Map", "runs", "f", "over", "the", "q", "." ]
3493be98f11f3ca46cdb973a968f09f7cacc645d
https://github.com/google/zoekt/blob/3493be98f11f3ca46cdb973a968f09f7cacc645d/query/query.go#L346-L356
train
google/zoekt
query/query.go
VisitAtoms
func VisitAtoms(q Q, v func(q Q)) { Map(q, func(iQ Q) Q { switch iQ.(type) { case *And: case *Or: case *Not: default: v(iQ) } return iQ }) }
go
func VisitAtoms(q Q, v func(q Q)) { Map(q, func(iQ Q) Q { switch iQ.(type) { case *And: case *Or: case *Not: default: v(iQ) } return iQ }) }
[ "func", "VisitAtoms", "(", "q", "Q", ",", "v", "func", "(", "q", "Q", ")", ")", "{", "Map", "(", "q", ",", "func", "(", "iQ", "Q", ")", "Q", "{", "switch", "iQ", ".", "(", "type", ")", "{", "case", "*", "And", ":", "case", "*", "Or", ":",...
// VisitAtoms runs `v` on all atom queries within `q`.
[ "VisitAtoms", "runs", "v", "on", "all", "atom", "queries", "within", "q", "." ]
3493be98f11f3ca46cdb973a968f09f7cacc645d
https://github.com/google/zoekt/blob/3493be98f11f3ca46cdb973a968f09f7cacc645d/query/query.go#L383-L394
train
google/zoekt
indexbuilder.go
ContentSize
func (b *IndexBuilder) ContentSize() uint32 { // Add the name too so we don't skip building index if we have // lots of empty files. return b.contentPostings.endByte + b.namePostings.endByte }
go
func (b *IndexBuilder) ContentSize() uint32 { // Add the name too so we don't skip building index if we have // lots of empty files. return b.contentPostings.endByte + b.namePostings.endByte }
[ "func", "(", "b", "*", "IndexBuilder", ")", "ContentSize", "(", ")", "uint32", "{", "// Add the name too so we don't skip building index if we have", "// lots of empty files.", "return", "b", ".", "contentPostings", ".", "endByte", "+", "b", ".", "namePostings", ".", ...
// ContentSize returns the number of content bytes so far ingested.
[ "ContentSize", "returns", "the", "number", "of", "content", "bytes", "so", "far", "ingested", "." ]
3493be98f11f3ca46cdb973a968f09f7cacc645d
https://github.com/google/zoekt/blob/3493be98f11f3ca46cdb973a968f09f7cacc645d/indexbuilder.go#L186-L190
train
google/zoekt
indexbuilder.go
NewIndexBuilder
func NewIndexBuilder(r *Repository) (*IndexBuilder, error) { b := &IndexBuilder{ contentPostings: newPostingsBuilder(), namePostings: newPostingsBuilder(), languageMap: map[string]byte{}, } if r == nil { r = &Repository{} } if err := b.setRepository(r); err != nil { return nil, err } return b, nil }
go
func NewIndexBuilder(r *Repository) (*IndexBuilder, error) { b := &IndexBuilder{ contentPostings: newPostingsBuilder(), namePostings: newPostingsBuilder(), languageMap: map[string]byte{}, } if r == nil { r = &Repository{} } if err := b.setRepository(r); err != nil { return nil, err } return b, nil }
[ "func", "NewIndexBuilder", "(", "r", "*", "Repository", ")", "(", "*", "IndexBuilder", ",", "error", ")", "{", "b", ":=", "&", "IndexBuilder", "{", "contentPostings", ":", "newPostingsBuilder", "(", ")", ",", "namePostings", ":", "newPostingsBuilder", "(", "...
// NewIndexBuilder creates a fresh IndexBuilder. The passed in // Repository contains repo metadata, and may be set to nil.
[ "NewIndexBuilder", "creates", "a", "fresh", "IndexBuilder", ".", "The", "passed", "in", "Repository", "contains", "repo", "metadata", "and", "may", "be", "set", "to", "nil", "." ]
3493be98f11f3ca46cdb973a968f09f7cacc645d
https://github.com/google/zoekt/blob/3493be98f11f3ca46cdb973a968f09f7cacc645d/indexbuilder.go#L194-L208
train
google/zoekt
indexbuilder.go
AddFile
func (b *IndexBuilder) AddFile(name string, content []byte) error { return b.Add(Document{Name: name, Content: content}) }
go
func (b *IndexBuilder) AddFile(name string, content []byte) error { return b.Add(Document{Name: name, Content: content}) }
[ "func", "(", "b", "*", "IndexBuilder", ")", "AddFile", "(", "name", "string", ",", "content", "[", "]", "byte", ")", "error", "{", "return", "b", ".", "Add", "(", "Document", "{", "Name", ":", "name", ",", "Content", ":", "content", "}", ")", "\n",...
// AddFile is a convenience wrapper for Add
[ "AddFile", "is", "a", "convenience", "wrapper", "for", "Add" ]
3493be98f11f3ca46cdb973a968f09f7cacc645d
https://github.com/google/zoekt/blob/3493be98f11f3ca46cdb973a968f09f7cacc645d/indexbuilder.go#L271-L273
train
google/zoekt
indexbuilder.go
CheckText
func CheckText(content []byte) error { if len(content) == 0 { return nil } if len(content) < ngramSize { return fmt.Errorf("file size smaller than %d", ngramSize) } trigrams := map[ngram]struct{}{} var cur [3]rune byteCount := 0 for len(content) > 0 { if content[0] == 0 { return fmt.Errorf("binary data at byte offset %d", byteCount) } r, sz := utf8.DecodeRune(content) content = content[sz:] byteCount += sz cur[0], cur[1], cur[2] = cur[1], cur[2], r if cur[0] == 0 { // start of file. continue } trigrams[runesToNGram(cur)] = struct{}{} if len(trigrams) > maxTrigramCount { // probably not text. return fmt.Errorf("number of trigrams exceeds %d", maxTrigramCount) } } return nil }
go
func CheckText(content []byte) error { if len(content) == 0 { return nil } if len(content) < ngramSize { return fmt.Errorf("file size smaller than %d", ngramSize) } trigrams := map[ngram]struct{}{} var cur [3]rune byteCount := 0 for len(content) > 0 { if content[0] == 0 { return fmt.Errorf("binary data at byte offset %d", byteCount) } r, sz := utf8.DecodeRune(content) content = content[sz:] byteCount += sz cur[0], cur[1], cur[2] = cur[1], cur[2], r if cur[0] == 0 { // start of file. continue } trigrams[runesToNGram(cur)] = struct{}{} if len(trigrams) > maxTrigramCount { // probably not text. return fmt.Errorf("number of trigrams exceeds %d", maxTrigramCount) } } return nil }
[ "func", "CheckText", "(", "content", "[", "]", "byte", ")", "error", "{", "if", "len", "(", "content", ")", "==", "0", "{", "return", "nil", "\n", "}", "\n\n", "if", "len", "(", "content", ")", "<", "ngramSize", "{", "return", "fmt", ".", "Errorf",...
// CheckText returns a reason why the given contents are probably not source texts.
[ "CheckText", "returns", "a", "reason", "why", "the", "given", "contents", "are", "probably", "not", "source", "texts", "." ]
3493be98f11f3ca46cdb973a968f09f7cacc645d
https://github.com/google/zoekt/blob/3493be98f11f3ca46cdb973a968f09f7cacc645d/indexbuilder.go#L278-L313
train
google/zoekt
read.go
ReadMetadata
func ReadMetadata(inf IndexFile) (*Repository, *IndexMetadata, error) { rd := &reader{r: inf} var toc indexTOC if err := rd.readTOC(&toc); err != nil { return nil, nil, err } var md IndexMetadata if err := rd.readJSON(&md, &toc.metaData); err != nil { return nil, nil, err } var repo Repository if err := rd.readJSON(&repo, &toc.repoMetaData); err != nil { return nil, nil, err } return &repo, &md, nil }
go
func ReadMetadata(inf IndexFile) (*Repository, *IndexMetadata, error) { rd := &reader{r: inf} var toc indexTOC if err := rd.readTOC(&toc); err != nil { return nil, nil, err } var md IndexMetadata if err := rd.readJSON(&md, &toc.metaData); err != nil { return nil, nil, err } var repo Repository if err := rd.readJSON(&repo, &toc.repoMetaData); err != nil { return nil, nil, err } return &repo, &md, nil }
[ "func", "ReadMetadata", "(", "inf", "IndexFile", ")", "(", "*", "Repository", ",", "*", "IndexMetadata", ",", "error", ")", "{", "rd", ":=", "&", "reader", "{", "r", ":", "inf", "}", "\n", "var", "toc", "indexTOC", "\n", "if", "err", ":=", "rd", "....
// ReadMetadata returns the metadata of index shard without reading // the index data. The IndexFile is not closed.
[ "ReadMetadata", "returns", "the", "metadata", "of", "index", "shard", "without", "reading", "the", "index", "data", ".", "The", "IndexFile", "is", "not", "closed", "." ]
3493be98f11f3ca46cdb973a968f09f7cacc645d
https://github.com/google/zoekt/blob/3493be98f11f3ca46cdb973a968f09f7cacc645d/read.go#L364-L382
train
google/zoekt
gitindex/tree.go
subURL
func (w *repoWalker) subURL(relURL string) (*url.URL, error) { if w.repoURL == nil { return nil, fmt.Errorf("no URL for base repo") } if strings.HasPrefix(relURL, "../") { u := *w.repoURL u.Path = path.Join(u.Path, relURL) return &u, nil } return url.Parse(relURL) }
go
func (w *repoWalker) subURL(relURL string) (*url.URL, error) { if w.repoURL == nil { return nil, fmt.Errorf("no URL for base repo") } if strings.HasPrefix(relURL, "../") { u := *w.repoURL u.Path = path.Join(u.Path, relURL) return &u, nil } return url.Parse(relURL) }
[ "func", "(", "w", "*", "repoWalker", ")", "subURL", "(", "relURL", "string", ")", "(", "*", "url", ".", "URL", ",", "error", ")", "{", "if", "w", ".", "repoURL", "==", "nil", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ")"...
// subURL returns the URL for a submodule.
[ "subURL", "returns", "the", "URL", "for", "a", "submodule", "." ]
3493be98f11f3ca46cdb973a968f09f7cacc645d
https://github.com/google/zoekt/blob/3493be98f11f3ca46cdb973a968f09f7cacc645d/gitindex/tree.go#L52-L63
train
google/zoekt
gitindex/tree.go
newRepoWalker
func newRepoWalker(r *git.Repository, repoURL string, repoCache *RepoCache) *repoWalker { u, _ := url.Parse(repoURL) return &repoWalker{ repo: r, repoURL: u, tree: map[fileKey]BlobLocation{}, repoCache: repoCache, subRepoVersions: map[string]plumbing.Hash{}, ignoreMissingSubmodules: true, } }
go
func newRepoWalker(r *git.Repository, repoURL string, repoCache *RepoCache) *repoWalker { u, _ := url.Parse(repoURL) return &repoWalker{ repo: r, repoURL: u, tree: map[fileKey]BlobLocation{}, repoCache: repoCache, subRepoVersions: map[string]plumbing.Hash{}, ignoreMissingSubmodules: true, } }
[ "func", "newRepoWalker", "(", "r", "*", "git", ".", "Repository", ",", "repoURL", "string", ",", "repoCache", "*", "RepoCache", ")", "*", "repoWalker", "{", "u", ",", "_", ":=", "url", ".", "Parse", "(", "repoURL", ")", "\n", "return", "&", "repoWalker...
// newRepoWalker creates a new repoWalker.
[ "newRepoWalker", "creates", "a", "new", "repoWalker", "." ]
3493be98f11f3ca46cdb973a968f09f7cacc645d
https://github.com/google/zoekt/blob/3493be98f11f3ca46cdb973a968f09f7cacc645d/gitindex/tree.go#L66-L76
train
google/zoekt
gitindex/tree.go
parseModuleMap
func (rw *repoWalker) parseModuleMap(t *object.Tree) error { modEntry, _ := t.File(".gitmodules") if modEntry != nil { c, err := blobContents(&modEntry.Blob) if err != nil { return err } mods, err := ParseGitModules(c) if err != nil { return err } rw.submodules = map[string]*SubmoduleEntry{} for _, entry := range mods { rw.submodules[entry.Path] = entry } } return nil }
go
func (rw *repoWalker) parseModuleMap(t *object.Tree) error { modEntry, _ := t.File(".gitmodules") if modEntry != nil { c, err := blobContents(&modEntry.Blob) if err != nil { return err } mods, err := ParseGitModules(c) if err != nil { return err } rw.submodules = map[string]*SubmoduleEntry{} for _, entry := range mods { rw.submodules[entry.Path] = entry } } return nil }
[ "func", "(", "rw", "*", "repoWalker", ")", "parseModuleMap", "(", "t", "*", "object", ".", "Tree", ")", "error", "{", "modEntry", ",", "_", ":=", "t", ".", "File", "(", "\"", "\"", ")", "\n", "if", "modEntry", "!=", "nil", "{", "c", ",", "err", ...
// parseModuleMap initializes rw.submodules.
[ "parseModuleMap", "initializes", "rw", ".", "submodules", "." ]
3493be98f11f3ca46cdb973a968f09f7cacc645d
https://github.com/google/zoekt/blob/3493be98f11f3ca46cdb973a968f09f7cacc645d/gitindex/tree.go#L79-L96
train
google/zoekt
gitindex/tree.go
TreeToFiles
func TreeToFiles(r *git.Repository, t *object.Tree, repoURL string, repoCache *RepoCache) (map[fileKey]BlobLocation, map[string]plumbing.Hash, error) { rw := newRepoWalker(r, repoURL, repoCache) if err := rw.parseModuleMap(t); err != nil { return nil, nil, err } tw := object.NewTreeWalker(t, true, make(map[plumbing.Hash]bool)) defer tw.Close() for { name, entry, err := tw.Next() if err == io.EOF { break } if err := rw.handleEntry(name, &entry); err != nil { return nil, nil, err } } return rw.tree, rw.subRepoVersions, nil }
go
func TreeToFiles(r *git.Repository, t *object.Tree, repoURL string, repoCache *RepoCache) (map[fileKey]BlobLocation, map[string]plumbing.Hash, error) { rw := newRepoWalker(r, repoURL, repoCache) if err := rw.parseModuleMap(t); err != nil { return nil, nil, err } tw := object.NewTreeWalker(t, true, make(map[plumbing.Hash]bool)) defer tw.Close() for { name, entry, err := tw.Next() if err == io.EOF { break } if err := rw.handleEntry(name, &entry); err != nil { return nil, nil, err } } return rw.tree, rw.subRepoVersions, nil }
[ "func", "TreeToFiles", "(", "r", "*", "git", ".", "Repository", ",", "t", "*", "object", ".", "Tree", ",", "repoURL", "string", ",", "repoCache", "*", "RepoCache", ")", "(", "map", "[", "fileKey", "]", "BlobLocation", ",", "map", "[", "string", "]", ...
// TreeToFiles fetches the blob SHA1s for a tree. If repoCache is // non-nil, recurse into submodules. In addition, it returns a mapping // that indicates in which repo each SHA1 can be found.
[ "TreeToFiles", "fetches", "the", "blob", "SHA1s", "for", "a", "tree", ".", "If", "repoCache", "is", "non", "-", "nil", "recurse", "into", "submodules", ".", "In", "addition", "it", "returns", "a", "mapping", "that", "indicates", "in", "which", "repo", "eac...
3493be98f11f3ca46cdb973a968f09f7cacc645d
https://github.com/google/zoekt/blob/3493be98f11f3ca46cdb973a968f09f7cacc645d/gitindex/tree.go#L101-L121
train
google/zoekt
cmd/zoekt-archive-index/main.go
stripComponents
func stripComponents(path string, count int) string { for i := 0; path != "" && i < count; i++ { i := strings.Index(path, "/") if i < 0 { return "" } path = path[i+1:] } return path }
go
func stripComponents(path string, count int) string { for i := 0; path != "" && i < count; i++ { i := strings.Index(path, "/") if i < 0 { return "" } path = path[i+1:] } return path }
[ "func", "stripComponents", "(", "path", "string", ",", "count", "int", ")", "string", "{", "for", "i", ":=", "0", ";", "path", "!=", "\"", "\"", "&&", "i", "<", "count", ";", "i", "++", "{", "i", ":=", "strings", ".", "Index", "(", "path", ",", ...
// stripComponents removes the specified number of leading path // elements. Pathnames with fewer elements will return the empty string.
[ "stripComponents", "removes", "the", "specified", "number", "of", "leading", "path", "elements", ".", "Pathnames", "with", "fewer", "elements", "will", "return", "the", "empty", "string", "." ]
3493be98f11f3ca46cdb973a968f09f7cacc645d
https://github.com/google/zoekt/blob/3493be98f11f3ca46cdb973a968f09f7cacc645d/cmd/zoekt-archive-index/main.go#L29-L38
train
google/zoekt
cmd/zoekt-archive-index/archive.go
openArchive
func openArchive(u string) (Archive, error) { var ( r io.Reader closer io.Closer ) if strings.HasPrefix(u, "https://") || strings.HasPrefix(u, "http://") { resp, err := http.Get(u) if err != nil { return nil, err } if resp.StatusCode < 200 || resp.StatusCode >= 300 { b, err := ioutil.ReadAll(io.LimitReader(resp.Body, 1024)) resp.Body.Close() if err != nil { return nil, err } return nil, &url.Error{ Op: "Get", URL: u, Err: fmt.Errorf("%s: %s", resp.Status, string(b)), } } closer = resp.Body r = resp.Body if resp.Header.Get("Content-Type") == "application/x-gzip" { r, err = gzip.NewReader(r) if err != nil { resp.Body.Close() return nil, err } } } else if u == "-" { r = os.Stdin } else { f, err := os.Open(u) if err != nil { return nil, err } closer = f r = f } return &tarArchive{ tr: tar.NewReader(r), closer: closer, }, nil }
go
func openArchive(u string) (Archive, error) { var ( r io.Reader closer io.Closer ) if strings.HasPrefix(u, "https://") || strings.HasPrefix(u, "http://") { resp, err := http.Get(u) if err != nil { return nil, err } if resp.StatusCode < 200 || resp.StatusCode >= 300 { b, err := ioutil.ReadAll(io.LimitReader(resp.Body, 1024)) resp.Body.Close() if err != nil { return nil, err } return nil, &url.Error{ Op: "Get", URL: u, Err: fmt.Errorf("%s: %s", resp.Status, string(b)), } } closer = resp.Body r = resp.Body if resp.Header.Get("Content-Type") == "application/x-gzip" { r, err = gzip.NewReader(r) if err != nil { resp.Body.Close() return nil, err } } } else if u == "-" { r = os.Stdin } else { f, err := os.Open(u) if err != nil { return nil, err } closer = f r = f } return &tarArchive{ tr: tar.NewReader(r), closer: closer, }, nil }
[ "func", "openArchive", "(", "u", "string", ")", "(", "Archive", ",", "error", ")", "{", "var", "(", "r", "io", ".", "Reader", "\n", "closer", "io", ".", "Closer", "\n", ")", "\n\n", "if", "strings", ".", "HasPrefix", "(", "u", ",", "\"", "\"", ")...
// openArchive opens the tar at the URL or filepath u. Also supported is tgz // files over http.
[ "openArchive", "opens", "the", "tar", "at", "the", "URL", "or", "filepath", "u", ".", "Also", "supported", "is", "tgz", "files", "over", "http", "." ]
3493be98f11f3ca46cdb973a968f09f7cacc645d
https://github.com/google/zoekt/blob/3493be98f11f3ca46cdb973a968f09f7cacc645d/cmd/zoekt-archive-index/archive.go#L60-L107
train
google/zoekt
cmd/zoekt-repo-index/main.go
iterateManifest
func iterateManifest(mf *manifest.Manifest, baseURL url.URL, revPrefix string, cache *gitindex.RepoCache) (map[fileKey]gitindex.BlobLocation, map[string]plumbing.Hash, error) { allFiles := map[fileKey]gitindex.BlobLocation{} allVersions := map[string]plumbing.Hash{} for _, p := range mf.Project { rev := mf.ProjectRevision(&p) projURL := baseURL projURL.Path = path.Join(projURL.Path, p.Name) topRepo, err := cache.Open(&projURL) if err != nil { return nil, nil, err } ref, err := topRepo.Reference(plumbing.ReferenceName(revPrefix+rev), true) if err != nil { return nil, nil, err } commit, err := topRepo.CommitObject(ref.Hash()) if err != nil { return nil, nil, err } if err != nil { return nil, nil, err } allVersions[p.GetPath()] = commit.Hash tree, err := commit.Tree() if err != nil { return nil, nil, err } files, versions, err := gitindex.TreeToFiles(topRepo, tree, projURL.String(), cache) if err != nil { return nil, nil, err } for key, repo := range files { allFiles[fileKey{ SubRepoPath: filepath.Join(p.GetPath(), key.SubRepoPath), Path: key.Path, ID: key.ID, }] = repo } for path, version := range versions { allVersions[filepath.Join(p.GetPath(), path)] = version } } return allFiles, allVersions, nil }
go
func iterateManifest(mf *manifest.Manifest, baseURL url.URL, revPrefix string, cache *gitindex.RepoCache) (map[fileKey]gitindex.BlobLocation, map[string]plumbing.Hash, error) { allFiles := map[fileKey]gitindex.BlobLocation{} allVersions := map[string]plumbing.Hash{} for _, p := range mf.Project { rev := mf.ProjectRevision(&p) projURL := baseURL projURL.Path = path.Join(projURL.Path, p.Name) topRepo, err := cache.Open(&projURL) if err != nil { return nil, nil, err } ref, err := topRepo.Reference(plumbing.ReferenceName(revPrefix+rev), true) if err != nil { return nil, nil, err } commit, err := topRepo.CommitObject(ref.Hash()) if err != nil { return nil, nil, err } if err != nil { return nil, nil, err } allVersions[p.GetPath()] = commit.Hash tree, err := commit.Tree() if err != nil { return nil, nil, err } files, versions, err := gitindex.TreeToFiles(topRepo, tree, projURL.String(), cache) if err != nil { return nil, nil, err } for key, repo := range files { allFiles[fileKey{ SubRepoPath: filepath.Join(p.GetPath(), key.SubRepoPath), Path: key.Path, ID: key.ID, }] = repo } for path, version := range versions { allVersions[filepath.Join(p.GetPath(), path)] = version } } return allFiles, allVersions, nil }
[ "func", "iterateManifest", "(", "mf", "*", "manifest", ".", "Manifest", ",", "baseURL", "url", ".", "URL", ",", "revPrefix", "string", ",", "cache", "*", "gitindex", ".", "RepoCache", ")", "(", "map", "[", "fileKey", "]", "gitindex", ".", "BlobLocation", ...
// iterateManifest constructs a complete tree from the given Manifest.
[ "iterateManifest", "constructs", "a", "complete", "tree", "from", "the", "given", "Manifest", "." ]
3493be98f11f3ca46cdb973a968f09f7cacc645d
https://github.com/google/zoekt/blob/3493be98f11f3ca46cdb973a968f09f7cacc645d/cmd/zoekt-repo-index/main.go#L325-L380
train
google/zoekt
ctags/json.go
NewParser
func NewParser(bin string) (Parser, error) { if strings.Contains(bin, "universal-ctags") { // todo: restart, parallelization. proc, err := newProcess(bin) if err != nil { return nil, err } return &lockedParser{p: proc}, nil } log.Fatal("not implemented") return nil, nil }
go
func NewParser(bin string) (Parser, error) { if strings.Contains(bin, "universal-ctags") { // todo: restart, parallelization. proc, err := newProcess(bin) if err != nil { return nil, err } return &lockedParser{p: proc}, nil } log.Fatal("not implemented") return nil, nil }
[ "func", "NewParser", "(", "bin", "string", ")", "(", "Parser", ",", "error", ")", "{", "if", "strings", ".", "Contains", "(", "bin", ",", "\"", "\"", ")", "{", "// todo: restart, parallelization.", "proc", ",", "err", ":=", "newProcess", "(", "bin", ")",...
// NewParser creates a parser that is implemented by the given // universal-ctags binary. The parser is safe for concurrent use.
[ "NewParser", "creates", "a", "parser", "that", "is", "implemented", "by", "the", "given", "universal", "-", "ctags", "binary", ".", "The", "parser", "is", "safe", "for", "concurrent", "use", "." ]
3493be98f11f3ca46cdb973a968f09f7cacc645d
https://github.com/google/zoekt/blob/3493be98f11f3ca46cdb973a968f09f7cacc645d/ctags/json.go#L207-L219
train
google/zoekt
contentprovider.go
setDocument
func (p *contentProvider) setDocument(docID uint32) { fileStart := p.id.boundaries[docID] p.idx = docID p.fileSize = p.id.boundaries[docID+1] - fileStart p._nl = nil p._sects = nil p._data = nil }
go
func (p *contentProvider) setDocument(docID uint32) { fileStart := p.id.boundaries[docID] p.idx = docID p.fileSize = p.id.boundaries[docID+1] - fileStart p._nl = nil p._sects = nil p._data = nil }
[ "func", "(", "p", "*", "contentProvider", ")", "setDocument", "(", "docID", "uint32", ")", "{", "fileStart", ":=", "p", ".", "id", ".", "boundaries", "[", "docID", "]", "\n\n", "p", ".", "idx", "=", "docID", "\n", "p", ".", "fileSize", "=", "p", "....
// setDocument skips to the given document.
[ "setDocument", "skips", "to", "the", "given", "document", "." ]
3493be98f11f3ca46cdb973a968f09f7cacc645d
https://github.com/google/zoekt/blob/3493be98f11f3ca46cdb973a968f09f7cacc645d/contentprovider.go#L44-L53
train
google/zoekt
query/regexp.go
RegexpToQuery
func RegexpToQuery(r *syntax.Regexp, minTextSize int) Q { q := regexpToQueryRecursive(r, minTextSize) q = Simplify(q) return q }
go
func RegexpToQuery(r *syntax.Regexp, minTextSize int) Q { q := regexpToQueryRecursive(r, minTextSize) q = Simplify(q) return q }
[ "func", "RegexpToQuery", "(", "r", "*", "syntax", ".", "Regexp", ",", "minTextSize", "int", ")", "Q", "{", "q", ":=", "regexpToQueryRecursive", "(", "r", ",", "minTextSize", ")", "\n", "q", "=", "Simplify", "(", "q", ")", "\n", "return", "q", "\n", "...
// RegexpToQuery tries to distill a substring search query that // matches a superset of the regexp.
[ "RegexpToQuery", "tries", "to", "distill", "a", "substring", "search", "query", "that", "matches", "a", "superset", "of", "the", "regexp", "." ]
3493be98f11f3ca46cdb973a968f09f7cacc645d
https://github.com/google/zoekt/blob/3493be98f11f3ca46cdb973a968f09f7cacc645d/query/regexp.go#L48-L52
train
google/zoekt
cmd/zoekt-indexserver/main.go
periodicFetch
func periodicFetch(repoDir, indexDir string, opts *Options, pendingRepos chan<- string) { t := time.NewTicker(opts.fetchInterval) for { repos, err := gitindex.FindGitRepos(repoDir) if err != nil { log.Println(err) continue } if len(repos) == 0 { log.Printf("no repos found under %s", repoDir) } // TODO: Randomize to make sure quota throttling hits everyone. later := map[string]struct{}{} for _, dir := range repos { if ok := fetchGitRepo(dir); !ok { later[dir] = struct{}{} } else { pendingRepos <- dir } } for r := range later { pendingRepos <- r } <-t.C } }
go
func periodicFetch(repoDir, indexDir string, opts *Options, pendingRepos chan<- string) { t := time.NewTicker(opts.fetchInterval) for { repos, err := gitindex.FindGitRepos(repoDir) if err != nil { log.Println(err) continue } if len(repos) == 0 { log.Printf("no repos found under %s", repoDir) } // TODO: Randomize to make sure quota throttling hits everyone. later := map[string]struct{}{} for _, dir := range repos { if ok := fetchGitRepo(dir); !ok { later[dir] = struct{}{} } else { pendingRepos <- dir } } for r := range later { pendingRepos <- r } <-t.C } }
[ "func", "periodicFetch", "(", "repoDir", ",", "indexDir", "string", ",", "opts", "*", "Options", ",", "pendingRepos", "chan", "<-", "string", ")", "{", "t", ":=", "time", ".", "NewTicker", "(", "opts", ".", "fetchInterval", ")", "\n", "for", "{", "repos"...
// periodicFetch runs git-fetch every once in a while. Results are // posted on pendingRepos.
[ "periodicFetch", "runs", "git", "-", "fetch", "every", "once", "in", "a", "while", ".", "Results", "are", "posted", "on", "pendingRepos", "." ]
3493be98f11f3ca46cdb973a968f09f7cacc645d
https://github.com/google/zoekt/blob/3493be98f11f3ca46cdb973a968f09f7cacc645d/cmd/zoekt-indexserver/main.go#L95-L124
train
google/zoekt
cmd/zoekt-indexserver/main.go
fetchGitRepo
func fetchGitRepo(dir string) bool { cmd := exec.Command("git", "--git-dir", dir, "fetch", "origin") outBuf := &bytes.Buffer{} errBuf := &bytes.Buffer{} // Prevent prompting cmd.Stdin = &bytes.Buffer{} cmd.Stderr = errBuf cmd.Stdout = outBuf if err := cmd.Run(); err != nil { log.Printf("command %s failed: %v\nOUT: %s\nERR: %s", cmd.Args, err, outBuf.String(), errBuf.String()) } else { return len(outBuf.Bytes()) != 0 } return false }
go
func fetchGitRepo(dir string) bool { cmd := exec.Command("git", "--git-dir", dir, "fetch", "origin") outBuf := &bytes.Buffer{} errBuf := &bytes.Buffer{} // Prevent prompting cmd.Stdin = &bytes.Buffer{} cmd.Stderr = errBuf cmd.Stdout = outBuf if err := cmd.Run(); err != nil { log.Printf("command %s failed: %v\nOUT: %s\nERR: %s", cmd.Args, err, outBuf.String(), errBuf.String()) } else { return len(outBuf.Bytes()) != 0 } return false }
[ "func", "fetchGitRepo", "(", "dir", "string", ")", "bool", "{", "cmd", ":=", "exec", ".", "Command", "(", "\"", "\"", ",", "\"", "\"", ",", "dir", ",", "\"", "\"", ",", "\"", "\"", ")", "\n", "outBuf", ":=", "&", "bytes", ".", "Buffer", "{", "}...
// fetchGitRepo runs git-fetch, and returns true if there was an // update.
[ "fetchGitRepo", "runs", "git", "-", "fetch", "and", "returns", "true", "if", "there", "was", "an", "update", "." ]
3493be98f11f3ca46cdb973a968f09f7cacc645d
https://github.com/google/zoekt/blob/3493be98f11f3ca46cdb973a968f09f7cacc645d/cmd/zoekt-indexserver/main.go#L128-L144
train
google/zoekt
cmd/zoekt-indexserver/main.go
indexPendingRepos
func indexPendingRepos(indexDir, repoDir string, opts *Options, repos <-chan string) { for dir := range repos { args := []string{ "-require_ctags", fmt.Sprintf("-parallelism=%d", opts.cpuCount), "-repo_cache", repoDir, "-index", indexDir, "-incremental", } args = append(args, opts.indexFlags...) args = append(args, dir) cmd := exec.Command("zoekt-git-index", args...) loggedRun(cmd) } }
go
func indexPendingRepos(indexDir, repoDir string, opts *Options, repos <-chan string) { for dir := range repos { args := []string{ "-require_ctags", fmt.Sprintf("-parallelism=%d", opts.cpuCount), "-repo_cache", repoDir, "-index", indexDir, "-incremental", } args = append(args, opts.indexFlags...) args = append(args, dir) cmd := exec.Command("zoekt-git-index", args...) loggedRun(cmd) } }
[ "func", "indexPendingRepos", "(", "indexDir", ",", "repoDir", "string", ",", "opts", "*", "Options", ",", "repos", "<-", "chan", "string", ")", "{", "for", "dir", ":=", "range", "repos", "{", "args", ":=", "[", "]", "string", "{", "\"", "\"", ",", "f...
// indexPendingRepos consumes the directories on the repos channel and // indexes them, sequentially.
[ "indexPendingRepos", "consumes", "the", "directories", "on", "the", "repos", "channel", "and", "indexes", "them", "sequentially", "." ]
3493be98f11f3ca46cdb973a968f09f7cacc645d
https://github.com/google/zoekt/blob/3493be98f11f3ca46cdb973a968f09f7cacc645d/cmd/zoekt-indexserver/main.go#L148-L162
train
google/zoekt
cmd/zoekt-indexserver/main.go
deleteLogs
func deleteLogs(logDir string, maxAge time.Duration) { fs, err := filepath.Glob(filepath.Join(logDir, "*")) if err != nil { log.Fatalf("filepath.Glob(%s): %v", logDir, err) } threshold := time.Now().Add(-maxAge) for _, fn := range fs { if fi, err := os.Lstat(fn); err == nil && fi.ModTime().Before(threshold) { os.Remove(fn) } } }
go
func deleteLogs(logDir string, maxAge time.Duration) { fs, err := filepath.Glob(filepath.Join(logDir, "*")) if err != nil { log.Fatalf("filepath.Glob(%s): %v", logDir, err) } threshold := time.Now().Add(-maxAge) for _, fn := range fs { if fi, err := os.Lstat(fn); err == nil && fi.ModTime().Before(threshold) { os.Remove(fn) } } }
[ "func", "deleteLogs", "(", "logDir", "string", ",", "maxAge", "time", ".", "Duration", ")", "{", "fs", ",", "err", ":=", "filepath", ".", "Glob", "(", "filepath", ".", "Join", "(", "logDir", ",", "\"", "\"", ")", ")", "\n", "if", "err", "!=", "nil"...
// deleteLogs deletes old logs.
[ "deleteLogs", "deletes", "old", "logs", "." ]
3493be98f11f3ca46cdb973a968f09f7cacc645d
https://github.com/google/zoekt/blob/3493be98f11f3ca46cdb973a968f09f7cacc645d/cmd/zoekt-indexserver/main.go#L165-L177
train
google/zoekt
cmd/zoekt-indexserver/main.go
deleteIfOrphan
func deleteIfOrphan(repoDir string, fn string) error { f, err := os.Open(fn) if err != nil { return nil } defer f.Close() ifile, err := zoekt.NewIndexFile(f) if err != nil { return nil } defer ifile.Close() repo, _, err := zoekt.ReadMetadata(ifile) if err != nil { return nil } _, err = os.Stat(repo.Source) if os.IsNotExist(err) { log.Printf("deleting orphan shard %s; source %q not found", fn, repo.Source) return os.Remove(fn) } return err }
go
func deleteIfOrphan(repoDir string, fn string) error { f, err := os.Open(fn) if err != nil { return nil } defer f.Close() ifile, err := zoekt.NewIndexFile(f) if err != nil { return nil } defer ifile.Close() repo, _, err := zoekt.ReadMetadata(ifile) if err != nil { return nil } _, err = os.Stat(repo.Source) if os.IsNotExist(err) { log.Printf("deleting orphan shard %s; source %q not found", fn, repo.Source) return os.Remove(fn) } return err }
[ "func", "deleteIfOrphan", "(", "repoDir", "string", ",", "fn", "string", ")", "error", "{", "f", ",", "err", ":=", "os", ".", "Open", "(", "fn", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", "\n", "}", "\n", "defer", "f", ".", "Close...
// Delete the shard if its corresponding git repo can't be found.
[ "Delete", "the", "shard", "if", "its", "corresponding", "git", "repo", "can", "t", "be", "found", "." ]
3493be98f11f3ca46cdb973a968f09f7cacc645d
https://github.com/google/zoekt/blob/3493be98f11f3ca46cdb973a968f09f7cacc645d/cmd/zoekt-indexserver/main.go#L188-L213
train
derekparker/trie
trie.go
New
func New() *Trie { return &Trie{ root: &Node{children: make(map[rune]*Node), depth: 0}, size: 0, } }
go
func New() *Trie { return &Trie{ root: &Node{children: make(map[rune]*Node), depth: 0}, size: 0, } }
[ "func", "New", "(", ")", "*", "Trie", "{", "return", "&", "Trie", "{", "root", ":", "&", "Node", "{", "children", ":", "make", "(", "map", "[", "rune", "]", "*", "Node", ")", ",", "depth", ":", "0", "}", ",", "size", ":", "0", ",", "}", "\n...
// Creates a new Trie with an initialized root Node.
[ "Creates", "a", "new", "Trie", "with", "an", "initialized", "root", "Node", "." ]
1ce4922c7ad906a094c6298977755068ba76ad31
https://github.com/derekparker/trie/blob/1ce4922c7ad906a094c6298977755068ba76ad31/trie.go#L38-L43
train
derekparker/trie
trie.go
Find
func (t *Trie) Find(key string) (*Node, bool) { node := findNode(t.Root(), []rune(key)) if node == nil { return nil, false } node, ok := node.Children()[nul] if !ok || !node.term { return nil, false } return node, true }
go
func (t *Trie) Find(key string) (*Node, bool) { node := findNode(t.Root(), []rune(key)) if node == nil { return nil, false } node, ok := node.Children()[nul] if !ok || !node.term { return nil, false } return node, true }
[ "func", "(", "t", "*", "Trie", ")", "Find", "(", "key", "string", ")", "(", "*", "Node", ",", "bool", ")", "{", "node", ":=", "findNode", "(", "t", ".", "Root", "(", ")", ",", "[", "]", "rune", "(", "key", ")", ")", "\n", "if", "node", "=="...
// Finds and returns meta data associated // with `key`.
[ "Finds", "and", "returns", "meta", "data", "associated", "with", "key", "." ]
1ce4922c7ad906a094c6298977755068ba76ad31
https://github.com/derekparker/trie/blob/1ce4922c7ad906a094c6298977755068ba76ad31/trie.go#L78-L90
train
derekparker/trie
trie.go
Remove
func (t *Trie) Remove(key string) { var ( i int rs = []rune(key) node = findNode(t.Root(), []rune(key)) ) t.mu.Lock() defer t.mu.Unlock() t.size-- for n := node.Parent(); n != nil; n = n.Parent() { i++ if len(n.Children()) > 1 { r := rs[len(rs)-i] n.RemoveChild(r) break } } }
go
func (t *Trie) Remove(key string) { var ( i int rs = []rune(key) node = findNode(t.Root(), []rune(key)) ) t.mu.Lock() defer t.mu.Unlock() t.size-- for n := node.Parent(); n != nil; n = n.Parent() { i++ if len(n.Children()) > 1 { r := rs[len(rs)-i] n.RemoveChild(r) break } } }
[ "func", "(", "t", "*", "Trie", ")", "Remove", "(", "key", "string", ")", "{", "var", "(", "i", "int", "\n", "rs", "=", "[", "]", "rune", "(", "key", ")", "\n", "node", "=", "findNode", "(", "t", ".", "Root", "(", ")", ",", "[", "]", "rune",...
// Removes a key from the trie, ensuring that // all bitmasks up to root are appropriately recalculated.
[ "Removes", "a", "key", "from", "the", "trie", "ensuring", "that", "all", "bitmasks", "up", "to", "root", "are", "appropriately", "recalculated", "." ]
1ce4922c7ad906a094c6298977755068ba76ad31
https://github.com/derekparker/trie/blob/1ce4922c7ad906a094c6298977755068ba76ad31/trie.go#L99-L118
train
derekparker/trie
trie.go
FuzzySearch
func (t Trie) FuzzySearch(pre string) []string { keys := fuzzycollect(t.Root(), []rune(pre)) sort.Sort(ByKeys(keys)) return keys }
go
func (t Trie) FuzzySearch(pre string) []string { keys := fuzzycollect(t.Root(), []rune(pre)) sort.Sort(ByKeys(keys)) return keys }
[ "func", "(", "t", "Trie", ")", "FuzzySearch", "(", "pre", "string", ")", "[", "]", "string", "{", "keys", ":=", "fuzzycollect", "(", "t", ".", "Root", "(", ")", ",", "[", "]", "rune", "(", "pre", ")", ")", "\n", "sort", ".", "Sort", "(", "ByKey...
// Performs a fuzzy search against the keys in the trie.
[ "Performs", "a", "fuzzy", "search", "against", "the", "keys", "in", "the", "trie", "." ]
1ce4922c7ad906a094c6298977755068ba76ad31
https://github.com/derekparker/trie/blob/1ce4922c7ad906a094c6298977755068ba76ad31/trie.go#L126-L130
train