repo
stringlengths 5
67
| path
stringlengths 4
218
| func_name
stringlengths 0
151
| original_string
stringlengths 52
373k
| language
stringclasses 6
values | code
stringlengths 52
373k
| code_tokens
listlengths 10
512
| docstring
stringlengths 3
47.2k
| docstring_tokens
listlengths 3
234
| sha
stringlengths 40
40
| url
stringlengths 85
339
| partition
stringclasses 3
values |
|---|---|---|---|---|---|---|---|---|---|---|---|
bazelbuild/bazel-gazelle
|
rule/rule.go
|
MacroName
|
func (f *File) MacroName() string {
if f.function != nil && f.function.stmt != nil {
return f.function.stmt.Name
}
return ""
}
|
go
|
func (f *File) MacroName() string {
if f.function != nil && f.function.stmt != nil {
return f.function.stmt.Name
}
return ""
}
|
[
"func",
"(",
"f",
"*",
"File",
")",
"MacroName",
"(",
")",
"string",
"{",
"if",
"f",
".",
"function",
"!=",
"nil",
"&&",
"f",
".",
"function",
".",
"stmt",
"!=",
"nil",
"{",
"return",
"f",
".",
"function",
".",
"stmt",
".",
"Name",
"\n",
"}",
"\n",
"return",
"\"\"",
"\n",
"}"
] |
// MacroName returns the name of the macro function that this file is editing,
// or an empty string if a macro function is not being edited.
|
[
"MacroName",
"returns",
"the",
"name",
"of",
"the",
"macro",
"function",
"that",
"this",
"file",
"is",
"editing",
"or",
"an",
"empty",
"string",
"if",
"a",
"macro",
"function",
"is",
"not",
"being",
"edited",
"."
] |
e3805aaca69a9deb949b47bfc45b9b1870712f4f
|
https://github.com/bazelbuild/bazel-gazelle/blob/e3805aaca69a9deb949b47bfc45b9b1870712f4f/rule/rule.go#L255-L260
|
test
|
bazelbuild/bazel-gazelle
|
rule/rule.go
|
Sync
|
func (f *File) Sync() {
var loadInserts, loadDeletes, loadStmts []*stmt
var r, w int
for r, w = 0, 0; r < len(f.Loads); r++ {
s := f.Loads[r]
s.sync()
if s.deleted {
loadDeletes = append(loadDeletes, &s.stmt)
continue
}
if s.inserted {
loadInserts = append(loadInserts, &s.stmt)
s.inserted = false
} else {
loadStmts = append(loadStmts, &s.stmt)
}
f.Loads[w] = s
w++
}
f.Loads = f.Loads[:w]
var ruleInserts, ruleDeletes, ruleStmts []*stmt
for r, w = 0, 0; r < len(f.Rules); r++ {
s := f.Rules[r]
s.sync()
if s.deleted {
ruleDeletes = append(ruleDeletes, &s.stmt)
continue
}
if s.inserted {
ruleInserts = append(ruleInserts, &s.stmt)
s.inserted = false
} else {
ruleStmts = append(ruleStmts, &s.stmt)
}
f.Rules[w] = s
w++
}
f.Rules = f.Rules[:w]
if f.function == nil {
deletes := append(ruleDeletes, loadDeletes...)
inserts := append(ruleInserts, loadInserts...)
stmts := append(ruleStmts, loadStmts...)
updateStmt(&f.File.Stmt, inserts, deletes, stmts)
} else {
updateStmt(&f.File.Stmt, loadInserts, loadDeletes, loadStmts)
if f.function.hasPass && len(ruleInserts) > 0 {
f.function.stmt.Body = []bzl.Expr{}
f.function.hasPass = false
}
updateStmt(&f.function.stmt.Body, ruleInserts, ruleDeletes, ruleStmts)
if len(f.function.stmt.Body) == 0 {
f.function.stmt.Body = append(f.function.stmt.Body, &bzl.BranchStmt{Token: "pass"})
f.function.hasPass = true
}
if !f.function.inserted {
f.File.Stmt = append(f.File.Stmt, f.function.stmt)
f.function.inserted = true
}
}
}
|
go
|
func (f *File) Sync() {
var loadInserts, loadDeletes, loadStmts []*stmt
var r, w int
for r, w = 0, 0; r < len(f.Loads); r++ {
s := f.Loads[r]
s.sync()
if s.deleted {
loadDeletes = append(loadDeletes, &s.stmt)
continue
}
if s.inserted {
loadInserts = append(loadInserts, &s.stmt)
s.inserted = false
} else {
loadStmts = append(loadStmts, &s.stmt)
}
f.Loads[w] = s
w++
}
f.Loads = f.Loads[:w]
var ruleInserts, ruleDeletes, ruleStmts []*stmt
for r, w = 0, 0; r < len(f.Rules); r++ {
s := f.Rules[r]
s.sync()
if s.deleted {
ruleDeletes = append(ruleDeletes, &s.stmt)
continue
}
if s.inserted {
ruleInserts = append(ruleInserts, &s.stmt)
s.inserted = false
} else {
ruleStmts = append(ruleStmts, &s.stmt)
}
f.Rules[w] = s
w++
}
f.Rules = f.Rules[:w]
if f.function == nil {
deletes := append(ruleDeletes, loadDeletes...)
inserts := append(ruleInserts, loadInserts...)
stmts := append(ruleStmts, loadStmts...)
updateStmt(&f.File.Stmt, inserts, deletes, stmts)
} else {
updateStmt(&f.File.Stmt, loadInserts, loadDeletes, loadStmts)
if f.function.hasPass && len(ruleInserts) > 0 {
f.function.stmt.Body = []bzl.Expr{}
f.function.hasPass = false
}
updateStmt(&f.function.stmt.Body, ruleInserts, ruleDeletes, ruleStmts)
if len(f.function.stmt.Body) == 0 {
f.function.stmt.Body = append(f.function.stmt.Body, &bzl.BranchStmt{Token: "pass"})
f.function.hasPass = true
}
if !f.function.inserted {
f.File.Stmt = append(f.File.Stmt, f.function.stmt)
f.function.inserted = true
}
}
}
|
[
"func",
"(",
"f",
"*",
"File",
")",
"Sync",
"(",
")",
"{",
"var",
"loadInserts",
",",
"loadDeletes",
",",
"loadStmts",
"[",
"]",
"*",
"stmt",
"\n",
"var",
"r",
",",
"w",
"int",
"\n",
"for",
"r",
",",
"w",
"=",
"0",
",",
"0",
";",
"r",
"<",
"len",
"(",
"f",
".",
"Loads",
")",
";",
"r",
"++",
"{",
"s",
":=",
"f",
".",
"Loads",
"[",
"r",
"]",
"\n",
"s",
".",
"sync",
"(",
")",
"\n",
"if",
"s",
".",
"deleted",
"{",
"loadDeletes",
"=",
"append",
"(",
"loadDeletes",
",",
"&",
"s",
".",
"stmt",
")",
"\n",
"continue",
"\n",
"}",
"\n",
"if",
"s",
".",
"inserted",
"{",
"loadInserts",
"=",
"append",
"(",
"loadInserts",
",",
"&",
"s",
".",
"stmt",
")",
"\n",
"s",
".",
"inserted",
"=",
"false",
"\n",
"}",
"else",
"{",
"loadStmts",
"=",
"append",
"(",
"loadStmts",
",",
"&",
"s",
".",
"stmt",
")",
"\n",
"}",
"\n",
"f",
".",
"Loads",
"[",
"w",
"]",
"=",
"s",
"\n",
"w",
"++",
"\n",
"}",
"\n",
"f",
".",
"Loads",
"=",
"f",
".",
"Loads",
"[",
":",
"w",
"]",
"\n",
"var",
"ruleInserts",
",",
"ruleDeletes",
",",
"ruleStmts",
"[",
"]",
"*",
"stmt",
"\n",
"for",
"r",
",",
"w",
"=",
"0",
",",
"0",
";",
"r",
"<",
"len",
"(",
"f",
".",
"Rules",
")",
";",
"r",
"++",
"{",
"s",
":=",
"f",
".",
"Rules",
"[",
"r",
"]",
"\n",
"s",
".",
"sync",
"(",
")",
"\n",
"if",
"s",
".",
"deleted",
"{",
"ruleDeletes",
"=",
"append",
"(",
"ruleDeletes",
",",
"&",
"s",
".",
"stmt",
")",
"\n",
"continue",
"\n",
"}",
"\n",
"if",
"s",
".",
"inserted",
"{",
"ruleInserts",
"=",
"append",
"(",
"ruleInserts",
",",
"&",
"s",
".",
"stmt",
")",
"\n",
"s",
".",
"inserted",
"=",
"false",
"\n",
"}",
"else",
"{",
"ruleStmts",
"=",
"append",
"(",
"ruleStmts",
",",
"&",
"s",
".",
"stmt",
")",
"\n",
"}",
"\n",
"f",
".",
"Rules",
"[",
"w",
"]",
"=",
"s",
"\n",
"w",
"++",
"\n",
"}",
"\n",
"f",
".",
"Rules",
"=",
"f",
".",
"Rules",
"[",
":",
"w",
"]",
"\n",
"if",
"f",
".",
"function",
"==",
"nil",
"{",
"deletes",
":=",
"append",
"(",
"ruleDeletes",
",",
"loadDeletes",
"...",
")",
"\n",
"inserts",
":=",
"append",
"(",
"ruleInserts",
",",
"loadInserts",
"...",
")",
"\n",
"stmts",
":=",
"append",
"(",
"ruleStmts",
",",
"loadStmts",
"...",
")",
"\n",
"updateStmt",
"(",
"&",
"f",
".",
"File",
".",
"Stmt",
",",
"inserts",
",",
"deletes",
",",
"stmts",
")",
"\n",
"}",
"else",
"{",
"updateStmt",
"(",
"&",
"f",
".",
"File",
".",
"Stmt",
",",
"loadInserts",
",",
"loadDeletes",
",",
"loadStmts",
")",
"\n",
"if",
"f",
".",
"function",
".",
"hasPass",
"&&",
"len",
"(",
"ruleInserts",
")",
">",
"0",
"{",
"f",
".",
"function",
".",
"stmt",
".",
"Body",
"=",
"[",
"]",
"bzl",
".",
"Expr",
"{",
"}",
"\n",
"f",
".",
"function",
".",
"hasPass",
"=",
"false",
"\n",
"}",
"\n",
"updateStmt",
"(",
"&",
"f",
".",
"function",
".",
"stmt",
".",
"Body",
",",
"ruleInserts",
",",
"ruleDeletes",
",",
"ruleStmts",
")",
"\n",
"if",
"len",
"(",
"f",
".",
"function",
".",
"stmt",
".",
"Body",
")",
"==",
"0",
"{",
"f",
".",
"function",
".",
"stmt",
".",
"Body",
"=",
"append",
"(",
"f",
".",
"function",
".",
"stmt",
".",
"Body",
",",
"&",
"bzl",
".",
"BranchStmt",
"{",
"Token",
":",
"\"pass\"",
"}",
")",
"\n",
"f",
".",
"function",
".",
"hasPass",
"=",
"true",
"\n",
"}",
"\n",
"if",
"!",
"f",
".",
"function",
".",
"inserted",
"{",
"f",
".",
"File",
".",
"Stmt",
"=",
"append",
"(",
"f",
".",
"File",
".",
"Stmt",
",",
"f",
".",
"function",
".",
"stmt",
")",
"\n",
"f",
".",
"function",
".",
"inserted",
"=",
"true",
"\n",
"}",
"\n",
"}",
"\n",
"}"
] |
// Sync writes all changes back to the wrapped syntax tree. This should be
// called after editing operations, before reading the syntax tree again.
|
[
"Sync",
"writes",
"all",
"changes",
"back",
"to",
"the",
"wrapped",
"syntax",
"tree",
".",
"This",
"should",
"be",
"called",
"after",
"editing",
"operations",
"before",
"reading",
"the",
"syntax",
"tree",
"again",
"."
] |
e3805aaca69a9deb949b47bfc45b9b1870712f4f
|
https://github.com/bazelbuild/bazel-gazelle/blob/e3805aaca69a9deb949b47bfc45b9b1870712f4f/rule/rule.go#L264-L324
|
test
|
bazelbuild/bazel-gazelle
|
rule/rule.go
|
Format
|
func (f *File) Format() []byte {
f.Sync()
return bzl.Format(f.File)
}
|
go
|
func (f *File) Format() []byte {
f.Sync()
return bzl.Format(f.File)
}
|
[
"func",
"(",
"f",
"*",
"File",
")",
"Format",
"(",
")",
"[",
"]",
"byte",
"{",
"f",
".",
"Sync",
"(",
")",
"\n",
"return",
"bzl",
".",
"Format",
"(",
"f",
".",
"File",
")",
"\n",
"}"
] |
// Format formats the build file in a form that can be written to disk.
// This method calls Sync internally.
|
[
"Format",
"formats",
"the",
"build",
"file",
"in",
"a",
"form",
"that",
"can",
"be",
"written",
"to",
"disk",
".",
"This",
"method",
"calls",
"Sync",
"internally",
"."
] |
e3805aaca69a9deb949b47bfc45b9b1870712f4f
|
https://github.com/bazelbuild/bazel-gazelle/blob/e3805aaca69a9deb949b47bfc45b9b1870712f4f/rule/rule.go#L358-L361
|
test
|
bazelbuild/bazel-gazelle
|
rule/rule.go
|
Save
|
func (f *File) Save(path string) error {
f.Sync()
data := bzl.Format(f.File)
return ioutil.WriteFile(path, data, 0666)
}
|
go
|
func (f *File) Save(path string) error {
f.Sync()
data := bzl.Format(f.File)
return ioutil.WriteFile(path, data, 0666)
}
|
[
"func",
"(",
"f",
"*",
"File",
")",
"Save",
"(",
"path",
"string",
")",
"error",
"{",
"f",
".",
"Sync",
"(",
")",
"\n",
"data",
":=",
"bzl",
".",
"Format",
"(",
"f",
".",
"File",
")",
"\n",
"return",
"ioutil",
".",
"WriteFile",
"(",
"path",
",",
"data",
",",
"0666",
")",
"\n",
"}"
] |
// Save writes the build file to disk. This method calls Sync internally.
|
[
"Save",
"writes",
"the",
"build",
"file",
"to",
"disk",
".",
"This",
"method",
"calls",
"Sync",
"internally",
"."
] |
e3805aaca69a9deb949b47bfc45b9b1870712f4f
|
https://github.com/bazelbuild/bazel-gazelle/blob/e3805aaca69a9deb949b47bfc45b9b1870712f4f/rule/rule.go#L364-L368
|
test
|
bazelbuild/bazel-gazelle
|
rule/rule.go
|
HasDefaultVisibility
|
func (f *File) HasDefaultVisibility() bool {
for _, r := range f.Rules {
if r.Kind() == "package" && r.Attr("default_visibility") != nil {
return true
}
}
return false
}
|
go
|
func (f *File) HasDefaultVisibility() bool {
for _, r := range f.Rules {
if r.Kind() == "package" && r.Attr("default_visibility") != nil {
return true
}
}
return false
}
|
[
"func",
"(",
"f",
"*",
"File",
")",
"HasDefaultVisibility",
"(",
")",
"bool",
"{",
"for",
"_",
",",
"r",
":=",
"range",
"f",
".",
"Rules",
"{",
"if",
"r",
".",
"Kind",
"(",
")",
"==",
"\"package\"",
"&&",
"r",
".",
"Attr",
"(",
"\"default_visibility\"",
")",
"!=",
"nil",
"{",
"return",
"true",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"false",
"\n",
"}"
] |
// HasDefaultVisibility returns whether the File contains a "package" rule with
// a "default_visibility" attribute. Rules generated by Gazelle should not
// have their own visibility attributes if this is the case.
|
[
"HasDefaultVisibility",
"returns",
"whether",
"the",
"File",
"contains",
"a",
"package",
"rule",
"with",
"a",
"default_visibility",
"attribute",
".",
"Rules",
"generated",
"by",
"Gazelle",
"should",
"not",
"have",
"their",
"own",
"visibility",
"attributes",
"if",
"this",
"is",
"the",
"case",
"."
] |
e3805aaca69a9deb949b47bfc45b9b1870712f4f
|
https://github.com/bazelbuild/bazel-gazelle/blob/e3805aaca69a9deb949b47bfc45b9b1870712f4f/rule/rule.go#L373-L380
|
test
|
bazelbuild/bazel-gazelle
|
rule/rule.go
|
NewLoad
|
func NewLoad(name string) *Load {
return &Load{
stmt: stmt{
expr: &bzl.LoadStmt{
Module: &bzl.StringExpr{Value: name},
ForceCompact: true,
},
},
name: name,
symbols: make(map[string]identPair),
}
}
|
go
|
func NewLoad(name string) *Load {
return &Load{
stmt: stmt{
expr: &bzl.LoadStmt{
Module: &bzl.StringExpr{Value: name},
ForceCompact: true,
},
},
name: name,
symbols: make(map[string]identPair),
}
}
|
[
"func",
"NewLoad",
"(",
"name",
"string",
")",
"*",
"Load",
"{",
"return",
"&",
"Load",
"{",
"stmt",
":",
"stmt",
"{",
"expr",
":",
"&",
"bzl",
".",
"LoadStmt",
"{",
"Module",
":",
"&",
"bzl",
".",
"StringExpr",
"{",
"Value",
":",
"name",
"}",
",",
"ForceCompact",
":",
"true",
",",
"}",
",",
"}",
",",
"name",
":",
"name",
",",
"symbols",
":",
"make",
"(",
"map",
"[",
"string",
"]",
"identPair",
")",
",",
"}",
"\n",
"}"
] |
// NewLoad creates a new, empty load statement for the given file name.
|
[
"NewLoad",
"creates",
"a",
"new",
"empty",
"load",
"statement",
"for",
"the",
"given",
"file",
"name",
"."
] |
e3805aaca69a9deb949b47bfc45b9b1870712f4f
|
https://github.com/bazelbuild/bazel-gazelle/blob/e3805aaca69a9deb949b47bfc45b9b1870712f4f/rule/rule.go#L426-L437
|
test
|
bazelbuild/bazel-gazelle
|
rule/rule.go
|
Symbols
|
func (l *Load) Symbols() []string {
syms := make([]string, 0, len(l.symbols))
for sym := range l.symbols {
syms = append(syms, sym)
}
sort.Strings(syms)
return syms
}
|
go
|
func (l *Load) Symbols() []string {
syms := make([]string, 0, len(l.symbols))
for sym := range l.symbols {
syms = append(syms, sym)
}
sort.Strings(syms)
return syms
}
|
[
"func",
"(",
"l",
"*",
"Load",
")",
"Symbols",
"(",
")",
"[",
"]",
"string",
"{",
"syms",
":=",
"make",
"(",
"[",
"]",
"string",
",",
"0",
",",
"len",
"(",
"l",
".",
"symbols",
")",
")",
"\n",
"for",
"sym",
":=",
"range",
"l",
".",
"symbols",
"{",
"syms",
"=",
"append",
"(",
"syms",
",",
"sym",
")",
"\n",
"}",
"\n",
"sort",
".",
"Strings",
"(",
"syms",
")",
"\n",
"return",
"syms",
"\n",
"}"
] |
// Symbols returns a list of symbols this statement loads.
|
[
"Symbols",
"returns",
"a",
"list",
"of",
"symbols",
"this",
"statement",
"loads",
"."
] |
e3805aaca69a9deb949b47bfc45b9b1870712f4f
|
https://github.com/bazelbuild/bazel-gazelle/blob/e3805aaca69a9deb949b47bfc45b9b1870712f4f/rule/rule.go#L458-L465
|
test
|
bazelbuild/bazel-gazelle
|
rule/rule.go
|
Has
|
func (l *Load) Has(sym string) bool {
_, ok := l.symbols[sym]
return ok
}
|
go
|
func (l *Load) Has(sym string) bool {
_, ok := l.symbols[sym]
return ok
}
|
[
"func",
"(",
"l",
"*",
"Load",
")",
"Has",
"(",
"sym",
"string",
")",
"bool",
"{",
"_",
",",
"ok",
":=",
"l",
".",
"symbols",
"[",
"sym",
"]",
"\n",
"return",
"ok",
"\n",
"}"
] |
// Has returns true if sym is loaded by this statement.
|
[
"Has",
"returns",
"true",
"if",
"sym",
"is",
"loaded",
"by",
"this",
"statement",
"."
] |
e3805aaca69a9deb949b47bfc45b9b1870712f4f
|
https://github.com/bazelbuild/bazel-gazelle/blob/e3805aaca69a9deb949b47bfc45b9b1870712f4f/rule/rule.go#L468-L471
|
test
|
bazelbuild/bazel-gazelle
|
rule/rule.go
|
Add
|
func (l *Load) Add(sym string) {
if _, ok := l.symbols[sym]; !ok {
i := &bzl.Ident{Name: sym}
l.symbols[sym] = identPair{to: i, from: i}
l.updated = true
}
}
|
go
|
func (l *Load) Add(sym string) {
if _, ok := l.symbols[sym]; !ok {
i := &bzl.Ident{Name: sym}
l.symbols[sym] = identPair{to: i, from: i}
l.updated = true
}
}
|
[
"func",
"(",
"l",
"*",
"Load",
")",
"Add",
"(",
"sym",
"string",
")",
"{",
"if",
"_",
",",
"ok",
":=",
"l",
".",
"symbols",
"[",
"sym",
"]",
";",
"!",
"ok",
"{",
"i",
":=",
"&",
"bzl",
".",
"Ident",
"{",
"Name",
":",
"sym",
"}",
"\n",
"l",
".",
"symbols",
"[",
"sym",
"]",
"=",
"identPair",
"{",
"to",
":",
"i",
",",
"from",
":",
"i",
"}",
"\n",
"l",
".",
"updated",
"=",
"true",
"\n",
"}",
"\n",
"}"
] |
// Add inserts a new symbol into the load statement. This has no effect if
// the symbol is already loaded. Symbols will be sorted, so the order
// doesn't matter.
|
[
"Add",
"inserts",
"a",
"new",
"symbol",
"into",
"the",
"load",
"statement",
".",
"This",
"has",
"no",
"effect",
"if",
"the",
"symbol",
"is",
"already",
"loaded",
".",
"Symbols",
"will",
"be",
"sorted",
"so",
"the",
"order",
"doesn",
"t",
"matter",
"."
] |
e3805aaca69a9deb949b47bfc45b9b1870712f4f
|
https://github.com/bazelbuild/bazel-gazelle/blob/e3805aaca69a9deb949b47bfc45b9b1870712f4f/rule/rule.go#L476-L482
|
test
|
bazelbuild/bazel-gazelle
|
rule/rule.go
|
Remove
|
func (l *Load) Remove(sym string) {
if _, ok := l.symbols[sym]; ok {
delete(l.symbols, sym)
l.updated = true
}
}
|
go
|
func (l *Load) Remove(sym string) {
if _, ok := l.symbols[sym]; ok {
delete(l.symbols, sym)
l.updated = true
}
}
|
[
"func",
"(",
"l",
"*",
"Load",
")",
"Remove",
"(",
"sym",
"string",
")",
"{",
"if",
"_",
",",
"ok",
":=",
"l",
".",
"symbols",
"[",
"sym",
"]",
";",
"ok",
"{",
"delete",
"(",
"l",
".",
"symbols",
",",
"sym",
")",
"\n",
"l",
".",
"updated",
"=",
"true",
"\n",
"}",
"\n",
"}"
] |
// Remove deletes a symbol from the load statement. This has no effect if
// the symbol is not loaded.
|
[
"Remove",
"deletes",
"a",
"symbol",
"from",
"the",
"load",
"statement",
".",
"This",
"has",
"no",
"effect",
"if",
"the",
"symbol",
"is",
"not",
"loaded",
"."
] |
e3805aaca69a9deb949b47bfc45b9b1870712f4f
|
https://github.com/bazelbuild/bazel-gazelle/blob/e3805aaca69a9deb949b47bfc45b9b1870712f4f/rule/rule.go#L486-L491
|
test
|
bazelbuild/bazel-gazelle
|
rule/rule.go
|
Insert
|
func (l *Load) Insert(f *File, index int) {
l.index = index
l.inserted = true
f.Loads = append(f.Loads, l)
}
|
go
|
func (l *Load) Insert(f *File, index int) {
l.index = index
l.inserted = true
f.Loads = append(f.Loads, l)
}
|
[
"func",
"(",
"l",
"*",
"Load",
")",
"Insert",
"(",
"f",
"*",
"File",
",",
"index",
"int",
")",
"{",
"l",
".",
"index",
"=",
"index",
"\n",
"l",
".",
"inserted",
"=",
"true",
"\n",
"f",
".",
"Loads",
"=",
"append",
"(",
"f",
".",
"Loads",
",",
"l",
")",
"\n",
"}"
] |
// Insert marks this statement for insertion at the given index. If multiple
// statements are inserted at the same index, they will be inserted in the
// order Insert is called.
|
[
"Insert",
"marks",
"this",
"statement",
"for",
"insertion",
"at",
"the",
"given",
"index",
".",
"If",
"multiple",
"statements",
"are",
"inserted",
"at",
"the",
"same",
"index",
"they",
"will",
"be",
"inserted",
"in",
"the",
"order",
"Insert",
"is",
"called",
"."
] |
e3805aaca69a9deb949b47bfc45b9b1870712f4f
|
https://github.com/bazelbuild/bazel-gazelle/blob/e3805aaca69a9deb949b47bfc45b9b1870712f4f/rule/rule.go#L501-L505
|
test
|
bazelbuild/bazel-gazelle
|
rule/rule.go
|
NewRule
|
func NewRule(kind, name string) *Rule {
nameAttr := &bzl.AssignExpr{
LHS: &bzl.Ident{Name: "name"},
RHS: &bzl.StringExpr{Value: name},
Op: "=",
}
r := &Rule{
stmt: stmt{
expr: &bzl.CallExpr{
X: &bzl.Ident{Name: kind},
List: []bzl.Expr{nameAttr},
},
},
kind: kind,
attrs: map[string]*bzl.AssignExpr{"name": nameAttr},
private: map[string]interface{}{},
}
return r
}
|
go
|
func NewRule(kind, name string) *Rule {
nameAttr := &bzl.AssignExpr{
LHS: &bzl.Ident{Name: "name"},
RHS: &bzl.StringExpr{Value: name},
Op: "=",
}
r := &Rule{
stmt: stmt{
expr: &bzl.CallExpr{
X: &bzl.Ident{Name: kind},
List: []bzl.Expr{nameAttr},
},
},
kind: kind,
attrs: map[string]*bzl.AssignExpr{"name": nameAttr},
private: map[string]interface{}{},
}
return r
}
|
[
"func",
"NewRule",
"(",
"kind",
",",
"name",
"string",
")",
"*",
"Rule",
"{",
"nameAttr",
":=",
"&",
"bzl",
".",
"AssignExpr",
"{",
"LHS",
":",
"&",
"bzl",
".",
"Ident",
"{",
"Name",
":",
"\"name\"",
"}",
",",
"RHS",
":",
"&",
"bzl",
".",
"StringExpr",
"{",
"Value",
":",
"name",
"}",
",",
"Op",
":",
"\"=\"",
",",
"}",
"\n",
"r",
":=",
"&",
"Rule",
"{",
"stmt",
":",
"stmt",
"{",
"expr",
":",
"&",
"bzl",
".",
"CallExpr",
"{",
"X",
":",
"&",
"bzl",
".",
"Ident",
"{",
"Name",
":",
"kind",
"}",
",",
"List",
":",
"[",
"]",
"bzl",
".",
"Expr",
"{",
"nameAttr",
"}",
",",
"}",
",",
"}",
",",
"kind",
":",
"kind",
",",
"attrs",
":",
"map",
"[",
"string",
"]",
"*",
"bzl",
".",
"AssignExpr",
"{",
"\"name\"",
":",
"nameAttr",
"}",
",",
"private",
":",
"map",
"[",
"string",
"]",
"interface",
"{",
"}",
"{",
"}",
",",
"}",
"\n",
"return",
"r",
"\n",
"}"
] |
// NewRule creates a new, empty rule with the given kind and name.
|
[
"NewRule",
"creates",
"a",
"new",
"empty",
"rule",
"with",
"the",
"given",
"kind",
"and",
"name",
"."
] |
e3805aaca69a9deb949b47bfc45b9b1870712f4f
|
https://github.com/bazelbuild/bazel-gazelle/blob/e3805aaca69a9deb949b47bfc45b9b1870712f4f/rule/rule.go#L551-L569
|
test
|
bazelbuild/bazel-gazelle
|
rule/rule.go
|
SetKind
|
func (r *Rule) SetKind(kind string) {
r.kind = kind
r.updated = true
}
|
go
|
func (r *Rule) SetKind(kind string) {
r.kind = kind
r.updated = true
}
|
[
"func",
"(",
"r",
"*",
"Rule",
")",
"SetKind",
"(",
"kind",
"string",
")",
"{",
"r",
".",
"kind",
"=",
"kind",
"\n",
"r",
".",
"updated",
"=",
"true",
"\n",
"}"
] |
// SetKind changes the kind of rule this is.
|
[
"SetKind",
"changes",
"the",
"kind",
"of",
"rule",
"this",
"is",
"."
] |
e3805aaca69a9deb949b47bfc45b9b1870712f4f
|
https://github.com/bazelbuild/bazel-gazelle/blob/e3805aaca69a9deb949b47bfc45b9b1870712f4f/rule/rule.go#L616-L619
|
test
|
bazelbuild/bazel-gazelle
|
rule/rule.go
|
AttrKeys
|
func (r *Rule) AttrKeys() []string {
keys := make([]string, 0, len(r.attrs))
for k := range r.attrs {
keys = append(keys, k)
}
sort.SliceStable(keys, func(i, j int) bool {
if cmp := bt.NamePriority[keys[i]] - bt.NamePriority[keys[j]]; cmp != 0 {
return cmp < 0
}
return keys[i] < keys[j]
})
return keys
}
|
go
|
func (r *Rule) AttrKeys() []string {
keys := make([]string, 0, len(r.attrs))
for k := range r.attrs {
keys = append(keys, k)
}
sort.SliceStable(keys, func(i, j int) bool {
if cmp := bt.NamePriority[keys[i]] - bt.NamePriority[keys[j]]; cmp != 0 {
return cmp < 0
}
return keys[i] < keys[j]
})
return keys
}
|
[
"func",
"(",
"r",
"*",
"Rule",
")",
"AttrKeys",
"(",
")",
"[",
"]",
"string",
"{",
"keys",
":=",
"make",
"(",
"[",
"]",
"string",
",",
"0",
",",
"len",
"(",
"r",
".",
"attrs",
")",
")",
"\n",
"for",
"k",
":=",
"range",
"r",
".",
"attrs",
"{",
"keys",
"=",
"append",
"(",
"keys",
",",
"k",
")",
"\n",
"}",
"\n",
"sort",
".",
"SliceStable",
"(",
"keys",
",",
"func",
"(",
"i",
",",
"j",
"int",
")",
"bool",
"{",
"if",
"cmp",
":=",
"bt",
".",
"NamePriority",
"[",
"keys",
"[",
"i",
"]",
"]",
"-",
"bt",
".",
"NamePriority",
"[",
"keys",
"[",
"j",
"]",
"]",
";",
"cmp",
"!=",
"0",
"{",
"return",
"cmp",
"<",
"0",
"\n",
"}",
"\n",
"return",
"keys",
"[",
"i",
"]",
"<",
"keys",
"[",
"j",
"]",
"\n",
"}",
")",
"\n",
"return",
"keys",
"\n",
"}"
] |
// AttrKeys returns a sorted list of attribute keys used in this rule.
|
[
"AttrKeys",
"returns",
"a",
"sorted",
"list",
"of",
"attribute",
"keys",
"used",
"in",
"this",
"rule",
"."
] |
e3805aaca69a9deb949b47bfc45b9b1870712f4f
|
https://github.com/bazelbuild/bazel-gazelle/blob/e3805aaca69a9deb949b47bfc45b9b1870712f4f/rule/rule.go#L633-L645
|
test
|
bazelbuild/bazel-gazelle
|
rule/rule.go
|
Attr
|
func (r *Rule) Attr(key string) bzl.Expr {
attr, ok := r.attrs[key]
if !ok {
return nil
}
return attr.RHS
}
|
go
|
func (r *Rule) Attr(key string) bzl.Expr {
attr, ok := r.attrs[key]
if !ok {
return nil
}
return attr.RHS
}
|
[
"func",
"(",
"r",
"*",
"Rule",
")",
"Attr",
"(",
"key",
"string",
")",
"bzl",
".",
"Expr",
"{",
"attr",
",",
"ok",
":=",
"r",
".",
"attrs",
"[",
"key",
"]",
"\n",
"if",
"!",
"ok",
"{",
"return",
"nil",
"\n",
"}",
"\n",
"return",
"attr",
".",
"RHS",
"\n",
"}"
] |
// Attr returns the value of the named attribute. nil is returned when the
// attribute is not set.
|
[
"Attr",
"returns",
"the",
"value",
"of",
"the",
"named",
"attribute",
".",
"nil",
"is",
"returned",
"when",
"the",
"attribute",
"is",
"not",
"set",
"."
] |
e3805aaca69a9deb949b47bfc45b9b1870712f4f
|
https://github.com/bazelbuild/bazel-gazelle/blob/e3805aaca69a9deb949b47bfc45b9b1870712f4f/rule/rule.go#L649-L655
|
test
|
bazelbuild/bazel-gazelle
|
rule/rule.go
|
AttrString
|
func (r *Rule) AttrString(key string) string {
attr, ok := r.attrs[key]
if !ok {
return ""
}
str, ok := attr.RHS.(*bzl.StringExpr)
if !ok {
return ""
}
return str.Value
}
|
go
|
func (r *Rule) AttrString(key string) string {
attr, ok := r.attrs[key]
if !ok {
return ""
}
str, ok := attr.RHS.(*bzl.StringExpr)
if !ok {
return ""
}
return str.Value
}
|
[
"func",
"(",
"r",
"*",
"Rule",
")",
"AttrString",
"(",
"key",
"string",
")",
"string",
"{",
"attr",
",",
"ok",
":=",
"r",
".",
"attrs",
"[",
"key",
"]",
"\n",
"if",
"!",
"ok",
"{",
"return",
"\"\"",
"\n",
"}",
"\n",
"str",
",",
"ok",
":=",
"attr",
".",
"RHS",
".",
"(",
"*",
"bzl",
".",
"StringExpr",
")",
"\n",
"if",
"!",
"ok",
"{",
"return",
"\"\"",
"\n",
"}",
"\n",
"return",
"str",
".",
"Value",
"\n",
"}"
] |
// AttrString returns the value of the named attribute if it is a scalar string.
// "" is returned if the attribute is not set or is not a string.
|
[
"AttrString",
"returns",
"the",
"value",
"of",
"the",
"named",
"attribute",
"if",
"it",
"is",
"a",
"scalar",
"string",
".",
"is",
"returned",
"if",
"the",
"attribute",
"is",
"not",
"set",
"or",
"is",
"not",
"a",
"string",
"."
] |
e3805aaca69a9deb949b47bfc45b9b1870712f4f
|
https://github.com/bazelbuild/bazel-gazelle/blob/e3805aaca69a9deb949b47bfc45b9b1870712f4f/rule/rule.go#L659-L669
|
test
|
bazelbuild/bazel-gazelle
|
rule/rule.go
|
AttrStrings
|
func (r *Rule) AttrStrings(key string) []string {
attr, ok := r.attrs[key]
if !ok {
return nil
}
list, ok := attr.RHS.(*bzl.ListExpr)
if !ok {
return nil
}
strs := make([]string, 0, len(list.List))
for _, e := range list.List {
if str, ok := e.(*bzl.StringExpr); ok {
strs = append(strs, str.Value)
}
}
return strs
}
|
go
|
func (r *Rule) AttrStrings(key string) []string {
attr, ok := r.attrs[key]
if !ok {
return nil
}
list, ok := attr.RHS.(*bzl.ListExpr)
if !ok {
return nil
}
strs := make([]string, 0, len(list.List))
for _, e := range list.List {
if str, ok := e.(*bzl.StringExpr); ok {
strs = append(strs, str.Value)
}
}
return strs
}
|
[
"func",
"(",
"r",
"*",
"Rule",
")",
"AttrStrings",
"(",
"key",
"string",
")",
"[",
"]",
"string",
"{",
"attr",
",",
"ok",
":=",
"r",
".",
"attrs",
"[",
"key",
"]",
"\n",
"if",
"!",
"ok",
"{",
"return",
"nil",
"\n",
"}",
"\n",
"list",
",",
"ok",
":=",
"attr",
".",
"RHS",
".",
"(",
"*",
"bzl",
".",
"ListExpr",
")",
"\n",
"if",
"!",
"ok",
"{",
"return",
"nil",
"\n",
"}",
"\n",
"strs",
":=",
"make",
"(",
"[",
"]",
"string",
",",
"0",
",",
"len",
"(",
"list",
".",
"List",
")",
")",
"\n",
"for",
"_",
",",
"e",
":=",
"range",
"list",
".",
"List",
"{",
"if",
"str",
",",
"ok",
":=",
"e",
".",
"(",
"*",
"bzl",
".",
"StringExpr",
")",
";",
"ok",
"{",
"strs",
"=",
"append",
"(",
"strs",
",",
"str",
".",
"Value",
")",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"strs",
"\n",
"}"
] |
// AttrStrings returns the string values of an attribute if it is a list.
// nil is returned if the attribute is not set or is not a list. Non-string
// values within the list won't be returned.
|
[
"AttrStrings",
"returns",
"the",
"string",
"values",
"of",
"an",
"attribute",
"if",
"it",
"is",
"a",
"list",
".",
"nil",
"is",
"returned",
"if",
"the",
"attribute",
"is",
"not",
"set",
"or",
"is",
"not",
"a",
"list",
".",
"Non",
"-",
"string",
"values",
"within",
"the",
"list",
"won",
"t",
"be",
"returned",
"."
] |
e3805aaca69a9deb949b47bfc45b9b1870712f4f
|
https://github.com/bazelbuild/bazel-gazelle/blob/e3805aaca69a9deb949b47bfc45b9b1870712f4f/rule/rule.go#L674-L690
|
test
|
bazelbuild/bazel-gazelle
|
rule/rule.go
|
DelAttr
|
func (r *Rule) DelAttr(key string) {
delete(r.attrs, key)
r.updated = true
}
|
go
|
func (r *Rule) DelAttr(key string) {
delete(r.attrs, key)
r.updated = true
}
|
[
"func",
"(",
"r",
"*",
"Rule",
")",
"DelAttr",
"(",
"key",
"string",
")",
"{",
"delete",
"(",
"r",
".",
"attrs",
",",
"key",
")",
"\n",
"r",
".",
"updated",
"=",
"true",
"\n",
"}"
] |
// DelAttr removes the named attribute from the rule.
|
[
"DelAttr",
"removes",
"the",
"named",
"attribute",
"from",
"the",
"rule",
"."
] |
e3805aaca69a9deb949b47bfc45b9b1870712f4f
|
https://github.com/bazelbuild/bazel-gazelle/blob/e3805aaca69a9deb949b47bfc45b9b1870712f4f/rule/rule.go#L693-L696
|
test
|
bazelbuild/bazel-gazelle
|
rule/rule.go
|
SetAttr
|
func (r *Rule) SetAttr(key string, value interface{}) {
rhs := ExprFromValue(value)
if attr, ok := r.attrs[key]; ok {
attr.RHS = rhs
} else {
r.attrs[key] = &bzl.AssignExpr{
LHS: &bzl.Ident{Name: key},
RHS: rhs,
Op: "=",
}
}
r.updated = true
}
|
go
|
func (r *Rule) SetAttr(key string, value interface{}) {
rhs := ExprFromValue(value)
if attr, ok := r.attrs[key]; ok {
attr.RHS = rhs
} else {
r.attrs[key] = &bzl.AssignExpr{
LHS: &bzl.Ident{Name: key},
RHS: rhs,
Op: "=",
}
}
r.updated = true
}
|
[
"func",
"(",
"r",
"*",
"Rule",
")",
"SetAttr",
"(",
"key",
"string",
",",
"value",
"interface",
"{",
"}",
")",
"{",
"rhs",
":=",
"ExprFromValue",
"(",
"value",
")",
"\n",
"if",
"attr",
",",
"ok",
":=",
"r",
".",
"attrs",
"[",
"key",
"]",
";",
"ok",
"{",
"attr",
".",
"RHS",
"=",
"rhs",
"\n",
"}",
"else",
"{",
"r",
".",
"attrs",
"[",
"key",
"]",
"=",
"&",
"bzl",
".",
"AssignExpr",
"{",
"LHS",
":",
"&",
"bzl",
".",
"Ident",
"{",
"Name",
":",
"key",
"}",
",",
"RHS",
":",
"rhs",
",",
"Op",
":",
"\"=\"",
",",
"}",
"\n",
"}",
"\n",
"r",
".",
"updated",
"=",
"true",
"\n",
"}"
] |
// SetAttr adds or replaces the named attribute with an expression produced
// by ExprFromValue.
|
[
"SetAttr",
"adds",
"or",
"replaces",
"the",
"named",
"attribute",
"with",
"an",
"expression",
"produced",
"by",
"ExprFromValue",
"."
] |
e3805aaca69a9deb949b47bfc45b9b1870712f4f
|
https://github.com/bazelbuild/bazel-gazelle/blob/e3805aaca69a9deb949b47bfc45b9b1870712f4f/rule/rule.go#L700-L712
|
test
|
bazelbuild/bazel-gazelle
|
rule/rule.go
|
PrivateAttrKeys
|
func (r *Rule) PrivateAttrKeys() []string {
keys := make([]string, 0, len(r.private))
for k := range r.private {
keys = append(keys, k)
}
sort.Strings(keys)
return keys
}
|
go
|
func (r *Rule) PrivateAttrKeys() []string {
keys := make([]string, 0, len(r.private))
for k := range r.private {
keys = append(keys, k)
}
sort.Strings(keys)
return keys
}
|
[
"func",
"(",
"r",
"*",
"Rule",
")",
"PrivateAttrKeys",
"(",
")",
"[",
"]",
"string",
"{",
"keys",
":=",
"make",
"(",
"[",
"]",
"string",
",",
"0",
",",
"len",
"(",
"r",
".",
"private",
")",
")",
"\n",
"for",
"k",
":=",
"range",
"r",
".",
"private",
"{",
"keys",
"=",
"append",
"(",
"keys",
",",
"k",
")",
"\n",
"}",
"\n",
"sort",
".",
"Strings",
"(",
"keys",
")",
"\n",
"return",
"keys",
"\n",
"}"
] |
// PrivateAttrKeys returns a sorted list of private attribute names.
|
[
"PrivateAttrKeys",
"returns",
"a",
"sorted",
"list",
"of",
"private",
"attribute",
"names",
"."
] |
e3805aaca69a9deb949b47bfc45b9b1870712f4f
|
https://github.com/bazelbuild/bazel-gazelle/blob/e3805aaca69a9deb949b47bfc45b9b1870712f4f/rule/rule.go#L715-L722
|
test
|
bazelbuild/bazel-gazelle
|
rule/rule.go
|
SetPrivateAttr
|
func (r *Rule) SetPrivateAttr(key string, value interface{}) {
r.private[key] = value
}
|
go
|
func (r *Rule) SetPrivateAttr(key string, value interface{}) {
r.private[key] = value
}
|
[
"func",
"(",
"r",
"*",
"Rule",
")",
"SetPrivateAttr",
"(",
"key",
"string",
",",
"value",
"interface",
"{",
"}",
")",
"{",
"r",
".",
"private",
"[",
"key",
"]",
"=",
"value",
"\n",
"}"
] |
// SetPrivateAttr associates a value with a key. Unlike SetAttr, this value
// is not converted to a build syntax tree and will not be written to a build
// file.
|
[
"SetPrivateAttr",
"associates",
"a",
"value",
"with",
"a",
"key",
".",
"Unlike",
"SetAttr",
"this",
"value",
"is",
"not",
"converted",
"to",
"a",
"build",
"syntax",
"tree",
"and",
"will",
"not",
"be",
"written",
"to",
"a",
"build",
"file",
"."
] |
e3805aaca69a9deb949b47bfc45b9b1870712f4f
|
https://github.com/bazelbuild/bazel-gazelle/blob/e3805aaca69a9deb949b47bfc45b9b1870712f4f/rule/rule.go#L732-L734
|
test
|
bazelbuild/bazel-gazelle
|
rule/rule.go
|
Insert
|
func (r *Rule) Insert(f *File) {
// TODO(jayconrod): should rules always be inserted at the end? Should there
// be some sort order?
var stmt []bzl.Expr
if f.function == nil {
stmt = f.File.Stmt
} else {
stmt = f.function.stmt.Body
}
r.index = len(stmt)
r.inserted = true
f.Rules = append(f.Rules, r)
}
|
go
|
func (r *Rule) Insert(f *File) {
// TODO(jayconrod): should rules always be inserted at the end? Should there
// be some sort order?
var stmt []bzl.Expr
if f.function == nil {
stmt = f.File.Stmt
} else {
stmt = f.function.stmt.Body
}
r.index = len(stmt)
r.inserted = true
f.Rules = append(f.Rules, r)
}
|
[
"func",
"(",
"r",
"*",
"Rule",
")",
"Insert",
"(",
"f",
"*",
"File",
")",
"{",
"var",
"stmt",
"[",
"]",
"bzl",
".",
"Expr",
"\n",
"if",
"f",
".",
"function",
"==",
"nil",
"{",
"stmt",
"=",
"f",
".",
"File",
".",
"Stmt",
"\n",
"}",
"else",
"{",
"stmt",
"=",
"f",
".",
"function",
".",
"stmt",
".",
"Body",
"\n",
"}",
"\n",
"r",
".",
"index",
"=",
"len",
"(",
"stmt",
")",
"\n",
"r",
".",
"inserted",
"=",
"true",
"\n",
"f",
".",
"Rules",
"=",
"append",
"(",
"f",
".",
"Rules",
",",
"r",
")",
"\n",
"}"
] |
// Insert marks this statement for insertion at the end of the file. Multiple
// statements will be inserted in the order Insert is called.
|
[
"Insert",
"marks",
"this",
"statement",
"for",
"insertion",
"at",
"the",
"end",
"of",
"the",
"file",
".",
"Multiple",
"statements",
"will",
"be",
"inserted",
"in",
"the",
"order",
"Insert",
"is",
"called",
"."
] |
e3805aaca69a9deb949b47bfc45b9b1870712f4f
|
https://github.com/bazelbuild/bazel-gazelle/blob/e3805aaca69a9deb949b47bfc45b9b1870712f4f/rule/rule.go#L743-L755
|
test
|
bazelbuild/bazel-gazelle
|
rule/rule.go
|
IsEmpty
|
func (r *Rule) IsEmpty(info KindInfo) bool {
if info.NonEmptyAttrs == nil {
return false
}
for k := range info.NonEmptyAttrs {
if _, ok := r.attrs[k]; ok {
return false
}
}
return true
}
|
go
|
func (r *Rule) IsEmpty(info KindInfo) bool {
if info.NonEmptyAttrs == nil {
return false
}
for k := range info.NonEmptyAttrs {
if _, ok := r.attrs[k]; ok {
return false
}
}
return true
}
|
[
"func",
"(",
"r",
"*",
"Rule",
")",
"IsEmpty",
"(",
"info",
"KindInfo",
")",
"bool",
"{",
"if",
"info",
".",
"NonEmptyAttrs",
"==",
"nil",
"{",
"return",
"false",
"\n",
"}",
"\n",
"for",
"k",
":=",
"range",
"info",
".",
"NonEmptyAttrs",
"{",
"if",
"_",
",",
"ok",
":=",
"r",
".",
"attrs",
"[",
"k",
"]",
";",
"ok",
"{",
"return",
"false",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"true",
"\n",
"}"
] |
// IsEmpty returns true when the rule contains none of the attributes in attrs
// for its kind. attrs should contain attributes that make the rule buildable
// like srcs or deps and not descriptive attributes like name or visibility.
|
[
"IsEmpty",
"returns",
"true",
"when",
"the",
"rule",
"contains",
"none",
"of",
"the",
"attributes",
"in",
"attrs",
"for",
"its",
"kind",
".",
"attrs",
"should",
"contain",
"attributes",
"that",
"make",
"the",
"rule",
"buildable",
"like",
"srcs",
"or",
"deps",
"and",
"not",
"descriptive",
"attributes",
"like",
"name",
"or",
"visibility",
"."
] |
e3805aaca69a9deb949b47bfc45b9b1870712f4f
|
https://github.com/bazelbuild/bazel-gazelle/blob/e3805aaca69a9deb949b47bfc45b9b1870712f4f/rule/rule.go#L760-L770
|
test
|
bazelbuild/bazel-gazelle
|
rule/rule.go
|
CheckInternalVisibility
|
func CheckInternalVisibility(rel, visibility string) string {
if i := strings.LastIndex(rel, "/internal/"); i >= 0 {
visibility = fmt.Sprintf("//%s:__subpackages__", rel[:i])
} else if strings.HasPrefix(rel, "internal/") {
visibility = "//:__subpackages__"
}
return visibility
}
|
go
|
func CheckInternalVisibility(rel, visibility string) string {
if i := strings.LastIndex(rel, "/internal/"); i >= 0 {
visibility = fmt.Sprintf("//%s:__subpackages__", rel[:i])
} else if strings.HasPrefix(rel, "internal/") {
visibility = "//:__subpackages__"
}
return visibility
}
|
[
"func",
"CheckInternalVisibility",
"(",
"rel",
",",
"visibility",
"string",
")",
"string",
"{",
"if",
"i",
":=",
"strings",
".",
"LastIndex",
"(",
"rel",
",",
"\"/internal/\"",
")",
";",
"i",
">=",
"0",
"{",
"visibility",
"=",
"fmt",
".",
"Sprintf",
"(",
"\"//%s:__subpackages__\"",
",",
"rel",
"[",
":",
"i",
"]",
")",
"\n",
"}",
"else",
"if",
"strings",
".",
"HasPrefix",
"(",
"rel",
",",
"\"internal/\"",
")",
"{",
"visibility",
"=",
"\"//:__subpackages__\"",
"\n",
"}",
"\n",
"return",
"visibility",
"\n",
"}"
] |
// CheckInternalVisibility overrides the given visibility if the package is
// internal.
|
[
"CheckInternalVisibility",
"overrides",
"the",
"given",
"visibility",
"if",
"the",
"package",
"is",
"internal",
"."
] |
e3805aaca69a9deb949b47bfc45b9b1870712f4f
|
https://github.com/bazelbuild/bazel-gazelle/blob/e3805aaca69a9deb949b47bfc45b9b1870712f4f/rule/rule.go#L824-L831
|
test
|
bazelbuild/bazel-gazelle
|
label/label.go
|
New
|
func New(repo, pkg, name string) Label {
return Label{Repo: repo, Pkg: pkg, Name: name}
}
|
go
|
func New(repo, pkg, name string) Label {
return Label{Repo: repo, Pkg: pkg, Name: name}
}
|
[
"func",
"New",
"(",
"repo",
",",
"pkg",
",",
"name",
"string",
")",
"Label",
"{",
"return",
"Label",
"{",
"Repo",
":",
"repo",
",",
"Pkg",
":",
"pkg",
",",
"Name",
":",
"name",
"}",
"\n",
"}"
] |
// New constructs a new label from components.
|
[
"New",
"constructs",
"a",
"new",
"label",
"from",
"components",
"."
] |
e3805aaca69a9deb949b47bfc45b9b1870712f4f
|
https://github.com/bazelbuild/bazel-gazelle/blob/e3805aaca69a9deb949b47bfc45b9b1870712f4f/label/label.go#L54-L56
|
test
|
bazelbuild/bazel-gazelle
|
label/label.go
|
Rel
|
func (l Label) Rel(repo, pkg string) Label {
if l.Relative || l.Repo != repo {
return l
}
if l.Pkg == pkg {
return Label{Name: l.Name, Relative: true}
}
return Label{Pkg: l.Pkg, Name: l.Name}
}
|
go
|
func (l Label) Rel(repo, pkg string) Label {
if l.Relative || l.Repo != repo {
return l
}
if l.Pkg == pkg {
return Label{Name: l.Name, Relative: true}
}
return Label{Pkg: l.Pkg, Name: l.Name}
}
|
[
"func",
"(",
"l",
"Label",
")",
"Rel",
"(",
"repo",
",",
"pkg",
"string",
")",
"Label",
"{",
"if",
"l",
".",
"Relative",
"||",
"l",
".",
"Repo",
"!=",
"repo",
"{",
"return",
"l",
"\n",
"}",
"\n",
"if",
"l",
".",
"Pkg",
"==",
"pkg",
"{",
"return",
"Label",
"{",
"Name",
":",
"l",
".",
"Name",
",",
"Relative",
":",
"true",
"}",
"\n",
"}",
"\n",
"return",
"Label",
"{",
"Pkg",
":",
"l",
".",
"Pkg",
",",
"Name",
":",
"l",
".",
"Name",
"}",
"\n",
"}"
] |
// Rel attempts to compute a relative label from this label. If this label
// is already relative or is in a different package, this label may be
// returned unchanged.
|
[
"Rel",
"attempts",
"to",
"compute",
"a",
"relative",
"label",
"from",
"this",
"label",
".",
"If",
"this",
"label",
"is",
"already",
"relative",
"or",
"is",
"in",
"a",
"different",
"package",
"this",
"label",
"may",
"be",
"returned",
"unchanged",
"."
] |
e3805aaca69a9deb949b47bfc45b9b1870712f4f
|
https://github.com/bazelbuild/bazel-gazelle/blob/e3805aaca69a9deb949b47bfc45b9b1870712f4f/label/label.go#L156-L164
|
test
|
bazelbuild/bazel-gazelle
|
label/label.go
|
Equal
|
func (l Label) Equal(other Label) bool {
return l.Repo == other.Repo &&
l.Pkg == other.Pkg &&
l.Name == other.Name &&
l.Relative == other.Relative
}
|
go
|
func (l Label) Equal(other Label) bool {
return l.Repo == other.Repo &&
l.Pkg == other.Pkg &&
l.Name == other.Name &&
l.Relative == other.Relative
}
|
[
"func",
"(",
"l",
"Label",
")",
"Equal",
"(",
"other",
"Label",
")",
"bool",
"{",
"return",
"l",
".",
"Repo",
"==",
"other",
".",
"Repo",
"&&",
"l",
".",
"Pkg",
"==",
"other",
".",
"Pkg",
"&&",
"l",
".",
"Name",
"==",
"other",
".",
"Name",
"&&",
"l",
".",
"Relative",
"==",
"other",
".",
"Relative",
"\n",
"}"
] |
// Equal returns whether two labels are exactly the same. It does not return
// true for different labels that refer to the same target.
|
[
"Equal",
"returns",
"whether",
"two",
"labels",
"are",
"exactly",
"the",
"same",
".",
"It",
"does",
"not",
"return",
"true",
"for",
"different",
"labels",
"that",
"refer",
"to",
"the",
"same",
"target",
"."
] |
e3805aaca69a9deb949b47bfc45b9b1870712f4f
|
https://github.com/bazelbuild/bazel-gazelle/blob/e3805aaca69a9deb949b47bfc45b9b1870712f4f/label/label.go#L168-L173
|
test
|
bazelbuild/bazel-gazelle
|
label/label.go
|
Contains
|
func (l Label) Contains(other Label) bool {
if l.Relative {
log.Panicf("l must not be relative: %s", l)
}
if other.Relative {
log.Panicf("other must not be relative: %s", other)
}
result := l.Repo == other.Repo && pathtools.HasPrefix(other.Pkg, l.Pkg)
return result
}
|
go
|
func (l Label) Contains(other Label) bool {
if l.Relative {
log.Panicf("l must not be relative: %s", l)
}
if other.Relative {
log.Panicf("other must not be relative: %s", other)
}
result := l.Repo == other.Repo && pathtools.HasPrefix(other.Pkg, l.Pkg)
return result
}
|
[
"func",
"(",
"l",
"Label",
")",
"Contains",
"(",
"other",
"Label",
")",
"bool",
"{",
"if",
"l",
".",
"Relative",
"{",
"log",
".",
"Panicf",
"(",
"\"l must not be relative: %s\"",
",",
"l",
")",
"\n",
"}",
"\n",
"if",
"other",
".",
"Relative",
"{",
"log",
".",
"Panicf",
"(",
"\"other must not be relative: %s\"",
",",
"other",
")",
"\n",
"}",
"\n",
"result",
":=",
"l",
".",
"Repo",
"==",
"other",
".",
"Repo",
"&&",
"pathtools",
".",
"HasPrefix",
"(",
"other",
".",
"Pkg",
",",
"l",
".",
"Pkg",
")",
"\n",
"return",
"result",
"\n",
"}"
] |
// Contains returns whether other is contained by the package of l or a
// sub-package. Neither label may be relative.
|
[
"Contains",
"returns",
"whether",
"other",
"is",
"contained",
"by",
"the",
"package",
"of",
"l",
"or",
"a",
"sub",
"-",
"package",
".",
"Neither",
"label",
"may",
"be",
"relative",
"."
] |
e3805aaca69a9deb949b47bfc45b9b1870712f4f
|
https://github.com/bazelbuild/bazel-gazelle/blob/e3805aaca69a9deb949b47bfc45b9b1870712f4f/label/label.go#L177-L186
|
test
|
bazelbuild/bazel-gazelle
|
language/proto/gen/update_proto_csv.go
|
generateFromPath
|
func generateFromPath(w io.Writer, rootPath string) error {
return filepath.Walk(rootPath, func(path string, info os.FileInfo, err error) error {
if err != nil {
return err
}
if !strings.HasSuffix(path, ".proto") {
return nil
}
relPath, err := filepath.Rel(rootPath, path)
if err != nil || strings.HasPrefix(relPath, "..") {
log.Panicf("file %q not in repository rootPath %q", path, rootPath)
}
relPath = filepath.ToSlash(relPath)
if strings.HasPrefix(relPath, "google/api/experimental/") {
// Special case: these protos need to be built together with protos in
// google/api. They have the same 'option go_package'. The proto_library
// rule requires them to be in the same Bazel package, so we don't
// create a build file in experimental.
packagePath := "google.golang.org/genproto/googleapis/api"
protoLabel, goLabel := protoLabels("google/api/x", "api")
fmt.Fprintf(w, "%s,%s,%s,%s\n", relPath, protoLabel, packagePath, goLabel)
return nil
}
packagePath, packageName, err := loadGoPackage(path)
if err != nil {
log.Print(err)
return nil
}
protoLabel, goLabel := protoLabels(relPath, packageName)
fmt.Fprintf(w, "%s,%s,%s,%s\n", relPath, protoLabel, packagePath, goLabel)
return nil
})
}
|
go
|
func generateFromPath(w io.Writer, rootPath string) error {
return filepath.Walk(rootPath, func(path string, info os.FileInfo, err error) error {
if err != nil {
return err
}
if !strings.HasSuffix(path, ".proto") {
return nil
}
relPath, err := filepath.Rel(rootPath, path)
if err != nil || strings.HasPrefix(relPath, "..") {
log.Panicf("file %q not in repository rootPath %q", path, rootPath)
}
relPath = filepath.ToSlash(relPath)
if strings.HasPrefix(relPath, "google/api/experimental/") {
// Special case: these protos need to be built together with protos in
// google/api. They have the same 'option go_package'. The proto_library
// rule requires them to be in the same Bazel package, so we don't
// create a build file in experimental.
packagePath := "google.golang.org/genproto/googleapis/api"
protoLabel, goLabel := protoLabels("google/api/x", "api")
fmt.Fprintf(w, "%s,%s,%s,%s\n", relPath, protoLabel, packagePath, goLabel)
return nil
}
packagePath, packageName, err := loadGoPackage(path)
if err != nil {
log.Print(err)
return nil
}
protoLabel, goLabel := protoLabels(relPath, packageName)
fmt.Fprintf(w, "%s,%s,%s,%s\n", relPath, protoLabel, packagePath, goLabel)
return nil
})
}
|
[
"func",
"generateFromPath",
"(",
"w",
"io",
".",
"Writer",
",",
"rootPath",
"string",
")",
"error",
"{",
"return",
"filepath",
".",
"Walk",
"(",
"rootPath",
",",
"func",
"(",
"path",
"string",
",",
"info",
"os",
".",
"FileInfo",
",",
"err",
"error",
")",
"error",
"{",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"if",
"!",
"strings",
".",
"HasSuffix",
"(",
"path",
",",
"\".proto\"",
")",
"{",
"return",
"nil",
"\n",
"}",
"\n",
"relPath",
",",
"err",
":=",
"filepath",
".",
"Rel",
"(",
"rootPath",
",",
"path",
")",
"\n",
"if",
"err",
"!=",
"nil",
"||",
"strings",
".",
"HasPrefix",
"(",
"relPath",
",",
"\"..\"",
")",
"{",
"log",
".",
"Panicf",
"(",
"\"file %q not in repository rootPath %q\"",
",",
"path",
",",
"rootPath",
")",
"\n",
"}",
"\n",
"relPath",
"=",
"filepath",
".",
"ToSlash",
"(",
"relPath",
")",
"\n",
"if",
"strings",
".",
"HasPrefix",
"(",
"relPath",
",",
"\"google/api/experimental/\"",
")",
"{",
"packagePath",
":=",
"\"google.golang.org/genproto/googleapis/api\"",
"\n",
"protoLabel",
",",
"goLabel",
":=",
"protoLabels",
"(",
"\"google/api/x\"",
",",
"\"api\"",
")",
"\n",
"fmt",
".",
"Fprintf",
"(",
"w",
",",
"\"%s,%s,%s,%s\\n\"",
",",
"\\n",
",",
"relPath",
",",
"protoLabel",
",",
"packagePath",
")",
"\n",
"goLabel",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"packagePath",
",",
"packageName",
",",
"err",
":=",
"loadGoPackage",
"(",
"path",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"log",
".",
"Print",
"(",
"err",
")",
"\n",
"return",
"nil",
"\n",
"}",
"\n",
"protoLabel",
",",
"goLabel",
":=",
"protoLabels",
"(",
"relPath",
",",
"packageName",
")",
"\n",
"fmt",
".",
"Fprintf",
"(",
"w",
",",
"\"%s,%s,%s,%s\\n\"",
",",
"\\n",
",",
"relPath",
",",
"protoLabel",
",",
"packagePath",
")",
"\n",
"}",
")",
"\n",
"}"
] |
//
// Process -go_googleapis case
//
|
[
"Process",
"-",
"go_googleapis",
"case"
] |
e3805aaca69a9deb949b47bfc45b9b1870712f4f
|
https://github.com/bazelbuild/bazel-gazelle/blob/e3805aaca69a9deb949b47bfc45b9b1870712f4f/language/proto/gen/update_proto_csv.go#L289-L325
|
test
|
bazelbuild/bazel-gazelle
|
walk/walk.go
|
shouldCall
|
func shouldCall(rel string, mode Mode, updateRels map[string]bool) bool {
return mode != UpdateDirsMode || updateRels[rel]
}
|
go
|
func shouldCall(rel string, mode Mode, updateRels map[string]bool) bool {
return mode != UpdateDirsMode || updateRels[rel]
}
|
[
"func",
"shouldCall",
"(",
"rel",
"string",
",",
"mode",
"Mode",
",",
"updateRels",
"map",
"[",
"string",
"]",
"bool",
")",
"bool",
"{",
"return",
"mode",
"!=",
"UpdateDirsMode",
"||",
"updateRels",
"[",
"rel",
"]",
"\n",
"}"
] |
// shouldCall returns true if Walk should call the callback in the
// directory rel.
|
[
"shouldCall",
"returns",
"true",
"if",
"Walk",
"should",
"call",
"the",
"callback",
"in",
"the",
"directory",
"rel",
"."
] |
e3805aaca69a9deb949b47bfc45b9b1870712f4f
|
https://github.com/bazelbuild/bazel-gazelle/blob/e3805aaca69a9deb949b47bfc45b9b1870712f4f/walk/walk.go#L209-L211
|
test
|
bazelbuild/bazel-gazelle
|
walk/walk.go
|
shouldUpdate
|
func shouldUpdate(rel string, mode Mode, updateParent bool, updateRels map[string]bool) bool {
return mode == VisitAllUpdateSubdirsMode && updateParent || updateRels[rel]
}
|
go
|
func shouldUpdate(rel string, mode Mode, updateParent bool, updateRels map[string]bool) bool {
return mode == VisitAllUpdateSubdirsMode && updateParent || updateRels[rel]
}
|
[
"func",
"shouldUpdate",
"(",
"rel",
"string",
",",
"mode",
"Mode",
",",
"updateParent",
"bool",
",",
"updateRels",
"map",
"[",
"string",
"]",
"bool",
")",
"bool",
"{",
"return",
"mode",
"==",
"VisitAllUpdateSubdirsMode",
"&&",
"updateParent",
"||",
"updateRels",
"[",
"rel",
"]",
"\n",
"}"
] |
// shouldUpdate returns true if Walk should pass true to the callback's update
// parameter in the directory rel. This indicates the build file should be
// updated.
|
[
"shouldUpdate",
"returns",
"true",
"if",
"Walk",
"should",
"pass",
"true",
"to",
"the",
"callback",
"s",
"update",
"parameter",
"in",
"the",
"directory",
"rel",
".",
"This",
"indicates",
"the",
"build",
"file",
"should",
"be",
"updated",
"."
] |
e3805aaca69a9deb949b47bfc45b9b1870712f4f
|
https://github.com/bazelbuild/bazel-gazelle/blob/e3805aaca69a9deb949b47bfc45b9b1870712f4f/walk/walk.go#L216-L218
|
test
|
bazelbuild/bazel-gazelle
|
walk/walk.go
|
shouldVisit
|
func shouldVisit(rel string, mode Mode, updateRels map[string]bool) bool {
if mode != UpdateDirsMode {
return true
}
_, ok := updateRels[rel]
return ok
}
|
go
|
func shouldVisit(rel string, mode Mode, updateRels map[string]bool) bool {
if mode != UpdateDirsMode {
return true
}
_, ok := updateRels[rel]
return ok
}
|
[
"func",
"shouldVisit",
"(",
"rel",
"string",
",",
"mode",
"Mode",
",",
"updateRels",
"map",
"[",
"string",
"]",
"bool",
")",
"bool",
"{",
"if",
"mode",
"!=",
"UpdateDirsMode",
"{",
"return",
"true",
"\n",
"}",
"\n",
"_",
",",
"ok",
":=",
"updateRels",
"[",
"rel",
"]",
"\n",
"return",
"ok",
"\n",
"}"
] |
// shouldVisit returns true if Walk should visit the subdirectory rel.
|
[
"shouldVisit",
"returns",
"true",
"if",
"Walk",
"should",
"visit",
"the",
"subdirectory",
"rel",
"."
] |
e3805aaca69a9deb949b47bfc45b9b1870712f4f
|
https://github.com/bazelbuild/bazel-gazelle/blob/e3805aaca69a9deb949b47bfc45b9b1870712f4f/walk/walk.go#L221-L227
|
test
|
bazelbuild/bazel-gazelle
|
rule/merge.go
|
SquashRules
|
func SquashRules(src, dst *Rule, filename string) error {
if dst.ShouldKeep() {
return nil
}
for key, srcAttr := range src.attrs {
srcValue := srcAttr.RHS
if dstAttr, ok := dst.attrs[key]; !ok {
dst.SetAttr(key, srcValue)
} else if !ShouldKeep(dstAttr) {
dstValue := dstAttr.RHS
if squashedValue, err := squashExprs(srcValue, dstValue); err != nil {
start, end := dstValue.Span()
return fmt.Errorf("%s:%d.%d-%d.%d: could not squash expression", filename, start.Line, start.LineRune, end.Line, end.LineRune)
} else {
dst.SetAttr(key, squashedValue)
}
}
}
dst.expr.Comment().Before = append(dst.expr.Comment().Before, src.expr.Comment().Before...)
dst.expr.Comment().Suffix = append(dst.expr.Comment().Suffix, src.expr.Comment().Suffix...)
dst.expr.Comment().After = append(dst.expr.Comment().After, src.expr.Comment().After...)
return nil
}
|
go
|
func SquashRules(src, dst *Rule, filename string) error {
if dst.ShouldKeep() {
return nil
}
for key, srcAttr := range src.attrs {
srcValue := srcAttr.RHS
if dstAttr, ok := dst.attrs[key]; !ok {
dst.SetAttr(key, srcValue)
} else if !ShouldKeep(dstAttr) {
dstValue := dstAttr.RHS
if squashedValue, err := squashExprs(srcValue, dstValue); err != nil {
start, end := dstValue.Span()
return fmt.Errorf("%s:%d.%d-%d.%d: could not squash expression", filename, start.Line, start.LineRune, end.Line, end.LineRune)
} else {
dst.SetAttr(key, squashedValue)
}
}
}
dst.expr.Comment().Before = append(dst.expr.Comment().Before, src.expr.Comment().Before...)
dst.expr.Comment().Suffix = append(dst.expr.Comment().Suffix, src.expr.Comment().Suffix...)
dst.expr.Comment().After = append(dst.expr.Comment().After, src.expr.Comment().After...)
return nil
}
|
[
"func",
"SquashRules",
"(",
"src",
",",
"dst",
"*",
"Rule",
",",
"filename",
"string",
")",
"error",
"{",
"if",
"dst",
".",
"ShouldKeep",
"(",
")",
"{",
"return",
"nil",
"\n",
"}",
"\n",
"for",
"key",
",",
"srcAttr",
":=",
"range",
"src",
".",
"attrs",
"{",
"srcValue",
":=",
"srcAttr",
".",
"RHS",
"\n",
"if",
"dstAttr",
",",
"ok",
":=",
"dst",
".",
"attrs",
"[",
"key",
"]",
";",
"!",
"ok",
"{",
"dst",
".",
"SetAttr",
"(",
"key",
",",
"srcValue",
")",
"\n",
"}",
"else",
"if",
"!",
"ShouldKeep",
"(",
"dstAttr",
")",
"{",
"dstValue",
":=",
"dstAttr",
".",
"RHS",
"\n",
"if",
"squashedValue",
",",
"err",
":=",
"squashExprs",
"(",
"srcValue",
",",
"dstValue",
")",
";",
"err",
"!=",
"nil",
"{",
"start",
",",
"end",
":=",
"dstValue",
".",
"Span",
"(",
")",
"\n",
"return",
"fmt",
".",
"Errorf",
"(",
"\"%s:%d.%d-%d.%d: could not squash expression\"",
",",
"filename",
",",
"start",
".",
"Line",
",",
"start",
".",
"LineRune",
",",
"end",
".",
"Line",
",",
"end",
".",
"LineRune",
")",
"\n",
"}",
"else",
"{",
"dst",
".",
"SetAttr",
"(",
"key",
",",
"squashedValue",
")",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n",
"dst",
".",
"expr",
".",
"Comment",
"(",
")",
".",
"Before",
"=",
"append",
"(",
"dst",
".",
"expr",
".",
"Comment",
"(",
")",
".",
"Before",
",",
"src",
".",
"expr",
".",
"Comment",
"(",
")",
".",
"Before",
"...",
")",
"\n",
"dst",
".",
"expr",
".",
"Comment",
"(",
")",
".",
"Suffix",
"=",
"append",
"(",
"dst",
".",
"expr",
".",
"Comment",
"(",
")",
".",
"Suffix",
",",
"src",
".",
"expr",
".",
"Comment",
"(",
")",
".",
"Suffix",
"...",
")",
"\n",
"dst",
".",
"expr",
".",
"Comment",
"(",
")",
".",
"After",
"=",
"append",
"(",
"dst",
".",
"expr",
".",
"Comment",
"(",
")",
".",
"After",
",",
"src",
".",
"expr",
".",
"Comment",
"(",
")",
".",
"After",
"...",
")",
"\n",
"return",
"nil",
"\n",
"}"
] |
// SquashRules copies information from src into dst without discarding
// information in dst. SquashRules detects duplicate elements in lists and
// dictionaries, but it doesn't sort elements after squashing. If squashing
// fails because the expression is not understood, an error is returned,
// and neither rule is modified.
|
[
"SquashRules",
"copies",
"information",
"from",
"src",
"into",
"dst",
"without",
"discarding",
"information",
"in",
"dst",
".",
"SquashRules",
"detects",
"duplicate",
"elements",
"in",
"lists",
"and",
"dictionaries",
"but",
"it",
"doesn",
"t",
"sort",
"elements",
"after",
"squashing",
".",
"If",
"squashing",
"fails",
"because",
"the",
"expression",
"is",
"not",
"understood",
"an",
"error",
"is",
"returned",
"and",
"neither",
"rule",
"is",
"modified",
"."
] |
e3805aaca69a9deb949b47bfc45b9b1870712f4f
|
https://github.com/bazelbuild/bazel-gazelle/blob/e3805aaca69a9deb949b47bfc45b9b1870712f4f/rule/merge.go#L272-L295
|
test
|
bazelbuild/bazel-gazelle
|
cmd/autogazelle/client_unix.go
|
runClient
|
func runClient() error {
startTime := time.Now()
conn, err := net.Dial("unix", *socketPath)
if err != nil {
if err := startServer(); err != nil {
return fmt.Errorf("error starting server: %v", err)
}
for retry := 0; retry < 3; retry++ {
conn, err = net.Dial("unix", *socketPath)
if err == nil {
break
}
// Wait for server to start listening.
time.Sleep(1 * time.Second)
}
if err != nil {
return fmt.Errorf("failed to connect to server: %v", err)
}
}
defer conn.Close()
if _, err := io.Copy(os.Stderr, conn); err != nil {
log.Print(err)
}
elapsedTime := time.Since(startTime)
log.Printf("ran gazelle in %.3f s", elapsedTime.Seconds())
return nil
}
|
go
|
func runClient() error {
startTime := time.Now()
conn, err := net.Dial("unix", *socketPath)
if err != nil {
if err := startServer(); err != nil {
return fmt.Errorf("error starting server: %v", err)
}
for retry := 0; retry < 3; retry++ {
conn, err = net.Dial("unix", *socketPath)
if err == nil {
break
}
// Wait for server to start listening.
time.Sleep(1 * time.Second)
}
if err != nil {
return fmt.Errorf("failed to connect to server: %v", err)
}
}
defer conn.Close()
if _, err := io.Copy(os.Stderr, conn); err != nil {
log.Print(err)
}
elapsedTime := time.Since(startTime)
log.Printf("ran gazelle in %.3f s", elapsedTime.Seconds())
return nil
}
|
[
"func",
"runClient",
"(",
")",
"error",
"{",
"startTime",
":=",
"time",
".",
"Now",
"(",
")",
"\n",
"conn",
",",
"err",
":=",
"net",
".",
"Dial",
"(",
"\"unix\"",
",",
"*",
"socketPath",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"if",
"err",
":=",
"startServer",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"error starting server: %v\"",
",",
"err",
")",
"\n",
"}",
"\n",
"for",
"retry",
":=",
"0",
";",
"retry",
"<",
"3",
";",
"retry",
"++",
"{",
"conn",
",",
"err",
"=",
"net",
".",
"Dial",
"(",
"\"unix\"",
",",
"*",
"socketPath",
")",
"\n",
"if",
"err",
"==",
"nil",
"{",
"break",
"\n",
"}",
"\n",
"time",
".",
"Sleep",
"(",
"1",
"*",
"time",
".",
"Second",
")",
"\n",
"}",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"failed to connect to server: %v\"",
",",
"err",
")",
"\n",
"}",
"\n",
"}",
"\n",
"defer",
"conn",
".",
"Close",
"(",
")",
"\n",
"if",
"_",
",",
"err",
":=",
"io",
".",
"Copy",
"(",
"os",
".",
"Stderr",
",",
"conn",
")",
";",
"err",
"!=",
"nil",
"{",
"log",
".",
"Print",
"(",
"err",
")",
"\n",
"}",
"\n",
"elapsedTime",
":=",
"time",
".",
"Since",
"(",
"startTime",
")",
"\n",
"log",
".",
"Printf",
"(",
"\"ran gazelle in %.3f s\"",
",",
"elapsedTime",
".",
"Seconds",
"(",
")",
")",
"\n",
"return",
"nil",
"\n",
"}"
] |
// runClient performs the main work of the client. It attempts to connect
// to the server via a UNIX-domain socket. If the server is not running,
// it starts the server and tries again. The server does all the work, so
// the client just waits for the server to complete, then exits.
|
[
"runClient",
"performs",
"the",
"main",
"work",
"of",
"the",
"client",
".",
"It",
"attempts",
"to",
"connect",
"to",
"the",
"server",
"via",
"a",
"UNIX",
"-",
"domain",
"socket",
".",
"If",
"the",
"server",
"is",
"not",
"running",
"it",
"starts",
"the",
"server",
"and",
"tries",
"again",
".",
"The",
"server",
"does",
"all",
"the",
"work",
"so",
"the",
"client",
"just",
"waits",
"for",
"the",
"server",
"to",
"complete",
"then",
"exits",
"."
] |
e3805aaca69a9deb949b47bfc45b9b1870712f4f
|
https://github.com/bazelbuild/bazel-gazelle/blob/e3805aaca69a9deb949b47bfc45b9b1870712f4f/cmd/autogazelle/client_unix.go#L33-L61
|
test
|
bazelbuild/bazel-gazelle
|
repo/remote.go
|
UpdateRepo
|
func UpdateRepo(rc *RemoteCache, importPath string) (Repo, error) {
root, name, err := rc.Root(importPath)
if err != nil {
return Repo{}, err
}
remote, vcs, err := rc.Remote(root)
if err != nil {
return Repo{}, err
}
commit, tag, err := rc.Head(remote, vcs)
if err != nil {
return Repo{}, err
}
repo := Repo{
Name: name,
GoPrefix: root,
Commit: commit,
Tag: tag,
Remote: remote,
VCS: vcs,
}
return repo, nil
}
|
go
|
func UpdateRepo(rc *RemoteCache, importPath string) (Repo, error) {
root, name, err := rc.Root(importPath)
if err != nil {
return Repo{}, err
}
remote, vcs, err := rc.Remote(root)
if err != nil {
return Repo{}, err
}
commit, tag, err := rc.Head(remote, vcs)
if err != nil {
return Repo{}, err
}
repo := Repo{
Name: name,
GoPrefix: root,
Commit: commit,
Tag: tag,
Remote: remote,
VCS: vcs,
}
return repo, nil
}
|
[
"func",
"UpdateRepo",
"(",
"rc",
"*",
"RemoteCache",
",",
"importPath",
"string",
")",
"(",
"Repo",
",",
"error",
")",
"{",
"root",
",",
"name",
",",
"err",
":=",
"rc",
".",
"Root",
"(",
"importPath",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"Repo",
"{",
"}",
",",
"err",
"\n",
"}",
"\n",
"remote",
",",
"vcs",
",",
"err",
":=",
"rc",
".",
"Remote",
"(",
"root",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"Repo",
"{",
"}",
",",
"err",
"\n",
"}",
"\n",
"commit",
",",
"tag",
",",
"err",
":=",
"rc",
".",
"Head",
"(",
"remote",
",",
"vcs",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"Repo",
"{",
"}",
",",
"err",
"\n",
"}",
"\n",
"repo",
":=",
"Repo",
"{",
"Name",
":",
"name",
",",
"GoPrefix",
":",
"root",
",",
"Commit",
":",
"commit",
",",
"Tag",
":",
"tag",
",",
"Remote",
":",
"remote",
",",
"VCS",
":",
"vcs",
",",
"}",
"\n",
"return",
"repo",
",",
"nil",
"\n",
"}"
] |
// UpdateRepo returns an object describing a repository at the most recent
// commit or version tag.
//
// This function uses RemoteCache to retrieve information about the repository.
// Depending on how the RemoteCache was initialized and used earlier, some
// information may already be locally available. Frequently though, information
// will be fetched over the network, so this function may be slow.
|
[
"UpdateRepo",
"returns",
"an",
"object",
"describing",
"a",
"repository",
"at",
"the",
"most",
"recent",
"commit",
"or",
"version",
"tag",
".",
"This",
"function",
"uses",
"RemoteCache",
"to",
"retrieve",
"information",
"about",
"the",
"repository",
".",
"Depending",
"on",
"how",
"the",
"RemoteCache",
"was",
"initialized",
"and",
"used",
"earlier",
"some",
"information",
"may",
"already",
"be",
"locally",
"available",
".",
"Frequently",
"though",
"information",
"will",
"be",
"fetched",
"over",
"the",
"network",
"so",
"this",
"function",
"may",
"be",
"slow",
"."
] |
e3805aaca69a9deb949b47bfc45b9b1870712f4f
|
https://github.com/bazelbuild/bazel-gazelle/blob/e3805aaca69a9deb949b47bfc45b9b1870712f4f/repo/remote.go#L42-L64
|
test
|
bazelbuild/bazel-gazelle
|
repo/remote.go
|
NewRemoteCache
|
func NewRemoteCache(knownRepos []Repo) (r *RemoteCache, cleanup func() error) {
r = &RemoteCache{
RepoRootForImportPath: vcs.RepoRootForImportPath,
HeadCmd: defaultHeadCmd,
root: remoteCacheMap{cache: make(map[string]*remoteCacheEntry)},
remote: remoteCacheMap{cache: make(map[string]*remoteCacheEntry)},
head: remoteCacheMap{cache: make(map[string]*remoteCacheEntry)},
mod: remoteCacheMap{cache: make(map[string]*remoteCacheEntry)},
}
r.ModInfo = func(importPath string) (string, error) {
return defaultModInfo(r, importPath)
}
for _, repo := range knownRepos {
r.root.cache[repo.GoPrefix] = &remoteCacheEntry{
value: rootValue{
root: repo.GoPrefix,
name: repo.Name,
},
}
if repo.Remote != "" {
r.remote.cache[repo.GoPrefix] = &remoteCacheEntry{
value: remoteValue{
remote: repo.Remote,
vcs: repo.VCS,
},
}
}
r.mod.cache[repo.GoPrefix] = &remoteCacheEntry{
value: modValue{
path: repo.GoPrefix,
name: repo.Name,
known: true,
},
}
}
return r, r.cleanup
}
|
go
|
func NewRemoteCache(knownRepos []Repo) (r *RemoteCache, cleanup func() error) {
r = &RemoteCache{
RepoRootForImportPath: vcs.RepoRootForImportPath,
HeadCmd: defaultHeadCmd,
root: remoteCacheMap{cache: make(map[string]*remoteCacheEntry)},
remote: remoteCacheMap{cache: make(map[string]*remoteCacheEntry)},
head: remoteCacheMap{cache: make(map[string]*remoteCacheEntry)},
mod: remoteCacheMap{cache: make(map[string]*remoteCacheEntry)},
}
r.ModInfo = func(importPath string) (string, error) {
return defaultModInfo(r, importPath)
}
for _, repo := range knownRepos {
r.root.cache[repo.GoPrefix] = &remoteCacheEntry{
value: rootValue{
root: repo.GoPrefix,
name: repo.Name,
},
}
if repo.Remote != "" {
r.remote.cache[repo.GoPrefix] = &remoteCacheEntry{
value: remoteValue{
remote: repo.Remote,
vcs: repo.VCS,
},
}
}
r.mod.cache[repo.GoPrefix] = &remoteCacheEntry{
value: modValue{
path: repo.GoPrefix,
name: repo.Name,
known: true,
},
}
}
return r, r.cleanup
}
|
[
"func",
"NewRemoteCache",
"(",
"knownRepos",
"[",
"]",
"Repo",
")",
"(",
"r",
"*",
"RemoteCache",
",",
"cleanup",
"func",
"(",
")",
"error",
")",
"{",
"r",
"=",
"&",
"RemoteCache",
"{",
"RepoRootForImportPath",
":",
"vcs",
".",
"RepoRootForImportPath",
",",
"HeadCmd",
":",
"defaultHeadCmd",
",",
"root",
":",
"remoteCacheMap",
"{",
"cache",
":",
"make",
"(",
"map",
"[",
"string",
"]",
"*",
"remoteCacheEntry",
")",
"}",
",",
"remote",
":",
"remoteCacheMap",
"{",
"cache",
":",
"make",
"(",
"map",
"[",
"string",
"]",
"*",
"remoteCacheEntry",
")",
"}",
",",
"head",
":",
"remoteCacheMap",
"{",
"cache",
":",
"make",
"(",
"map",
"[",
"string",
"]",
"*",
"remoteCacheEntry",
")",
"}",
",",
"mod",
":",
"remoteCacheMap",
"{",
"cache",
":",
"make",
"(",
"map",
"[",
"string",
"]",
"*",
"remoteCacheEntry",
")",
"}",
",",
"}",
"\n",
"r",
".",
"ModInfo",
"=",
"func",
"(",
"importPath",
"string",
")",
"(",
"string",
",",
"error",
")",
"{",
"return",
"defaultModInfo",
"(",
"r",
",",
"importPath",
")",
"\n",
"}",
"\n",
"for",
"_",
",",
"repo",
":=",
"range",
"knownRepos",
"{",
"r",
".",
"root",
".",
"cache",
"[",
"repo",
".",
"GoPrefix",
"]",
"=",
"&",
"remoteCacheEntry",
"{",
"value",
":",
"rootValue",
"{",
"root",
":",
"repo",
".",
"GoPrefix",
",",
"name",
":",
"repo",
".",
"Name",
",",
"}",
",",
"}",
"\n",
"if",
"repo",
".",
"Remote",
"!=",
"\"\"",
"{",
"r",
".",
"remote",
".",
"cache",
"[",
"repo",
".",
"GoPrefix",
"]",
"=",
"&",
"remoteCacheEntry",
"{",
"value",
":",
"remoteValue",
"{",
"remote",
":",
"repo",
".",
"Remote",
",",
"vcs",
":",
"repo",
".",
"VCS",
",",
"}",
",",
"}",
"\n",
"}",
"\n",
"r",
".",
"mod",
".",
"cache",
"[",
"repo",
".",
"GoPrefix",
"]",
"=",
"&",
"remoteCacheEntry",
"{",
"value",
":",
"modValue",
"{",
"path",
":",
"repo",
".",
"GoPrefix",
",",
"name",
":",
"repo",
".",
"Name",
",",
"known",
":",
"true",
",",
"}",
",",
"}",
"\n",
"}",
"\n",
"return",
"r",
",",
"r",
".",
"cleanup",
"\n",
"}"
] |
// NewRemoteCache creates a new RemoteCache with a set of known repositories.
// The Root and Remote methods will return information about repositories listed
// here without accessing the network. However, the Head method will still
// access the network for these repositories to retrieve information about new
// versions.
//
// A cleanup function is also returned. The caller must call this when
// RemoteCache is no longer needed. RemoteCache may write files to a temporary
// directory. This will delete them.
|
[
"NewRemoteCache",
"creates",
"a",
"new",
"RemoteCache",
"with",
"a",
"set",
"of",
"known",
"repositories",
".",
"The",
"Root",
"and",
"Remote",
"methods",
"will",
"return",
"information",
"about",
"repositories",
"listed",
"here",
"without",
"accessing",
"the",
"network",
".",
"However",
"the",
"Head",
"method",
"will",
"still",
"access",
"the",
"network",
"for",
"these",
"repositories",
"to",
"retrieve",
"information",
"about",
"new",
"versions",
".",
"A",
"cleanup",
"function",
"is",
"also",
"returned",
".",
"The",
"caller",
"must",
"call",
"this",
"when",
"RemoteCache",
"is",
"no",
"longer",
"needed",
".",
"RemoteCache",
"may",
"write",
"files",
"to",
"a",
"temporary",
"directory",
".",
"This",
"will",
"delete",
"them",
"."
] |
e3805aaca69a9deb949b47bfc45b9b1870712f4f
|
https://github.com/bazelbuild/bazel-gazelle/blob/e3805aaca69a9deb949b47bfc45b9b1870712f4f/repo/remote.go#L139-L175
|
test
|
bazelbuild/bazel-gazelle
|
repo/remote.go
|
Remote
|
func (r *RemoteCache) Remote(root string) (remote, vcs string, err error) {
v, err := r.remote.ensure(root, func() (interface{}, error) {
repo, err := r.RepoRootForImportPath(root, false)
if err != nil {
return nil, err
}
return remoteValue{remote: repo.Repo, vcs: repo.VCS.Cmd}, nil
})
if err != nil {
return "", "", err
}
value := v.(remoteValue)
return value.remote, value.vcs, nil
}
|
go
|
func (r *RemoteCache) Remote(root string) (remote, vcs string, err error) {
v, err := r.remote.ensure(root, func() (interface{}, error) {
repo, err := r.RepoRootForImportPath(root, false)
if err != nil {
return nil, err
}
return remoteValue{remote: repo.Repo, vcs: repo.VCS.Cmd}, nil
})
if err != nil {
return "", "", err
}
value := v.(remoteValue)
return value.remote, value.vcs, nil
}
|
[
"func",
"(",
"r",
"*",
"RemoteCache",
")",
"Remote",
"(",
"root",
"string",
")",
"(",
"remote",
",",
"vcs",
"string",
",",
"err",
"error",
")",
"{",
"v",
",",
"err",
":=",
"r",
".",
"remote",
".",
"ensure",
"(",
"root",
",",
"func",
"(",
")",
"(",
"interface",
"{",
"}",
",",
"error",
")",
"{",
"repo",
",",
"err",
":=",
"r",
".",
"RepoRootForImportPath",
"(",
"root",
",",
"false",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"return",
"remoteValue",
"{",
"remote",
":",
"repo",
".",
"Repo",
",",
"vcs",
":",
"repo",
".",
"VCS",
".",
"Cmd",
"}",
",",
"nil",
"\n",
"}",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\"\"",
",",
"\"\"",
",",
"err",
"\n",
"}",
"\n",
"value",
":=",
"v",
".",
"(",
"remoteValue",
")",
"\n",
"return",
"value",
".",
"remote",
",",
"value",
".",
"vcs",
",",
"nil",
"\n",
"}"
] |
// Remote returns the VCS name and the remote URL for a repository with the
// given root import path. This is suitable for creating new repository rules.
|
[
"Remote",
"returns",
"the",
"VCS",
"name",
"and",
"the",
"remote",
"URL",
"for",
"a",
"repository",
"with",
"the",
"given",
"root",
"import",
"path",
".",
"This",
"is",
"suitable",
"for",
"creating",
"new",
"repository",
"rules",
"."
] |
e3805aaca69a9deb949b47bfc45b9b1870712f4f
|
https://github.com/bazelbuild/bazel-gazelle/blob/e3805aaca69a9deb949b47bfc45b9b1870712f4f/repo/remote.go#L268-L281
|
test
|
bazelbuild/bazel-gazelle
|
repo/remote.go
|
get
|
func (m *remoteCacheMap) get(key string) (value interface{}, ok bool, err error) {
m.mu.Lock()
e, ok := m.cache[key]
m.mu.Unlock()
if !ok {
return nil, ok, nil
}
if e.ready != nil {
<-e.ready
}
return e.value, ok, e.err
}
|
go
|
func (m *remoteCacheMap) get(key string) (value interface{}, ok bool, err error) {
m.mu.Lock()
e, ok := m.cache[key]
m.mu.Unlock()
if !ok {
return nil, ok, nil
}
if e.ready != nil {
<-e.ready
}
return e.value, ok, e.err
}
|
[
"func",
"(",
"m",
"*",
"remoteCacheMap",
")",
"get",
"(",
"key",
"string",
")",
"(",
"value",
"interface",
"{",
"}",
",",
"ok",
"bool",
",",
"err",
"error",
")",
"{",
"m",
".",
"mu",
".",
"Lock",
"(",
")",
"\n",
"e",
",",
"ok",
":=",
"m",
".",
"cache",
"[",
"key",
"]",
"\n",
"m",
".",
"mu",
".",
"Unlock",
"(",
")",
"\n",
"if",
"!",
"ok",
"{",
"return",
"nil",
",",
"ok",
",",
"nil",
"\n",
"}",
"\n",
"if",
"e",
".",
"ready",
"!=",
"nil",
"{",
"<-",
"e",
".",
"ready",
"\n",
"}",
"\n",
"return",
"e",
".",
"value",
",",
"ok",
",",
"e",
".",
"err",
"\n",
"}"
] |
// get retrieves a value associated with the given key from the cache. ok will
// be true if the key exists in the cache, even if it's in the process of
// being fetched.
|
[
"get",
"retrieves",
"a",
"value",
"associated",
"with",
"the",
"given",
"key",
"from",
"the",
"cache",
".",
"ok",
"will",
"be",
"true",
"if",
"the",
"key",
"exists",
"in",
"the",
"cache",
"even",
"if",
"it",
"s",
"in",
"the",
"process",
"of",
"being",
"fetched",
"."
] |
e3805aaca69a9deb949b47bfc45b9b1870712f4f
|
https://github.com/bazelbuild/bazel-gazelle/blob/e3805aaca69a9deb949b47bfc45b9b1870712f4f/repo/remote.go#L416-L427
|
test
|
bazelbuild/bazel-gazelle
|
repo/remote.go
|
ensure
|
func (m *remoteCacheMap) ensure(key string, load func() (interface{}, error)) (interface{}, error) {
m.mu.Lock()
e, ok := m.cache[key]
if !ok {
e = &remoteCacheEntry{ready: make(chan struct{})}
m.cache[key] = e
m.mu.Unlock()
e.value, e.err = load()
close(e.ready)
} else {
m.mu.Unlock()
if e.ready != nil {
<-e.ready
}
}
return e.value, e.err
}
|
go
|
func (m *remoteCacheMap) ensure(key string, load func() (interface{}, error)) (interface{}, error) {
m.mu.Lock()
e, ok := m.cache[key]
if !ok {
e = &remoteCacheEntry{ready: make(chan struct{})}
m.cache[key] = e
m.mu.Unlock()
e.value, e.err = load()
close(e.ready)
} else {
m.mu.Unlock()
if e.ready != nil {
<-e.ready
}
}
return e.value, e.err
}
|
[
"func",
"(",
"m",
"*",
"remoteCacheMap",
")",
"ensure",
"(",
"key",
"string",
",",
"load",
"func",
"(",
")",
"(",
"interface",
"{",
"}",
",",
"error",
")",
")",
"(",
"interface",
"{",
"}",
",",
"error",
")",
"{",
"m",
".",
"mu",
".",
"Lock",
"(",
")",
"\n",
"e",
",",
"ok",
":=",
"m",
".",
"cache",
"[",
"key",
"]",
"\n",
"if",
"!",
"ok",
"{",
"e",
"=",
"&",
"remoteCacheEntry",
"{",
"ready",
":",
"make",
"(",
"chan",
"struct",
"{",
"}",
")",
"}",
"\n",
"m",
".",
"cache",
"[",
"key",
"]",
"=",
"e",
"\n",
"m",
".",
"mu",
".",
"Unlock",
"(",
")",
"\n",
"e",
".",
"value",
",",
"e",
".",
"err",
"=",
"load",
"(",
")",
"\n",
"close",
"(",
"e",
".",
"ready",
")",
"\n",
"}",
"else",
"{",
"m",
".",
"mu",
".",
"Unlock",
"(",
")",
"\n",
"if",
"e",
".",
"ready",
"!=",
"nil",
"{",
"<-",
"e",
".",
"ready",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"e",
".",
"value",
",",
"e",
".",
"err",
"\n",
"}"
] |
// ensure retreives a value associated with the given key from the cache. If
// the key does not exist in the cache, the load function will be called,
// and its result will be associated with the key. The load function will not
// be called more than once for any key.
|
[
"ensure",
"retreives",
"a",
"value",
"associated",
"with",
"the",
"given",
"key",
"from",
"the",
"cache",
".",
"If",
"the",
"key",
"does",
"not",
"exist",
"in",
"the",
"cache",
"the",
"load",
"function",
"will",
"be",
"called",
"and",
"its",
"result",
"will",
"be",
"associated",
"with",
"the",
"key",
".",
"The",
"load",
"function",
"will",
"not",
"be",
"called",
"more",
"than",
"once",
"for",
"any",
"key",
"."
] |
e3805aaca69a9deb949b47bfc45b9b1870712f4f
|
https://github.com/bazelbuild/bazel-gazelle/blob/e3805aaca69a9deb949b47bfc45b9b1870712f4f/repo/remote.go#L433-L449
|
test
|
bazelbuild/bazel-gazelle
|
pathtools/path.go
|
RelBaseName
|
func RelBaseName(rel, prefix, root string) string {
base := path.Base(rel)
if base == "." || base == "/" {
base = path.Base(prefix)
}
if base == "." || base == "/" {
base = filepath.Base(root)
}
if base == "." || base == "/" {
base = "root"
}
return base
}
|
go
|
func RelBaseName(rel, prefix, root string) string {
base := path.Base(rel)
if base == "." || base == "/" {
base = path.Base(prefix)
}
if base == "." || base == "/" {
base = filepath.Base(root)
}
if base == "." || base == "/" {
base = "root"
}
return base
}
|
[
"func",
"RelBaseName",
"(",
"rel",
",",
"prefix",
",",
"root",
"string",
")",
"string",
"{",
"base",
":=",
"path",
".",
"Base",
"(",
"rel",
")",
"\n",
"if",
"base",
"==",
"\".\"",
"||",
"base",
"==",
"\"/\"",
"{",
"base",
"=",
"path",
".",
"Base",
"(",
"prefix",
")",
"\n",
"}",
"\n",
"if",
"base",
"==",
"\".\"",
"||",
"base",
"==",
"\"/\"",
"{",
"base",
"=",
"filepath",
".",
"Base",
"(",
"root",
")",
"\n",
"}",
"\n",
"if",
"base",
"==",
"\".\"",
"||",
"base",
"==",
"\"/\"",
"{",
"base",
"=",
"\"root\"",
"\n",
"}",
"\n",
"return",
"base",
"\n",
"}"
] |
// RelBaseName returns the base name for rel, a slash-separated path relative
// to the repository root. If rel is empty, RelBaseName returns the base name
// of prefix. If prefix is empty, RelBaseName returns the base name of root,
// the absolute file path of the repository root directory. If that's empty
// to, then RelBaseName returns "root".
|
[
"RelBaseName",
"returns",
"the",
"base",
"name",
"for",
"rel",
"a",
"slash",
"-",
"separated",
"path",
"relative",
"to",
"the",
"repository",
"root",
".",
"If",
"rel",
"is",
"empty",
"RelBaseName",
"returns",
"the",
"base",
"name",
"of",
"prefix",
".",
"If",
"prefix",
"is",
"empty",
"RelBaseName",
"returns",
"the",
"base",
"name",
"of",
"root",
"the",
"absolute",
"file",
"path",
"of",
"the",
"repository",
"root",
"directory",
".",
"If",
"that",
"s",
"empty",
"to",
"then",
"RelBaseName",
"returns",
"root",
"."
] |
e3805aaca69a9deb949b47bfc45b9b1870712f4f
|
https://github.com/bazelbuild/bazel-gazelle/blob/e3805aaca69a9deb949b47bfc45b9b1870712f4f/pathtools/path.go#L55-L67
|
test
|
bazelbuild/bazel-gazelle
|
config/config.go
|
Clone
|
func (c *Config) Clone() *Config {
cc := *c
cc.Exts = make(map[string]interface{})
for k, v := range c.Exts {
cc.Exts[k] = v
}
cc.KindMap = make(map[string]MappedKind)
for k, v := range c.KindMap {
cc.KindMap[k] = v
}
return &cc
}
|
go
|
func (c *Config) Clone() *Config {
cc := *c
cc.Exts = make(map[string]interface{})
for k, v := range c.Exts {
cc.Exts[k] = v
}
cc.KindMap = make(map[string]MappedKind)
for k, v := range c.KindMap {
cc.KindMap[k] = v
}
return &cc
}
|
[
"func",
"(",
"c",
"*",
"Config",
")",
"Clone",
"(",
")",
"*",
"Config",
"{",
"cc",
":=",
"*",
"c",
"\n",
"cc",
".",
"Exts",
"=",
"make",
"(",
"map",
"[",
"string",
"]",
"interface",
"{",
"}",
")",
"\n",
"for",
"k",
",",
"v",
":=",
"range",
"c",
".",
"Exts",
"{",
"cc",
".",
"Exts",
"[",
"k",
"]",
"=",
"v",
"\n",
"}",
"\n",
"cc",
".",
"KindMap",
"=",
"make",
"(",
"map",
"[",
"string",
"]",
"MappedKind",
")",
"\n",
"for",
"k",
",",
"v",
":=",
"range",
"c",
".",
"KindMap",
"{",
"cc",
".",
"KindMap",
"[",
"k",
"]",
"=",
"v",
"\n",
"}",
"\n",
"return",
"&",
"cc",
"\n",
"}"
] |
// Clone creates a copy of the configuration for use in a subdirectory.
// Note that the Exts map is copied, but its contents are not.
// Configurer.Configure should do this, if needed.
|
[
"Clone",
"creates",
"a",
"copy",
"of",
"the",
"configuration",
"for",
"use",
"in",
"a",
"subdirectory",
".",
"Note",
"that",
"the",
"Exts",
"map",
"is",
"copied",
"but",
"its",
"contents",
"are",
"not",
".",
"Configurer",
".",
"Configure",
"should",
"do",
"this",
"if",
"needed",
"."
] |
e3805aaca69a9deb949b47bfc45b9b1870712f4f
|
https://github.com/bazelbuild/bazel-gazelle/blob/e3805aaca69a9deb949b47bfc45b9b1870712f4f/config/config.go#L105-L116
|
test
|
bazelbuild/bazel-gazelle
|
config/config.go
|
IsValidBuildFileName
|
func (c *Config) IsValidBuildFileName(name string) bool {
for _, n := range c.ValidBuildFileNames {
if name == n {
return true
}
}
return false
}
|
go
|
func (c *Config) IsValidBuildFileName(name string) bool {
for _, n := range c.ValidBuildFileNames {
if name == n {
return true
}
}
return false
}
|
[
"func",
"(",
"c",
"*",
"Config",
")",
"IsValidBuildFileName",
"(",
"name",
"string",
")",
"bool",
"{",
"for",
"_",
",",
"n",
":=",
"range",
"c",
".",
"ValidBuildFileNames",
"{",
"if",
"name",
"==",
"n",
"{",
"return",
"true",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"false",
"\n",
"}"
] |
// IsValidBuildFileName returns true if a file with the given base name
// should be treated as a build file.
|
[
"IsValidBuildFileName",
"returns",
"true",
"if",
"a",
"file",
"with",
"the",
"given",
"base",
"name",
"should",
"be",
"treated",
"as",
"a",
"build",
"file",
"."
] |
e3805aaca69a9deb949b47bfc45b9b1870712f4f
|
https://github.com/bazelbuild/bazel-gazelle/blob/e3805aaca69a9deb949b47bfc45b9b1870712f4f/config/config.go#L122-L129
|
test
|
bazelbuild/bazel-gazelle
|
language/go/fileinfo.go
|
check
|
func (l tagLine) check(c *config.Config, os, arch string) bool {
if len(l) == 0 {
return false
}
for _, g := range l {
if g.check(c, os, arch) {
return true
}
}
return false
}
|
go
|
func (l tagLine) check(c *config.Config, os, arch string) bool {
if len(l) == 0 {
return false
}
for _, g := range l {
if g.check(c, os, arch) {
return true
}
}
return false
}
|
[
"func",
"(",
"l",
"tagLine",
")",
"check",
"(",
"c",
"*",
"config",
".",
"Config",
",",
"os",
",",
"arch",
"string",
")",
"bool",
"{",
"if",
"len",
"(",
"l",
")",
"==",
"0",
"{",
"return",
"false",
"\n",
"}",
"\n",
"for",
"_",
",",
"g",
":=",
"range",
"l",
"{",
"if",
"g",
".",
"check",
"(",
"c",
",",
"os",
",",
"arch",
")",
"{",
"return",
"true",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"false",
"\n",
"}"
] |
// check returns true if at least one of the tag groups is satisfied.
|
[
"check",
"returns",
"true",
"if",
"at",
"least",
"one",
"of",
"the",
"tag",
"groups",
"is",
"satisfied",
"."
] |
e3805aaca69a9deb949b47bfc45b9b1870712f4f
|
https://github.com/bazelbuild/bazel-gazelle/blob/e3805aaca69a9deb949b47bfc45b9b1870712f4f/language/go/fileinfo.go#L92-L102
|
test
|
bazelbuild/bazel-gazelle
|
language/go/fileinfo.go
|
fileNameInfo
|
func fileNameInfo(path_ string) fileInfo {
name := filepath.Base(path_)
var ext ext
switch path.Ext(name) {
case ".go":
ext = goExt
case ".c", ".cc", ".cpp", ".cxx", ".m", ".mm":
ext = cExt
case ".h", ".hh", ".hpp", ".hxx":
ext = hExt
case ".s":
ext = sExt
case ".S":
ext = csExt
case ".proto":
ext = protoExt
default:
ext = unknownExt
}
if strings.HasPrefix(name, ".") || strings.HasPrefix(name, "_") {
ext = unknownExt
}
// Determine test, goos, and goarch. This is intended to match the logic
// in goodOSArchFile in go/build.
var isTest bool
var goos, goarch string
l := strings.Split(name[:len(name)-len(path.Ext(name))], "_")
if len(l) >= 2 && l[len(l)-1] == "test" {
isTest = ext == goExt
l = l[:len(l)-1]
}
switch {
case len(l) >= 3 && rule.KnownOSSet[l[len(l)-2]] && rule.KnownArchSet[l[len(l)-1]]:
goos = l[len(l)-2]
goarch = l[len(l)-1]
case len(l) >= 2 && rule.KnownOSSet[l[len(l)-1]]:
goos = l[len(l)-1]
case len(l) >= 2 && rule.KnownArchSet[l[len(l)-1]]:
goarch = l[len(l)-1]
}
return fileInfo{
path: path_,
name: name,
ext: ext,
isTest: isTest,
goos: goos,
goarch: goarch,
}
}
|
go
|
func fileNameInfo(path_ string) fileInfo {
name := filepath.Base(path_)
var ext ext
switch path.Ext(name) {
case ".go":
ext = goExt
case ".c", ".cc", ".cpp", ".cxx", ".m", ".mm":
ext = cExt
case ".h", ".hh", ".hpp", ".hxx":
ext = hExt
case ".s":
ext = sExt
case ".S":
ext = csExt
case ".proto":
ext = protoExt
default:
ext = unknownExt
}
if strings.HasPrefix(name, ".") || strings.HasPrefix(name, "_") {
ext = unknownExt
}
// Determine test, goos, and goarch. This is intended to match the logic
// in goodOSArchFile in go/build.
var isTest bool
var goos, goarch string
l := strings.Split(name[:len(name)-len(path.Ext(name))], "_")
if len(l) >= 2 && l[len(l)-1] == "test" {
isTest = ext == goExt
l = l[:len(l)-1]
}
switch {
case len(l) >= 3 && rule.KnownOSSet[l[len(l)-2]] && rule.KnownArchSet[l[len(l)-1]]:
goos = l[len(l)-2]
goarch = l[len(l)-1]
case len(l) >= 2 && rule.KnownOSSet[l[len(l)-1]]:
goos = l[len(l)-1]
case len(l) >= 2 && rule.KnownArchSet[l[len(l)-1]]:
goarch = l[len(l)-1]
}
return fileInfo{
path: path_,
name: name,
ext: ext,
isTest: isTest,
goos: goos,
goarch: goarch,
}
}
|
[
"func",
"fileNameInfo",
"(",
"path_",
"string",
")",
"fileInfo",
"{",
"name",
":=",
"filepath",
".",
"Base",
"(",
"path_",
")",
"\n",
"var",
"ext",
"ext",
"\n",
"switch",
"path",
".",
"Ext",
"(",
"name",
")",
"{",
"case",
"\".go\"",
":",
"ext",
"=",
"goExt",
"\n",
"case",
"\".c\"",
",",
"\".cc\"",
",",
"\".cpp\"",
",",
"\".cxx\"",
",",
"\".m\"",
",",
"\".mm\"",
":",
"ext",
"=",
"cExt",
"\n",
"case",
"\".h\"",
",",
"\".hh\"",
",",
"\".hpp\"",
",",
"\".hxx\"",
":",
"ext",
"=",
"hExt",
"\n",
"case",
"\".s\"",
":",
"ext",
"=",
"sExt",
"\n",
"case",
"\".S\"",
":",
"ext",
"=",
"csExt",
"\n",
"case",
"\".proto\"",
":",
"ext",
"=",
"protoExt",
"\n",
"default",
":",
"ext",
"=",
"unknownExt",
"\n",
"}",
"\n",
"if",
"strings",
".",
"HasPrefix",
"(",
"name",
",",
"\".\"",
")",
"||",
"strings",
".",
"HasPrefix",
"(",
"name",
",",
"\"_\"",
")",
"{",
"ext",
"=",
"unknownExt",
"\n",
"}",
"\n",
"var",
"isTest",
"bool",
"\n",
"var",
"goos",
",",
"goarch",
"string",
"\n",
"l",
":=",
"strings",
".",
"Split",
"(",
"name",
"[",
":",
"len",
"(",
"name",
")",
"-",
"len",
"(",
"path",
".",
"Ext",
"(",
"name",
")",
")",
"]",
",",
"\"_\"",
")",
"\n",
"if",
"len",
"(",
"l",
")",
">=",
"2",
"&&",
"l",
"[",
"len",
"(",
"l",
")",
"-",
"1",
"]",
"==",
"\"test\"",
"{",
"isTest",
"=",
"ext",
"==",
"goExt",
"\n",
"l",
"=",
"l",
"[",
":",
"len",
"(",
"l",
")",
"-",
"1",
"]",
"\n",
"}",
"\n",
"switch",
"{",
"case",
"len",
"(",
"l",
")",
">=",
"3",
"&&",
"rule",
".",
"KnownOSSet",
"[",
"l",
"[",
"len",
"(",
"l",
")",
"-",
"2",
"]",
"]",
"&&",
"rule",
".",
"KnownArchSet",
"[",
"l",
"[",
"len",
"(",
"l",
")",
"-",
"1",
"]",
"]",
":",
"goos",
"=",
"l",
"[",
"len",
"(",
"l",
")",
"-",
"2",
"]",
"\n",
"goarch",
"=",
"l",
"[",
"len",
"(",
"l",
")",
"-",
"1",
"]",
"\n",
"case",
"len",
"(",
"l",
")",
">=",
"2",
"&&",
"rule",
".",
"KnownOSSet",
"[",
"l",
"[",
"len",
"(",
"l",
")",
"-",
"1",
"]",
"]",
":",
"goos",
"=",
"l",
"[",
"len",
"(",
"l",
")",
"-",
"1",
"]",
"\n",
"case",
"len",
"(",
"l",
")",
">=",
"2",
"&&",
"rule",
".",
"KnownArchSet",
"[",
"l",
"[",
"len",
"(",
"l",
")",
"-",
"1",
"]",
"]",
":",
"goarch",
"=",
"l",
"[",
"len",
"(",
"l",
")",
"-",
"1",
"]",
"\n",
"}",
"\n",
"return",
"fileInfo",
"{",
"path",
":",
"path_",
",",
"name",
":",
"name",
",",
"ext",
":",
"ext",
",",
"isTest",
":",
"isTest",
",",
"goos",
":",
"goos",
",",
"goarch",
":",
"goarch",
",",
"}",
"\n",
"}"
] |
// fileNameInfo returns information that can be inferred from the name of
// a file. It does not read data from the file.
|
[
"fileNameInfo",
"returns",
"information",
"that",
"can",
"be",
"inferred",
"from",
"the",
"name",
"of",
"a",
"file",
".",
"It",
"does",
"not",
"read",
"data",
"from",
"the",
"file",
"."
] |
e3805aaca69a9deb949b47bfc45b9b1870712f4f
|
https://github.com/bazelbuild/bazel-gazelle/blob/e3805aaca69a9deb949b47bfc45b9b1870712f4f/language/go/fileinfo.go#L199-L249
|
test
|
bazelbuild/bazel-gazelle
|
language/go/fileinfo.go
|
otherFileInfo
|
func otherFileInfo(path string) fileInfo {
info := fileNameInfo(path)
if info.ext == unknownExt {
return info
}
tags, err := readTags(info.path)
if err != nil {
log.Printf("%s: error reading file: %v", info.path, err)
return info
}
info.tags = tags
return info
}
|
go
|
func otherFileInfo(path string) fileInfo {
info := fileNameInfo(path)
if info.ext == unknownExt {
return info
}
tags, err := readTags(info.path)
if err != nil {
log.Printf("%s: error reading file: %v", info.path, err)
return info
}
info.tags = tags
return info
}
|
[
"func",
"otherFileInfo",
"(",
"path",
"string",
")",
"fileInfo",
"{",
"info",
":=",
"fileNameInfo",
"(",
"path",
")",
"\n",
"if",
"info",
".",
"ext",
"==",
"unknownExt",
"{",
"return",
"info",
"\n",
"}",
"\n",
"tags",
",",
"err",
":=",
"readTags",
"(",
"info",
".",
"path",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"log",
".",
"Printf",
"(",
"\"%s: error reading file: %v\"",
",",
"info",
".",
"path",
",",
"err",
")",
"\n",
"return",
"info",
"\n",
"}",
"\n",
"info",
".",
"tags",
"=",
"tags",
"\n",
"return",
"info",
"\n",
"}"
] |
// otherFileInfo returns information about a non-.go file. It will parse
// part of the file to determine build tags. If the file can't be read, an
// error will be logged, and partial information will be returned.
|
[
"otherFileInfo",
"returns",
"information",
"about",
"a",
"non",
"-",
".",
"go",
"file",
".",
"It",
"will",
"parse",
"part",
"of",
"the",
"file",
"to",
"determine",
"build",
"tags",
".",
"If",
"the",
"file",
"can",
"t",
"be",
"read",
"an",
"error",
"will",
"be",
"logged",
"and",
"partial",
"information",
"will",
"be",
"returned",
"."
] |
e3805aaca69a9deb949b47bfc45b9b1870712f4f
|
https://github.com/bazelbuild/bazel-gazelle/blob/e3805aaca69a9deb949b47bfc45b9b1870712f4f/language/go/fileinfo.go#L254-L267
|
test
|
bazelbuild/bazel-gazelle
|
language/go/fileinfo.go
|
protoFileInfo
|
func protoFileInfo(path_ string, protoInfo proto.FileInfo) fileInfo {
info := fileNameInfo(path_)
// Look for "option go_package". If there's no / in the package option, then
// it's just a simple package name, not a full import path.
for _, opt := range protoInfo.Options {
if opt.Key != "go_package" {
continue
}
if strings.LastIndexByte(opt.Value, '/') == -1 {
info.packageName = opt.Value
} else {
if i := strings.LastIndexByte(opt.Value, ';'); i != -1 {
info.importPath = opt.Value[:i]
info.packageName = opt.Value[i+1:]
} else {
info.importPath = opt.Value
info.packageName = path.Base(opt.Value)
}
}
}
// Set the Go package name from the proto package name if there was no
// option go_package.
if info.packageName == "" && protoInfo.PackageName != "" {
info.packageName = strings.Replace(protoInfo.PackageName, ".", "_", -1)
}
info.imports = protoInfo.Imports
info.hasServices = protoInfo.HasServices
return info
}
|
go
|
func protoFileInfo(path_ string, protoInfo proto.FileInfo) fileInfo {
info := fileNameInfo(path_)
// Look for "option go_package". If there's no / in the package option, then
// it's just a simple package name, not a full import path.
for _, opt := range protoInfo.Options {
if opt.Key != "go_package" {
continue
}
if strings.LastIndexByte(opt.Value, '/') == -1 {
info.packageName = opt.Value
} else {
if i := strings.LastIndexByte(opt.Value, ';'); i != -1 {
info.importPath = opt.Value[:i]
info.packageName = opt.Value[i+1:]
} else {
info.importPath = opt.Value
info.packageName = path.Base(opt.Value)
}
}
}
// Set the Go package name from the proto package name if there was no
// option go_package.
if info.packageName == "" && protoInfo.PackageName != "" {
info.packageName = strings.Replace(protoInfo.PackageName, ".", "_", -1)
}
info.imports = protoInfo.Imports
info.hasServices = protoInfo.HasServices
return info
}
|
[
"func",
"protoFileInfo",
"(",
"path_",
"string",
",",
"protoInfo",
"proto",
".",
"FileInfo",
")",
"fileInfo",
"{",
"info",
":=",
"fileNameInfo",
"(",
"path_",
")",
"\n",
"for",
"_",
",",
"opt",
":=",
"range",
"protoInfo",
".",
"Options",
"{",
"if",
"opt",
".",
"Key",
"!=",
"\"go_package\"",
"{",
"continue",
"\n",
"}",
"\n",
"if",
"strings",
".",
"LastIndexByte",
"(",
"opt",
".",
"Value",
",",
"'/'",
")",
"==",
"-",
"1",
"{",
"info",
".",
"packageName",
"=",
"opt",
".",
"Value",
"\n",
"}",
"else",
"{",
"if",
"i",
":=",
"strings",
".",
"LastIndexByte",
"(",
"opt",
".",
"Value",
",",
"';'",
")",
";",
"i",
"!=",
"-",
"1",
"{",
"info",
".",
"importPath",
"=",
"opt",
".",
"Value",
"[",
":",
"i",
"]",
"\n",
"info",
".",
"packageName",
"=",
"opt",
".",
"Value",
"[",
"i",
"+",
"1",
":",
"]",
"\n",
"}",
"else",
"{",
"info",
".",
"importPath",
"=",
"opt",
".",
"Value",
"\n",
"info",
".",
"packageName",
"=",
"path",
".",
"Base",
"(",
"opt",
".",
"Value",
")",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n",
"if",
"info",
".",
"packageName",
"==",
"\"\"",
"&&",
"protoInfo",
".",
"PackageName",
"!=",
"\"\"",
"{",
"info",
".",
"packageName",
"=",
"strings",
".",
"Replace",
"(",
"protoInfo",
".",
"PackageName",
",",
"\".\"",
",",
"\"_\"",
",",
"-",
"1",
")",
"\n",
"}",
"\n",
"info",
".",
"imports",
"=",
"protoInfo",
".",
"Imports",
"\n",
"info",
".",
"hasServices",
"=",
"protoInfo",
".",
"HasServices",
"\n",
"return",
"info",
"\n",
"}"
] |
// protoFileInfo extracts metadata from a proto file. The proto extension
// already "parses" these and stores metadata in proto.FileInfo, so this is
// just processing relevant options.
|
[
"protoFileInfo",
"extracts",
"metadata",
"from",
"a",
"proto",
"file",
".",
"The",
"proto",
"extension",
"already",
"parses",
"these",
"and",
"stores",
"metadata",
"in",
"proto",
".",
"FileInfo",
"so",
"this",
"is",
"just",
"processing",
"relevant",
"options",
"."
] |
e3805aaca69a9deb949b47bfc45b9b1870712f4f
|
https://github.com/bazelbuild/bazel-gazelle/blob/e3805aaca69a9deb949b47bfc45b9b1870712f4f/language/go/fileinfo.go#L650-L681
|
test
|
bazelbuild/bazel-gazelle
|
resolve/index.go
|
AddRule
|
func (ix *RuleIndex) AddRule(c *config.Config, r *rule.Rule, f *rule.File) {
var imps []ImportSpec
if rslv := ix.mrslv(r, f.Pkg); rslv != nil {
imps = rslv.Imports(c, r, f)
}
// If imps == nil, the rule is not importable. If imps is the empty slice,
// it may still be importable if it embeds importable libraries.
if imps == nil {
return
}
record := &ruleRecord{
rule: r,
label: label.New(c.RepoName, f.Pkg, r.Name()),
file: f,
importedAs: imps,
}
if _, ok := ix.labelMap[record.label]; ok {
log.Printf("multiple rules found with label %s", record.label)
return
}
ix.rules = append(ix.rules, record)
ix.labelMap[record.label] = record
}
|
go
|
func (ix *RuleIndex) AddRule(c *config.Config, r *rule.Rule, f *rule.File) {
var imps []ImportSpec
if rslv := ix.mrslv(r, f.Pkg); rslv != nil {
imps = rslv.Imports(c, r, f)
}
// If imps == nil, the rule is not importable. If imps is the empty slice,
// it may still be importable if it embeds importable libraries.
if imps == nil {
return
}
record := &ruleRecord{
rule: r,
label: label.New(c.RepoName, f.Pkg, r.Name()),
file: f,
importedAs: imps,
}
if _, ok := ix.labelMap[record.label]; ok {
log.Printf("multiple rules found with label %s", record.label)
return
}
ix.rules = append(ix.rules, record)
ix.labelMap[record.label] = record
}
|
[
"func",
"(",
"ix",
"*",
"RuleIndex",
")",
"AddRule",
"(",
"c",
"*",
"config",
".",
"Config",
",",
"r",
"*",
"rule",
".",
"Rule",
",",
"f",
"*",
"rule",
".",
"File",
")",
"{",
"var",
"imps",
"[",
"]",
"ImportSpec",
"\n",
"if",
"rslv",
":=",
"ix",
".",
"mrslv",
"(",
"r",
",",
"f",
".",
"Pkg",
")",
";",
"rslv",
"!=",
"nil",
"{",
"imps",
"=",
"rslv",
".",
"Imports",
"(",
"c",
",",
"r",
",",
"f",
")",
"\n",
"}",
"\n",
"if",
"imps",
"==",
"nil",
"{",
"return",
"\n",
"}",
"\n",
"record",
":=",
"&",
"ruleRecord",
"{",
"rule",
":",
"r",
",",
"label",
":",
"label",
".",
"New",
"(",
"c",
".",
"RepoName",
",",
"f",
".",
"Pkg",
",",
"r",
".",
"Name",
"(",
")",
")",
",",
"file",
":",
"f",
",",
"importedAs",
":",
"imps",
",",
"}",
"\n",
"if",
"_",
",",
"ok",
":=",
"ix",
".",
"labelMap",
"[",
"record",
".",
"label",
"]",
";",
"ok",
"{",
"log",
".",
"Printf",
"(",
"\"multiple rules found with label %s\"",
",",
"record",
".",
"label",
")",
"\n",
"return",
"\n",
"}",
"\n",
"ix",
".",
"rules",
"=",
"append",
"(",
"ix",
".",
"rules",
",",
"record",
")",
"\n",
"ix",
".",
"labelMap",
"[",
"record",
".",
"label",
"]",
"=",
"record",
"\n",
"}"
] |
// AddRule adds a rule r to the index. The rule will only be indexed if there
// is a known resolver for the rule's kind and Resolver.Imports returns a
// non-nil slice.
//
// AddRule may only be called before Finish.
|
[
"AddRule",
"adds",
"a",
"rule",
"r",
"to",
"the",
"index",
".",
"The",
"rule",
"will",
"only",
"be",
"indexed",
"if",
"there",
"is",
"a",
"known",
"resolver",
"for",
"the",
"rule",
"s",
"kind",
"and",
"Resolver",
".",
"Imports",
"returns",
"a",
"non",
"-",
"nil",
"slice",
".",
"AddRule",
"may",
"only",
"be",
"called",
"before",
"Finish",
"."
] |
e3805aaca69a9deb949b47bfc45b9b1870712f4f
|
https://github.com/bazelbuild/bazel-gazelle/blob/e3805aaca69a9deb949b47bfc45b9b1870712f4f/resolve/index.go#L112-L135
|
test
|
bazelbuild/bazel-gazelle
|
resolve/index.go
|
Finish
|
func (ix *RuleIndex) Finish() {
for _, r := range ix.rules {
ix.collectEmbeds(r)
}
ix.buildImportIndex()
}
|
go
|
func (ix *RuleIndex) Finish() {
for _, r := range ix.rules {
ix.collectEmbeds(r)
}
ix.buildImportIndex()
}
|
[
"func",
"(",
"ix",
"*",
"RuleIndex",
")",
"Finish",
"(",
")",
"{",
"for",
"_",
",",
"r",
":=",
"range",
"ix",
".",
"rules",
"{",
"ix",
".",
"collectEmbeds",
"(",
"r",
")",
"\n",
"}",
"\n",
"ix",
".",
"buildImportIndex",
"(",
")",
"\n",
"}"
] |
// Finish constructs the import index and performs any other necessary indexing
// actions after all rules have been added. This step is necessary because
// a rule may be indexed differently based on what rules are added later.
//
// Finish must be called after all AddRule calls and before any
// FindRulesByImport calls.
|
[
"Finish",
"constructs",
"the",
"import",
"index",
"and",
"performs",
"any",
"other",
"necessary",
"indexing",
"actions",
"after",
"all",
"rules",
"have",
"been",
"added",
".",
"This",
"step",
"is",
"necessary",
"because",
"a",
"rule",
"may",
"be",
"indexed",
"differently",
"based",
"on",
"what",
"rules",
"are",
"added",
"later",
".",
"Finish",
"must",
"be",
"called",
"after",
"all",
"AddRule",
"calls",
"and",
"before",
"any",
"FindRulesByImport",
"calls",
"."
] |
e3805aaca69a9deb949b47bfc45b9b1870712f4f
|
https://github.com/bazelbuild/bazel-gazelle/blob/e3805aaca69a9deb949b47bfc45b9b1870712f4f/resolve/index.go#L143-L148
|
test
|
bazelbuild/bazel-gazelle
|
resolve/index.go
|
buildImportIndex
|
func (ix *RuleIndex) buildImportIndex() {
ix.importMap = make(map[ImportSpec][]*ruleRecord)
for _, r := range ix.rules {
if r.embedded {
continue
}
indexed := make(map[ImportSpec]bool)
for _, imp := range r.importedAs {
if indexed[imp] {
continue
}
indexed[imp] = true
ix.importMap[imp] = append(ix.importMap[imp], r)
}
}
}
|
go
|
func (ix *RuleIndex) buildImportIndex() {
ix.importMap = make(map[ImportSpec][]*ruleRecord)
for _, r := range ix.rules {
if r.embedded {
continue
}
indexed := make(map[ImportSpec]bool)
for _, imp := range r.importedAs {
if indexed[imp] {
continue
}
indexed[imp] = true
ix.importMap[imp] = append(ix.importMap[imp], r)
}
}
}
|
[
"func",
"(",
"ix",
"*",
"RuleIndex",
")",
"buildImportIndex",
"(",
")",
"{",
"ix",
".",
"importMap",
"=",
"make",
"(",
"map",
"[",
"ImportSpec",
"]",
"[",
"]",
"*",
"ruleRecord",
")",
"\n",
"for",
"_",
",",
"r",
":=",
"range",
"ix",
".",
"rules",
"{",
"if",
"r",
".",
"embedded",
"{",
"continue",
"\n",
"}",
"\n",
"indexed",
":=",
"make",
"(",
"map",
"[",
"ImportSpec",
"]",
"bool",
")",
"\n",
"for",
"_",
",",
"imp",
":=",
"range",
"r",
".",
"importedAs",
"{",
"if",
"indexed",
"[",
"imp",
"]",
"{",
"continue",
"\n",
"}",
"\n",
"indexed",
"[",
"imp",
"]",
"=",
"true",
"\n",
"ix",
".",
"importMap",
"[",
"imp",
"]",
"=",
"append",
"(",
"ix",
".",
"importMap",
"[",
"imp",
"]",
",",
"r",
")",
"\n",
"}",
"\n",
"}",
"\n",
"}"
] |
// buildImportIndex constructs the map used by FindRulesByImport.
|
[
"buildImportIndex",
"constructs",
"the",
"map",
"used",
"by",
"FindRulesByImport",
"."
] |
e3805aaca69a9deb949b47bfc45b9b1870712f4f
|
https://github.com/bazelbuild/bazel-gazelle/blob/e3805aaca69a9deb949b47bfc45b9b1870712f4f/resolve/index.go#L173-L188
|
test
|
bazelbuild/bazel-gazelle
|
resolve/index.go
|
IsSelfImport
|
func (r FindResult) IsSelfImport(from label.Label) bool {
if from.Equal(r.Label) {
return true
}
for _, e := range r.Embeds {
if from.Equal(e) {
return true
}
}
return false
}
|
go
|
func (r FindResult) IsSelfImport(from label.Label) bool {
if from.Equal(r.Label) {
return true
}
for _, e := range r.Embeds {
if from.Equal(e) {
return true
}
}
return false
}
|
[
"func",
"(",
"r",
"FindResult",
")",
"IsSelfImport",
"(",
"from",
"label",
".",
"Label",
")",
"bool",
"{",
"if",
"from",
".",
"Equal",
"(",
"r",
".",
"Label",
")",
"{",
"return",
"true",
"\n",
"}",
"\n",
"for",
"_",
",",
"e",
":=",
"range",
"r",
".",
"Embeds",
"{",
"if",
"from",
".",
"Equal",
"(",
"e",
")",
"{",
"return",
"true",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"false",
"\n",
"}"
] |
// IsSelfImport returns true if the result's label matches the given label
// or the result's rule transitively embeds the rule with the given label.
// Self imports cause cyclic dependencies, so the caller may want to omit
// the dependency or report an error.
|
[
"IsSelfImport",
"returns",
"true",
"if",
"the",
"result",
"s",
"label",
"matches",
"the",
"given",
"label",
"or",
"the",
"result",
"s",
"rule",
"transitively",
"embeds",
"the",
"rule",
"with",
"the",
"given",
"label",
".",
"Self",
"imports",
"cause",
"cyclic",
"dependencies",
"so",
"the",
"caller",
"may",
"want",
"to",
"omit",
"the",
"dependency",
"or",
"report",
"an",
"error",
"."
] |
e3805aaca69a9deb949b47bfc45b9b1870712f4f
|
https://github.com/bazelbuild/bazel-gazelle/blob/e3805aaca69a9deb949b47bfc45b9b1870712f4f/resolve/index.go#L236-L246
|
test
|
bazelbuild/bazel-gazelle
|
cmd/gazelle/fix-update.go
|
applyKindMappings
|
func applyKindMappings(mappedKinds []config.MappedKind, loads []rule.LoadInfo) []rule.LoadInfo {
if len(mappedKinds) == 0 {
return loads
}
// Add new RuleInfos or replace existing ones with merged ones.
mappedLoads := make([]rule.LoadInfo, len(loads))
copy(mappedLoads, loads)
for _, mappedKind := range mappedKinds {
mappedLoads = appendOrMergeKindMapping(mappedLoads, mappedKind)
}
return mappedLoads
}
|
go
|
func applyKindMappings(mappedKinds []config.MappedKind, loads []rule.LoadInfo) []rule.LoadInfo {
if len(mappedKinds) == 0 {
return loads
}
// Add new RuleInfos or replace existing ones with merged ones.
mappedLoads := make([]rule.LoadInfo, len(loads))
copy(mappedLoads, loads)
for _, mappedKind := range mappedKinds {
mappedLoads = appendOrMergeKindMapping(mappedLoads, mappedKind)
}
return mappedLoads
}
|
[
"func",
"applyKindMappings",
"(",
"mappedKinds",
"[",
"]",
"config",
".",
"MappedKind",
",",
"loads",
"[",
"]",
"rule",
".",
"LoadInfo",
")",
"[",
"]",
"rule",
".",
"LoadInfo",
"{",
"if",
"len",
"(",
"mappedKinds",
")",
"==",
"0",
"{",
"return",
"loads",
"\n",
"}",
"\n",
"mappedLoads",
":=",
"make",
"(",
"[",
"]",
"rule",
".",
"LoadInfo",
",",
"len",
"(",
"loads",
")",
")",
"\n",
"copy",
"(",
"mappedLoads",
",",
"loads",
")",
"\n",
"for",
"_",
",",
"mappedKind",
":=",
"range",
"mappedKinds",
"{",
"mappedLoads",
"=",
"appendOrMergeKindMapping",
"(",
"mappedLoads",
",",
"mappedKind",
")",
"\n",
"}",
"\n",
"return",
"mappedLoads",
"\n",
"}"
] |
// applyKindMappings returns a copy of LoadInfo that includes c.KindMap.
|
[
"applyKindMappings",
"returns",
"a",
"copy",
"of",
"LoadInfo",
"that",
"includes",
"c",
".",
"KindMap",
"."
] |
e3805aaca69a9deb949b47bfc45b9b1870712f4f
|
https://github.com/bazelbuild/bazel-gazelle/blob/e3805aaca69a9deb949b47bfc45b9b1870712f4f/cmd/gazelle/fix-update.go#L517-L529
|
test
|
bazelbuild/bazel-gazelle
|
cmd/gazelle/fix-update.go
|
appendOrMergeKindMapping
|
func appendOrMergeKindMapping(mappedLoads []rule.LoadInfo, mappedKind config.MappedKind) []rule.LoadInfo {
// If mappedKind.KindLoad already exists in the list, create a merged copy.
for _, load := range mappedLoads {
if load.Name == mappedKind.KindLoad {
load.Symbols = append(load.Symbols, mappedKind.KindName)
return mappedLoads
}
}
// Add a new LoadInfo.
return append(mappedLoads, rule.LoadInfo{
Name: mappedKind.KindLoad,
Symbols: []string{mappedKind.KindName},
})
}
|
go
|
func appendOrMergeKindMapping(mappedLoads []rule.LoadInfo, mappedKind config.MappedKind) []rule.LoadInfo {
// If mappedKind.KindLoad already exists in the list, create a merged copy.
for _, load := range mappedLoads {
if load.Name == mappedKind.KindLoad {
load.Symbols = append(load.Symbols, mappedKind.KindName)
return mappedLoads
}
}
// Add a new LoadInfo.
return append(mappedLoads, rule.LoadInfo{
Name: mappedKind.KindLoad,
Symbols: []string{mappedKind.KindName},
})
}
|
[
"func",
"appendOrMergeKindMapping",
"(",
"mappedLoads",
"[",
"]",
"rule",
".",
"LoadInfo",
",",
"mappedKind",
"config",
".",
"MappedKind",
")",
"[",
"]",
"rule",
".",
"LoadInfo",
"{",
"for",
"_",
",",
"load",
":=",
"range",
"mappedLoads",
"{",
"if",
"load",
".",
"Name",
"==",
"mappedKind",
".",
"KindLoad",
"{",
"load",
".",
"Symbols",
"=",
"append",
"(",
"load",
".",
"Symbols",
",",
"mappedKind",
".",
"KindName",
")",
"\n",
"return",
"mappedLoads",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"append",
"(",
"mappedLoads",
",",
"rule",
".",
"LoadInfo",
"{",
"Name",
":",
"mappedKind",
".",
"KindLoad",
",",
"Symbols",
":",
"[",
"]",
"string",
"{",
"mappedKind",
".",
"KindName",
"}",
",",
"}",
")",
"\n",
"}"
] |
// appendOrMergeKindMapping adds LoadInfo for the given replacement.
|
[
"appendOrMergeKindMapping",
"adds",
"LoadInfo",
"for",
"the",
"given",
"replacement",
"."
] |
e3805aaca69a9deb949b47bfc45b9b1870712f4f
|
https://github.com/bazelbuild/bazel-gazelle/blob/e3805aaca69a9deb949b47bfc45b9b1870712f4f/cmd/gazelle/fix-update.go#L532-L546
|
test
|
bazelbuild/bazel-gazelle
|
language/proto/generate.go
|
RuleName
|
func RuleName(names ...string) string {
base := "root"
for _, name := range names {
notIdent := func(c rune) bool {
return !('A' <= c && c <= 'Z' ||
'a' <= c && c <= 'z' ||
'0' <= c && c <= '9' ||
c == '_')
}
if i := strings.LastIndexFunc(name, notIdent); i >= 0 {
name = name[i+1:]
}
if name != "" {
base = name
break
}
}
return base + "_proto"
}
|
go
|
func RuleName(names ...string) string {
base := "root"
for _, name := range names {
notIdent := func(c rune) bool {
return !('A' <= c && c <= 'Z' ||
'a' <= c && c <= 'z' ||
'0' <= c && c <= '9' ||
c == '_')
}
if i := strings.LastIndexFunc(name, notIdent); i >= 0 {
name = name[i+1:]
}
if name != "" {
base = name
break
}
}
return base + "_proto"
}
|
[
"func",
"RuleName",
"(",
"names",
"...",
"string",
")",
"string",
"{",
"base",
":=",
"\"root\"",
"\n",
"for",
"_",
",",
"name",
":=",
"range",
"names",
"{",
"notIdent",
":=",
"func",
"(",
"c",
"rune",
")",
"bool",
"{",
"return",
"!",
"(",
"'A'",
"<=",
"c",
"&&",
"c",
"<=",
"'Z'",
"||",
"'a'",
"<=",
"c",
"&&",
"c",
"<=",
"'z'",
"||",
"'0'",
"<=",
"c",
"&&",
"c",
"<=",
"'9'",
"||",
"c",
"==",
"'_'",
")",
"\n",
"}",
"\n",
"if",
"i",
":=",
"strings",
".",
"LastIndexFunc",
"(",
"name",
",",
"notIdent",
")",
";",
"i",
">=",
"0",
"{",
"name",
"=",
"name",
"[",
"i",
"+",
"1",
":",
"]",
"\n",
"}",
"\n",
"if",
"name",
"!=",
"\"\"",
"{",
"base",
"=",
"name",
"\n",
"break",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"base",
"+",
"\"_proto\"",
"\n",
"}"
] |
// RuleName returns a name for a proto_library derived from the given strings.
// For each string, RuleName will look for a non-empty suffix of identifier
// characters and then append "_proto" to that.
|
[
"RuleName",
"returns",
"a",
"name",
"for",
"a",
"proto_library",
"derived",
"from",
"the",
"given",
"strings",
".",
"For",
"each",
"string",
"RuleName",
"will",
"look",
"for",
"a",
"non",
"-",
"empty",
"suffix",
"of",
"identifier",
"characters",
"and",
"then",
"append",
"_proto",
"to",
"that",
"."
] |
e3805aaca69a9deb949b47bfc45b9b1870712f4f
|
https://github.com/bazelbuild/bazel-gazelle/blob/e3805aaca69a9deb949b47bfc45b9b1870712f4f/language/proto/generate.go#L75-L93
|
test
|
bazelbuild/bazel-gazelle
|
language/proto/generate.go
|
buildPackages
|
func buildPackages(pc *ProtoConfig, dir, rel string, protoFiles, genFiles []string) []*Package {
packageMap := make(map[string]*Package)
for _, name := range protoFiles {
info := protoFileInfo(dir, name)
key := info.PackageName
if pc.groupOption != "" {
for _, opt := range info.Options {
if opt.Key == pc.groupOption {
key = opt.Value
break
}
}
}
if packageMap[key] == nil {
packageMap[key] = newPackage(info.PackageName)
}
packageMap[key].addFile(info)
}
switch pc.Mode {
case DefaultMode:
pkg, err := selectPackage(dir, rel, packageMap)
if err != nil {
log.Print(err)
}
if pkg == nil {
return nil // empty rule created in generateEmpty
}
for _, name := range genFiles {
pkg.addGenFile(dir, name)
}
return []*Package{pkg}
case PackageMode:
pkgs := make([]*Package, 0, len(packageMap))
for _, pkg := range packageMap {
pkgs = append(pkgs, pkg)
}
return pkgs
default:
return nil
}
}
|
go
|
func buildPackages(pc *ProtoConfig, dir, rel string, protoFiles, genFiles []string) []*Package {
packageMap := make(map[string]*Package)
for _, name := range protoFiles {
info := protoFileInfo(dir, name)
key := info.PackageName
if pc.groupOption != "" {
for _, opt := range info.Options {
if opt.Key == pc.groupOption {
key = opt.Value
break
}
}
}
if packageMap[key] == nil {
packageMap[key] = newPackage(info.PackageName)
}
packageMap[key].addFile(info)
}
switch pc.Mode {
case DefaultMode:
pkg, err := selectPackage(dir, rel, packageMap)
if err != nil {
log.Print(err)
}
if pkg == nil {
return nil // empty rule created in generateEmpty
}
for _, name := range genFiles {
pkg.addGenFile(dir, name)
}
return []*Package{pkg}
case PackageMode:
pkgs := make([]*Package, 0, len(packageMap))
for _, pkg := range packageMap {
pkgs = append(pkgs, pkg)
}
return pkgs
default:
return nil
}
}
|
[
"func",
"buildPackages",
"(",
"pc",
"*",
"ProtoConfig",
",",
"dir",
",",
"rel",
"string",
",",
"protoFiles",
",",
"genFiles",
"[",
"]",
"string",
")",
"[",
"]",
"*",
"Package",
"{",
"packageMap",
":=",
"make",
"(",
"map",
"[",
"string",
"]",
"*",
"Package",
")",
"\n",
"for",
"_",
",",
"name",
":=",
"range",
"protoFiles",
"{",
"info",
":=",
"protoFileInfo",
"(",
"dir",
",",
"name",
")",
"\n",
"key",
":=",
"info",
".",
"PackageName",
"\n",
"if",
"pc",
".",
"groupOption",
"!=",
"\"\"",
"{",
"for",
"_",
",",
"opt",
":=",
"range",
"info",
".",
"Options",
"{",
"if",
"opt",
".",
"Key",
"==",
"pc",
".",
"groupOption",
"{",
"key",
"=",
"opt",
".",
"Value",
"\n",
"break",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n",
"if",
"packageMap",
"[",
"key",
"]",
"==",
"nil",
"{",
"packageMap",
"[",
"key",
"]",
"=",
"newPackage",
"(",
"info",
".",
"PackageName",
")",
"\n",
"}",
"\n",
"packageMap",
"[",
"key",
"]",
".",
"addFile",
"(",
"info",
")",
"\n",
"}",
"\n",
"switch",
"pc",
".",
"Mode",
"{",
"case",
"DefaultMode",
":",
"pkg",
",",
"err",
":=",
"selectPackage",
"(",
"dir",
",",
"rel",
",",
"packageMap",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"log",
".",
"Print",
"(",
"err",
")",
"\n",
"}",
"\n",
"if",
"pkg",
"==",
"nil",
"{",
"return",
"nil",
"\n",
"}",
"\n",
"for",
"_",
",",
"name",
":=",
"range",
"genFiles",
"{",
"pkg",
".",
"addGenFile",
"(",
"dir",
",",
"name",
")",
"\n",
"}",
"\n",
"return",
"[",
"]",
"*",
"Package",
"{",
"pkg",
"}",
"\n",
"case",
"PackageMode",
":",
"pkgs",
":=",
"make",
"(",
"[",
"]",
"*",
"Package",
",",
"0",
",",
"len",
"(",
"packageMap",
")",
")",
"\n",
"for",
"_",
",",
"pkg",
":=",
"range",
"packageMap",
"{",
"pkgs",
"=",
"append",
"(",
"pkgs",
",",
"pkg",
")",
"\n",
"}",
"\n",
"return",
"pkgs",
"\n",
"default",
":",
"return",
"nil",
"\n",
"}",
"\n",
"}"
] |
// buildPackage extracts metadata from the .proto files in a directory and
// constructs possibly several packages, then selects a package to generate
// a proto_library rule for.
|
[
"buildPackage",
"extracts",
"metadata",
"from",
"the",
".",
"proto",
"files",
"in",
"a",
"directory",
"and",
"constructs",
"possibly",
"several",
"packages",
"then",
"selects",
"a",
"package",
"to",
"generate",
"a",
"proto_library",
"rule",
"for",
"."
] |
e3805aaca69a9deb949b47bfc45b9b1870712f4f
|
https://github.com/bazelbuild/bazel-gazelle/blob/e3805aaca69a9deb949b47bfc45b9b1870712f4f/language/proto/generate.go#L98-L141
|
test
|
bazelbuild/bazel-gazelle
|
language/proto/generate.go
|
selectPackage
|
func selectPackage(dir, rel string, packageMap map[string]*Package) (*Package, error) {
if len(packageMap) == 0 {
return nil, nil
}
if len(packageMap) == 1 {
for _, pkg := range packageMap {
return pkg, nil
}
}
defaultPackageName := strings.Replace(rel, "/", "_", -1)
for _, pkg := range packageMap {
if pkgName := goPackageName(pkg); pkgName != "" && pkgName == defaultPackageName {
return pkg, nil
}
}
return nil, fmt.Errorf("%s: directory contains multiple proto packages. Gazelle can only generate a proto_library for one package.", dir)
}
|
go
|
func selectPackage(dir, rel string, packageMap map[string]*Package) (*Package, error) {
if len(packageMap) == 0 {
return nil, nil
}
if len(packageMap) == 1 {
for _, pkg := range packageMap {
return pkg, nil
}
}
defaultPackageName := strings.Replace(rel, "/", "_", -1)
for _, pkg := range packageMap {
if pkgName := goPackageName(pkg); pkgName != "" && pkgName == defaultPackageName {
return pkg, nil
}
}
return nil, fmt.Errorf("%s: directory contains multiple proto packages. Gazelle can only generate a proto_library for one package.", dir)
}
|
[
"func",
"selectPackage",
"(",
"dir",
",",
"rel",
"string",
",",
"packageMap",
"map",
"[",
"string",
"]",
"*",
"Package",
")",
"(",
"*",
"Package",
",",
"error",
")",
"{",
"if",
"len",
"(",
"packageMap",
")",
"==",
"0",
"{",
"return",
"nil",
",",
"nil",
"\n",
"}",
"\n",
"if",
"len",
"(",
"packageMap",
")",
"==",
"1",
"{",
"for",
"_",
",",
"pkg",
":=",
"range",
"packageMap",
"{",
"return",
"pkg",
",",
"nil",
"\n",
"}",
"\n",
"}",
"\n",
"defaultPackageName",
":=",
"strings",
".",
"Replace",
"(",
"rel",
",",
"\"/\"",
",",
"\"_\"",
",",
"-",
"1",
")",
"\n",
"for",
"_",
",",
"pkg",
":=",
"range",
"packageMap",
"{",
"if",
"pkgName",
":=",
"goPackageName",
"(",
"pkg",
")",
";",
"pkgName",
"!=",
"\"\"",
"&&",
"pkgName",
"==",
"defaultPackageName",
"{",
"return",
"pkg",
",",
"nil",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"%s: directory contains multiple proto packages. Gazelle can only generate a proto_library for one package.\"",
",",
"dir",
")",
"\n",
"}"
] |
// selectPackage chooses a package to generate rules for.
|
[
"selectPackage",
"chooses",
"a",
"package",
"to",
"generate",
"rules",
"for",
"."
] |
e3805aaca69a9deb949b47bfc45b9b1870712f4f
|
https://github.com/bazelbuild/bazel-gazelle/blob/e3805aaca69a9deb949b47bfc45b9b1870712f4f/language/proto/generate.go#L144-L160
|
test
|
bazelbuild/bazel-gazelle
|
language/proto/generate.go
|
generateProto
|
func generateProto(pc *ProtoConfig, rel string, pkg *Package, shouldSetVisibility bool) *rule.Rule {
var name string
if pc.Mode == DefaultMode {
name = RuleName(goPackageName(pkg), pc.GoPrefix, rel)
} else {
name = RuleName(pkg.Options[pc.groupOption], pkg.Name, rel)
}
r := rule.NewRule("proto_library", name)
srcs := make([]string, 0, len(pkg.Files))
for f := range pkg.Files {
srcs = append(srcs, f)
}
sort.Strings(srcs)
if len(srcs) > 0 {
r.SetAttr("srcs", srcs)
}
r.SetPrivateAttr(PackageKey, *pkg)
imports := make([]string, 0, len(pkg.Imports))
for i := range pkg.Imports {
imports = append(imports, i)
}
sort.Strings(imports)
// NOTE: This attribute should not be used outside this extension. It's still
// convenient for testing though.
r.SetPrivateAttr(config.GazelleImportsKey, imports)
for k, v := range pkg.Options {
r.SetPrivateAttr(k, v)
}
if shouldSetVisibility {
vis := rule.CheckInternalVisibility(rel, "//visibility:public")
r.SetAttr("visibility", []string{vis})
}
if pc.stripImportPrefix != "" {
r.SetAttr("strip_import_prefix", pc.stripImportPrefix)
}
if pc.importPrefix != "" {
r.SetAttr("import_prefix", pc.importPrefix)
}
return r
}
|
go
|
func generateProto(pc *ProtoConfig, rel string, pkg *Package, shouldSetVisibility bool) *rule.Rule {
var name string
if pc.Mode == DefaultMode {
name = RuleName(goPackageName(pkg), pc.GoPrefix, rel)
} else {
name = RuleName(pkg.Options[pc.groupOption], pkg.Name, rel)
}
r := rule.NewRule("proto_library", name)
srcs := make([]string, 0, len(pkg.Files))
for f := range pkg.Files {
srcs = append(srcs, f)
}
sort.Strings(srcs)
if len(srcs) > 0 {
r.SetAttr("srcs", srcs)
}
r.SetPrivateAttr(PackageKey, *pkg)
imports := make([]string, 0, len(pkg.Imports))
for i := range pkg.Imports {
imports = append(imports, i)
}
sort.Strings(imports)
// NOTE: This attribute should not be used outside this extension. It's still
// convenient for testing though.
r.SetPrivateAttr(config.GazelleImportsKey, imports)
for k, v := range pkg.Options {
r.SetPrivateAttr(k, v)
}
if shouldSetVisibility {
vis := rule.CheckInternalVisibility(rel, "//visibility:public")
r.SetAttr("visibility", []string{vis})
}
if pc.stripImportPrefix != "" {
r.SetAttr("strip_import_prefix", pc.stripImportPrefix)
}
if pc.importPrefix != "" {
r.SetAttr("import_prefix", pc.importPrefix)
}
return r
}
|
[
"func",
"generateProto",
"(",
"pc",
"*",
"ProtoConfig",
",",
"rel",
"string",
",",
"pkg",
"*",
"Package",
",",
"shouldSetVisibility",
"bool",
")",
"*",
"rule",
".",
"Rule",
"{",
"var",
"name",
"string",
"\n",
"if",
"pc",
".",
"Mode",
"==",
"DefaultMode",
"{",
"name",
"=",
"RuleName",
"(",
"goPackageName",
"(",
"pkg",
")",
",",
"pc",
".",
"GoPrefix",
",",
"rel",
")",
"\n",
"}",
"else",
"{",
"name",
"=",
"RuleName",
"(",
"pkg",
".",
"Options",
"[",
"pc",
".",
"groupOption",
"]",
",",
"pkg",
".",
"Name",
",",
"rel",
")",
"\n",
"}",
"\n",
"r",
":=",
"rule",
".",
"NewRule",
"(",
"\"proto_library\"",
",",
"name",
")",
"\n",
"srcs",
":=",
"make",
"(",
"[",
"]",
"string",
",",
"0",
",",
"len",
"(",
"pkg",
".",
"Files",
")",
")",
"\n",
"for",
"f",
":=",
"range",
"pkg",
".",
"Files",
"{",
"srcs",
"=",
"append",
"(",
"srcs",
",",
"f",
")",
"\n",
"}",
"\n",
"sort",
".",
"Strings",
"(",
"srcs",
")",
"\n",
"if",
"len",
"(",
"srcs",
")",
">",
"0",
"{",
"r",
".",
"SetAttr",
"(",
"\"srcs\"",
",",
"srcs",
")",
"\n",
"}",
"\n",
"r",
".",
"SetPrivateAttr",
"(",
"PackageKey",
",",
"*",
"pkg",
")",
"\n",
"imports",
":=",
"make",
"(",
"[",
"]",
"string",
",",
"0",
",",
"len",
"(",
"pkg",
".",
"Imports",
")",
")",
"\n",
"for",
"i",
":=",
"range",
"pkg",
".",
"Imports",
"{",
"imports",
"=",
"append",
"(",
"imports",
",",
"i",
")",
"\n",
"}",
"\n",
"sort",
".",
"Strings",
"(",
"imports",
")",
"\n",
"r",
".",
"SetPrivateAttr",
"(",
"config",
".",
"GazelleImportsKey",
",",
"imports",
")",
"\n",
"for",
"k",
",",
"v",
":=",
"range",
"pkg",
".",
"Options",
"{",
"r",
".",
"SetPrivateAttr",
"(",
"k",
",",
"v",
")",
"\n",
"}",
"\n",
"if",
"shouldSetVisibility",
"{",
"vis",
":=",
"rule",
".",
"CheckInternalVisibility",
"(",
"rel",
",",
"\"//visibility:public\"",
")",
"\n",
"r",
".",
"SetAttr",
"(",
"\"visibility\"",
",",
"[",
"]",
"string",
"{",
"vis",
"}",
")",
"\n",
"}",
"\n",
"if",
"pc",
".",
"stripImportPrefix",
"!=",
"\"\"",
"{",
"r",
".",
"SetAttr",
"(",
"\"strip_import_prefix\"",
",",
"pc",
".",
"stripImportPrefix",
")",
"\n",
"}",
"\n",
"if",
"pc",
".",
"importPrefix",
"!=",
"\"\"",
"{",
"r",
".",
"SetAttr",
"(",
"\"import_prefix\"",
",",
"pc",
".",
"importPrefix",
")",
"\n",
"}",
"\n",
"return",
"r",
"\n",
"}"
] |
// generateProto creates a new proto_library rule for a package. The rule may
// be empty if there are no sources.
|
[
"generateProto",
"creates",
"a",
"new",
"proto_library",
"rule",
"for",
"a",
"package",
".",
"The",
"rule",
"may",
"be",
"empty",
"if",
"there",
"are",
"no",
"sources",
"."
] |
e3805aaca69a9deb949b47bfc45b9b1870712f4f
|
https://github.com/bazelbuild/bazel-gazelle/blob/e3805aaca69a9deb949b47bfc45b9b1870712f4f/language/proto/generate.go#L191-L230
|
test
|
bazelbuild/bazel-gazelle
|
language/proto/generate.go
|
generateEmpty
|
func generateEmpty(f *rule.File, regularFiles, genFiles []string) []*rule.Rule {
if f == nil {
return nil
}
knownFiles := make(map[string]bool)
for _, f := range regularFiles {
knownFiles[f] = true
}
for _, f := range genFiles {
knownFiles[f] = true
}
var empty []*rule.Rule
outer:
for _, r := range f.Rules {
if r.Kind() != "proto_library" {
continue
}
srcs := r.AttrStrings("srcs")
if len(srcs) == 0 && r.Attr("srcs") != nil {
// srcs is not a string list; leave it alone
continue
}
for _, src := range r.AttrStrings("srcs") {
if knownFiles[src] {
continue outer
}
}
empty = append(empty, rule.NewRule("proto_library", r.Name()))
}
return empty
}
|
go
|
func generateEmpty(f *rule.File, regularFiles, genFiles []string) []*rule.Rule {
if f == nil {
return nil
}
knownFiles := make(map[string]bool)
for _, f := range regularFiles {
knownFiles[f] = true
}
for _, f := range genFiles {
knownFiles[f] = true
}
var empty []*rule.Rule
outer:
for _, r := range f.Rules {
if r.Kind() != "proto_library" {
continue
}
srcs := r.AttrStrings("srcs")
if len(srcs) == 0 && r.Attr("srcs") != nil {
// srcs is not a string list; leave it alone
continue
}
for _, src := range r.AttrStrings("srcs") {
if knownFiles[src] {
continue outer
}
}
empty = append(empty, rule.NewRule("proto_library", r.Name()))
}
return empty
}
|
[
"func",
"generateEmpty",
"(",
"f",
"*",
"rule",
".",
"File",
",",
"regularFiles",
",",
"genFiles",
"[",
"]",
"string",
")",
"[",
"]",
"*",
"rule",
".",
"Rule",
"{",
"if",
"f",
"==",
"nil",
"{",
"return",
"nil",
"\n",
"}",
"\n",
"knownFiles",
":=",
"make",
"(",
"map",
"[",
"string",
"]",
"bool",
")",
"\n",
"for",
"_",
",",
"f",
":=",
"range",
"regularFiles",
"{",
"knownFiles",
"[",
"f",
"]",
"=",
"true",
"\n",
"}",
"\n",
"for",
"_",
",",
"f",
":=",
"range",
"genFiles",
"{",
"knownFiles",
"[",
"f",
"]",
"=",
"true",
"\n",
"}",
"\n",
"var",
"empty",
"[",
"]",
"*",
"rule",
".",
"Rule",
"\n",
"outer",
":",
"for",
"_",
",",
"r",
":=",
"range",
"f",
".",
"Rules",
"{",
"if",
"r",
".",
"Kind",
"(",
")",
"!=",
"\"proto_library\"",
"{",
"continue",
"\n",
"}",
"\n",
"srcs",
":=",
"r",
".",
"AttrStrings",
"(",
"\"srcs\"",
")",
"\n",
"if",
"len",
"(",
"srcs",
")",
"==",
"0",
"&&",
"r",
".",
"Attr",
"(",
"\"srcs\"",
")",
"!=",
"nil",
"{",
"continue",
"\n",
"}",
"\n",
"for",
"_",
",",
"src",
":=",
"range",
"r",
".",
"AttrStrings",
"(",
"\"srcs\"",
")",
"{",
"if",
"knownFiles",
"[",
"src",
"]",
"{",
"continue",
"outer",
"\n",
"}",
"\n",
"}",
"\n",
"empty",
"=",
"append",
"(",
"empty",
",",
"rule",
".",
"NewRule",
"(",
"\"proto_library\"",
",",
"r",
".",
"Name",
"(",
")",
")",
")",
"\n",
"}",
"\n",
"return",
"empty",
"\n",
"}"
] |
// generateEmpty generates a list of proto_library rules that may be deleted.
// This is generated from existing proto_library rules with srcs lists that
// don't match any static or generated files.
|
[
"generateEmpty",
"generates",
"a",
"list",
"of",
"proto_library",
"rules",
"that",
"may",
"be",
"deleted",
".",
"This",
"is",
"generated",
"from",
"existing",
"proto_library",
"rules",
"with",
"srcs",
"lists",
"that",
"don",
"t",
"match",
"any",
"static",
"or",
"generated",
"files",
"."
] |
e3805aaca69a9deb949b47bfc45b9b1870712f4f
|
https://github.com/bazelbuild/bazel-gazelle/blob/e3805aaca69a9deb949b47bfc45b9b1870712f4f/language/proto/generate.go#L235-L265
|
test
|
bazelbuild/bazel-gazelle
|
repo/repo.go
|
ImportRepoRules
|
func ImportRepoRules(filename string, repoCache *RemoteCache) ([]*rule.Rule, error) {
format := getLockFileFormat(filename)
if format == unknownFormat {
return nil, fmt.Errorf(`%s: unrecognized lock file format. Expected "Gopkg.lock", "go.mod", or "Godeps.json"`, filename)
}
parser := lockFileParsers[format]
repos, err := parser(filename, repoCache)
if err != nil {
return nil, fmt.Errorf("error parsing %q: %v", filename, err)
}
sort.Stable(byName(repos))
rules := make([]*rule.Rule, 0, len(repos))
for _, repo := range repos {
rules = append(rules, GenerateRule(repo))
}
return rules, nil
}
|
go
|
func ImportRepoRules(filename string, repoCache *RemoteCache) ([]*rule.Rule, error) {
format := getLockFileFormat(filename)
if format == unknownFormat {
return nil, fmt.Errorf(`%s: unrecognized lock file format. Expected "Gopkg.lock", "go.mod", or "Godeps.json"`, filename)
}
parser := lockFileParsers[format]
repos, err := parser(filename, repoCache)
if err != nil {
return nil, fmt.Errorf("error parsing %q: %v", filename, err)
}
sort.Stable(byName(repos))
rules := make([]*rule.Rule, 0, len(repos))
for _, repo := range repos {
rules = append(rules, GenerateRule(repo))
}
return rules, nil
}
|
[
"func",
"ImportRepoRules",
"(",
"filename",
"string",
",",
"repoCache",
"*",
"RemoteCache",
")",
"(",
"[",
"]",
"*",
"rule",
".",
"Rule",
",",
"error",
")",
"{",
"format",
":=",
"getLockFileFormat",
"(",
"filename",
")",
"\n",
"if",
"format",
"==",
"unknownFormat",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"`%s: unrecognized lock file format. Expected \"Gopkg.lock\", \"go.mod\", or \"Godeps.json\"`",
",",
"filename",
")",
"\n",
"}",
"\n",
"parser",
":=",
"lockFileParsers",
"[",
"format",
"]",
"\n",
"repos",
",",
"err",
":=",
"parser",
"(",
"filename",
",",
"repoCache",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"error parsing %q: %v\"",
",",
"filename",
",",
"err",
")",
"\n",
"}",
"\n",
"sort",
".",
"Stable",
"(",
"byName",
"(",
"repos",
")",
")",
"\n",
"rules",
":=",
"make",
"(",
"[",
"]",
"*",
"rule",
".",
"Rule",
",",
"0",
",",
"len",
"(",
"repos",
")",
")",
"\n",
"for",
"_",
",",
"repo",
":=",
"range",
"repos",
"{",
"rules",
"=",
"append",
"(",
"rules",
",",
"GenerateRule",
"(",
"repo",
")",
")",
"\n",
"}",
"\n",
"return",
"rules",
",",
"nil",
"\n",
"}"
] |
// ImportRepoRules reads the lock file of a vendoring tool and returns
// a list of equivalent repository rules that can be merged into a WORKSPACE
// file. The format of the file is inferred from its basename.
|
[
"ImportRepoRules",
"reads",
"the",
"lock",
"file",
"of",
"a",
"vendoring",
"tool",
"and",
"returns",
"a",
"list",
"of",
"equivalent",
"repository",
"rules",
"that",
"can",
"be",
"merged",
"into",
"a",
"WORKSPACE",
"file",
".",
"The",
"format",
"of",
"the",
"file",
"is",
"inferred",
"from",
"its",
"basename",
"."
] |
e3805aaca69a9deb949b47bfc45b9b1870712f4f
|
https://github.com/bazelbuild/bazel-gazelle/blob/e3805aaca69a9deb949b47bfc45b9b1870712f4f/repo/repo.go#L95-L112
|
test
|
bazelbuild/bazel-gazelle
|
repo/repo.go
|
MergeRules
|
func MergeRules(genRules []*rule.Rule, existingRules map[*rule.File][]string, destFile *rule.File, kinds map[string]rule.KindInfo) []*rule.File {
sort.Stable(byRuleName(genRules))
repoMap := make(map[string]*rule.File)
for file, repoNames := range existingRules {
if file.Path == destFile.Path && file.MacroName() != "" && file.MacroName() == destFile.MacroName() {
file = destFile
}
for _, name := range repoNames {
repoMap[name] = file
}
}
rulesByFile := make(map[*rule.File][]*rule.Rule)
for _, rule := range genRules {
dest := destFile
if file, ok := repoMap[rule.Name()]; ok {
dest = file
}
rulesByFile[dest] = append(rulesByFile[dest], rule)
}
updatedFiles := make(map[string]*rule.File)
for f, rules := range rulesByFile {
merger.MergeFile(f, nil, rules, merger.PreResolve, kinds)
f.Sync()
if uf, ok := updatedFiles[f.Path]; ok {
uf.SyncMacroFile(f)
} else {
updatedFiles[f.Path] = f
}
}
files := make([]*rule.File, 0, len(updatedFiles))
for _, f := range updatedFiles {
files = append(files, f)
}
return files
}
|
go
|
func MergeRules(genRules []*rule.Rule, existingRules map[*rule.File][]string, destFile *rule.File, kinds map[string]rule.KindInfo) []*rule.File {
sort.Stable(byRuleName(genRules))
repoMap := make(map[string]*rule.File)
for file, repoNames := range existingRules {
if file.Path == destFile.Path && file.MacroName() != "" && file.MacroName() == destFile.MacroName() {
file = destFile
}
for _, name := range repoNames {
repoMap[name] = file
}
}
rulesByFile := make(map[*rule.File][]*rule.Rule)
for _, rule := range genRules {
dest := destFile
if file, ok := repoMap[rule.Name()]; ok {
dest = file
}
rulesByFile[dest] = append(rulesByFile[dest], rule)
}
updatedFiles := make(map[string]*rule.File)
for f, rules := range rulesByFile {
merger.MergeFile(f, nil, rules, merger.PreResolve, kinds)
f.Sync()
if uf, ok := updatedFiles[f.Path]; ok {
uf.SyncMacroFile(f)
} else {
updatedFiles[f.Path] = f
}
}
files := make([]*rule.File, 0, len(updatedFiles))
for _, f := range updatedFiles {
files = append(files, f)
}
return files
}
|
[
"func",
"MergeRules",
"(",
"genRules",
"[",
"]",
"*",
"rule",
".",
"Rule",
",",
"existingRules",
"map",
"[",
"*",
"rule",
".",
"File",
"]",
"[",
"]",
"string",
",",
"destFile",
"*",
"rule",
".",
"File",
",",
"kinds",
"map",
"[",
"string",
"]",
"rule",
".",
"KindInfo",
")",
"[",
"]",
"*",
"rule",
".",
"File",
"{",
"sort",
".",
"Stable",
"(",
"byRuleName",
"(",
"genRules",
")",
")",
"\n",
"repoMap",
":=",
"make",
"(",
"map",
"[",
"string",
"]",
"*",
"rule",
".",
"File",
")",
"\n",
"for",
"file",
",",
"repoNames",
":=",
"range",
"existingRules",
"{",
"if",
"file",
".",
"Path",
"==",
"destFile",
".",
"Path",
"&&",
"file",
".",
"MacroName",
"(",
")",
"!=",
"\"\"",
"&&",
"file",
".",
"MacroName",
"(",
")",
"==",
"destFile",
".",
"MacroName",
"(",
")",
"{",
"file",
"=",
"destFile",
"\n",
"}",
"\n",
"for",
"_",
",",
"name",
":=",
"range",
"repoNames",
"{",
"repoMap",
"[",
"name",
"]",
"=",
"file",
"\n",
"}",
"\n",
"}",
"\n",
"rulesByFile",
":=",
"make",
"(",
"map",
"[",
"*",
"rule",
".",
"File",
"]",
"[",
"]",
"*",
"rule",
".",
"Rule",
")",
"\n",
"for",
"_",
",",
"rule",
":=",
"range",
"genRules",
"{",
"dest",
":=",
"destFile",
"\n",
"if",
"file",
",",
"ok",
":=",
"repoMap",
"[",
"rule",
".",
"Name",
"(",
")",
"]",
";",
"ok",
"{",
"dest",
"=",
"file",
"\n",
"}",
"\n",
"rulesByFile",
"[",
"dest",
"]",
"=",
"append",
"(",
"rulesByFile",
"[",
"dest",
"]",
",",
"rule",
")",
"\n",
"}",
"\n",
"updatedFiles",
":=",
"make",
"(",
"map",
"[",
"string",
"]",
"*",
"rule",
".",
"File",
")",
"\n",
"for",
"f",
",",
"rules",
":=",
"range",
"rulesByFile",
"{",
"merger",
".",
"MergeFile",
"(",
"f",
",",
"nil",
",",
"rules",
",",
"merger",
".",
"PreResolve",
",",
"kinds",
")",
"\n",
"f",
".",
"Sync",
"(",
")",
"\n",
"if",
"uf",
",",
"ok",
":=",
"updatedFiles",
"[",
"f",
".",
"Path",
"]",
";",
"ok",
"{",
"uf",
".",
"SyncMacroFile",
"(",
"f",
")",
"\n",
"}",
"else",
"{",
"updatedFiles",
"[",
"f",
".",
"Path",
"]",
"=",
"f",
"\n",
"}",
"\n",
"}",
"\n",
"files",
":=",
"make",
"(",
"[",
"]",
"*",
"rule",
".",
"File",
",",
"0",
",",
"len",
"(",
"updatedFiles",
")",
")",
"\n",
"for",
"_",
",",
"f",
":=",
"range",
"updatedFiles",
"{",
"files",
"=",
"append",
"(",
"files",
",",
"f",
")",
"\n",
"}",
"\n",
"return",
"files",
"\n",
"}"
] |
// MergeRules merges a list of generated repo rules with the already defined repo rules,
// and then updates each rule's underlying file. If the generated rule matches an existing
// one, then it inherits the file where the existing rule was defined. If the rule is new then
// its file is set as the destFile parameter. A list of the updated files is returned.
|
[
"MergeRules",
"merges",
"a",
"list",
"of",
"generated",
"repo",
"rules",
"with",
"the",
"already",
"defined",
"repo",
"rules",
"and",
"then",
"updates",
"each",
"rule",
"s",
"underlying",
"file",
".",
"If",
"the",
"generated",
"rule",
"matches",
"an",
"existing",
"one",
"then",
"it",
"inherits",
"the",
"file",
"where",
"the",
"existing",
"rule",
"was",
"defined",
".",
"If",
"the",
"rule",
"is",
"new",
"then",
"its",
"file",
"is",
"set",
"as",
"the",
"destFile",
"parameter",
".",
"A",
"list",
"of",
"the",
"updated",
"files",
"is",
"returned",
"."
] |
e3805aaca69a9deb949b47bfc45b9b1870712f4f
|
https://github.com/bazelbuild/bazel-gazelle/blob/e3805aaca69a9deb949b47bfc45b9b1870712f4f/repo/repo.go#L118-L155
|
test
|
bazelbuild/bazel-gazelle
|
repo/repo.go
|
GenerateRule
|
func GenerateRule(repo Repo) *rule.Rule {
r := rule.NewRule("go_repository", repo.Name)
if repo.Commit != "" {
r.SetAttr("commit", repo.Commit)
}
if repo.Tag != "" {
r.SetAttr("tag", repo.Tag)
}
r.SetAttr("importpath", repo.GoPrefix)
if repo.Remote != "" {
r.SetAttr("remote", repo.Remote)
}
if repo.VCS != "" {
r.SetAttr("vcs", repo.VCS)
}
if repo.Version != "" {
r.SetAttr("version", repo.Version)
}
if repo.Sum != "" {
r.SetAttr("sum", repo.Sum)
}
if repo.Replace != "" {
r.SetAttr("replace", repo.Replace)
}
return r
}
|
go
|
func GenerateRule(repo Repo) *rule.Rule {
r := rule.NewRule("go_repository", repo.Name)
if repo.Commit != "" {
r.SetAttr("commit", repo.Commit)
}
if repo.Tag != "" {
r.SetAttr("tag", repo.Tag)
}
r.SetAttr("importpath", repo.GoPrefix)
if repo.Remote != "" {
r.SetAttr("remote", repo.Remote)
}
if repo.VCS != "" {
r.SetAttr("vcs", repo.VCS)
}
if repo.Version != "" {
r.SetAttr("version", repo.Version)
}
if repo.Sum != "" {
r.SetAttr("sum", repo.Sum)
}
if repo.Replace != "" {
r.SetAttr("replace", repo.Replace)
}
return r
}
|
[
"func",
"GenerateRule",
"(",
"repo",
"Repo",
")",
"*",
"rule",
".",
"Rule",
"{",
"r",
":=",
"rule",
".",
"NewRule",
"(",
"\"go_repository\"",
",",
"repo",
".",
"Name",
")",
"\n",
"if",
"repo",
".",
"Commit",
"!=",
"\"\"",
"{",
"r",
".",
"SetAttr",
"(",
"\"commit\"",
",",
"repo",
".",
"Commit",
")",
"\n",
"}",
"\n",
"if",
"repo",
".",
"Tag",
"!=",
"\"\"",
"{",
"r",
".",
"SetAttr",
"(",
"\"tag\"",
",",
"repo",
".",
"Tag",
")",
"\n",
"}",
"\n",
"r",
".",
"SetAttr",
"(",
"\"importpath\"",
",",
"repo",
".",
"GoPrefix",
")",
"\n",
"if",
"repo",
".",
"Remote",
"!=",
"\"\"",
"{",
"r",
".",
"SetAttr",
"(",
"\"remote\"",
",",
"repo",
".",
"Remote",
")",
"\n",
"}",
"\n",
"if",
"repo",
".",
"VCS",
"!=",
"\"\"",
"{",
"r",
".",
"SetAttr",
"(",
"\"vcs\"",
",",
"repo",
".",
"VCS",
")",
"\n",
"}",
"\n",
"if",
"repo",
".",
"Version",
"!=",
"\"\"",
"{",
"r",
".",
"SetAttr",
"(",
"\"version\"",
",",
"repo",
".",
"Version",
")",
"\n",
"}",
"\n",
"if",
"repo",
".",
"Sum",
"!=",
"\"\"",
"{",
"r",
".",
"SetAttr",
"(",
"\"sum\"",
",",
"repo",
".",
"Sum",
")",
"\n",
"}",
"\n",
"if",
"repo",
".",
"Replace",
"!=",
"\"\"",
"{",
"r",
".",
"SetAttr",
"(",
"\"replace\"",
",",
"repo",
".",
"Replace",
")",
"\n",
"}",
"\n",
"return",
"r",
"\n",
"}"
] |
// GenerateRule returns a repository rule for the given repository that can
// be written in a WORKSPACE file.
|
[
"GenerateRule",
"returns",
"a",
"repository",
"rule",
"for",
"the",
"given",
"repository",
"that",
"can",
"be",
"written",
"in",
"a",
"WORKSPACE",
"file",
"."
] |
e3805aaca69a9deb949b47bfc45b9b1870712f4f
|
https://github.com/bazelbuild/bazel-gazelle/blob/e3805aaca69a9deb949b47bfc45b9b1870712f4f/repo/repo.go#L172-L197
|
test
|
bazelbuild/bazel-gazelle
|
repo/repo.go
|
FindExternalRepo
|
func FindExternalRepo(repoRoot, name string) (string, error) {
// See https://docs.bazel.build/versions/master/output_directories.html
// for documentation on Bazel directory layout.
// We expect the bazel-out symlink in the workspace root directory to point to
// <output-base>/execroot/<workspace-name>/bazel-out
// We expect the external repository to be checked out at
// <output-base>/external/<name>
// Note that users can change the prefix for most of the Bazel symlinks with
// --symlink_prefix, but this does not include bazel-out.
externalPath := strings.Join([]string{repoRoot, "bazel-out", "..", "..", "..", "external", name}, string(os.PathSeparator))
cleanPath, err := filepath.EvalSymlinks(externalPath)
if err != nil {
return "", err
}
st, err := os.Stat(cleanPath)
if err != nil {
return "", err
}
if !st.IsDir() {
return "", fmt.Errorf("%s: not a directory", externalPath)
}
return cleanPath, nil
}
|
go
|
func FindExternalRepo(repoRoot, name string) (string, error) {
// See https://docs.bazel.build/versions/master/output_directories.html
// for documentation on Bazel directory layout.
// We expect the bazel-out symlink in the workspace root directory to point to
// <output-base>/execroot/<workspace-name>/bazel-out
// We expect the external repository to be checked out at
// <output-base>/external/<name>
// Note that users can change the prefix for most of the Bazel symlinks with
// --symlink_prefix, but this does not include bazel-out.
externalPath := strings.Join([]string{repoRoot, "bazel-out", "..", "..", "..", "external", name}, string(os.PathSeparator))
cleanPath, err := filepath.EvalSymlinks(externalPath)
if err != nil {
return "", err
}
st, err := os.Stat(cleanPath)
if err != nil {
return "", err
}
if !st.IsDir() {
return "", fmt.Errorf("%s: not a directory", externalPath)
}
return cleanPath, nil
}
|
[
"func",
"FindExternalRepo",
"(",
"repoRoot",
",",
"name",
"string",
")",
"(",
"string",
",",
"error",
")",
"{",
"externalPath",
":=",
"strings",
".",
"Join",
"(",
"[",
"]",
"string",
"{",
"repoRoot",
",",
"\"bazel-out\"",
",",
"\"..\"",
",",
"\"..\"",
",",
"\"..\"",
",",
"\"external\"",
",",
"name",
"}",
",",
"string",
"(",
"os",
".",
"PathSeparator",
")",
")",
"\n",
"cleanPath",
",",
"err",
":=",
"filepath",
".",
"EvalSymlinks",
"(",
"externalPath",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\"\"",
",",
"err",
"\n",
"}",
"\n",
"st",
",",
"err",
":=",
"os",
".",
"Stat",
"(",
"cleanPath",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\"\"",
",",
"err",
"\n",
"}",
"\n",
"if",
"!",
"st",
".",
"IsDir",
"(",
")",
"{",
"return",
"\"\"",
",",
"fmt",
".",
"Errorf",
"(",
"\"%s: not a directory\"",
",",
"externalPath",
")",
"\n",
"}",
"\n",
"return",
"cleanPath",
",",
"nil",
"\n",
"}"
] |
// FindExternalRepo attempts to locate the directory where Bazel has fetched
// the external repository with the given name. An error is returned if the
// repository directory cannot be located.
|
[
"FindExternalRepo",
"attempts",
"to",
"locate",
"the",
"directory",
"where",
"Bazel",
"has",
"fetched",
"the",
"external",
"repository",
"with",
"the",
"given",
"name",
".",
"An",
"error",
"is",
"returned",
"if",
"the",
"repository",
"directory",
"cannot",
"be",
"located",
"."
] |
e3805aaca69a9deb949b47bfc45b9b1870712f4f
|
https://github.com/bazelbuild/bazel-gazelle/blob/e3805aaca69a9deb949b47bfc45b9b1870712f4f/repo/repo.go#L202-L224
|
test
|
bazelbuild/bazel-gazelle
|
repo/repo.go
|
ListRepositories
|
func ListRepositories(workspace *rule.File) (repos []Repo, repoNamesByFile map[*rule.File][]string, err error) {
repoNamesByFile = make(map[*rule.File][]string)
repos, repoNamesByFile[workspace] = getRepos(workspace.Rules)
for _, d := range workspace.Directives {
switch d.Key {
case "repository_macro":
f, defName, err := parseRepositoryMacroDirective(d.Value)
if err != nil {
return nil, nil, err
}
f = filepath.Join(filepath.Dir(workspace.Path), filepath.Clean(f))
macroFile, err := rule.LoadMacroFile(f, "", defName)
if err != nil {
return nil, nil, err
}
currRepos, names := getRepos(macroFile.Rules)
repoNamesByFile[macroFile] = names
repos = append(repos, currRepos...)
}
}
return repos, repoNamesByFile, nil
}
|
go
|
func ListRepositories(workspace *rule.File) (repos []Repo, repoNamesByFile map[*rule.File][]string, err error) {
repoNamesByFile = make(map[*rule.File][]string)
repos, repoNamesByFile[workspace] = getRepos(workspace.Rules)
for _, d := range workspace.Directives {
switch d.Key {
case "repository_macro":
f, defName, err := parseRepositoryMacroDirective(d.Value)
if err != nil {
return nil, nil, err
}
f = filepath.Join(filepath.Dir(workspace.Path), filepath.Clean(f))
macroFile, err := rule.LoadMacroFile(f, "", defName)
if err != nil {
return nil, nil, err
}
currRepos, names := getRepos(macroFile.Rules)
repoNamesByFile[macroFile] = names
repos = append(repos, currRepos...)
}
}
return repos, repoNamesByFile, nil
}
|
[
"func",
"ListRepositories",
"(",
"workspace",
"*",
"rule",
".",
"File",
")",
"(",
"repos",
"[",
"]",
"Repo",
",",
"repoNamesByFile",
"map",
"[",
"*",
"rule",
".",
"File",
"]",
"[",
"]",
"string",
",",
"err",
"error",
")",
"{",
"repoNamesByFile",
"=",
"make",
"(",
"map",
"[",
"*",
"rule",
".",
"File",
"]",
"[",
"]",
"string",
")",
"\n",
"repos",
",",
"repoNamesByFile",
"[",
"workspace",
"]",
"=",
"getRepos",
"(",
"workspace",
".",
"Rules",
")",
"\n",
"for",
"_",
",",
"d",
":=",
"range",
"workspace",
".",
"Directives",
"{",
"switch",
"d",
".",
"Key",
"{",
"case",
"\"repository_macro\"",
":",
"f",
",",
"defName",
",",
"err",
":=",
"parseRepositoryMacroDirective",
"(",
"d",
".",
"Value",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"nil",
",",
"err",
"\n",
"}",
"\n",
"f",
"=",
"filepath",
".",
"Join",
"(",
"filepath",
".",
"Dir",
"(",
"workspace",
".",
"Path",
")",
",",
"filepath",
".",
"Clean",
"(",
"f",
")",
")",
"\n",
"macroFile",
",",
"err",
":=",
"rule",
".",
"LoadMacroFile",
"(",
"f",
",",
"\"\"",
",",
"defName",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"nil",
",",
"err",
"\n",
"}",
"\n",
"currRepos",
",",
"names",
":=",
"getRepos",
"(",
"macroFile",
".",
"Rules",
")",
"\n",
"repoNamesByFile",
"[",
"macroFile",
"]",
"=",
"names",
"\n",
"repos",
"=",
"append",
"(",
"repos",
",",
"currRepos",
"...",
")",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"repos",
",",
"repoNamesByFile",
",",
"nil",
"\n",
"}"
] |
// ListRepositories extracts metadata about repositories declared in a
// file.
|
[
"ListRepositories",
"extracts",
"metadata",
"about",
"repositories",
"declared",
"in",
"a",
"file",
"."
] |
e3805aaca69a9deb949b47bfc45b9b1870712f4f
|
https://github.com/bazelbuild/bazel-gazelle/blob/e3805aaca69a9deb949b47bfc45b9b1870712f4f/repo/repo.go#L228-L250
|
test
|
bazelbuild/bazel-gazelle
|
language/go/fix.go
|
migrateLibraryEmbed
|
func migrateLibraryEmbed(c *config.Config, f *rule.File) {
for _, r := range f.Rules {
if !isGoRule(r.Kind()) {
continue
}
libExpr := r.Attr("library")
if libExpr == nil || rule.ShouldKeep(libExpr) || r.Attr("embed") != nil {
continue
}
r.DelAttr("library")
r.SetAttr("embed", &bzl.ListExpr{List: []bzl.Expr{libExpr}})
}
}
|
go
|
func migrateLibraryEmbed(c *config.Config, f *rule.File) {
for _, r := range f.Rules {
if !isGoRule(r.Kind()) {
continue
}
libExpr := r.Attr("library")
if libExpr == nil || rule.ShouldKeep(libExpr) || r.Attr("embed") != nil {
continue
}
r.DelAttr("library")
r.SetAttr("embed", &bzl.ListExpr{List: []bzl.Expr{libExpr}})
}
}
|
[
"func",
"migrateLibraryEmbed",
"(",
"c",
"*",
"config",
".",
"Config",
",",
"f",
"*",
"rule",
".",
"File",
")",
"{",
"for",
"_",
",",
"r",
":=",
"range",
"f",
".",
"Rules",
"{",
"if",
"!",
"isGoRule",
"(",
"r",
".",
"Kind",
"(",
")",
")",
"{",
"continue",
"\n",
"}",
"\n",
"libExpr",
":=",
"r",
".",
"Attr",
"(",
"\"library\"",
")",
"\n",
"if",
"libExpr",
"==",
"nil",
"||",
"rule",
".",
"ShouldKeep",
"(",
"libExpr",
")",
"||",
"r",
".",
"Attr",
"(",
"\"embed\"",
")",
"!=",
"nil",
"{",
"continue",
"\n",
"}",
"\n",
"r",
".",
"DelAttr",
"(",
"\"library\"",
")",
"\n",
"r",
".",
"SetAttr",
"(",
"\"embed\"",
",",
"&",
"bzl",
".",
"ListExpr",
"{",
"List",
":",
"[",
"]",
"bzl",
".",
"Expr",
"{",
"libExpr",
"}",
"}",
")",
"\n",
"}",
"\n",
"}"
] |
// migrateLibraryEmbed converts "library" attributes to "embed" attributes,
// preserving comments. This only applies to Go rules, and only if there is
// no keep comment on "library" and no existing "embed" attribute.
|
[
"migrateLibraryEmbed",
"converts",
"library",
"attributes",
"to",
"embed",
"attributes",
"preserving",
"comments",
".",
"This",
"only",
"applies",
"to",
"Go",
"rules",
"and",
"only",
"if",
"there",
"is",
"no",
"keep",
"comment",
"on",
"library",
"and",
"no",
"existing",
"embed",
"attribute",
"."
] |
e3805aaca69a9deb949b47bfc45b9b1870712f4f
|
https://github.com/bazelbuild/bazel-gazelle/blob/e3805aaca69a9deb949b47bfc45b9b1870712f4f/language/go/fix.go#L40-L52
|
test
|
bazelbuild/bazel-gazelle
|
language/go/fix.go
|
migrateGrpcCompilers
|
func migrateGrpcCompilers(c *config.Config, f *rule.File) {
for _, r := range f.Rules {
if r.Kind() != "go_grpc_library" || r.ShouldKeep() || r.Attr("compilers") != nil {
continue
}
r.SetKind("go_proto_library")
r.SetAttr("compilers", []string{grpcCompilerLabel})
}
}
|
go
|
func migrateGrpcCompilers(c *config.Config, f *rule.File) {
for _, r := range f.Rules {
if r.Kind() != "go_grpc_library" || r.ShouldKeep() || r.Attr("compilers") != nil {
continue
}
r.SetKind("go_proto_library")
r.SetAttr("compilers", []string{grpcCompilerLabel})
}
}
|
[
"func",
"migrateGrpcCompilers",
"(",
"c",
"*",
"config",
".",
"Config",
",",
"f",
"*",
"rule",
".",
"File",
")",
"{",
"for",
"_",
",",
"r",
":=",
"range",
"f",
".",
"Rules",
"{",
"if",
"r",
".",
"Kind",
"(",
")",
"!=",
"\"go_grpc_library\"",
"||",
"r",
".",
"ShouldKeep",
"(",
")",
"||",
"r",
".",
"Attr",
"(",
"\"compilers\"",
")",
"!=",
"nil",
"{",
"continue",
"\n",
"}",
"\n",
"r",
".",
"SetKind",
"(",
"\"go_proto_library\"",
")",
"\n",
"r",
".",
"SetAttr",
"(",
"\"compilers\"",
",",
"[",
"]",
"string",
"{",
"grpcCompilerLabel",
"}",
")",
"\n",
"}",
"\n",
"}"
] |
// migrateGrpcCompilers converts "go_grpc_library" rules into "go_proto_library"
// rules with a "compilers" attribute.
|
[
"migrateGrpcCompilers",
"converts",
"go_grpc_library",
"rules",
"into",
"go_proto_library",
"rules",
"with",
"a",
"compilers",
"attribute",
"."
] |
e3805aaca69a9deb949b47bfc45b9b1870712f4f
|
https://github.com/bazelbuild/bazel-gazelle/blob/e3805aaca69a9deb949b47bfc45b9b1870712f4f/language/go/fix.go#L56-L64
|
test
|
bazelbuild/bazel-gazelle
|
language/go/fix.go
|
squashCgoLibrary
|
func squashCgoLibrary(c *config.Config, f *rule.File) {
// Find the default cgo_library and go_library rules.
var cgoLibrary, goLibrary *rule.Rule
for _, r := range f.Rules {
if r.Kind() == "cgo_library" && r.Name() == "cgo_default_library" && !r.ShouldKeep() {
if cgoLibrary != nil {
log.Printf("%s: when fixing existing file, multiple cgo_library rules with default name found", f.Path)
continue
}
cgoLibrary = r
continue
}
if r.Kind() == "go_library" && r.Name() == defaultLibName {
if goLibrary != nil {
log.Printf("%s: when fixing existing file, multiple go_library rules with default name referencing cgo_library found", f.Path)
}
goLibrary = r
continue
}
}
if cgoLibrary == nil {
return
}
if !c.ShouldFix {
log.Printf("%s: cgo_library is deprecated. Run 'gazelle fix' to squash with go_library.", f.Path)
return
}
if goLibrary == nil {
cgoLibrary.SetKind("go_library")
cgoLibrary.SetName(defaultLibName)
cgoLibrary.SetAttr("cgo", true)
return
}
if err := rule.SquashRules(cgoLibrary, goLibrary, f.Path); err != nil {
log.Print(err)
return
}
goLibrary.DelAttr("embed")
goLibrary.SetAttr("cgo", true)
cgoLibrary.Delete()
}
|
go
|
func squashCgoLibrary(c *config.Config, f *rule.File) {
// Find the default cgo_library and go_library rules.
var cgoLibrary, goLibrary *rule.Rule
for _, r := range f.Rules {
if r.Kind() == "cgo_library" && r.Name() == "cgo_default_library" && !r.ShouldKeep() {
if cgoLibrary != nil {
log.Printf("%s: when fixing existing file, multiple cgo_library rules with default name found", f.Path)
continue
}
cgoLibrary = r
continue
}
if r.Kind() == "go_library" && r.Name() == defaultLibName {
if goLibrary != nil {
log.Printf("%s: when fixing existing file, multiple go_library rules with default name referencing cgo_library found", f.Path)
}
goLibrary = r
continue
}
}
if cgoLibrary == nil {
return
}
if !c.ShouldFix {
log.Printf("%s: cgo_library is deprecated. Run 'gazelle fix' to squash with go_library.", f.Path)
return
}
if goLibrary == nil {
cgoLibrary.SetKind("go_library")
cgoLibrary.SetName(defaultLibName)
cgoLibrary.SetAttr("cgo", true)
return
}
if err := rule.SquashRules(cgoLibrary, goLibrary, f.Path); err != nil {
log.Print(err)
return
}
goLibrary.DelAttr("embed")
goLibrary.SetAttr("cgo", true)
cgoLibrary.Delete()
}
|
[
"func",
"squashCgoLibrary",
"(",
"c",
"*",
"config",
".",
"Config",
",",
"f",
"*",
"rule",
".",
"File",
")",
"{",
"var",
"cgoLibrary",
",",
"goLibrary",
"*",
"rule",
".",
"Rule",
"\n",
"for",
"_",
",",
"r",
":=",
"range",
"f",
".",
"Rules",
"{",
"if",
"r",
".",
"Kind",
"(",
")",
"==",
"\"cgo_library\"",
"&&",
"r",
".",
"Name",
"(",
")",
"==",
"\"cgo_default_library\"",
"&&",
"!",
"r",
".",
"ShouldKeep",
"(",
")",
"{",
"if",
"cgoLibrary",
"!=",
"nil",
"{",
"log",
".",
"Printf",
"(",
"\"%s: when fixing existing file, multiple cgo_library rules with default name found\"",
",",
"f",
".",
"Path",
")",
"\n",
"continue",
"\n",
"}",
"\n",
"cgoLibrary",
"=",
"r",
"\n",
"continue",
"\n",
"}",
"\n",
"if",
"r",
".",
"Kind",
"(",
")",
"==",
"\"go_library\"",
"&&",
"r",
".",
"Name",
"(",
")",
"==",
"defaultLibName",
"{",
"if",
"goLibrary",
"!=",
"nil",
"{",
"log",
".",
"Printf",
"(",
"\"%s: when fixing existing file, multiple go_library rules with default name referencing cgo_library found\"",
",",
"f",
".",
"Path",
")",
"\n",
"}",
"\n",
"goLibrary",
"=",
"r",
"\n",
"continue",
"\n",
"}",
"\n",
"}",
"\n",
"if",
"cgoLibrary",
"==",
"nil",
"{",
"return",
"\n",
"}",
"\n",
"if",
"!",
"c",
".",
"ShouldFix",
"{",
"log",
".",
"Printf",
"(",
"\"%s: cgo_library is deprecated. Run 'gazelle fix' to squash with go_library.\"",
",",
"f",
".",
"Path",
")",
"\n",
"return",
"\n",
"}",
"\n",
"if",
"goLibrary",
"==",
"nil",
"{",
"cgoLibrary",
".",
"SetKind",
"(",
"\"go_library\"",
")",
"\n",
"cgoLibrary",
".",
"SetName",
"(",
"defaultLibName",
")",
"\n",
"cgoLibrary",
".",
"SetAttr",
"(",
"\"cgo\"",
",",
"true",
")",
"\n",
"return",
"\n",
"}",
"\n",
"if",
"err",
":=",
"rule",
".",
"SquashRules",
"(",
"cgoLibrary",
",",
"goLibrary",
",",
"f",
".",
"Path",
")",
";",
"err",
"!=",
"nil",
"{",
"log",
".",
"Print",
"(",
"err",
")",
"\n",
"return",
"\n",
"}",
"\n",
"goLibrary",
".",
"DelAttr",
"(",
"\"embed\"",
")",
"\n",
"goLibrary",
".",
"SetAttr",
"(",
"\"cgo\"",
",",
"true",
")",
"\n",
"cgoLibrary",
".",
"Delete",
"(",
")",
"\n",
"}"
] |
// squashCgoLibrary removes cgo_library rules with the default name and
// merges their attributes with go_library with the default name. If no
// go_library rule exists, a new one will be created.
//
// Note that the library attribute is disregarded, so cgo_library and
// go_library attributes will be squashed even if the cgo_library was unlinked.
// MergeFile will remove unused values and attributes later.
|
[
"squashCgoLibrary",
"removes",
"cgo_library",
"rules",
"with",
"the",
"default",
"name",
"and",
"merges",
"their",
"attributes",
"with",
"go_library",
"with",
"the",
"default",
"name",
".",
"If",
"no",
"go_library",
"rule",
"exists",
"a",
"new",
"one",
"will",
"be",
"created",
".",
"Note",
"that",
"the",
"library",
"attribute",
"is",
"disregarded",
"so",
"cgo_library",
"and",
"go_library",
"attributes",
"will",
"be",
"squashed",
"even",
"if",
"the",
"cgo_library",
"was",
"unlinked",
".",
"MergeFile",
"will",
"remove",
"unused",
"values",
"and",
"attributes",
"later",
"."
] |
e3805aaca69a9deb949b47bfc45b9b1870712f4f
|
https://github.com/bazelbuild/bazel-gazelle/blob/e3805aaca69a9deb949b47bfc45b9b1870712f4f/language/go/fix.go#L73-L116
|
test
|
bazelbuild/bazel-gazelle
|
language/go/fix.go
|
removeLegacyProto
|
func removeLegacyProto(c *config.Config, f *rule.File) {
// Don't fix if the proto mode was set to something other than the default.
if pcMode := getProtoMode(c); pcMode != proto.DefaultMode {
return
}
// Scan for definitions to delete.
var protoLoads []*rule.Load
for _, l := range f.Loads {
if l.Name() == "@io_bazel_rules_go//proto:go_proto_library.bzl" {
protoLoads = append(protoLoads, l)
}
}
var protoFilegroups, protoRules []*rule.Rule
for _, r := range f.Rules {
if r.Kind() == "filegroup" && r.Name() == legacyProtoFilegroupName {
protoFilegroups = append(protoFilegroups, r)
}
if r.Kind() == "go_proto_library" {
protoRules = append(protoRules, r)
}
}
if len(protoLoads)+len(protoFilegroups) == 0 {
return
}
if !c.ShouldFix {
log.Printf("%s: go_proto_library.bzl is deprecated. Run 'gazelle fix' to replace old rules.", f.Path)
return
}
// Delete legacy proto loads and filegroups. Only delete go_proto_library
// rules if we deleted a load.
for _, l := range protoLoads {
l.Delete()
}
for _, r := range protoFilegroups {
r.Delete()
}
if len(protoLoads) > 0 {
for _, r := range protoRules {
r.Delete()
}
}
}
|
go
|
func removeLegacyProto(c *config.Config, f *rule.File) {
// Don't fix if the proto mode was set to something other than the default.
if pcMode := getProtoMode(c); pcMode != proto.DefaultMode {
return
}
// Scan for definitions to delete.
var protoLoads []*rule.Load
for _, l := range f.Loads {
if l.Name() == "@io_bazel_rules_go//proto:go_proto_library.bzl" {
protoLoads = append(protoLoads, l)
}
}
var protoFilegroups, protoRules []*rule.Rule
for _, r := range f.Rules {
if r.Kind() == "filegroup" && r.Name() == legacyProtoFilegroupName {
protoFilegroups = append(protoFilegroups, r)
}
if r.Kind() == "go_proto_library" {
protoRules = append(protoRules, r)
}
}
if len(protoLoads)+len(protoFilegroups) == 0 {
return
}
if !c.ShouldFix {
log.Printf("%s: go_proto_library.bzl is deprecated. Run 'gazelle fix' to replace old rules.", f.Path)
return
}
// Delete legacy proto loads and filegroups. Only delete go_proto_library
// rules if we deleted a load.
for _, l := range protoLoads {
l.Delete()
}
for _, r := range protoFilegroups {
r.Delete()
}
if len(protoLoads) > 0 {
for _, r := range protoRules {
r.Delete()
}
}
}
|
[
"func",
"removeLegacyProto",
"(",
"c",
"*",
"config",
".",
"Config",
",",
"f",
"*",
"rule",
".",
"File",
")",
"{",
"if",
"pcMode",
":=",
"getProtoMode",
"(",
"c",
")",
";",
"pcMode",
"!=",
"proto",
".",
"DefaultMode",
"{",
"return",
"\n",
"}",
"\n",
"var",
"protoLoads",
"[",
"]",
"*",
"rule",
".",
"Load",
"\n",
"for",
"_",
",",
"l",
":=",
"range",
"f",
".",
"Loads",
"{",
"if",
"l",
".",
"Name",
"(",
")",
"==",
"\"@io_bazel_rules_go//proto:go_proto_library.bzl\"",
"{",
"protoLoads",
"=",
"append",
"(",
"protoLoads",
",",
"l",
")",
"\n",
"}",
"\n",
"}",
"\n",
"var",
"protoFilegroups",
",",
"protoRules",
"[",
"]",
"*",
"rule",
".",
"Rule",
"\n",
"for",
"_",
",",
"r",
":=",
"range",
"f",
".",
"Rules",
"{",
"if",
"r",
".",
"Kind",
"(",
")",
"==",
"\"filegroup\"",
"&&",
"r",
".",
"Name",
"(",
")",
"==",
"legacyProtoFilegroupName",
"{",
"protoFilegroups",
"=",
"append",
"(",
"protoFilegroups",
",",
"r",
")",
"\n",
"}",
"\n",
"if",
"r",
".",
"Kind",
"(",
")",
"==",
"\"go_proto_library\"",
"{",
"protoRules",
"=",
"append",
"(",
"protoRules",
",",
"r",
")",
"\n",
"}",
"\n",
"}",
"\n",
"if",
"len",
"(",
"protoLoads",
")",
"+",
"len",
"(",
"protoFilegroups",
")",
"==",
"0",
"{",
"return",
"\n",
"}",
"\n",
"if",
"!",
"c",
".",
"ShouldFix",
"{",
"log",
".",
"Printf",
"(",
"\"%s: go_proto_library.bzl is deprecated. Run 'gazelle fix' to replace old rules.\"",
",",
"f",
".",
"Path",
")",
"\n",
"return",
"\n",
"}",
"\n",
"for",
"_",
",",
"l",
":=",
"range",
"protoLoads",
"{",
"l",
".",
"Delete",
"(",
")",
"\n",
"}",
"\n",
"for",
"_",
",",
"r",
":=",
"range",
"protoFilegroups",
"{",
"r",
".",
"Delete",
"(",
")",
"\n",
"}",
"\n",
"if",
"len",
"(",
"protoLoads",
")",
">",
"0",
"{",
"for",
"_",
",",
"r",
":=",
"range",
"protoRules",
"{",
"r",
".",
"Delete",
"(",
")",
"\n",
"}",
"\n",
"}",
"\n",
"}"
] |
// removeLegacyProto removes uses of the old proto rules. It deletes loads
// from go_proto_library.bzl. It deletes proto filegroups. It removes
// go_proto_library attributes which are no longer recognized. New rules
// are generated in place of the deleted rules, but attributes and comments
// are not migrated.
|
[
"removeLegacyProto",
"removes",
"uses",
"of",
"the",
"old",
"proto",
"rules",
".",
"It",
"deletes",
"loads",
"from",
"go_proto_library",
".",
"bzl",
".",
"It",
"deletes",
"proto",
"filegroups",
".",
"It",
"removes",
"go_proto_library",
"attributes",
"which",
"are",
"no",
"longer",
"recognized",
".",
"New",
"rules",
"are",
"generated",
"in",
"place",
"of",
"the",
"deleted",
"rules",
"but",
"attributes",
"and",
"comments",
"are",
"not",
"migrated",
"."
] |
e3805aaca69a9deb949b47bfc45b9b1870712f4f
|
https://github.com/bazelbuild/bazel-gazelle/blob/e3805aaca69a9deb949b47bfc45b9b1870712f4f/language/go/fix.go#L188-L231
|
test
|
bazelbuild/bazel-gazelle
|
language/go/fix.go
|
removeLegacyGazelle
|
func removeLegacyGazelle(c *config.Config, f *rule.File) {
for _, l := range f.Loads {
if l.Name() == "@io_bazel_rules_go//go:def.bzl" && l.Has("gazelle") {
l.Remove("gazelle")
if l.IsEmpty() {
l.Delete()
}
}
}
}
|
go
|
func removeLegacyGazelle(c *config.Config, f *rule.File) {
for _, l := range f.Loads {
if l.Name() == "@io_bazel_rules_go//go:def.bzl" && l.Has("gazelle") {
l.Remove("gazelle")
if l.IsEmpty() {
l.Delete()
}
}
}
}
|
[
"func",
"removeLegacyGazelle",
"(",
"c",
"*",
"config",
".",
"Config",
",",
"f",
"*",
"rule",
".",
"File",
")",
"{",
"for",
"_",
",",
"l",
":=",
"range",
"f",
".",
"Loads",
"{",
"if",
"l",
".",
"Name",
"(",
")",
"==",
"\"@io_bazel_rules_go//go:def.bzl\"",
"&&",
"l",
".",
"Has",
"(",
"\"gazelle\"",
")",
"{",
"l",
".",
"Remove",
"(",
"\"gazelle\"",
")",
"\n",
"if",
"l",
".",
"IsEmpty",
"(",
")",
"{",
"l",
".",
"Delete",
"(",
")",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n",
"}"
] |
// removeLegacyGazelle removes loads of the "gazelle" macro from
// @io_bazel_rules_go//go:def.bzl. The definition has moved to
// @bazel_gazelle//:def.bzl, and the old one will be deleted soon.
|
[
"removeLegacyGazelle",
"removes",
"loads",
"of",
"the",
"gazelle",
"macro",
"from"
] |
e3805aaca69a9deb949b47bfc45b9b1870712f4f
|
https://github.com/bazelbuild/bazel-gazelle/blob/e3805aaca69a9deb949b47bfc45b9b1870712f4f/language/go/fix.go#L236-L245
|
test
|
bazelbuild/bazel-gazelle
|
language/go/generate.go
|
selectPackage
|
func selectPackage(c *config.Config, dir string, packageMap map[string]*goPackage) (*goPackage, error) {
buildablePackages := make(map[string]*goPackage)
for name, pkg := range packageMap {
if pkg.isBuildable(c) {
buildablePackages[name] = pkg
}
}
if len(buildablePackages) == 0 {
return nil, &build.NoGoError{Dir: dir}
}
if len(buildablePackages) == 1 {
for _, pkg := range buildablePackages {
return pkg, nil
}
}
if pkg, ok := buildablePackages[defaultPackageName(c, dir)]; ok {
return pkg, nil
}
err := &build.MultiplePackageError{Dir: dir}
for name, pkg := range buildablePackages {
// Add the first file for each package for the error message.
// Error() method expects these lists to be the same length. File
// lists must be non-empty. These lists are only created by
// buildPackage for packages with .go files present.
err.Packages = append(err.Packages, name)
err.Files = append(err.Files, pkg.firstGoFile())
}
return nil, err
}
|
go
|
func selectPackage(c *config.Config, dir string, packageMap map[string]*goPackage) (*goPackage, error) {
buildablePackages := make(map[string]*goPackage)
for name, pkg := range packageMap {
if pkg.isBuildable(c) {
buildablePackages[name] = pkg
}
}
if len(buildablePackages) == 0 {
return nil, &build.NoGoError{Dir: dir}
}
if len(buildablePackages) == 1 {
for _, pkg := range buildablePackages {
return pkg, nil
}
}
if pkg, ok := buildablePackages[defaultPackageName(c, dir)]; ok {
return pkg, nil
}
err := &build.MultiplePackageError{Dir: dir}
for name, pkg := range buildablePackages {
// Add the first file for each package for the error message.
// Error() method expects these lists to be the same length. File
// lists must be non-empty. These lists are only created by
// buildPackage for packages with .go files present.
err.Packages = append(err.Packages, name)
err.Files = append(err.Files, pkg.firstGoFile())
}
return nil, err
}
|
[
"func",
"selectPackage",
"(",
"c",
"*",
"config",
".",
"Config",
",",
"dir",
"string",
",",
"packageMap",
"map",
"[",
"string",
"]",
"*",
"goPackage",
")",
"(",
"*",
"goPackage",
",",
"error",
")",
"{",
"buildablePackages",
":=",
"make",
"(",
"map",
"[",
"string",
"]",
"*",
"goPackage",
")",
"\n",
"for",
"name",
",",
"pkg",
":=",
"range",
"packageMap",
"{",
"if",
"pkg",
".",
"isBuildable",
"(",
"c",
")",
"{",
"buildablePackages",
"[",
"name",
"]",
"=",
"pkg",
"\n",
"}",
"\n",
"}",
"\n",
"if",
"len",
"(",
"buildablePackages",
")",
"==",
"0",
"{",
"return",
"nil",
",",
"&",
"build",
".",
"NoGoError",
"{",
"Dir",
":",
"dir",
"}",
"\n",
"}",
"\n",
"if",
"len",
"(",
"buildablePackages",
")",
"==",
"1",
"{",
"for",
"_",
",",
"pkg",
":=",
"range",
"buildablePackages",
"{",
"return",
"pkg",
",",
"nil",
"\n",
"}",
"\n",
"}",
"\n",
"if",
"pkg",
",",
"ok",
":=",
"buildablePackages",
"[",
"defaultPackageName",
"(",
"c",
",",
"dir",
")",
"]",
";",
"ok",
"{",
"return",
"pkg",
",",
"nil",
"\n",
"}",
"\n",
"err",
":=",
"&",
"build",
".",
"MultiplePackageError",
"{",
"Dir",
":",
"dir",
"}",
"\n",
"for",
"name",
",",
"pkg",
":=",
"range",
"buildablePackages",
"{",
"err",
".",
"Packages",
"=",
"append",
"(",
"err",
".",
"Packages",
",",
"name",
")",
"\n",
"err",
".",
"Files",
"=",
"append",
"(",
"err",
".",
"Files",
",",
"pkg",
".",
"firstGoFile",
"(",
")",
")",
"\n",
"}",
"\n",
"return",
"nil",
",",
"err",
"\n",
"}"
] |
// selectPackages selects one Go packages out of the buildable packages found
// in a directory. If multiple packages are found, it returns the package
// whose name matches the directory if such a package exists.
|
[
"selectPackages",
"selects",
"one",
"Go",
"packages",
"out",
"of",
"the",
"buildable",
"packages",
"found",
"in",
"a",
"directory",
".",
"If",
"multiple",
"packages",
"are",
"found",
"it",
"returns",
"the",
"package",
"whose",
"name",
"matches",
"the",
"directory",
"if",
"such",
"a",
"package",
"exists",
"."
] |
e3805aaca69a9deb949b47bfc45b9b1870712f4f
|
https://github.com/bazelbuild/bazel-gazelle/blob/e3805aaca69a9deb949b47bfc45b9b1870712f4f/language/go/generate.go#L299-L331
|
test
|
bazelbuild/bazel-gazelle
|
cmd/gazelle/metaresolver.go
|
AddBuiltin
|
func (mr *metaResolver) AddBuiltin(kindName string, resolver resolve.Resolver) {
mr.builtins[kindName] = resolver
}
|
go
|
func (mr *metaResolver) AddBuiltin(kindName string, resolver resolve.Resolver) {
mr.builtins[kindName] = resolver
}
|
[
"func",
"(",
"mr",
"*",
"metaResolver",
")",
"AddBuiltin",
"(",
"kindName",
"string",
",",
"resolver",
"resolve",
".",
"Resolver",
")",
"{",
"mr",
".",
"builtins",
"[",
"kindName",
"]",
"=",
"resolver",
"\n",
"}"
] |
// AddBuiltin registers a builtin kind with its info.
|
[
"AddBuiltin",
"registers",
"a",
"builtin",
"kind",
"with",
"its",
"info",
"."
] |
e3805aaca69a9deb949b47bfc45b9b1870712f4f
|
https://github.com/bazelbuild/bazel-gazelle/blob/e3805aaca69a9deb949b47bfc45b9b1870712f4f/cmd/gazelle/metaresolver.go#L41-L43
|
test
|
bazelbuild/bazel-gazelle
|
cmd/gazelle/metaresolver.go
|
MappedKind
|
func (mr *metaResolver) MappedKind(pkgRel string, kind config.MappedKind) {
mr.mappedKinds[pkgRel] = append(mr.mappedKinds[pkgRel], kind)
}
|
go
|
func (mr *metaResolver) MappedKind(pkgRel string, kind config.MappedKind) {
mr.mappedKinds[pkgRel] = append(mr.mappedKinds[pkgRel], kind)
}
|
[
"func",
"(",
"mr",
"*",
"metaResolver",
")",
"MappedKind",
"(",
"pkgRel",
"string",
",",
"kind",
"config",
".",
"MappedKind",
")",
"{",
"mr",
".",
"mappedKinds",
"[",
"pkgRel",
"]",
"=",
"append",
"(",
"mr",
".",
"mappedKinds",
"[",
"pkgRel",
"]",
",",
"kind",
")",
"\n",
"}"
] |
// MappedKind records the fact that the given mapping was applied while
// processing the given package.
|
[
"MappedKind",
"records",
"the",
"fact",
"that",
"the",
"given",
"mapping",
"was",
"applied",
"while",
"processing",
"the",
"given",
"package",
"."
] |
e3805aaca69a9deb949b47bfc45b9b1870712f4f
|
https://github.com/bazelbuild/bazel-gazelle/blob/e3805aaca69a9deb949b47bfc45b9b1870712f4f/cmd/gazelle/metaresolver.go#L47-L49
|
test
|
bazelbuild/bazel-gazelle
|
cmd/gazelle/metaresolver.go
|
Resolver
|
func (mr metaResolver) Resolver(r *rule.Rule, pkgRel string) resolve.Resolver {
for _, mappedKind := range mr.mappedKinds[pkgRel] {
if mappedKind.KindName == r.Kind() {
return mr.builtins[mappedKind.FromKind]
}
}
return mr.builtins[r.Kind()]
}
|
go
|
func (mr metaResolver) Resolver(r *rule.Rule, pkgRel string) resolve.Resolver {
for _, mappedKind := range mr.mappedKinds[pkgRel] {
if mappedKind.KindName == r.Kind() {
return mr.builtins[mappedKind.FromKind]
}
}
return mr.builtins[r.Kind()]
}
|
[
"func",
"(",
"mr",
"metaResolver",
")",
"Resolver",
"(",
"r",
"*",
"rule",
".",
"Rule",
",",
"pkgRel",
"string",
")",
"resolve",
".",
"Resolver",
"{",
"for",
"_",
",",
"mappedKind",
":=",
"range",
"mr",
".",
"mappedKinds",
"[",
"pkgRel",
"]",
"{",
"if",
"mappedKind",
".",
"KindName",
"==",
"r",
".",
"Kind",
"(",
")",
"{",
"return",
"mr",
".",
"builtins",
"[",
"mappedKind",
".",
"FromKind",
"]",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"mr",
".",
"builtins",
"[",
"r",
".",
"Kind",
"(",
")",
"]",
"\n",
"}"
] |
// Resolver returns a resolver for the given rule and package, and a bool
// indicating whether one was found. Empty string may be passed for pkgRel,
// which results in consulting the builtin kinds only.
|
[
"Resolver",
"returns",
"a",
"resolver",
"for",
"the",
"given",
"rule",
"and",
"package",
"and",
"a",
"bool",
"indicating",
"whether",
"one",
"was",
"found",
".",
"Empty",
"string",
"may",
"be",
"passed",
"for",
"pkgRel",
"which",
"results",
"in",
"consulting",
"the",
"builtin",
"kinds",
"only",
"."
] |
e3805aaca69a9deb949b47bfc45b9b1870712f4f
|
https://github.com/bazelbuild/bazel-gazelle/blob/e3805aaca69a9deb949b47bfc45b9b1870712f4f/cmd/gazelle/metaresolver.go#L54-L61
|
test
|
bazelbuild/bazel-gazelle
|
rule/sort_labels.go
|
sortExprLabels
|
func sortExprLabels(e bzl.Expr, _ []bzl.Expr) {
list, ok := e.(*bzl.ListExpr)
if !ok || len(list.List) == 0 {
return
}
keys := make([]stringSortKey, len(list.List))
for i, elem := range list.List {
s, ok := elem.(*bzl.StringExpr)
if !ok {
return // don't sort lists unless all elements are strings
}
keys[i] = makeSortKey(i, s)
}
before := keys[0].x.Comment().Before
keys[0].x.Comment().Before = nil
sort.Sort(byStringExpr(keys))
keys[0].x.Comment().Before = append(before, keys[0].x.Comment().Before...)
for i, k := range keys {
list.List[i] = k.x
}
}
|
go
|
func sortExprLabels(e bzl.Expr, _ []bzl.Expr) {
list, ok := e.(*bzl.ListExpr)
if !ok || len(list.List) == 0 {
return
}
keys := make([]stringSortKey, len(list.List))
for i, elem := range list.List {
s, ok := elem.(*bzl.StringExpr)
if !ok {
return // don't sort lists unless all elements are strings
}
keys[i] = makeSortKey(i, s)
}
before := keys[0].x.Comment().Before
keys[0].x.Comment().Before = nil
sort.Sort(byStringExpr(keys))
keys[0].x.Comment().Before = append(before, keys[0].x.Comment().Before...)
for i, k := range keys {
list.List[i] = k.x
}
}
|
[
"func",
"sortExprLabels",
"(",
"e",
"bzl",
".",
"Expr",
",",
"_",
"[",
"]",
"bzl",
".",
"Expr",
")",
"{",
"list",
",",
"ok",
":=",
"e",
".",
"(",
"*",
"bzl",
".",
"ListExpr",
")",
"\n",
"if",
"!",
"ok",
"||",
"len",
"(",
"list",
".",
"List",
")",
"==",
"0",
"{",
"return",
"\n",
"}",
"\n",
"keys",
":=",
"make",
"(",
"[",
"]",
"stringSortKey",
",",
"len",
"(",
"list",
".",
"List",
")",
")",
"\n",
"for",
"i",
",",
"elem",
":=",
"range",
"list",
".",
"List",
"{",
"s",
",",
"ok",
":=",
"elem",
".",
"(",
"*",
"bzl",
".",
"StringExpr",
")",
"\n",
"if",
"!",
"ok",
"{",
"return",
"\n",
"}",
"\n",
"keys",
"[",
"i",
"]",
"=",
"makeSortKey",
"(",
"i",
",",
"s",
")",
"\n",
"}",
"\n",
"before",
":=",
"keys",
"[",
"0",
"]",
".",
"x",
".",
"Comment",
"(",
")",
".",
"Before",
"\n",
"keys",
"[",
"0",
"]",
".",
"x",
".",
"Comment",
"(",
")",
".",
"Before",
"=",
"nil",
"\n",
"sort",
".",
"Sort",
"(",
"byStringExpr",
"(",
"keys",
")",
")",
"\n",
"keys",
"[",
"0",
"]",
".",
"x",
".",
"Comment",
"(",
")",
".",
"Before",
"=",
"append",
"(",
"before",
",",
"keys",
"[",
"0",
"]",
".",
"x",
".",
"Comment",
"(",
")",
".",
"Before",
"...",
")",
"\n",
"for",
"i",
",",
"k",
":=",
"range",
"keys",
"{",
"list",
".",
"List",
"[",
"i",
"]",
"=",
"k",
".",
"x",
"\n",
"}",
"\n",
"}"
] |
// sortExprLabels sorts lists of strings using the same order as buildifier.
// Buildifier also sorts string lists, but not those involved with "select"
// expressions. This function is intended to be used with bzl.Walk.
|
[
"sortExprLabels",
"sorts",
"lists",
"of",
"strings",
"using",
"the",
"same",
"order",
"as",
"buildifier",
".",
"Buildifier",
"also",
"sorts",
"string",
"lists",
"but",
"not",
"those",
"involved",
"with",
"select",
"expressions",
".",
"This",
"function",
"is",
"intended",
"to",
"be",
"used",
"with",
"bzl",
".",
"Walk",
"."
] |
e3805aaca69a9deb949b47bfc45b9b1870712f4f
|
https://github.com/bazelbuild/bazel-gazelle/blob/e3805aaca69a9deb949b47bfc45b9b1870712f4f/rule/sort_labels.go#L28-L50
|
test
|
bazelbuild/bazel-gazelle
|
cmd/gazelle/version.go
|
checkRulesGoVersion
|
func checkRulesGoVersion(repoRoot string) {
const message = `Gazelle may not be compatible with this version of rules_go.
Update io_bazel_rules_go to a newer version in your WORKSPACE file.`
rulesGoPath, err := repo.FindExternalRepo(repoRoot, config.RulesGoRepoName)
if err != nil {
return
}
defBzlPath := filepath.Join(rulesGoPath, "go", "def.bzl")
defBzlContent, err := ioutil.ReadFile(defBzlPath)
if err != nil {
return
}
versionRe := regexp.MustCompile(`(?m)^RULES_GO_VERSION = ['"]([0-9.]*)['"]`)
match := versionRe.FindSubmatch(defBzlContent)
if match == nil {
log.Printf("RULES_GO_VERSION not found in @%s//go:def.bzl.\n%s", config.RulesGoRepoName, message)
return
}
vstr := string(match[1])
v, err := version.ParseVersion(vstr)
if err != nil {
log.Printf("RULES_GO_VERSION %q could not be parsed in @%s//go:def.bzl.\n%s", vstr, config.RulesGoRepoName, message)
}
if v.Compare(minimumRulesGoVersion) < 0 {
log.Printf("Found RULES_GO_VERSION %s. Minimum compatible version is %s.\n%s", v, minimumRulesGoVersion, message)
}
}
|
go
|
func checkRulesGoVersion(repoRoot string) {
const message = `Gazelle may not be compatible with this version of rules_go.
Update io_bazel_rules_go to a newer version in your WORKSPACE file.`
rulesGoPath, err := repo.FindExternalRepo(repoRoot, config.RulesGoRepoName)
if err != nil {
return
}
defBzlPath := filepath.Join(rulesGoPath, "go", "def.bzl")
defBzlContent, err := ioutil.ReadFile(defBzlPath)
if err != nil {
return
}
versionRe := regexp.MustCompile(`(?m)^RULES_GO_VERSION = ['"]([0-9.]*)['"]`)
match := versionRe.FindSubmatch(defBzlContent)
if match == nil {
log.Printf("RULES_GO_VERSION not found in @%s//go:def.bzl.\n%s", config.RulesGoRepoName, message)
return
}
vstr := string(match[1])
v, err := version.ParseVersion(vstr)
if err != nil {
log.Printf("RULES_GO_VERSION %q could not be parsed in @%s//go:def.bzl.\n%s", vstr, config.RulesGoRepoName, message)
}
if v.Compare(minimumRulesGoVersion) < 0 {
log.Printf("Found RULES_GO_VERSION %s. Minimum compatible version is %s.\n%s", v, minimumRulesGoVersion, message)
}
}
|
[
"func",
"checkRulesGoVersion",
"(",
"repoRoot",
"string",
")",
"{",
"const",
"message",
"=",
"`Gazelle may not be compatible with this version of rules_go.Update io_bazel_rules_go to a newer version in your WORKSPACE file.`",
"\n",
"rulesGoPath",
",",
"err",
":=",
"repo",
".",
"FindExternalRepo",
"(",
"repoRoot",
",",
"config",
".",
"RulesGoRepoName",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\n",
"}",
"\n",
"defBzlPath",
":=",
"filepath",
".",
"Join",
"(",
"rulesGoPath",
",",
"\"go\"",
",",
"\"def.bzl\"",
")",
"\n",
"defBzlContent",
",",
"err",
":=",
"ioutil",
".",
"ReadFile",
"(",
"defBzlPath",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\n",
"}",
"\n",
"versionRe",
":=",
"regexp",
".",
"MustCompile",
"(",
"`(?m)^RULES_GO_VERSION = ['\"]([0-9.]*)['\"]`",
")",
"\n",
"match",
":=",
"versionRe",
".",
"FindSubmatch",
"(",
"defBzlContent",
")",
"\n",
"if",
"match",
"==",
"nil",
"{",
"log",
".",
"Printf",
"(",
"\"RULES_GO_VERSION not found in @%s//go:def.bzl.\\n%s\"",
",",
"\\n",
",",
"config",
".",
"RulesGoRepoName",
")",
"\n",
"message",
"\n",
"}",
"\n",
"return",
"\n",
"vstr",
":=",
"string",
"(",
"match",
"[",
"1",
"]",
")",
"\n",
"v",
",",
"err",
":=",
"version",
".",
"ParseVersion",
"(",
"vstr",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"log",
".",
"Printf",
"(",
"\"RULES_GO_VERSION %q could not be parsed in @%s//go:def.bzl.\\n%s\"",
",",
"\\n",
",",
"vstr",
",",
"config",
".",
"RulesGoRepoName",
")",
"\n",
"}",
"\n",
"}"
] |
// checkRulesGoVersion checks whether a compatible version of rules_go is
// being used in the workspace. A message will be logged if an incompatible
// version is found.
//
// Note that we can't always determine the version of rules_go in use. Also,
// if we find an incompatible version, we shouldn't bail out since the
// incompatibility may not matter in the current workspace.
|
[
"checkRulesGoVersion",
"checks",
"whether",
"a",
"compatible",
"version",
"of",
"rules_go",
"is",
"being",
"used",
"in",
"the",
"workspace",
".",
"A",
"message",
"will",
"be",
"logged",
"if",
"an",
"incompatible",
"version",
"is",
"found",
".",
"Note",
"that",
"we",
"can",
"t",
"always",
"determine",
"the",
"version",
"of",
"rules_go",
"in",
"use",
".",
"Also",
"if",
"we",
"find",
"an",
"incompatible",
"version",
"we",
"shouldn",
"t",
"bail",
"out",
"since",
"the",
"incompatibility",
"may",
"not",
"matter",
"in",
"the",
"current",
"workspace",
"."
] |
e3805aaca69a9deb949b47bfc45b9b1870712f4f
|
https://github.com/bazelbuild/bazel-gazelle/blob/e3805aaca69a9deb949b47bfc45b9b1870712f4f/cmd/gazelle/version.go#L38-L65
|
test
|
bazelbuild/bazel-gazelle
|
language/go/config.go
|
preprocessTags
|
func (gc *goConfig) preprocessTags() {
if gc.genericTags == nil {
gc.genericTags = make(map[string]bool)
}
gc.genericTags["gc"] = true
}
|
go
|
func (gc *goConfig) preprocessTags() {
if gc.genericTags == nil {
gc.genericTags = make(map[string]bool)
}
gc.genericTags["gc"] = true
}
|
[
"func",
"(",
"gc",
"*",
"goConfig",
")",
"preprocessTags",
"(",
")",
"{",
"if",
"gc",
".",
"genericTags",
"==",
"nil",
"{",
"gc",
".",
"genericTags",
"=",
"make",
"(",
"map",
"[",
"string",
"]",
"bool",
")",
"\n",
"}",
"\n",
"gc",
".",
"genericTags",
"[",
"\"gc\"",
"]",
"=",
"true",
"\n",
"}"
] |
// preprocessTags adds some tags which are on by default before they are
// used to match files.
|
[
"preprocessTags",
"adds",
"some",
"tags",
"which",
"are",
"on",
"by",
"default",
"before",
"they",
"are",
"used",
"to",
"match",
"files",
"."
] |
e3805aaca69a9deb949b47bfc45b9b1870712f4f
|
https://github.com/bazelbuild/bazel-gazelle/blob/e3805aaca69a9deb949b47bfc45b9b1870712f4f/language/go/config.go#L111-L116
|
test
|
bazelbuild/bazel-gazelle
|
language/go/config.go
|
setBuildTags
|
func (gc *goConfig) setBuildTags(tags string) error {
if tags == "" {
return nil
}
for _, t := range strings.Split(tags, ",") {
if strings.HasPrefix(t, "!") {
return fmt.Errorf("build tags can't be negated: %s", t)
}
gc.genericTags[t] = true
}
return nil
}
|
go
|
func (gc *goConfig) setBuildTags(tags string) error {
if tags == "" {
return nil
}
for _, t := range strings.Split(tags, ",") {
if strings.HasPrefix(t, "!") {
return fmt.Errorf("build tags can't be negated: %s", t)
}
gc.genericTags[t] = true
}
return nil
}
|
[
"func",
"(",
"gc",
"*",
"goConfig",
")",
"setBuildTags",
"(",
"tags",
"string",
")",
"error",
"{",
"if",
"tags",
"==",
"\"\"",
"{",
"return",
"nil",
"\n",
"}",
"\n",
"for",
"_",
",",
"t",
":=",
"range",
"strings",
".",
"Split",
"(",
"tags",
",",
"\",\"",
")",
"{",
"if",
"strings",
".",
"HasPrefix",
"(",
"t",
",",
"\"!\"",
")",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"build tags can't be negated: %s\"",
",",
"t",
")",
"\n",
"}",
"\n",
"gc",
".",
"genericTags",
"[",
"t",
"]",
"=",
"true",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] |
// setBuildTags sets genericTags by parsing as a comma separated list. An
// error will be returned for tags that wouldn't be recognized by "go build".
// preprocessTags should be called before this.
|
[
"setBuildTags",
"sets",
"genericTags",
"by",
"parsing",
"as",
"a",
"comma",
"separated",
"list",
".",
"An",
"error",
"will",
"be",
"returned",
"for",
"tags",
"that",
"wouldn",
"t",
"be",
"recognized",
"by",
"go",
"build",
".",
"preprocessTags",
"should",
"be",
"called",
"before",
"this",
"."
] |
e3805aaca69a9deb949b47bfc45b9b1870712f4f
|
https://github.com/bazelbuild/bazel-gazelle/blob/e3805aaca69a9deb949b47bfc45b9b1870712f4f/language/go/config.go#L121-L132
|
test
|
bazelbuild/bazel-gazelle
|
language/go/config.go
|
splitValue
|
func splitValue(value string) []string {
parts := strings.Split(value, ",")
values := make([]string, 0, len(parts))
for _, part := range parts {
values = append(values, strings.TrimSpace(part))
}
return values
}
|
go
|
func splitValue(value string) []string {
parts := strings.Split(value, ",")
values := make([]string, 0, len(parts))
for _, part := range parts {
values = append(values, strings.TrimSpace(part))
}
return values
}
|
[
"func",
"splitValue",
"(",
"value",
"string",
")",
"[",
"]",
"string",
"{",
"parts",
":=",
"strings",
".",
"Split",
"(",
"value",
",",
"\",\"",
")",
"\n",
"values",
":=",
"make",
"(",
"[",
"]",
"string",
",",
"0",
",",
"len",
"(",
"parts",
")",
")",
"\n",
"for",
"_",
",",
"part",
":=",
"range",
"parts",
"{",
"values",
"=",
"append",
"(",
"values",
",",
"strings",
".",
"TrimSpace",
"(",
"part",
")",
")",
"\n",
"}",
"\n",
"return",
"values",
"\n",
"}"
] |
// splitDirective splits a comma-separated directive value into its component
// parts, trimming each of any whitespace characters.
|
[
"splitDirective",
"splits",
"a",
"comma",
"-",
"separated",
"directive",
"value",
"into",
"its",
"component",
"parts",
"trimming",
"each",
"of",
"any",
"whitespace",
"characters",
"."
] |
e3805aaca69a9deb949b47bfc45b9b1870712f4f
|
https://github.com/bazelbuild/bazel-gazelle/blob/e3805aaca69a9deb949b47bfc45b9b1870712f4f/language/go/config.go#L360-L367
|
test
|
bazelbuild/bazel-gazelle
|
repo/modules.go
|
copyGoModToTemp
|
func copyGoModToTemp(filename string) (tempDir string, err error) {
goModOrig, err := os.Open(filename)
if err != nil {
return "", err
}
defer goModOrig.Close()
tempDir, err = ioutil.TempDir("", "gazelle-temp-gomod")
if err != nil {
return "", err
}
goModCopy, err := os.Create(filepath.Join(tempDir, "go.mod"))
if err != nil {
os.Remove(tempDir)
return "", err
}
defer func() {
if cerr := goModCopy.Close(); err == nil && cerr != nil {
err = cerr
}
}()
_, err = io.Copy(goModCopy, goModOrig)
if err != nil {
os.RemoveAll(tempDir)
return "", err
}
return tempDir, err
}
|
go
|
func copyGoModToTemp(filename string) (tempDir string, err error) {
goModOrig, err := os.Open(filename)
if err != nil {
return "", err
}
defer goModOrig.Close()
tempDir, err = ioutil.TempDir("", "gazelle-temp-gomod")
if err != nil {
return "", err
}
goModCopy, err := os.Create(filepath.Join(tempDir, "go.mod"))
if err != nil {
os.Remove(tempDir)
return "", err
}
defer func() {
if cerr := goModCopy.Close(); err == nil && cerr != nil {
err = cerr
}
}()
_, err = io.Copy(goModCopy, goModOrig)
if err != nil {
os.RemoveAll(tempDir)
return "", err
}
return tempDir, err
}
|
[
"func",
"copyGoModToTemp",
"(",
"filename",
"string",
")",
"(",
"tempDir",
"string",
",",
"err",
"error",
")",
"{",
"goModOrig",
",",
"err",
":=",
"os",
".",
"Open",
"(",
"filename",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\"\"",
",",
"err",
"\n",
"}",
"\n",
"defer",
"goModOrig",
".",
"Close",
"(",
")",
"\n",
"tempDir",
",",
"err",
"=",
"ioutil",
".",
"TempDir",
"(",
"\"\"",
",",
"\"gazelle-temp-gomod\"",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\"\"",
",",
"err",
"\n",
"}",
"\n",
"goModCopy",
",",
"err",
":=",
"os",
".",
"Create",
"(",
"filepath",
".",
"Join",
"(",
"tempDir",
",",
"\"go.mod\"",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"os",
".",
"Remove",
"(",
"tempDir",
")",
"\n",
"return",
"\"\"",
",",
"err",
"\n",
"}",
"\n",
"defer",
"func",
"(",
")",
"{",
"if",
"cerr",
":=",
"goModCopy",
".",
"Close",
"(",
")",
";",
"err",
"==",
"nil",
"&&",
"cerr",
"!=",
"nil",
"{",
"err",
"=",
"cerr",
"\n",
"}",
"\n",
"}",
"(",
")",
"\n",
"_",
",",
"err",
"=",
"io",
".",
"Copy",
"(",
"goModCopy",
",",
"goModOrig",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"os",
".",
"RemoveAll",
"(",
"tempDir",
")",
"\n",
"return",
"\"\"",
",",
"err",
"\n",
"}",
"\n",
"return",
"tempDir",
",",
"err",
"\n",
"}"
] |
// copyGoModToTemp copies to given go.mod file to a temporary directory.
// go list tends to mutate go.mod files, but gazelle shouldn't do that.
|
[
"copyGoModToTemp",
"copies",
"to",
"given",
"go",
".",
"mod",
"file",
"to",
"a",
"temporary",
"directory",
".",
"go",
"list",
"tends",
"to",
"mutate",
"go",
".",
"mod",
"files",
"but",
"gazelle",
"shouldn",
"t",
"do",
"that",
"."
] |
e3805aaca69a9deb949b47bfc45b9b1870712f4f
|
https://github.com/bazelbuild/bazel-gazelle/blob/e3805aaca69a9deb949b47bfc45b9b1870712f4f/repo/modules.go#L174-L203
|
test
|
bazelbuild/bazel-gazelle
|
repo/modules.go
|
findGoTool
|
func findGoTool() string {
path := "go" // rely on PATH by default
if goroot, ok := os.LookupEnv("GOROOT"); ok {
path = filepath.Join(goroot, "bin", "go")
}
if runtime.GOOS == "windows" {
path += ".exe"
}
return path
}
|
go
|
func findGoTool() string {
path := "go" // rely on PATH by default
if goroot, ok := os.LookupEnv("GOROOT"); ok {
path = filepath.Join(goroot, "bin", "go")
}
if runtime.GOOS == "windows" {
path += ".exe"
}
return path
}
|
[
"func",
"findGoTool",
"(",
")",
"string",
"{",
"path",
":=",
"\"go\"",
"\n",
"if",
"goroot",
",",
"ok",
":=",
"os",
".",
"LookupEnv",
"(",
"\"GOROOT\"",
")",
";",
"ok",
"{",
"path",
"=",
"filepath",
".",
"Join",
"(",
"goroot",
",",
"\"bin\"",
",",
"\"go\"",
")",
"\n",
"}",
"\n",
"if",
"runtime",
".",
"GOOS",
"==",
"\"windows\"",
"{",
"path",
"+=",
"\".exe\"",
"\n",
"}",
"\n",
"return",
"path",
"\n",
"}"
] |
// findGoTool attempts to locate the go executable. If GOROOT is set, we'll
// prefer the one in there; otherwise, we'll rely on PATH. If the wrapper
// script generated by the gazelle rule is invoked by Bazel, it will set
// GOROOT to the configured SDK. We don't want to rely on the host SDK in
// that situation.
|
[
"findGoTool",
"attempts",
"to",
"locate",
"the",
"go",
"executable",
".",
"If",
"GOROOT",
"is",
"set",
"we",
"ll",
"prefer",
"the",
"one",
"in",
"there",
";",
"otherwise",
"we",
"ll",
"rely",
"on",
"PATH",
".",
"If",
"the",
"wrapper",
"script",
"generated",
"by",
"the",
"gazelle",
"rule",
"is",
"invoked",
"by",
"Bazel",
"it",
"will",
"set",
"GOROOT",
"to",
"the",
"configured",
"SDK",
".",
"We",
"don",
"t",
"want",
"to",
"rely",
"on",
"the",
"host",
"SDK",
"in",
"that",
"situation",
"."
] |
e3805aaca69a9deb949b47bfc45b9b1870712f4f
|
https://github.com/bazelbuild/bazel-gazelle/blob/e3805aaca69a9deb949b47bfc45b9b1870712f4f/repo/modules.go#L210-L219
|
test
|
bazelbuild/bazel-gazelle
|
language/go/package.go
|
isBuildable
|
func (pkg *goPackage) isBuildable(c *config.Config) bool {
return pkg.firstGoFile() != "" || !pkg.proto.sources.isEmpty()
}
|
go
|
func (pkg *goPackage) isBuildable(c *config.Config) bool {
return pkg.firstGoFile() != "" || !pkg.proto.sources.isEmpty()
}
|
[
"func",
"(",
"pkg",
"*",
"goPackage",
")",
"isBuildable",
"(",
"c",
"*",
"config",
".",
"Config",
")",
"bool",
"{",
"return",
"pkg",
".",
"firstGoFile",
"(",
")",
"!=",
"\"\"",
"||",
"!",
"pkg",
".",
"proto",
".",
"sources",
".",
"isEmpty",
"(",
")",
"\n",
"}"
] |
// isBuildable returns true if anything in the package is buildable.
// This is true if the package has Go code that satisfies build constraints
// on any platform or has proto files not in legacy mode.
|
[
"isBuildable",
"returns",
"true",
"if",
"anything",
"in",
"the",
"package",
"is",
"buildable",
".",
"This",
"is",
"true",
"if",
"the",
"package",
"has",
"Go",
"code",
"that",
"satisfies",
"build",
"constraints",
"on",
"any",
"platform",
"or",
"has",
"proto",
"files",
"not",
"in",
"legacy",
"mode",
"."
] |
e3805aaca69a9deb949b47bfc45b9b1870712f4f
|
https://github.com/bazelbuild/bazel-gazelle/blob/e3805aaca69a9deb949b47bfc45b9b1870712f4f/language/go/package.go#L121-L123
|
test
|
bazelbuild/bazel-gazelle
|
cmd/autogazelle/server_unix.go
|
startServer
|
func startServer() error {
exe, err := os.Executable()
if err != nil {
return err
}
args := []string{"-server"}
args = append(args, os.Args[1:]...)
cmd := exec.Command(exe, args...)
log.Printf("starting server: %s", strings.Join(cmd.Args, " "))
if err := cmd.Start(); err != nil {
return err
}
if err := cmd.Process.Release(); err != nil {
return err
}
return nil
}
|
go
|
func startServer() error {
exe, err := os.Executable()
if err != nil {
return err
}
args := []string{"-server"}
args = append(args, os.Args[1:]...)
cmd := exec.Command(exe, args...)
log.Printf("starting server: %s", strings.Join(cmd.Args, " "))
if err := cmd.Start(); err != nil {
return err
}
if err := cmd.Process.Release(); err != nil {
return err
}
return nil
}
|
[
"func",
"startServer",
"(",
")",
"error",
"{",
"exe",
",",
"err",
":=",
"os",
".",
"Executable",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"args",
":=",
"[",
"]",
"string",
"{",
"\"-server\"",
"}",
"\n",
"args",
"=",
"append",
"(",
"args",
",",
"os",
".",
"Args",
"[",
"1",
":",
"]",
"...",
")",
"\n",
"cmd",
":=",
"exec",
".",
"Command",
"(",
"exe",
",",
"args",
"...",
")",
"\n",
"log",
".",
"Printf",
"(",
"\"starting server: %s\"",
",",
"strings",
".",
"Join",
"(",
"cmd",
".",
"Args",
",",
"\" \"",
")",
")",
"\n",
"if",
"err",
":=",
"cmd",
".",
"Start",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"if",
"err",
":=",
"cmd",
".",
"Process",
".",
"Release",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] |
// startServer starts a new server process. This is called by the client.
|
[
"startServer",
"starts",
"a",
"new",
"server",
"process",
".",
"This",
"is",
"called",
"by",
"the",
"client",
"."
] |
e3805aaca69a9deb949b47bfc45b9b1870712f4f
|
https://github.com/bazelbuild/bazel-gazelle/blob/e3805aaca69a9deb949b47bfc45b9b1870712f4f/cmd/autogazelle/server_unix.go#L36-L52
|
test
|
bazelbuild/bazel-gazelle
|
cmd/autogazelle/server_unix.go
|
watchDir
|
func watchDir(root string, record func(string)) (cancel func(), err error) {
w, err := fsnotify.NewWatcher()
if err != nil {
return nil, err
}
dirs, errs := listDirs(root)
for _, err := range errs {
log.Print(err)
}
gitDir := filepath.Join(root, ".git")
for _, dir := range dirs {
if dir == gitDir {
continue
}
if err := w.Add(dir); err != nil {
log.Print(err)
}
}
done := make(chan struct{})
go func() {
for {
select {
case ev := <-w.Events:
if shouldIgnore(ev.Name) {
continue
}
if ev.Op == fsnotify.Create {
if st, err := os.Lstat(ev.Name); err != nil {
log.Print(err)
} else if st.IsDir() {
dirs, errs := listDirs(ev.Name)
for _, err := range errs {
log.Print(err)
}
for _, dir := range dirs {
if err := w.Add(dir); err != nil {
log.Print(err)
}
recordWrite(dir)
}
}
} else {
recordWrite(filepath.Dir(ev.Name))
}
case err := <-w.Errors:
log.Print(err)
case <-done:
if err := w.Close(); err != nil {
log.Print(err)
}
return
}
}
}()
return func() { close(done) }, nil
}
|
go
|
func watchDir(root string, record func(string)) (cancel func(), err error) {
w, err := fsnotify.NewWatcher()
if err != nil {
return nil, err
}
dirs, errs := listDirs(root)
for _, err := range errs {
log.Print(err)
}
gitDir := filepath.Join(root, ".git")
for _, dir := range dirs {
if dir == gitDir {
continue
}
if err := w.Add(dir); err != nil {
log.Print(err)
}
}
done := make(chan struct{})
go func() {
for {
select {
case ev := <-w.Events:
if shouldIgnore(ev.Name) {
continue
}
if ev.Op == fsnotify.Create {
if st, err := os.Lstat(ev.Name); err != nil {
log.Print(err)
} else if st.IsDir() {
dirs, errs := listDirs(ev.Name)
for _, err := range errs {
log.Print(err)
}
for _, dir := range dirs {
if err := w.Add(dir); err != nil {
log.Print(err)
}
recordWrite(dir)
}
}
} else {
recordWrite(filepath.Dir(ev.Name))
}
case err := <-w.Errors:
log.Print(err)
case <-done:
if err := w.Close(); err != nil {
log.Print(err)
}
return
}
}
}()
return func() { close(done) }, nil
}
|
[
"func",
"watchDir",
"(",
"root",
"string",
",",
"record",
"func",
"(",
"string",
")",
")",
"(",
"cancel",
"func",
"(",
")",
",",
"err",
"error",
")",
"{",
"w",
",",
"err",
":=",
"fsnotify",
".",
"NewWatcher",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"dirs",
",",
"errs",
":=",
"listDirs",
"(",
"root",
")",
"\n",
"for",
"_",
",",
"err",
":=",
"range",
"errs",
"{",
"log",
".",
"Print",
"(",
"err",
")",
"\n",
"}",
"\n",
"gitDir",
":=",
"filepath",
".",
"Join",
"(",
"root",
",",
"\".git\"",
")",
"\n",
"for",
"_",
",",
"dir",
":=",
"range",
"dirs",
"{",
"if",
"dir",
"==",
"gitDir",
"{",
"continue",
"\n",
"}",
"\n",
"if",
"err",
":=",
"w",
".",
"Add",
"(",
"dir",
")",
";",
"err",
"!=",
"nil",
"{",
"log",
".",
"Print",
"(",
"err",
")",
"\n",
"}",
"\n",
"}",
"\n",
"done",
":=",
"make",
"(",
"chan",
"struct",
"{",
"}",
")",
"\n",
"go",
"func",
"(",
")",
"{",
"for",
"{",
"select",
"{",
"case",
"ev",
":=",
"<-",
"w",
".",
"Events",
":",
"if",
"shouldIgnore",
"(",
"ev",
".",
"Name",
")",
"{",
"continue",
"\n",
"}",
"\n",
"if",
"ev",
".",
"Op",
"==",
"fsnotify",
".",
"Create",
"{",
"if",
"st",
",",
"err",
":=",
"os",
".",
"Lstat",
"(",
"ev",
".",
"Name",
")",
";",
"err",
"!=",
"nil",
"{",
"log",
".",
"Print",
"(",
"err",
")",
"\n",
"}",
"else",
"if",
"st",
".",
"IsDir",
"(",
")",
"{",
"dirs",
",",
"errs",
":=",
"listDirs",
"(",
"ev",
".",
"Name",
")",
"\n",
"for",
"_",
",",
"err",
":=",
"range",
"errs",
"{",
"log",
".",
"Print",
"(",
"err",
")",
"\n",
"}",
"\n",
"for",
"_",
",",
"dir",
":=",
"range",
"dirs",
"{",
"if",
"err",
":=",
"w",
".",
"Add",
"(",
"dir",
")",
";",
"err",
"!=",
"nil",
"{",
"log",
".",
"Print",
"(",
"err",
")",
"\n",
"}",
"\n",
"recordWrite",
"(",
"dir",
")",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"else",
"{",
"recordWrite",
"(",
"filepath",
".",
"Dir",
"(",
"ev",
".",
"Name",
")",
")",
"\n",
"}",
"\n",
"case",
"err",
":=",
"<-",
"w",
".",
"Errors",
":",
"log",
".",
"Print",
"(",
"err",
")",
"\n",
"case",
"<-",
"done",
":",
"if",
"err",
":=",
"w",
".",
"Close",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"log",
".",
"Print",
"(",
"err",
")",
"\n",
"}",
"\n",
"return",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"(",
")",
"\n",
"return",
"func",
"(",
")",
"{",
"close",
"(",
"done",
")",
"}",
",",
"nil",
"\n",
"}"
] |
// watchDir listens for file system changes in root and its
// subdirectories. The record function is called with directories whose
// contents have changed. New directories are watched recursively.
// The returned cancel function may be called to stop watching.
|
[
"watchDir",
"listens",
"for",
"file",
"system",
"changes",
"in",
"root",
"and",
"its",
"subdirectories",
".",
"The",
"record",
"function",
"is",
"called",
"with",
"directories",
"whose",
"contents",
"have",
"changed",
".",
"New",
"directories",
"are",
"watched",
"recursively",
".",
"The",
"returned",
"cancel",
"function",
"may",
"be",
"called",
"to",
"stop",
"watching",
"."
] |
e3805aaca69a9deb949b47bfc45b9b1870712f4f
|
https://github.com/bazelbuild/bazel-gazelle/blob/e3805aaca69a9deb949b47bfc45b9b1870712f4f/cmd/autogazelle/server_unix.go#L143-L200
|
test
|
bazelbuild/bazel-gazelle
|
cmd/autogazelle/server_unix.go
|
listDirs
|
func listDirs(dir string) ([]string, []error) {
var dirs []string
var errs []error
err := filepath.Walk(dir, func(path string, info os.FileInfo, err error) error {
if err != nil {
errs = append(errs, err)
return nil
}
if info.IsDir() {
dirs = append(dirs, path)
}
return nil
})
if err != nil {
errs = append(errs, err)
}
return dirs, errs
}
|
go
|
func listDirs(dir string) ([]string, []error) {
var dirs []string
var errs []error
err := filepath.Walk(dir, func(path string, info os.FileInfo, err error) error {
if err != nil {
errs = append(errs, err)
return nil
}
if info.IsDir() {
dirs = append(dirs, path)
}
return nil
})
if err != nil {
errs = append(errs, err)
}
return dirs, errs
}
|
[
"func",
"listDirs",
"(",
"dir",
"string",
")",
"(",
"[",
"]",
"string",
",",
"[",
"]",
"error",
")",
"{",
"var",
"dirs",
"[",
"]",
"string",
"\n",
"var",
"errs",
"[",
"]",
"error",
"\n",
"err",
":=",
"filepath",
".",
"Walk",
"(",
"dir",
",",
"func",
"(",
"path",
"string",
",",
"info",
"os",
".",
"FileInfo",
",",
"err",
"error",
")",
"error",
"{",
"if",
"err",
"!=",
"nil",
"{",
"errs",
"=",
"append",
"(",
"errs",
",",
"err",
")",
"\n",
"return",
"nil",
"\n",
"}",
"\n",
"if",
"info",
".",
"IsDir",
"(",
")",
"{",
"dirs",
"=",
"append",
"(",
"dirs",
",",
"path",
")",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"errs",
"=",
"append",
"(",
"errs",
",",
"err",
")",
"\n",
"}",
"\n",
"return",
"dirs",
",",
"errs",
"\n",
"}"
] |
// listDirs returns a slice containing all the subdirectories under dir,
// including dir itself.
|
[
"listDirs",
"returns",
"a",
"slice",
"containing",
"all",
"the",
"subdirectories",
"under",
"dir",
"including",
"dir",
"itself",
"."
] |
e3805aaca69a9deb949b47bfc45b9b1870712f4f
|
https://github.com/bazelbuild/bazel-gazelle/blob/e3805aaca69a9deb949b47bfc45b9b1870712f4f/cmd/autogazelle/server_unix.go#L204-L221
|
test
|
bazelbuild/bazel-gazelle
|
cmd/autogazelle/server_unix.go
|
shouldIgnore
|
func shouldIgnore(p string) bool {
p = strings.TrimPrefix(filepath.ToSlash(p), "./")
base := path.Base(p)
return strings.HasPrefix(p, "tools/") || base == ".git" || base == "BUILD" || base == "BUILD.bazel"
}
|
go
|
func shouldIgnore(p string) bool {
p = strings.TrimPrefix(filepath.ToSlash(p), "./")
base := path.Base(p)
return strings.HasPrefix(p, "tools/") || base == ".git" || base == "BUILD" || base == "BUILD.bazel"
}
|
[
"func",
"shouldIgnore",
"(",
"p",
"string",
")",
"bool",
"{",
"p",
"=",
"strings",
".",
"TrimPrefix",
"(",
"filepath",
".",
"ToSlash",
"(",
"p",
")",
",",
"\"./\"",
")",
"\n",
"base",
":=",
"path",
".",
"Base",
"(",
"p",
")",
"\n",
"return",
"strings",
".",
"HasPrefix",
"(",
"p",
",",
"\"tools/\"",
")",
"||",
"base",
"==",
"\".git\"",
"||",
"base",
"==",
"\"BUILD\"",
"||",
"base",
"==",
"\"BUILD.bazel\"",
"\n",
"}"
] |
// shouldIgnore returns whether a write to the given file should be ignored
// because they were caused by gazelle or autogazelle or something unrelated
// to the build.
|
[
"shouldIgnore",
"returns",
"whether",
"a",
"write",
"to",
"the",
"given",
"file",
"should",
"be",
"ignored",
"because",
"they",
"were",
"caused",
"by",
"gazelle",
"or",
"autogazelle",
"or",
"something",
"unrelated",
"to",
"the",
"build",
"."
] |
e3805aaca69a9deb949b47bfc45b9b1870712f4f
|
https://github.com/bazelbuild/bazel-gazelle/blob/e3805aaca69a9deb949b47bfc45b9b1870712f4f/cmd/autogazelle/server_unix.go#L226-L230
|
test
|
bazelbuild/bazel-gazelle
|
cmd/autogazelle/server_unix.go
|
recordWrite
|
func recordWrite(path string) {
dirSetMutex.Lock()
defer dirSetMutex.Unlock()
dirSet[path] = true
}
|
go
|
func recordWrite(path string) {
dirSetMutex.Lock()
defer dirSetMutex.Unlock()
dirSet[path] = true
}
|
[
"func",
"recordWrite",
"(",
"path",
"string",
")",
"{",
"dirSetMutex",
".",
"Lock",
"(",
")",
"\n",
"defer",
"dirSetMutex",
".",
"Unlock",
"(",
")",
"\n",
"dirSet",
"[",
"path",
"]",
"=",
"true",
"\n",
"}"
] |
// recordWrite records that a directory has been modified and that its build
// file should be updated the next time gazelle runs.
|
[
"recordWrite",
"records",
"that",
"a",
"directory",
"has",
"been",
"modified",
"and",
"that",
"its",
"build",
"file",
"should",
"be",
"updated",
"the",
"next",
"time",
"gazelle",
"runs",
"."
] |
e3805aaca69a9deb949b47bfc45b9b1870712f4f
|
https://github.com/bazelbuild/bazel-gazelle/blob/e3805aaca69a9deb949b47bfc45b9b1870712f4f/cmd/autogazelle/server_unix.go#L239-L243
|
test
|
bazelbuild/bazel-gazelle
|
cmd/autogazelle/server_unix.go
|
getAndClearWrittenDirs
|
func getAndClearWrittenDirs() []string {
dirSetMutex.Lock()
defer dirSetMutex.Unlock()
dirs := make([]string, 0, len(dirSet))
for d := range dirSet {
dirs = append(dirs, d)
}
dirSet = make(map[string]bool)
return dirs
}
|
go
|
func getAndClearWrittenDirs() []string {
dirSetMutex.Lock()
defer dirSetMutex.Unlock()
dirs := make([]string, 0, len(dirSet))
for d := range dirSet {
dirs = append(dirs, d)
}
dirSet = make(map[string]bool)
return dirs
}
|
[
"func",
"getAndClearWrittenDirs",
"(",
")",
"[",
"]",
"string",
"{",
"dirSetMutex",
".",
"Lock",
"(",
")",
"\n",
"defer",
"dirSetMutex",
".",
"Unlock",
"(",
")",
"\n",
"dirs",
":=",
"make",
"(",
"[",
"]",
"string",
",",
"0",
",",
"len",
"(",
"dirSet",
")",
")",
"\n",
"for",
"d",
":=",
"range",
"dirSet",
"{",
"dirs",
"=",
"append",
"(",
"dirs",
",",
"d",
")",
"\n",
"}",
"\n",
"dirSet",
"=",
"make",
"(",
"map",
"[",
"string",
"]",
"bool",
")",
"\n",
"return",
"dirs",
"\n",
"}"
] |
// getAndClearWrittenDirs retrieves a list of directories that have been
// modified since the last time getAndClearWrittenDirs was called.
|
[
"getAndClearWrittenDirs",
"retrieves",
"a",
"list",
"of",
"directories",
"that",
"have",
"been",
"modified",
"since",
"the",
"last",
"time",
"getAndClearWrittenDirs",
"was",
"called",
"."
] |
e3805aaca69a9deb949b47bfc45b9b1870712f4f
|
https://github.com/bazelbuild/bazel-gazelle/blob/e3805aaca69a9deb949b47bfc45b9b1870712f4f/cmd/autogazelle/server_unix.go#L247-L256
|
test
|
onsi/gomega
|
ghttp/handlers.go
|
CombineHandlers
|
func CombineHandlers(handlers ...http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, req *http.Request) {
for _, handler := range handlers {
handler(w, req)
}
}
}
|
go
|
func CombineHandlers(handlers ...http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, req *http.Request) {
for _, handler := range handlers {
handler(w, req)
}
}
}
|
[
"func",
"CombineHandlers",
"(",
"handlers",
"...",
"http",
".",
"HandlerFunc",
")",
"http",
".",
"HandlerFunc",
"{",
"return",
"func",
"(",
"w",
"http",
".",
"ResponseWriter",
",",
"req",
"*",
"http",
".",
"Request",
")",
"{",
"for",
"_",
",",
"handler",
":=",
"range",
"handlers",
"{",
"handler",
"(",
"w",
",",
"req",
")",
"\n",
"}",
"\n",
"}",
"\n",
"}"
] |
//CombineHandler takes variadic list of handlers and produces one handler
//that calls each handler in order.
|
[
"CombineHandler",
"takes",
"variadic",
"list",
"of",
"handlers",
"and",
"produces",
"one",
"handler",
"that",
"calls",
"each",
"handler",
"in",
"order",
"."
] |
f0e010e04c08c48a875f83d17df37b04eb3a985b
|
https://github.com/onsi/gomega/blob/f0e010e04c08c48a875f83d17df37b04eb3a985b/ghttp/handlers.go#L20-L26
|
test
|
onsi/gomega
|
ghttp/handlers.go
|
VerifyContentType
|
func VerifyContentType(contentType string) http.HandlerFunc {
return func(w http.ResponseWriter, req *http.Request) {
Expect(req.Header.Get("Content-Type")).Should(Equal(contentType))
}
}
|
go
|
func VerifyContentType(contentType string) http.HandlerFunc {
return func(w http.ResponseWriter, req *http.Request) {
Expect(req.Header.Get("Content-Type")).Should(Equal(contentType))
}
}
|
[
"func",
"VerifyContentType",
"(",
"contentType",
"string",
")",
"http",
".",
"HandlerFunc",
"{",
"return",
"func",
"(",
"w",
"http",
".",
"ResponseWriter",
",",
"req",
"*",
"http",
".",
"Request",
")",
"{",
"Expect",
"(",
"req",
".",
"Header",
".",
"Get",
"(",
"\"Content-Type\"",
")",
")",
".",
"Should",
"(",
"Equal",
"(",
"contentType",
")",
")",
"\n",
"}",
"\n",
"}"
] |
//VerifyContentType returns a handler that verifies that a request has a Content-Type header set to the
//specified value
|
[
"VerifyContentType",
"returns",
"a",
"handler",
"that",
"verifies",
"that",
"a",
"request",
"has",
"a",
"Content",
"-",
"Type",
"header",
"set",
"to",
"the",
"specified",
"value"
] |
f0e010e04c08c48a875f83d17df37b04eb3a985b
|
https://github.com/onsi/gomega/blob/f0e010e04c08c48a875f83d17df37b04eb3a985b/ghttp/handlers.go#L53-L57
|
test
|
onsi/gomega
|
ghttp/handlers.go
|
VerifyMimeType
|
func VerifyMimeType(mimeType string) http.HandlerFunc {
return func(w http.ResponseWriter, req *http.Request) {
Expect(strings.Split(req.Header.Get("Content-Type"), ";")[0]).Should(Equal(mimeType))
}
}
|
go
|
func VerifyMimeType(mimeType string) http.HandlerFunc {
return func(w http.ResponseWriter, req *http.Request) {
Expect(strings.Split(req.Header.Get("Content-Type"), ";")[0]).Should(Equal(mimeType))
}
}
|
[
"func",
"VerifyMimeType",
"(",
"mimeType",
"string",
")",
"http",
".",
"HandlerFunc",
"{",
"return",
"func",
"(",
"w",
"http",
".",
"ResponseWriter",
",",
"req",
"*",
"http",
".",
"Request",
")",
"{",
"Expect",
"(",
"strings",
".",
"Split",
"(",
"req",
".",
"Header",
".",
"Get",
"(",
"\"Content-Type\"",
")",
",",
"\";\"",
")",
"[",
"0",
"]",
")",
".",
"Should",
"(",
"Equal",
"(",
"mimeType",
")",
")",
"\n",
"}",
"\n",
"}"
] |
//VerifyMimeType returns a handler that verifies that a request has a specified mime type set
//in Content-Type header
|
[
"VerifyMimeType",
"returns",
"a",
"handler",
"that",
"verifies",
"that",
"a",
"request",
"has",
"a",
"specified",
"mime",
"type",
"set",
"in",
"Content",
"-",
"Type",
"header"
] |
f0e010e04c08c48a875f83d17df37b04eb3a985b
|
https://github.com/onsi/gomega/blob/f0e010e04c08c48a875f83d17df37b04eb3a985b/ghttp/handlers.go#L61-L65
|
test
|
onsi/gomega
|
ghttp/handlers.go
|
VerifyBasicAuth
|
func VerifyBasicAuth(username string, password string) http.HandlerFunc {
return func(w http.ResponseWriter, req *http.Request) {
auth := req.Header.Get("Authorization")
Expect(auth).ShouldNot(Equal(""), "Authorization header must be specified")
decoded, err := base64.StdEncoding.DecodeString(auth[6:])
Expect(err).ShouldNot(HaveOccurred())
Expect(string(decoded)).Should(Equal(fmt.Sprintf("%s:%s", username, password)), "Authorization mismatch")
}
}
|
go
|
func VerifyBasicAuth(username string, password string) http.HandlerFunc {
return func(w http.ResponseWriter, req *http.Request) {
auth := req.Header.Get("Authorization")
Expect(auth).ShouldNot(Equal(""), "Authorization header must be specified")
decoded, err := base64.StdEncoding.DecodeString(auth[6:])
Expect(err).ShouldNot(HaveOccurred())
Expect(string(decoded)).Should(Equal(fmt.Sprintf("%s:%s", username, password)), "Authorization mismatch")
}
}
|
[
"func",
"VerifyBasicAuth",
"(",
"username",
"string",
",",
"password",
"string",
")",
"http",
".",
"HandlerFunc",
"{",
"return",
"func",
"(",
"w",
"http",
".",
"ResponseWriter",
",",
"req",
"*",
"http",
".",
"Request",
")",
"{",
"auth",
":=",
"req",
".",
"Header",
".",
"Get",
"(",
"\"Authorization\"",
")",
"\n",
"Expect",
"(",
"auth",
")",
".",
"ShouldNot",
"(",
"Equal",
"(",
"\"\"",
")",
",",
"\"Authorization header must be specified\"",
")",
"\n",
"decoded",
",",
"err",
":=",
"base64",
".",
"StdEncoding",
".",
"DecodeString",
"(",
"auth",
"[",
"6",
":",
"]",
")",
"\n",
"Expect",
"(",
"err",
")",
".",
"ShouldNot",
"(",
"HaveOccurred",
"(",
")",
")",
"\n",
"Expect",
"(",
"string",
"(",
"decoded",
")",
")",
".",
"Should",
"(",
"Equal",
"(",
"fmt",
".",
"Sprintf",
"(",
"\"%s:%s\"",
",",
"username",
",",
"password",
")",
")",
",",
"\"Authorization mismatch\"",
")",
"\n",
"}",
"\n",
"}"
] |
//VerifyBasicAuth returns a handler that verifies the request contains a BasicAuth Authorization header
//matching the passed in username and password
|
[
"VerifyBasicAuth",
"returns",
"a",
"handler",
"that",
"verifies",
"the",
"request",
"contains",
"a",
"BasicAuth",
"Authorization",
"header",
"matching",
"the",
"passed",
"in",
"username",
"and",
"password"
] |
f0e010e04c08c48a875f83d17df37b04eb3a985b
|
https://github.com/onsi/gomega/blob/f0e010e04c08c48a875f83d17df37b04eb3a985b/ghttp/handlers.go#L69-L79
|
test
|
onsi/gomega
|
ghttp/handlers.go
|
VerifyJSONRepresenting
|
func VerifyJSONRepresenting(object interface{}) http.HandlerFunc {
data, err := json.Marshal(object)
Expect(err).ShouldNot(HaveOccurred())
return CombineHandlers(
VerifyContentType("application/json"),
VerifyJSON(string(data)),
)
}
|
go
|
func VerifyJSONRepresenting(object interface{}) http.HandlerFunc {
data, err := json.Marshal(object)
Expect(err).ShouldNot(HaveOccurred())
return CombineHandlers(
VerifyContentType("application/json"),
VerifyJSON(string(data)),
)
}
|
[
"func",
"VerifyJSONRepresenting",
"(",
"object",
"interface",
"{",
"}",
")",
"http",
".",
"HandlerFunc",
"{",
"data",
",",
"err",
":=",
"json",
".",
"Marshal",
"(",
"object",
")",
"\n",
"Expect",
"(",
"err",
")",
".",
"ShouldNot",
"(",
"HaveOccurred",
"(",
")",
")",
"\n",
"return",
"CombineHandlers",
"(",
"VerifyContentType",
"(",
"\"application/json\"",
")",
",",
"VerifyJSON",
"(",
"string",
"(",
"data",
")",
")",
",",
")",
"\n",
"}"
] |
//VerifyJSONRepresenting is similar to VerifyJSON. Instead of taking a JSON string, however, it
//takes an arbitrary JSON-encodable object and verifies that the requests's body is a JSON representation
//that matches the object
|
[
"VerifyJSONRepresenting",
"is",
"similar",
"to",
"VerifyJSON",
".",
"Instead",
"of",
"taking",
"a",
"JSON",
"string",
"however",
"it",
"takes",
"an",
"arbitrary",
"JSON",
"-",
"encodable",
"object",
"and",
"verifies",
"that",
"the",
"requests",
"s",
"body",
"is",
"a",
"JSON",
"representation",
"that",
"matches",
"the",
"object"
] |
f0e010e04c08c48a875f83d17df37b04eb3a985b
|
https://github.com/onsi/gomega/blob/f0e010e04c08c48a875f83d17df37b04eb3a985b/ghttp/handlers.go#L134-L141
|
test
|
onsi/gomega
|
ghttp/handlers.go
|
VerifyFormKV
|
func VerifyFormKV(key string, values ...string) http.HandlerFunc {
return VerifyForm(url.Values{key: values})
}
|
go
|
func VerifyFormKV(key string, values ...string) http.HandlerFunc {
return VerifyForm(url.Values{key: values})
}
|
[
"func",
"VerifyFormKV",
"(",
"key",
"string",
",",
"values",
"...",
"string",
")",
"http",
".",
"HandlerFunc",
"{",
"return",
"VerifyForm",
"(",
"url",
".",
"Values",
"{",
"key",
":",
"values",
"}",
")",
"\n",
"}"
] |
//VerifyFormKV returns a handler that verifies a request contains a form key with the specified values.
//
//It is a convenience wrapper around `VerifyForm` that lets you avoid having to create a `url.Values` object.
|
[
"VerifyFormKV",
"returns",
"a",
"handler",
"that",
"verifies",
"a",
"request",
"contains",
"a",
"form",
"key",
"with",
"the",
"specified",
"values",
".",
"It",
"is",
"a",
"convenience",
"wrapper",
"around",
"VerifyForm",
"that",
"lets",
"you",
"avoid",
"having",
"to",
"create",
"a",
"url",
".",
"Values",
"object",
"."
] |
f0e010e04c08c48a875f83d17df37b04eb3a985b
|
https://github.com/onsi/gomega/blob/f0e010e04c08c48a875f83d17df37b04eb3a985b/ghttp/handlers.go#L160-L162
|
test
|
onsi/gomega
|
ghttp/handlers.go
|
RespondWithProto
|
func RespondWithProto(statusCode int, message proto.Message, optionalHeader ...http.Header) http.HandlerFunc {
return func(w http.ResponseWriter, req *http.Request) {
data, err := proto.Marshal(message)
Expect(err).ShouldNot(HaveOccurred())
var headers http.Header
if len(optionalHeader) == 1 {
headers = optionalHeader[0]
} else {
headers = make(http.Header)
}
if _, found := headers["Content-Type"]; !found {
headers["Content-Type"] = []string{"application/x-protobuf"}
}
copyHeader(headers, w.Header())
w.WriteHeader(statusCode)
w.Write(data)
}
}
|
go
|
func RespondWithProto(statusCode int, message proto.Message, optionalHeader ...http.Header) http.HandlerFunc {
return func(w http.ResponseWriter, req *http.Request) {
data, err := proto.Marshal(message)
Expect(err).ShouldNot(HaveOccurred())
var headers http.Header
if len(optionalHeader) == 1 {
headers = optionalHeader[0]
} else {
headers = make(http.Header)
}
if _, found := headers["Content-Type"]; !found {
headers["Content-Type"] = []string{"application/x-protobuf"}
}
copyHeader(headers, w.Header())
w.WriteHeader(statusCode)
w.Write(data)
}
}
|
[
"func",
"RespondWithProto",
"(",
"statusCode",
"int",
",",
"message",
"proto",
".",
"Message",
",",
"optionalHeader",
"...",
"http",
".",
"Header",
")",
"http",
".",
"HandlerFunc",
"{",
"return",
"func",
"(",
"w",
"http",
".",
"ResponseWriter",
",",
"req",
"*",
"http",
".",
"Request",
")",
"{",
"data",
",",
"err",
":=",
"proto",
".",
"Marshal",
"(",
"message",
")",
"\n",
"Expect",
"(",
"err",
")",
".",
"ShouldNot",
"(",
"HaveOccurred",
"(",
")",
")",
"\n",
"var",
"headers",
"http",
".",
"Header",
"\n",
"if",
"len",
"(",
"optionalHeader",
")",
"==",
"1",
"{",
"headers",
"=",
"optionalHeader",
"[",
"0",
"]",
"\n",
"}",
"else",
"{",
"headers",
"=",
"make",
"(",
"http",
".",
"Header",
")",
"\n",
"}",
"\n",
"if",
"_",
",",
"found",
":=",
"headers",
"[",
"\"Content-Type\"",
"]",
";",
"!",
"found",
"{",
"headers",
"[",
"\"Content-Type\"",
"]",
"=",
"[",
"]",
"string",
"{",
"\"application/x-protobuf\"",
"}",
"\n",
"}",
"\n",
"copyHeader",
"(",
"headers",
",",
"w",
".",
"Header",
"(",
")",
")",
"\n",
"w",
".",
"WriteHeader",
"(",
"statusCode",
")",
"\n",
"w",
".",
"Write",
"(",
"data",
")",
"\n",
"}",
"\n",
"}"
] |
//RespondWithProto returns a handler that responds to a request with the specified status code and a body
//containing the protobuf serialization of the provided message.
//
//Also, RespondWithProto can be given an optional http.Header. The headers defined therein will be added to the response headers.
|
[
"RespondWithProto",
"returns",
"a",
"handler",
"that",
"responds",
"to",
"a",
"request",
"with",
"the",
"specified",
"status",
"code",
"and",
"a",
"body",
"containing",
"the",
"protobuf",
"serialization",
"of",
"the",
"provided",
"message",
".",
"Also",
"RespondWithProto",
"can",
"be",
"given",
"an",
"optional",
"http",
".",
"Header",
".",
"The",
"headers",
"defined",
"therein",
"will",
"be",
"added",
"to",
"the",
"response",
"headers",
"."
] |
f0e010e04c08c48a875f83d17df37b04eb3a985b
|
https://github.com/onsi/gomega/blob/f0e010e04c08c48a875f83d17df37b04eb3a985b/ghttp/handlers.go#L303-L322
|
test
|
onsi/gomega
|
gomega_dsl.go
|
RegisterFailHandlerWithT
|
func RegisterFailHandlerWithT(t types.TWithHelper, handler types.GomegaFailHandler) {
if handler == nil {
globalFailWrapper = nil
return
}
globalFailWrapper = &types.GomegaFailWrapper{
Fail: handler,
TWithHelper: t,
}
}
|
go
|
func RegisterFailHandlerWithT(t types.TWithHelper, handler types.GomegaFailHandler) {
if handler == nil {
globalFailWrapper = nil
return
}
globalFailWrapper = &types.GomegaFailWrapper{
Fail: handler,
TWithHelper: t,
}
}
|
[
"func",
"RegisterFailHandlerWithT",
"(",
"t",
"types",
".",
"TWithHelper",
",",
"handler",
"types",
".",
"GomegaFailHandler",
")",
"{",
"if",
"handler",
"==",
"nil",
"{",
"globalFailWrapper",
"=",
"nil",
"\n",
"return",
"\n",
"}",
"\n",
"globalFailWrapper",
"=",
"&",
"types",
".",
"GomegaFailWrapper",
"{",
"Fail",
":",
"handler",
",",
"TWithHelper",
":",
"t",
",",
"}",
"\n",
"}"
] |
// RegisterFailHandlerWithT ensures that the given types.TWithHelper and fail handler
// are used globally.
|
[
"RegisterFailHandlerWithT",
"ensures",
"that",
"the",
"given",
"types",
".",
"TWithHelper",
"and",
"fail",
"handler",
"are",
"used",
"globally",
"."
] |
f0e010e04c08c48a875f83d17df37b04eb3a985b
|
https://github.com/onsi/gomega/blob/f0e010e04c08c48a875f83d17df37b04eb3a985b/gomega_dsl.go#L50-L60
|
test
|
onsi/gomega
|
gomega_dsl.go
|
EventuallyWithOffset
|
func EventuallyWithOffset(offset int, actual interface{}, intervals ...interface{}) AsyncAssertion {
if globalFailWrapper == nil {
panic(nilFailHandlerPanic)
}
timeoutInterval := defaultEventuallyTimeout
pollingInterval := defaultEventuallyPollingInterval
if len(intervals) > 0 {
timeoutInterval = toDuration(intervals[0])
}
if len(intervals) > 1 {
pollingInterval = toDuration(intervals[1])
}
return asyncassertion.New(asyncassertion.AsyncAssertionTypeEventually, actual, globalFailWrapper, timeoutInterval, pollingInterval, offset)
}
|
go
|
func EventuallyWithOffset(offset int, actual interface{}, intervals ...interface{}) AsyncAssertion {
if globalFailWrapper == nil {
panic(nilFailHandlerPanic)
}
timeoutInterval := defaultEventuallyTimeout
pollingInterval := defaultEventuallyPollingInterval
if len(intervals) > 0 {
timeoutInterval = toDuration(intervals[0])
}
if len(intervals) > 1 {
pollingInterval = toDuration(intervals[1])
}
return asyncassertion.New(asyncassertion.AsyncAssertionTypeEventually, actual, globalFailWrapper, timeoutInterval, pollingInterval, offset)
}
|
[
"func",
"EventuallyWithOffset",
"(",
"offset",
"int",
",",
"actual",
"interface",
"{",
"}",
",",
"intervals",
"...",
"interface",
"{",
"}",
")",
"AsyncAssertion",
"{",
"if",
"globalFailWrapper",
"==",
"nil",
"{",
"panic",
"(",
"nilFailHandlerPanic",
")",
"\n",
"}",
"\n",
"timeoutInterval",
":=",
"defaultEventuallyTimeout",
"\n",
"pollingInterval",
":=",
"defaultEventuallyPollingInterval",
"\n",
"if",
"len",
"(",
"intervals",
")",
">",
"0",
"{",
"timeoutInterval",
"=",
"toDuration",
"(",
"intervals",
"[",
"0",
"]",
")",
"\n",
"}",
"\n",
"if",
"len",
"(",
"intervals",
")",
">",
"1",
"{",
"pollingInterval",
"=",
"toDuration",
"(",
"intervals",
"[",
"1",
"]",
")",
"\n",
"}",
"\n",
"return",
"asyncassertion",
".",
"New",
"(",
"asyncassertion",
".",
"AsyncAssertionTypeEventually",
",",
"actual",
",",
"globalFailWrapper",
",",
"timeoutInterval",
",",
"pollingInterval",
",",
"offset",
")",
"\n",
"}"
] |
// EventuallyWithOffset operates like Eventually but takes an additional
// initial argument to indicate an offset in the call stack. This is useful when building helper
// functions that contain matchers. To learn more, read about `ExpectWithOffset`.
|
[
"EventuallyWithOffset",
"operates",
"like",
"Eventually",
"but",
"takes",
"an",
"additional",
"initial",
"argument",
"to",
"indicate",
"an",
"offset",
"in",
"the",
"call",
"stack",
".",
"This",
"is",
"useful",
"when",
"building",
"helper",
"functions",
"that",
"contain",
"matchers",
".",
"To",
"learn",
"more",
"read",
"about",
"ExpectWithOffset",
"."
] |
f0e010e04c08c48a875f83d17df37b04eb3a985b
|
https://github.com/onsi/gomega/blob/f0e010e04c08c48a875f83d17df37b04eb3a985b/gomega_dsl.go#L213-L226
|
test
|
onsi/gomega
|
gomega_dsl.go
|
ConsistentlyWithOffset
|
func ConsistentlyWithOffset(offset int, actual interface{}, intervals ...interface{}) AsyncAssertion {
if globalFailWrapper == nil {
panic(nilFailHandlerPanic)
}
timeoutInterval := defaultConsistentlyDuration
pollingInterval := defaultConsistentlyPollingInterval
if len(intervals) > 0 {
timeoutInterval = toDuration(intervals[0])
}
if len(intervals) > 1 {
pollingInterval = toDuration(intervals[1])
}
return asyncassertion.New(asyncassertion.AsyncAssertionTypeConsistently, actual, globalFailWrapper, timeoutInterval, pollingInterval, offset)
}
|
go
|
func ConsistentlyWithOffset(offset int, actual interface{}, intervals ...interface{}) AsyncAssertion {
if globalFailWrapper == nil {
panic(nilFailHandlerPanic)
}
timeoutInterval := defaultConsistentlyDuration
pollingInterval := defaultConsistentlyPollingInterval
if len(intervals) > 0 {
timeoutInterval = toDuration(intervals[0])
}
if len(intervals) > 1 {
pollingInterval = toDuration(intervals[1])
}
return asyncassertion.New(asyncassertion.AsyncAssertionTypeConsistently, actual, globalFailWrapper, timeoutInterval, pollingInterval, offset)
}
|
[
"func",
"ConsistentlyWithOffset",
"(",
"offset",
"int",
",",
"actual",
"interface",
"{",
"}",
",",
"intervals",
"...",
"interface",
"{",
"}",
")",
"AsyncAssertion",
"{",
"if",
"globalFailWrapper",
"==",
"nil",
"{",
"panic",
"(",
"nilFailHandlerPanic",
")",
"\n",
"}",
"\n",
"timeoutInterval",
":=",
"defaultConsistentlyDuration",
"\n",
"pollingInterval",
":=",
"defaultConsistentlyPollingInterval",
"\n",
"if",
"len",
"(",
"intervals",
")",
">",
"0",
"{",
"timeoutInterval",
"=",
"toDuration",
"(",
"intervals",
"[",
"0",
"]",
")",
"\n",
"}",
"\n",
"if",
"len",
"(",
"intervals",
")",
">",
"1",
"{",
"pollingInterval",
"=",
"toDuration",
"(",
"intervals",
"[",
"1",
"]",
")",
"\n",
"}",
"\n",
"return",
"asyncassertion",
".",
"New",
"(",
"asyncassertion",
".",
"AsyncAssertionTypeConsistently",
",",
"actual",
",",
"globalFailWrapper",
",",
"timeoutInterval",
",",
"pollingInterval",
",",
"offset",
")",
"\n",
"}"
] |
// ConsistentlyWithOffset operates like Consistnetly but takes an additional
// initial argument to indicate an offset in the call stack. This is useful when building helper
// functions that contain matchers. To learn more, read about `ExpectWithOffset`.
|
[
"ConsistentlyWithOffset",
"operates",
"like",
"Consistnetly",
"but",
"takes",
"an",
"additional",
"initial",
"argument",
"to",
"indicate",
"an",
"offset",
"in",
"the",
"call",
"stack",
".",
"This",
"is",
"useful",
"when",
"building",
"helper",
"functions",
"that",
"contain",
"matchers",
".",
"To",
"learn",
"more",
"read",
"about",
"ExpectWithOffset",
"."
] |
f0e010e04c08c48a875f83d17df37b04eb3a985b
|
https://github.com/onsi/gomega/blob/f0e010e04c08c48a875f83d17df37b04eb3a985b/gomega_dsl.go#L258-L271
|
test
|
onsi/gomega
|
gomega_dsl.go
|
Expect
|
func (g *WithT) Expect(actual interface{}, extra ...interface{}) Assertion {
return assertion.New(actual, testingtsupport.BuildTestingTGomegaFailWrapper(g.t), 0, extra...)
}
|
go
|
func (g *WithT) Expect(actual interface{}, extra ...interface{}) Assertion {
return assertion.New(actual, testingtsupport.BuildTestingTGomegaFailWrapper(g.t), 0, extra...)
}
|
[
"func",
"(",
"g",
"*",
"WithT",
")",
"Expect",
"(",
"actual",
"interface",
"{",
"}",
",",
"extra",
"...",
"interface",
"{",
"}",
")",
"Assertion",
"{",
"return",
"assertion",
".",
"New",
"(",
"actual",
",",
"testingtsupport",
".",
"BuildTestingTGomegaFailWrapper",
"(",
"g",
".",
"t",
")",
",",
"0",
",",
"extra",
"...",
")",
"\n",
"}"
] |
// Expect is used to make assertions. See documentation for Expect.
|
[
"Expect",
"is",
"used",
"to",
"make",
"assertions",
".",
"See",
"documentation",
"for",
"Expect",
"."
] |
f0e010e04c08c48a875f83d17df37b04eb3a985b
|
https://github.com/onsi/gomega/blob/f0e010e04c08c48a875f83d17df37b04eb3a985b/gomega_dsl.go#L375-L377
|
test
|
onsi/gomega
|
gomega_dsl.go
|
Eventually
|
func (g *WithT) Eventually(actual interface{}, intervals ...interface{}) AsyncAssertion {
timeoutInterval := defaultEventuallyTimeout
pollingInterval := defaultEventuallyPollingInterval
if len(intervals) > 0 {
timeoutInterval = toDuration(intervals[0])
}
if len(intervals) > 1 {
pollingInterval = toDuration(intervals[1])
}
return asyncassertion.New(asyncassertion.AsyncAssertionTypeEventually, actual, testingtsupport.BuildTestingTGomegaFailWrapper(g.t), timeoutInterval, pollingInterval, 0)
}
|
go
|
func (g *WithT) Eventually(actual interface{}, intervals ...interface{}) AsyncAssertion {
timeoutInterval := defaultEventuallyTimeout
pollingInterval := defaultEventuallyPollingInterval
if len(intervals) > 0 {
timeoutInterval = toDuration(intervals[0])
}
if len(intervals) > 1 {
pollingInterval = toDuration(intervals[1])
}
return asyncassertion.New(asyncassertion.AsyncAssertionTypeEventually, actual, testingtsupport.BuildTestingTGomegaFailWrapper(g.t), timeoutInterval, pollingInterval, 0)
}
|
[
"func",
"(",
"g",
"*",
"WithT",
")",
"Eventually",
"(",
"actual",
"interface",
"{",
"}",
",",
"intervals",
"...",
"interface",
"{",
"}",
")",
"AsyncAssertion",
"{",
"timeoutInterval",
":=",
"defaultEventuallyTimeout",
"\n",
"pollingInterval",
":=",
"defaultEventuallyPollingInterval",
"\n",
"if",
"len",
"(",
"intervals",
")",
">",
"0",
"{",
"timeoutInterval",
"=",
"toDuration",
"(",
"intervals",
"[",
"0",
"]",
")",
"\n",
"}",
"\n",
"if",
"len",
"(",
"intervals",
")",
">",
"1",
"{",
"pollingInterval",
"=",
"toDuration",
"(",
"intervals",
"[",
"1",
"]",
")",
"\n",
"}",
"\n",
"return",
"asyncassertion",
".",
"New",
"(",
"asyncassertion",
".",
"AsyncAssertionTypeEventually",
",",
"actual",
",",
"testingtsupport",
".",
"BuildTestingTGomegaFailWrapper",
"(",
"g",
".",
"t",
")",
",",
"timeoutInterval",
",",
"pollingInterval",
",",
"0",
")",
"\n",
"}"
] |
// Eventually is used to make asynchronous assertions. See documentation for Eventually.
|
[
"Eventually",
"is",
"used",
"to",
"make",
"asynchronous",
"assertions",
".",
"See",
"documentation",
"for",
"Eventually",
"."
] |
f0e010e04c08c48a875f83d17df37b04eb3a985b
|
https://github.com/onsi/gomega/blob/f0e010e04c08c48a875f83d17df37b04eb3a985b/gomega_dsl.go#L380-L390
|
test
|
onsi/gomega
|
gomega_dsl.go
|
Consistently
|
func (g *WithT) Consistently(actual interface{}, intervals ...interface{}) AsyncAssertion {
timeoutInterval := defaultConsistentlyDuration
pollingInterval := defaultConsistentlyPollingInterval
if len(intervals) > 0 {
timeoutInterval = toDuration(intervals[0])
}
if len(intervals) > 1 {
pollingInterval = toDuration(intervals[1])
}
return asyncassertion.New(asyncassertion.AsyncAssertionTypeConsistently, actual, testingtsupport.BuildTestingTGomegaFailWrapper(g.t), timeoutInterval, pollingInterval, 0)
}
|
go
|
func (g *WithT) Consistently(actual interface{}, intervals ...interface{}) AsyncAssertion {
timeoutInterval := defaultConsistentlyDuration
pollingInterval := defaultConsistentlyPollingInterval
if len(intervals) > 0 {
timeoutInterval = toDuration(intervals[0])
}
if len(intervals) > 1 {
pollingInterval = toDuration(intervals[1])
}
return asyncassertion.New(asyncassertion.AsyncAssertionTypeConsistently, actual, testingtsupport.BuildTestingTGomegaFailWrapper(g.t), timeoutInterval, pollingInterval, 0)
}
|
[
"func",
"(",
"g",
"*",
"WithT",
")",
"Consistently",
"(",
"actual",
"interface",
"{",
"}",
",",
"intervals",
"...",
"interface",
"{",
"}",
")",
"AsyncAssertion",
"{",
"timeoutInterval",
":=",
"defaultConsistentlyDuration",
"\n",
"pollingInterval",
":=",
"defaultConsistentlyPollingInterval",
"\n",
"if",
"len",
"(",
"intervals",
")",
">",
"0",
"{",
"timeoutInterval",
"=",
"toDuration",
"(",
"intervals",
"[",
"0",
"]",
")",
"\n",
"}",
"\n",
"if",
"len",
"(",
"intervals",
")",
">",
"1",
"{",
"pollingInterval",
"=",
"toDuration",
"(",
"intervals",
"[",
"1",
"]",
")",
"\n",
"}",
"\n",
"return",
"asyncassertion",
".",
"New",
"(",
"asyncassertion",
".",
"AsyncAssertionTypeConsistently",
",",
"actual",
",",
"testingtsupport",
".",
"BuildTestingTGomegaFailWrapper",
"(",
"g",
".",
"t",
")",
",",
"timeoutInterval",
",",
"pollingInterval",
",",
"0",
")",
"\n",
"}"
] |
// Consistently is used to make asynchronous assertions. See documentation for Consistently.
|
[
"Consistently",
"is",
"used",
"to",
"make",
"asynchronous",
"assertions",
".",
"See",
"documentation",
"for",
"Consistently",
"."
] |
f0e010e04c08c48a875f83d17df37b04eb3a985b
|
https://github.com/onsi/gomega/blob/f0e010e04c08c48a875f83d17df37b04eb3a985b/gomega_dsl.go#L393-L403
|
test
|
onsi/gomega
|
gbytes/io_wrappers.go
|
TimeoutCloser
|
func TimeoutCloser(c io.Closer, timeout time.Duration) io.Closer {
return timeoutReaderWriterCloser{c: c, d: timeout}
}
|
go
|
func TimeoutCloser(c io.Closer, timeout time.Duration) io.Closer {
return timeoutReaderWriterCloser{c: c, d: timeout}
}
|
[
"func",
"TimeoutCloser",
"(",
"c",
"io",
".",
"Closer",
",",
"timeout",
"time",
".",
"Duration",
")",
"io",
".",
"Closer",
"{",
"return",
"timeoutReaderWriterCloser",
"{",
"c",
":",
"c",
",",
"d",
":",
"timeout",
"}",
"\n",
"}"
] |
// TimeoutCloser returns an io.Closer that wraps the passed-in io.Closer. If the underlying Closer fails to close within the alloted timeout ErrTimeout is returned.
|
[
"TimeoutCloser",
"returns",
"an",
"io",
".",
"Closer",
"that",
"wraps",
"the",
"passed",
"-",
"in",
"io",
".",
"Closer",
".",
"If",
"the",
"underlying",
"Closer",
"fails",
"to",
"close",
"within",
"the",
"alloted",
"timeout",
"ErrTimeout",
"is",
"returned",
"."
] |
f0e010e04c08c48a875f83d17df37b04eb3a985b
|
https://github.com/onsi/gomega/blob/f0e010e04c08c48a875f83d17df37b04eb3a985b/gbytes/io_wrappers.go#L13-L15
|
test
|
onsi/gomega
|
gbytes/io_wrappers.go
|
TimeoutReader
|
func TimeoutReader(r io.Reader, timeout time.Duration) io.Reader {
return timeoutReaderWriterCloser{r: r, d: timeout}
}
|
go
|
func TimeoutReader(r io.Reader, timeout time.Duration) io.Reader {
return timeoutReaderWriterCloser{r: r, d: timeout}
}
|
[
"func",
"TimeoutReader",
"(",
"r",
"io",
".",
"Reader",
",",
"timeout",
"time",
".",
"Duration",
")",
"io",
".",
"Reader",
"{",
"return",
"timeoutReaderWriterCloser",
"{",
"r",
":",
"r",
",",
"d",
":",
"timeout",
"}",
"\n",
"}"
] |
// TimeoutReader returns an io.Reader that wraps the passed-in io.Reader. If the underlying Reader fails to read within the alloted timeout ErrTimeout is returned.
|
[
"TimeoutReader",
"returns",
"an",
"io",
".",
"Reader",
"that",
"wraps",
"the",
"passed",
"-",
"in",
"io",
".",
"Reader",
".",
"If",
"the",
"underlying",
"Reader",
"fails",
"to",
"read",
"within",
"the",
"alloted",
"timeout",
"ErrTimeout",
"is",
"returned",
"."
] |
f0e010e04c08c48a875f83d17df37b04eb3a985b
|
https://github.com/onsi/gomega/blob/f0e010e04c08c48a875f83d17df37b04eb3a985b/gbytes/io_wrappers.go#L18-L20
|
test
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.