id int32 0 167k | repo stringlengths 5 54 | path stringlengths 4 155 | func_name stringlengths 1 118 | original_string stringlengths 52 85.5k | language stringclasses 1
value | code stringlengths 52 85.5k | code_tokens list | docstring stringlengths 6 2.61k | docstring_tokens list | sha stringlengths 40 40 | url stringlengths 85 252 |
|---|---|---|---|---|---|---|---|---|---|---|---|
5,900 | cloudfoundry/bbs | db/sqldb/lrp_convergence.go | lrpInstanceCounts | func (c *convergence) lrpInstanceCounts(logger lager.Logger, domainSet map[string]struct{}) {
logger = logger.Session("lrp-instance-counts")
rows, err := c.selectLRPInstanceCounts(logger, c.db)
if err != nil {
logger.Error("failed-query", err)
return
}
for rows.Next() {
var existingIndicesStr sql.NullString
var actualInstances int
schedulingInfo, err := c.fetchDesiredLRPSchedulingInfoAndMore(logger, rows, &actualInstances, &existingIndicesStr)
if err != nil {
continue
}
indices := []int{}
existingIndices := make(map[int]struct{})
if existingIndicesStr.String != "" {
for _, indexStr := range strings.Split(existingIndicesStr.String, ",") {
index, err := strconv.Atoi(indexStr)
if err != nil {
logger.Error("cannot-parse-index", err, lager.Data{
"index": indexStr,
"existing-indices-str": existingIndicesStr,
})
return
}
existingIndices[index] = struct{}{}
}
}
for i := 0; i < int(schedulingInfo.Instances); i++ {
_, found := existingIndices[i]
if found {
continue
}
indices = append(indices, i)
index := int32(i)
c.missingLRPKeys = append(c.missingLRPKeys, &models.ActualLRPKeyWithSchedulingInfo{
Key: &models.ActualLRPKey{
ProcessGuid: schedulingInfo.ProcessGuid,
Domain: schedulingInfo.Domain,
Index: index,
},
SchedulingInfo: schedulingInfo,
})
logger.Info("creating-start-request",
lager.Data{"reason": "missing-instance", "process_guid": schedulingInfo.ProcessGuid, "index": index})
}
for index := range existingIndices {
if index < int(schedulingInfo.Instances) {
continue
}
// only take destructive actions for fresh domains
if _, ok := domainSet[schedulingInfo.Domain]; ok {
c.keysToRetire = append(c.keysToRetire, &models.ActualLRPKey{
ProcessGuid: schedulingInfo.ProcessGuid,
Index: int32(index),
Domain: schedulingInfo.Domain,
})
}
}
}
if rows.Err() != nil {
logger.Error("failed-getting-next-row", rows.Err())
}
} | go | func (c *convergence) lrpInstanceCounts(logger lager.Logger, domainSet map[string]struct{}) {
logger = logger.Session("lrp-instance-counts")
rows, err := c.selectLRPInstanceCounts(logger, c.db)
if err != nil {
logger.Error("failed-query", err)
return
}
for rows.Next() {
var existingIndicesStr sql.NullString
var actualInstances int
schedulingInfo, err := c.fetchDesiredLRPSchedulingInfoAndMore(logger, rows, &actualInstances, &existingIndicesStr)
if err != nil {
continue
}
indices := []int{}
existingIndices := make(map[int]struct{})
if existingIndicesStr.String != "" {
for _, indexStr := range strings.Split(existingIndicesStr.String, ",") {
index, err := strconv.Atoi(indexStr)
if err != nil {
logger.Error("cannot-parse-index", err, lager.Data{
"index": indexStr,
"existing-indices-str": existingIndicesStr,
})
return
}
existingIndices[index] = struct{}{}
}
}
for i := 0; i < int(schedulingInfo.Instances); i++ {
_, found := existingIndices[i]
if found {
continue
}
indices = append(indices, i)
index := int32(i)
c.missingLRPKeys = append(c.missingLRPKeys, &models.ActualLRPKeyWithSchedulingInfo{
Key: &models.ActualLRPKey{
ProcessGuid: schedulingInfo.ProcessGuid,
Domain: schedulingInfo.Domain,
Index: index,
},
SchedulingInfo: schedulingInfo,
})
logger.Info("creating-start-request",
lager.Data{"reason": "missing-instance", "process_guid": schedulingInfo.ProcessGuid, "index": index})
}
for index := range existingIndices {
if index < int(schedulingInfo.Instances) {
continue
}
// only take destructive actions for fresh domains
if _, ok := domainSet[schedulingInfo.Domain]; ok {
c.keysToRetire = append(c.keysToRetire, &models.ActualLRPKey{
ProcessGuid: schedulingInfo.ProcessGuid,
Index: int32(index),
Domain: schedulingInfo.Domain,
})
}
}
}
if rows.Err() != nil {
logger.Error("failed-getting-next-row", rows.Err())
}
} | [
"func",
"(",
"c",
"*",
"convergence",
")",
"lrpInstanceCounts",
"(",
"logger",
"lager",
".",
"Logger",
",",
"domainSet",
"map",
"[",
"string",
"]",
"struct",
"{",
"}",
")",
"{",
"logger",
"=",
"logger",
".",
"Session",
"(",
"\"",
"\"",
")",
"\n\n",
"... | // Creates and adds missing Actual LRPs to the list of start requests.
// Adds extra Actual LRPs to the list of keys to retire. | [
"Creates",
"and",
"adds",
"missing",
"Actual",
"LRPs",
"to",
"the",
"list",
"of",
"start",
"requests",
".",
"Adds",
"extra",
"Actual",
"LRPs",
"to",
"the",
"list",
"of",
"keys",
"to",
"retire",
"."
] | 1978bb997cbd2527cc4fa52798b0af6f6d899698 | https://github.com/cloudfoundry/bbs/blob/1978bb997cbd2527cc4fa52798b0af6f6d899698/db/sqldb/lrp_convergence.go#L241-L314 |
5,901 | cloudfoundry/buildpackapplifecycle | buildpackrunner/runner.go | runSupplyBuildpacks | func (runner *Runner) runSupplyBuildpacks() (string, string, error) {
if err := runner.validateSupplyBuildpacks(); err != nil {
return "", "", err
}
for i, buildpack := range runner.config.SupplyBuildpacks() {
buildpackPath, err := runner.buildpackPath(buildpack)
if err != nil {
printError(err.Error())
return "", "", newDescriptiveError(err, buildpackapplifecycle.SupplyFailMsg)
}
err = runner.run(exec.Command(filepath.Join(buildpackPath, "bin", "supply"), runner.config.BuildDir(), runner.supplyCachePath(buildpack), runner.depsDir, runner.config.DepsIndex(i)), os.Stdout)
if err != nil {
return "", "", newDescriptiveError(err, buildpackapplifecycle.SupplyFailMsg)
}
}
finalBuildpack := runner.config.BuildpackOrder()[len(runner.config.SupplyBuildpacks())]
finalPath, err := runner.buildpackPath(finalBuildpack)
if err != nil {
return "", "", newDescriptiveError(err, buildpackapplifecycle.SupplyFailMsg)
}
return finalBuildpack, finalPath, nil
} | go | func (runner *Runner) runSupplyBuildpacks() (string, string, error) {
if err := runner.validateSupplyBuildpacks(); err != nil {
return "", "", err
}
for i, buildpack := range runner.config.SupplyBuildpacks() {
buildpackPath, err := runner.buildpackPath(buildpack)
if err != nil {
printError(err.Error())
return "", "", newDescriptiveError(err, buildpackapplifecycle.SupplyFailMsg)
}
err = runner.run(exec.Command(filepath.Join(buildpackPath, "bin", "supply"), runner.config.BuildDir(), runner.supplyCachePath(buildpack), runner.depsDir, runner.config.DepsIndex(i)), os.Stdout)
if err != nil {
return "", "", newDescriptiveError(err, buildpackapplifecycle.SupplyFailMsg)
}
}
finalBuildpack := runner.config.BuildpackOrder()[len(runner.config.SupplyBuildpacks())]
finalPath, err := runner.buildpackPath(finalBuildpack)
if err != nil {
return "", "", newDescriptiveError(err, buildpackapplifecycle.SupplyFailMsg)
}
return finalBuildpack, finalPath, nil
} | [
"func",
"(",
"runner",
"*",
"Runner",
")",
"runSupplyBuildpacks",
"(",
")",
"(",
"string",
",",
"string",
",",
"error",
")",
"{",
"if",
"err",
":=",
"runner",
".",
"validateSupplyBuildpacks",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"\"",
"\""... | // returns buildpack path, ok | [
"returns",
"buildpack",
"path",
"ok"
] | 5a0eeb8db891a528b4e44a7cd1fd47123a874ad1 | https://github.com/cloudfoundry/buildpackapplifecycle/blob/5a0eeb8db891a528b4e44a7cd1fd47123a874ad1/buildpackrunner/runner.go#L337-L361 |
5,902 | cloudfoundry/buildpackapplifecycle | buildpackrunner/runner.go | detect | func (runner *Runner) detect() (string, string, string, bool) {
for _, buildpack := range runner.config.BuildpackOrder() {
buildpackPath, err := runner.buildpackPath(buildpack)
if err != nil {
printError(err.Error())
continue
}
if runner.config.SkipDetect() {
return buildpack, buildpackPath, "", true
}
if err := runner.warnIfDetectNotExecutable(buildpackPath); err != nil {
printError(err.Error())
continue
}
output := new(bytes.Buffer)
err = runner.run(exec.Command(filepath.Join(buildpackPath, "bin", "detect"), runner.config.BuildDir()), output)
if err == nil {
return buildpack, buildpackPath, strings.TrimRight(output.String(), "\r\n"), true
}
}
return "", "", "", false
} | go | func (runner *Runner) detect() (string, string, string, bool) {
for _, buildpack := range runner.config.BuildpackOrder() {
buildpackPath, err := runner.buildpackPath(buildpack)
if err != nil {
printError(err.Error())
continue
}
if runner.config.SkipDetect() {
return buildpack, buildpackPath, "", true
}
if err := runner.warnIfDetectNotExecutable(buildpackPath); err != nil {
printError(err.Error())
continue
}
output := new(bytes.Buffer)
err = runner.run(exec.Command(filepath.Join(buildpackPath, "bin", "detect"), runner.config.BuildDir()), output)
if err == nil {
return buildpack, buildpackPath, strings.TrimRight(output.String(), "\r\n"), true
}
}
return "", "", "", false
} | [
"func",
"(",
"runner",
"*",
"Runner",
")",
"detect",
"(",
")",
"(",
"string",
",",
"string",
",",
"string",
",",
"bool",
")",
"{",
"for",
"_",
",",
"buildpack",
":=",
"range",
"runner",
".",
"config",
".",
"BuildpackOrder",
"(",
")",
"{",
"buildpackP... | // returns buildpack name, buildpack path, buildpack detect output, ok | [
"returns",
"buildpack",
"name",
"buildpack",
"path",
"buildpack",
"detect",
"output",
"ok"
] | 5a0eeb8db891a528b4e44a7cd1fd47123a874ad1 | https://github.com/cloudfoundry/buildpackapplifecycle/blob/5a0eeb8db891a528b4e44a7cd1fd47123a874ad1/buildpackrunner/runner.go#L423-L450 |
5,903 | yhat/scrape | scrape.go | FindAll | func FindAll(node *html.Node, matcher Matcher) []*html.Node {
return findAllInternal(node, matcher, false)
} | go | func FindAll(node *html.Node, matcher Matcher) []*html.Node {
return findAllInternal(node, matcher, false)
} | [
"func",
"FindAll",
"(",
"node",
"*",
"html",
".",
"Node",
",",
"matcher",
"Matcher",
")",
"[",
"]",
"*",
"html",
".",
"Node",
"{",
"return",
"findAllInternal",
"(",
"node",
",",
"matcher",
",",
"false",
")",
"\n",
"}"
] | // FindAll returns all nodes which match the provided Matcher. After discovering a matching
// node, it will _not_ discover matching subnodes of that node. | [
"FindAll",
"returns",
"all",
"nodes",
"which",
"match",
"the",
"provided",
"Matcher",
".",
"After",
"discovering",
"a",
"matching",
"node",
"it",
"will",
"_not_",
"discover",
"matching",
"subnodes",
"of",
"that",
"node",
"."
] | 24b7890b0945459dbf91743e4d2ac5d75a51fee2 | https://github.com/yhat/scrape/blob/24b7890b0945459dbf91743e4d2ac5d75a51fee2/scrape.go#L16-L18 |
5,904 | yhat/scrape | scrape.go | FindAllNested | func FindAllNested(node *html.Node, matcher Matcher) []*html.Node {
return findAllInternal(node, matcher, true)
} | go | func FindAllNested(node *html.Node, matcher Matcher) []*html.Node {
return findAllInternal(node, matcher, true)
} | [
"func",
"FindAllNested",
"(",
"node",
"*",
"html",
".",
"Node",
",",
"matcher",
"Matcher",
")",
"[",
"]",
"*",
"html",
".",
"Node",
"{",
"return",
"findAllInternal",
"(",
"node",
",",
"matcher",
",",
"true",
")",
"\n",
"}"
] | // FindAllNested returns all nodes which match the provided Matcher and _will_ discover
// matching subnodes of matching nodes. | [
"FindAllNested",
"returns",
"all",
"nodes",
"which",
"match",
"the",
"provided",
"Matcher",
"and",
"_will_",
"discover",
"matching",
"subnodes",
"of",
"matching",
"nodes",
"."
] | 24b7890b0945459dbf91743e4d2ac5d75a51fee2 | https://github.com/yhat/scrape/blob/24b7890b0945459dbf91743e4d2ac5d75a51fee2/scrape.go#L22-L24 |
5,905 | yhat/scrape | scrape.go | FindParent | func FindParent(node *html.Node, matcher Matcher) (n *html.Node, ok bool) {
for p := node.Parent; p != nil; p = p.Parent {
if matcher(p) {
return p, true
}
}
return nil, false
} | go | func FindParent(node *html.Node, matcher Matcher) (n *html.Node, ok bool) {
for p := node.Parent; p != nil; p = p.Parent {
if matcher(p) {
return p, true
}
}
return nil, false
} | [
"func",
"FindParent",
"(",
"node",
"*",
"html",
".",
"Node",
",",
"matcher",
"Matcher",
")",
"(",
"n",
"*",
"html",
".",
"Node",
",",
"ok",
"bool",
")",
"{",
"for",
"p",
":=",
"node",
".",
"Parent",
";",
"p",
"!=",
"nil",
";",
"p",
"=",
"p",
... | // FindParent searches up HTML tree from the current node until either a
// match is found or the top is hit. | [
"FindParent",
"searches",
"up",
"HTML",
"tree",
"from",
"the",
"current",
"node",
"until",
"either",
"a",
"match",
"is",
"found",
"or",
"the",
"top",
"is",
"hit",
"."
] | 24b7890b0945459dbf91743e4d2ac5d75a51fee2 | https://github.com/yhat/scrape/blob/24b7890b0945459dbf91743e4d2ac5d75a51fee2/scrape.go#L53-L60 |
5,906 | yhat/scrape | scrape.go | Text | func Text(node *html.Node) string {
joiner := func(s []string) string {
n := 0
for i := range s {
trimmed := strings.TrimSpace(s[i])
if trimmed != "" {
s[n] = trimmed
n++
}
}
return strings.Join(s[:n], " ")
}
return TextJoin(node, joiner)
} | go | func Text(node *html.Node) string {
joiner := func(s []string) string {
n := 0
for i := range s {
trimmed := strings.TrimSpace(s[i])
if trimmed != "" {
s[n] = trimmed
n++
}
}
return strings.Join(s[:n], " ")
}
return TextJoin(node, joiner)
} | [
"func",
"Text",
"(",
"node",
"*",
"html",
".",
"Node",
")",
"string",
"{",
"joiner",
":=",
"func",
"(",
"s",
"[",
"]",
"string",
")",
"string",
"{",
"n",
":=",
"0",
"\n",
"for",
"i",
":=",
"range",
"s",
"{",
"trimmed",
":=",
"strings",
".",
"Tr... | // Text returns text from all descendant text nodes joined.
// For control over the join function, see TextJoin. | [
"Text",
"returns",
"text",
"from",
"all",
"descendant",
"text",
"nodes",
"joined",
".",
"For",
"control",
"over",
"the",
"join",
"function",
"see",
"TextJoin",
"."
] | 24b7890b0945459dbf91743e4d2ac5d75a51fee2 | https://github.com/yhat/scrape/blob/24b7890b0945459dbf91743e4d2ac5d75a51fee2/scrape.go#L64-L77 |
5,907 | yhat/scrape | scrape.go | TextJoin | func TextJoin(node *html.Node, join func([]string) string) string {
nodes := FindAll(node, func(n *html.Node) bool { return n.Type == html.TextNode })
parts := make([]string, len(nodes))
for i, n := range nodes {
parts[i] = n.Data
}
return join(parts)
} | go | func TextJoin(node *html.Node, join func([]string) string) string {
nodes := FindAll(node, func(n *html.Node) bool { return n.Type == html.TextNode })
parts := make([]string, len(nodes))
for i, n := range nodes {
parts[i] = n.Data
}
return join(parts)
} | [
"func",
"TextJoin",
"(",
"node",
"*",
"html",
".",
"Node",
",",
"join",
"func",
"(",
"[",
"]",
"string",
")",
"string",
")",
"string",
"{",
"nodes",
":=",
"FindAll",
"(",
"node",
",",
"func",
"(",
"n",
"*",
"html",
".",
"Node",
")",
"bool",
"{",
... | // TextJoin returns a string from all descendant text nodes joined by a
// caller provided join function. | [
"TextJoin",
"returns",
"a",
"string",
"from",
"all",
"descendant",
"text",
"nodes",
"joined",
"by",
"a",
"caller",
"provided",
"join",
"function",
"."
] | 24b7890b0945459dbf91743e4d2ac5d75a51fee2 | https://github.com/yhat/scrape/blob/24b7890b0945459dbf91743e4d2ac5d75a51fee2/scrape.go#L81-L88 |
5,908 | yhat/scrape | scrape.go | Attr | func Attr(node *html.Node, key string) string {
for _, a := range node.Attr {
if a.Key == key {
return a.Val
}
}
return ""
} | go | func Attr(node *html.Node, key string) string {
for _, a := range node.Attr {
if a.Key == key {
return a.Val
}
}
return ""
} | [
"func",
"Attr",
"(",
"node",
"*",
"html",
".",
"Node",
",",
"key",
"string",
")",
"string",
"{",
"for",
"_",
",",
"a",
":=",
"range",
"node",
".",
"Attr",
"{",
"if",
"a",
".",
"Key",
"==",
"key",
"{",
"return",
"a",
".",
"Val",
"\n",
"}",
"\n... | // Attr returns the value of an HTML attribute. | [
"Attr",
"returns",
"the",
"value",
"of",
"an",
"HTML",
"attribute",
"."
] | 24b7890b0945459dbf91743e4d2ac5d75a51fee2 | https://github.com/yhat/scrape/blob/24b7890b0945459dbf91743e4d2ac5d75a51fee2/scrape.go#L91-L98 |
5,909 | yhat/scrape | scrape.go | ById | func ById(id string) Matcher {
return func(node *html.Node) bool { return Attr(node, "id") == id }
} | go | func ById(id string) Matcher {
return func(node *html.Node) bool { return Attr(node, "id") == id }
} | [
"func",
"ById",
"(",
"id",
"string",
")",
"Matcher",
"{",
"return",
"func",
"(",
"node",
"*",
"html",
".",
"Node",
")",
"bool",
"{",
"return",
"Attr",
"(",
"node",
",",
"\"",
"\"",
")",
"==",
"id",
"}",
"\n",
"}"
] | // ById returns a Matcher which matches all nodes with the provided id. | [
"ById",
"returns",
"a",
"Matcher",
"which",
"matches",
"all",
"nodes",
"with",
"the",
"provided",
"id",
"."
] | 24b7890b0945459dbf91743e4d2ac5d75a51fee2 | https://github.com/yhat/scrape/blob/24b7890b0945459dbf91743e4d2ac5d75a51fee2/scrape.go#L112-L114 |
5,910 | yhat/scrape | scrape.go | ByClass | func ByClass(class string) Matcher {
return func(node *html.Node) bool {
classes := strings.Fields(Attr(node, "class"))
for _, c := range classes {
if c == class {
return true
}
}
return false
}
} | go | func ByClass(class string) Matcher {
return func(node *html.Node) bool {
classes := strings.Fields(Attr(node, "class"))
for _, c := range classes {
if c == class {
return true
}
}
return false
}
} | [
"func",
"ByClass",
"(",
"class",
"string",
")",
"Matcher",
"{",
"return",
"func",
"(",
"node",
"*",
"html",
".",
"Node",
")",
"bool",
"{",
"classes",
":=",
"strings",
".",
"Fields",
"(",
"Attr",
"(",
"node",
",",
"\"",
"\"",
")",
")",
"\n",
"for",
... | // ByClass returns a Matcher which matches all nodes with the provided class. | [
"ByClass",
"returns",
"a",
"Matcher",
"which",
"matches",
"all",
"nodes",
"with",
"the",
"provided",
"class",
"."
] | 24b7890b0945459dbf91743e4d2ac5d75a51fee2 | https://github.com/yhat/scrape/blob/24b7890b0945459dbf91743e4d2ac5d75a51fee2/scrape.go#L117-L127 |
5,911 | yhat/scrape | scrape.go | findAllInternal | func findAllInternal(node *html.Node, matcher Matcher, searchNested bool) []*html.Node {
matched := []*html.Node{}
if matcher(node) {
matched = append(matched, node)
if !searchNested {
return matched
}
}
for c := node.FirstChild; c != nil; c = c.NextSibling {
found := findAllInternal(c, matcher, searchNested)
if len(found) > 0 {
matched = append(matched, found...)
}
}
return matched
} | go | func findAllInternal(node *html.Node, matcher Matcher, searchNested bool) []*html.Node {
matched := []*html.Node{}
if matcher(node) {
matched = append(matched, node)
if !searchNested {
return matched
}
}
for c := node.FirstChild; c != nil; c = c.NextSibling {
found := findAllInternal(c, matcher, searchNested)
if len(found) > 0 {
matched = append(matched, found...)
}
}
return matched
} | [
"func",
"findAllInternal",
"(",
"node",
"*",
"html",
".",
"Node",
",",
"matcher",
"Matcher",
",",
"searchNested",
"bool",
")",
"[",
"]",
"*",
"html",
".",
"Node",
"{",
"matched",
":=",
"[",
"]",
"*",
"html",
".",
"Node",
"{",
"}",
"\n\n",
"if",
"ma... | // findAllInternal encapsulates the node tree traversal | [
"findAllInternal",
"encapsulates",
"the",
"node",
"tree",
"traversal"
] | 24b7890b0945459dbf91743e4d2ac5d75a51fee2 | https://github.com/yhat/scrape/blob/24b7890b0945459dbf91743e4d2ac5d75a51fee2/scrape.go#L130-L148 |
5,912 | docker/go-units | size.go | CustomSize | func CustomSize(format string, size float64, base float64, _map []string) string {
size, unit := getSizeAndUnit(size, base, _map)
return fmt.Sprintf(format, size, unit)
} | go | func CustomSize(format string, size float64, base float64, _map []string) string {
size, unit := getSizeAndUnit(size, base, _map)
return fmt.Sprintf(format, size, unit)
} | [
"func",
"CustomSize",
"(",
"format",
"string",
",",
"size",
"float64",
",",
"base",
"float64",
",",
"_map",
"[",
"]",
"string",
")",
"string",
"{",
"size",
",",
"unit",
":=",
"getSizeAndUnit",
"(",
"size",
",",
"base",
",",
"_map",
")",
"\n",
"return",... | // CustomSize returns a human-readable approximation of a size
// using custom format. | [
"CustomSize",
"returns",
"a",
"human",
"-",
"readable",
"approximation",
"of",
"a",
"size",
"using",
"custom",
"format",
"."
] | 519db1ee28dcc9fd2474ae59fca29a810482bfb1 | https://github.com/docker/go-units/blob/519db1ee28dcc9fd2474ae59fca29a810482bfb1/size.go#L52-L55 |
5,913 | docker/go-units | size.go | HumanSizeWithPrecision | func HumanSizeWithPrecision(size float64, precision int) string {
size, unit := getSizeAndUnit(size, 1000.0, decimapAbbrs)
return fmt.Sprintf("%.*g%s", precision, size, unit)
} | go | func HumanSizeWithPrecision(size float64, precision int) string {
size, unit := getSizeAndUnit(size, 1000.0, decimapAbbrs)
return fmt.Sprintf("%.*g%s", precision, size, unit)
} | [
"func",
"HumanSizeWithPrecision",
"(",
"size",
"float64",
",",
"precision",
"int",
")",
"string",
"{",
"size",
",",
"unit",
":=",
"getSizeAndUnit",
"(",
"size",
",",
"1000.0",
",",
"decimapAbbrs",
")",
"\n",
"return",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\""... | // HumanSizeWithPrecision allows the size to be in any precision,
// instead of 4 digit precision used in units.HumanSize. | [
"HumanSizeWithPrecision",
"allows",
"the",
"size",
"to",
"be",
"in",
"any",
"precision",
"instead",
"of",
"4",
"digit",
"precision",
"used",
"in",
"units",
".",
"HumanSize",
"."
] | 519db1ee28dcc9fd2474ae59fca29a810482bfb1 | https://github.com/docker/go-units/blob/519db1ee28dcc9fd2474ae59fca29a810482bfb1/size.go#L59-L62 |
5,914 | STNS/STNS | model/backend_toml_file.go | tomlHighLowID | func tomlHighLowID(highorlow int, list map[string]UserGroup) int {
current := 0
if list != nil {
for _, v := range list {
if current == 0 || (highorlow == 0 && current < v.GetID()) || (highorlow == 1 && current > v.GetID()) {
current = v.GetID()
}
}
}
return current
} | go | func tomlHighLowID(highorlow int, list map[string]UserGroup) int {
current := 0
if list != nil {
for _, v := range list {
if current == 0 || (highorlow == 0 && current < v.GetID()) || (highorlow == 1 && current > v.GetID()) {
current = v.GetID()
}
}
}
return current
} | [
"func",
"tomlHighLowID",
"(",
"highorlow",
"int",
",",
"list",
"map",
"[",
"string",
"]",
"UserGroup",
")",
"int",
"{",
"current",
":=",
"0",
"\n",
"if",
"list",
"!=",
"nil",
"{",
"for",
"_",
",",
"v",
":=",
"range",
"list",
"{",
"if",
"current",
"... | // highest=0 lowest= 1 | [
"highest",
"=",
"0",
"lowest",
"=",
"1"
] | 189a00a7b4e36662d238e7a389464622c9561735 | https://github.com/STNS/STNS/blob/189a00a7b4e36662d238e7a389464622c9561735/model/backend_toml_file.go#L213-L223 |
5,915 | cpuguy83/go-md2man | md2man/roff.go | NewRoffRenderer | func NewRoffRenderer() *roffRenderer { // nolint: golint
var extensions blackfriday.Extensions
extensions |= blackfriday.NoIntraEmphasis
extensions |= blackfriday.Tables
extensions |= blackfriday.FencedCode
extensions |= blackfriday.SpaceHeadings
extensions |= blackfriday.Footnotes
extensions |= blackfriday.Titleblock
extensions |= blackfriday.DefinitionLists
return &roffRenderer{
extensions: extensions,
}
} | go | func NewRoffRenderer() *roffRenderer { // nolint: golint
var extensions blackfriday.Extensions
extensions |= blackfriday.NoIntraEmphasis
extensions |= blackfriday.Tables
extensions |= blackfriday.FencedCode
extensions |= blackfriday.SpaceHeadings
extensions |= blackfriday.Footnotes
extensions |= blackfriday.Titleblock
extensions |= blackfriday.DefinitionLists
return &roffRenderer{
extensions: extensions,
}
} | [
"func",
"NewRoffRenderer",
"(",
")",
"*",
"roffRenderer",
"{",
"// nolint: golint",
"var",
"extensions",
"blackfriday",
".",
"Extensions",
"\n\n",
"extensions",
"|=",
"blackfriday",
".",
"NoIntraEmphasis",
"\n",
"extensions",
"|=",
"blackfriday",
".",
"Tables",
"\n"... | // NewRoffRenderer creates a new blackfriday Renderer for generating roff documents
// from markdown | [
"NewRoffRenderer",
"creates",
"a",
"new",
"blackfriday",
"Renderer",
"for",
"generating",
"roff",
"documents",
"from",
"markdown"
] | f79a8a8ca69da163eee19ab442bedad7a35bba5a | https://github.com/cpuguy83/go-md2man/blob/f79a8a8ca69da163eee19ab442bedad7a35bba5a/md2man/roff.go#L54-L67 |
5,916 | cpuguy83/go-md2man | md2man/roff.go | RenderHeader | func (r *roffRenderer) RenderHeader(w io.Writer, ast *blackfriday.Node) {
// disable hyphenation
out(w, ".nh\n")
} | go | func (r *roffRenderer) RenderHeader(w io.Writer, ast *blackfriday.Node) {
// disable hyphenation
out(w, ".nh\n")
} | [
"func",
"(",
"r",
"*",
"roffRenderer",
")",
"RenderHeader",
"(",
"w",
"io",
".",
"Writer",
",",
"ast",
"*",
"blackfriday",
".",
"Node",
")",
"{",
"// disable hyphenation",
"out",
"(",
"w",
",",
"\"",
"\\n",
"\"",
")",
"\n",
"}"
] | // RenderHeader handles outputting the header at document start | [
"RenderHeader",
"handles",
"outputting",
"the",
"header",
"at",
"document",
"start"
] | f79a8a8ca69da163eee19ab442bedad7a35bba5a | https://github.com/cpuguy83/go-md2man/blob/f79a8a8ca69da163eee19ab442bedad7a35bba5a/md2man/roff.go#L75-L78 |
5,917 | cpuguy83/go-md2man | md2man/roff.go | RenderNode | func (r *roffRenderer) RenderNode(w io.Writer, node *blackfriday.Node, entering bool) blackfriday.WalkStatus {
var walkAction = blackfriday.GoToNext
switch node.Type {
case blackfriday.Text:
r.handleText(w, node, entering)
case blackfriday.Softbreak:
out(w, crTag)
case blackfriday.Hardbreak:
out(w, breakTag)
case blackfriday.Emph:
if entering {
out(w, emphTag)
} else {
out(w, emphCloseTag)
}
case blackfriday.Strong:
if entering {
out(w, strongTag)
} else {
out(w, strongCloseTag)
}
case blackfriday.Link:
if !entering {
out(w, linkTag+string(node.LinkData.Destination)+linkCloseTag)
}
case blackfriday.Image:
// ignore images
walkAction = blackfriday.SkipChildren
case blackfriday.Code:
out(w, codespanTag)
escapeSpecialChars(w, node.Literal)
out(w, codespanCloseTag)
case blackfriday.Document:
break
case blackfriday.Paragraph:
// roff .PP markers break lists
if r.listDepth > 0 {
return blackfriday.GoToNext
}
if entering {
out(w, paraTag)
} else {
out(w, crTag)
}
case blackfriday.BlockQuote:
if entering {
out(w, quoteTag)
} else {
out(w, quoteCloseTag)
}
case blackfriday.Heading:
r.handleHeading(w, node, entering)
case blackfriday.HorizontalRule:
out(w, hruleTag)
case blackfriday.List:
r.handleList(w, node, entering)
case blackfriday.Item:
r.handleItem(w, node, entering)
case blackfriday.CodeBlock:
out(w, codeTag)
escapeSpecialChars(w, node.Literal)
out(w, codeCloseTag)
case blackfriday.Table:
r.handleTable(w, node, entering)
case blackfriday.TableCell:
r.handleTableCell(w, node, entering)
case blackfriday.TableHead:
case blackfriday.TableBody:
case blackfriday.TableRow:
// no action as cell entries do all the nroff formatting
return blackfriday.GoToNext
default:
fmt.Fprintln(os.Stderr, "WARNING: go-md2man does not handle node type "+node.Type.String())
}
return walkAction
} | go | func (r *roffRenderer) RenderNode(w io.Writer, node *blackfriday.Node, entering bool) blackfriday.WalkStatus {
var walkAction = blackfriday.GoToNext
switch node.Type {
case blackfriday.Text:
r.handleText(w, node, entering)
case blackfriday.Softbreak:
out(w, crTag)
case blackfriday.Hardbreak:
out(w, breakTag)
case blackfriday.Emph:
if entering {
out(w, emphTag)
} else {
out(w, emphCloseTag)
}
case blackfriday.Strong:
if entering {
out(w, strongTag)
} else {
out(w, strongCloseTag)
}
case blackfriday.Link:
if !entering {
out(w, linkTag+string(node.LinkData.Destination)+linkCloseTag)
}
case blackfriday.Image:
// ignore images
walkAction = blackfriday.SkipChildren
case blackfriday.Code:
out(w, codespanTag)
escapeSpecialChars(w, node.Literal)
out(w, codespanCloseTag)
case blackfriday.Document:
break
case blackfriday.Paragraph:
// roff .PP markers break lists
if r.listDepth > 0 {
return blackfriday.GoToNext
}
if entering {
out(w, paraTag)
} else {
out(w, crTag)
}
case blackfriday.BlockQuote:
if entering {
out(w, quoteTag)
} else {
out(w, quoteCloseTag)
}
case blackfriday.Heading:
r.handleHeading(w, node, entering)
case blackfriday.HorizontalRule:
out(w, hruleTag)
case blackfriday.List:
r.handleList(w, node, entering)
case blackfriday.Item:
r.handleItem(w, node, entering)
case blackfriday.CodeBlock:
out(w, codeTag)
escapeSpecialChars(w, node.Literal)
out(w, codeCloseTag)
case blackfriday.Table:
r.handleTable(w, node, entering)
case blackfriday.TableCell:
r.handleTableCell(w, node, entering)
case blackfriday.TableHead:
case blackfriday.TableBody:
case blackfriday.TableRow:
// no action as cell entries do all the nroff formatting
return blackfriday.GoToNext
default:
fmt.Fprintln(os.Stderr, "WARNING: go-md2man does not handle node type "+node.Type.String())
}
return walkAction
} | [
"func",
"(",
"r",
"*",
"roffRenderer",
")",
"RenderNode",
"(",
"w",
"io",
".",
"Writer",
",",
"node",
"*",
"blackfriday",
".",
"Node",
",",
"entering",
"bool",
")",
"blackfriday",
".",
"WalkStatus",
"{",
"var",
"walkAction",
"=",
"blackfriday",
".",
"GoT... | // RenderNode is called for each node in a markdown document; based on the node
// type the equivalent roff output is sent to the writer | [
"RenderNode",
"is",
"called",
"for",
"each",
"node",
"in",
"a",
"markdown",
"document",
";",
"based",
"on",
"the",
"node",
"type",
"the",
"equivalent",
"roff",
"output",
"is",
"sent",
"to",
"the",
"writer"
] | f79a8a8ca69da163eee19ab442bedad7a35bba5a | https://github.com/cpuguy83/go-md2man/blob/f79a8a8ca69da163eee19ab442bedad7a35bba5a/md2man/roff.go#L87-L164 |
5,918 | cpuguy83/go-md2man | md2man/roff.go | countColumns | func countColumns(node *blackfriday.Node) int {
var columns int
node.Walk(func(node *blackfriday.Node, entering bool) blackfriday.WalkStatus {
switch node.Type {
case blackfriday.TableRow:
if !entering {
return blackfriday.Terminate
}
case blackfriday.TableCell:
if entering {
columns++
}
default:
}
return blackfriday.GoToNext
})
return columns
} | go | func countColumns(node *blackfriday.Node) int {
var columns int
node.Walk(func(node *blackfriday.Node, entering bool) blackfriday.WalkStatus {
switch node.Type {
case blackfriday.TableRow:
if !entering {
return blackfriday.Terminate
}
case blackfriday.TableCell:
if entering {
columns++
}
default:
}
return blackfriday.GoToNext
})
return columns
} | [
"func",
"countColumns",
"(",
"node",
"*",
"blackfriday",
".",
"Node",
")",
"int",
"{",
"var",
"columns",
"int",
"\n\n",
"node",
".",
"Walk",
"(",
"func",
"(",
"node",
"*",
"blackfriday",
".",
"Node",
",",
"entering",
"bool",
")",
"blackfriday",
".",
"W... | // because roff format requires knowing the column count before outputting any table
// data we need to walk a table tree and count the columns | [
"because",
"roff",
"format",
"requires",
"knowing",
"the",
"column",
"count",
"before",
"outputting",
"any",
"table",
"data",
"we",
"need",
"to",
"walk",
"a",
"table",
"tree",
"and",
"count",
"the",
"columns"
] | f79a8a8ca69da163eee19ab442bedad7a35bba5a | https://github.com/cpuguy83/go-md2man/blob/f79a8a8ca69da163eee19ab442bedad7a35bba5a/md2man/roff.go#L288-L306 |
5,919 | cpuguy83/go-md2man | md2man/md2man.go | Render | func Render(doc []byte) []byte {
renderer := NewRoffRenderer()
return blackfriday.Run(doc,
[]blackfriday.Option{blackfriday.WithRenderer(renderer),
blackfriday.WithExtensions(renderer.GetExtensions())}...)
} | go | func Render(doc []byte) []byte {
renderer := NewRoffRenderer()
return blackfriday.Run(doc,
[]blackfriday.Option{blackfriday.WithRenderer(renderer),
blackfriday.WithExtensions(renderer.GetExtensions())}...)
} | [
"func",
"Render",
"(",
"doc",
"[",
"]",
"byte",
")",
"[",
"]",
"byte",
"{",
"renderer",
":=",
"NewRoffRenderer",
"(",
")",
"\n\n",
"return",
"blackfriday",
".",
"Run",
"(",
"doc",
",",
"[",
"]",
"blackfriday",
".",
"Option",
"{",
"blackfriday",
".",
... | // Render converts a markdown document into a roff formatted document. | [
"Render",
"converts",
"a",
"markdown",
"document",
"into",
"a",
"roff",
"formatted",
"document",
"."
] | f79a8a8ca69da163eee19ab442bedad7a35bba5a | https://github.com/cpuguy83/go-md2man/blob/f79a8a8ca69da163eee19ab442bedad7a35bba5a/md2man/md2man.go#L8-L14 |
5,920 | RobotsAndPencils/buford | payload/badge/badge.go | String | func (b Badge) String() string {
if b.isSet {
return fmt.Sprintf("set %d", b.number)
}
return "preserve"
} | go | func (b Badge) String() string {
if b.isSet {
return fmt.Sprintf("set %d", b.number)
}
return "preserve"
} | [
"func",
"(",
"b",
"Badge",
")",
"String",
"(",
")",
"string",
"{",
"if",
"b",
".",
"isSet",
"{",
"return",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"b",
".",
"number",
")",
"\n",
"}",
"\n",
"return",
"\"",
"\"",
"\n",
"}"
] | // String prints out a badge | [
"String",
"prints",
"out",
"a",
"badge"
] | 75d85f30d5ffbe02a1fa39cb15c7a526ee70ab31 | https://github.com/RobotsAndPencils/buford/blob/75d85f30d5ffbe02a1fa39cb15c7a526ee70ab31/payload/badge/badge.go#L32-L37 |
5,921 | RobotsAndPencils/buford | push/service.go | NewService | func NewService(client *http.Client, host string) *Service {
return &Service{
Client: client,
Host: host,
}
} | go | func NewService(client *http.Client, host string) *Service {
return &Service{
Client: client,
Host: host,
}
} | [
"func",
"NewService",
"(",
"client",
"*",
"http",
".",
"Client",
",",
"host",
"string",
")",
"*",
"Service",
"{",
"return",
"&",
"Service",
"{",
"Client",
":",
"client",
",",
"Host",
":",
"host",
",",
"}",
"\n",
"}"
] | // NewService creates a new service to connect to APN. | [
"NewService",
"creates",
"a",
"new",
"service",
"to",
"connect",
"to",
"APN",
"."
] | 75d85f30d5ffbe02a1fa39cb15c7a526ee70ab31 | https://github.com/RobotsAndPencils/buford/blob/75d85f30d5ffbe02a1fa39cb15c7a526ee70ab31/push/service.go#L36-L41 |
5,922 | RobotsAndPencils/buford | push/service.go | Push | func (s *Service) Push(deviceToken string, headers *Headers, payload []byte) (string, error) {
// check payload length before even hitting Apple.
if len(payload) > maxPayload {
return "", &Error{
Reason: ErrPayloadTooLarge,
Status: http.StatusRequestEntityTooLarge,
}
}
urlStr := fmt.Sprintf("%v/3/device/%v", s.Host, deviceToken)
req, err := http.NewRequest("POST", urlStr, bytes.NewReader(payload))
if err != nil {
return "", err
}
req.Header.Set("Content-Type", "application/json")
headers.set(req.Header)
resp, err := s.Client.Do(req)
if err != nil {
if e, ok := err.(*url.Error); ok {
if e, ok := e.Err.(http2.GoAwayError); ok {
// parse DebugData as JSON. no status code known (0)
return "", parseErrorResponse(strings.NewReader(e.DebugData), 0)
}
}
return "", err
}
defer resp.Body.Close()
if resp.StatusCode == http.StatusOK {
return resp.Header.Get("apns-id"), nil
}
return "", parseErrorResponse(resp.Body, resp.StatusCode)
} | go | func (s *Service) Push(deviceToken string, headers *Headers, payload []byte) (string, error) {
// check payload length before even hitting Apple.
if len(payload) > maxPayload {
return "", &Error{
Reason: ErrPayloadTooLarge,
Status: http.StatusRequestEntityTooLarge,
}
}
urlStr := fmt.Sprintf("%v/3/device/%v", s.Host, deviceToken)
req, err := http.NewRequest("POST", urlStr, bytes.NewReader(payload))
if err != nil {
return "", err
}
req.Header.Set("Content-Type", "application/json")
headers.set(req.Header)
resp, err := s.Client.Do(req)
if err != nil {
if e, ok := err.(*url.Error); ok {
if e, ok := e.Err.(http2.GoAwayError); ok {
// parse DebugData as JSON. no status code known (0)
return "", parseErrorResponse(strings.NewReader(e.DebugData), 0)
}
}
return "", err
}
defer resp.Body.Close()
if resp.StatusCode == http.StatusOK {
return resp.Header.Get("apns-id"), nil
}
return "", parseErrorResponse(resp.Body, resp.StatusCode)
} | [
"func",
"(",
"s",
"*",
"Service",
")",
"Push",
"(",
"deviceToken",
"string",
",",
"headers",
"*",
"Headers",
",",
"payload",
"[",
"]",
"byte",
")",
"(",
"string",
",",
"error",
")",
"{",
"// check payload length before even hitting Apple.",
"if",
"len",
"(",... | // Push sends a notification and waits for a response. | [
"Push",
"sends",
"a",
"notification",
"and",
"waits",
"for",
"a",
"response",
"."
] | 75d85f30d5ffbe02a1fa39cb15c7a526ee70ab31 | https://github.com/RobotsAndPencils/buford/blob/75d85f30d5ffbe02a1fa39cb15c7a526ee70ab31/push/service.go#L59-L95 |
5,923 | RobotsAndPencils/buford | pushpackage/pushpackage.go | New | func New(w io.Writer) Package {
return Package{
z: zip.NewWriter(w),
manifest: make(map[string]string),
}
} | go | func New(w io.Writer) Package {
return Package{
z: zip.NewWriter(w),
manifest: make(map[string]string),
}
} | [
"func",
"New",
"(",
"w",
"io",
".",
"Writer",
")",
"Package",
"{",
"return",
"Package",
"{",
"z",
":",
"zip",
".",
"NewWriter",
"(",
"w",
")",
",",
"manifest",
":",
"make",
"(",
"map",
"[",
"string",
"]",
"string",
")",
",",
"}",
"\n",
"}"
] | // New push package will be written to w. | [
"New",
"push",
"package",
"will",
"be",
"written",
"to",
"w",
"."
] | 75d85f30d5ffbe02a1fa39cb15c7a526ee70ab31 | https://github.com/RobotsAndPencils/buford/blob/75d85f30d5ffbe02a1fa39cb15c7a526ee70ab31/pushpackage/pushpackage.go#L29-L34 |
5,924 | RobotsAndPencils/buford | pushpackage/pushpackage.go | EncodeJSON | func (p *Package) EncodeJSON(name string, e interface{}) {
if p.err != nil {
return
}
b, err := json.Marshal(e)
if err != nil {
p.err = err
return
}
r := bytes.NewReader(b)
p.Copy(name, r)
} | go | func (p *Package) EncodeJSON(name string, e interface{}) {
if p.err != nil {
return
}
b, err := json.Marshal(e)
if err != nil {
p.err = err
return
}
r := bytes.NewReader(b)
p.Copy(name, r)
} | [
"func",
"(",
"p",
"*",
"Package",
")",
"EncodeJSON",
"(",
"name",
"string",
",",
"e",
"interface",
"{",
"}",
")",
"{",
"if",
"p",
".",
"err",
"!=",
"nil",
"{",
"return",
"\n",
"}",
"\n\n",
"b",
",",
"err",
":=",
"json",
".",
"Marshal",
"(",
"e"... | // EncodeJSON to the push package. | [
"EncodeJSON",
"to",
"the",
"push",
"package",
"."
] | 75d85f30d5ffbe02a1fa39cb15c7a526ee70ab31 | https://github.com/RobotsAndPencils/buford/blob/75d85f30d5ffbe02a1fa39cb15c7a526ee70ab31/pushpackage/pushpackage.go#L37-L50 |
5,925 | RobotsAndPencils/buford | pushpackage/pushpackage.go | Copy | func (p *Package) Copy(name string, r io.Reader) {
if p.err != nil {
return
}
zf, err := p.z.Create(name)
if err != nil {
p.err = err
return
}
checksum, err := copyAndChecksum(zf, r)
if err != nil {
p.err = err
return
}
p.manifest[name] = checksum
} | go | func (p *Package) Copy(name string, r io.Reader) {
if p.err != nil {
return
}
zf, err := p.z.Create(name)
if err != nil {
p.err = err
return
}
checksum, err := copyAndChecksum(zf, r)
if err != nil {
p.err = err
return
}
p.manifest[name] = checksum
} | [
"func",
"(",
"p",
"*",
"Package",
")",
"Copy",
"(",
"name",
"string",
",",
"r",
"io",
".",
"Reader",
")",
"{",
"if",
"p",
".",
"err",
"!=",
"nil",
"{",
"return",
"\n",
"}",
"\n\n",
"zf",
",",
"err",
":=",
"p",
".",
"z",
".",
"Create",
"(",
... | // Copy reader to the push package. | [
"Copy",
"reader",
"to",
"the",
"push",
"package",
"."
] | 75d85f30d5ffbe02a1fa39cb15c7a526ee70ab31 | https://github.com/RobotsAndPencils/buford/blob/75d85f30d5ffbe02a1fa39cb15c7a526ee70ab31/pushpackage/pushpackage.go#L53-L71 |
5,926 | RobotsAndPencils/buford | pushpackage/pushpackage.go | Sign | func (p *Package) Sign(cert tls.Certificate, wwdr *x509.Certificate) error {
if p.err != nil {
return p.err
}
// assert that private key is RSA
key, ok := cert.PrivateKey.(*rsa.PrivateKey)
if !ok {
return errors.New("expected RSA private key type")
}
manifestBytes, err := json.Marshal(p.manifest)
if err != nil {
return err
}
zf, err := p.z.Create("manifest.json")
if err != nil {
return err
}
zf.Write(manifestBytes)
// sign manifest.json with PKCS #7
// and add signature to the zip file
zf, err = p.z.Create("signature")
if err != nil {
return err
}
sig, err := pkcs7.Sign2(bytes.NewReader(manifestBytes), cert.Leaf, key, wwdr)
if err != nil {
return err
}
zf.Write(sig)
return p.z.Close()
} | go | func (p *Package) Sign(cert tls.Certificate, wwdr *x509.Certificate) error {
if p.err != nil {
return p.err
}
// assert that private key is RSA
key, ok := cert.PrivateKey.(*rsa.PrivateKey)
if !ok {
return errors.New("expected RSA private key type")
}
manifestBytes, err := json.Marshal(p.manifest)
if err != nil {
return err
}
zf, err := p.z.Create("manifest.json")
if err != nil {
return err
}
zf.Write(manifestBytes)
// sign manifest.json with PKCS #7
// and add signature to the zip file
zf, err = p.z.Create("signature")
if err != nil {
return err
}
sig, err := pkcs7.Sign2(bytes.NewReader(manifestBytes), cert.Leaf, key, wwdr)
if err != nil {
return err
}
zf.Write(sig)
return p.z.Close()
} | [
"func",
"(",
"p",
"*",
"Package",
")",
"Sign",
"(",
"cert",
"tls",
".",
"Certificate",
",",
"wwdr",
"*",
"x509",
".",
"Certificate",
")",
"error",
"{",
"if",
"p",
".",
"err",
"!=",
"nil",
"{",
"return",
"p",
".",
"err",
"\n",
"}",
"\n\n",
"// ass... | // Sign the package and close.
// Passbook needs Apple's intermediate WWDR certificate. | [
"Sign",
"the",
"package",
"and",
"close",
".",
"Passbook",
"needs",
"Apple",
"s",
"intermediate",
"WWDR",
"certificate",
"."
] | 75d85f30d5ffbe02a1fa39cb15c7a526ee70ab31 | https://github.com/RobotsAndPencils/buford/blob/75d85f30d5ffbe02a1fa39cb15c7a526ee70ab31/pushpackage/pushpackage.go#L92-L127 |
5,927 | RobotsAndPencils/buford | push/queue.go | NewQueue | func NewQueue(service *Service, workers uint) *Queue {
// unbuffered channels
q := &Queue{
service: service,
notifications: make(chan notification),
Responses: make(chan Response),
}
// startup workers to send notifications
for i := uint(0); i < workers; i++ {
go worker(q)
}
return q
} | go | func NewQueue(service *Service, workers uint) *Queue {
// unbuffered channels
q := &Queue{
service: service,
notifications: make(chan notification),
Responses: make(chan Response),
}
// startup workers to send notifications
for i := uint(0); i < workers; i++ {
go worker(q)
}
return q
} | [
"func",
"NewQueue",
"(",
"service",
"*",
"Service",
",",
"workers",
"uint",
")",
"*",
"Queue",
"{",
"// unbuffered channels",
"q",
":=",
"&",
"Queue",
"{",
"service",
":",
"service",
",",
"notifications",
":",
"make",
"(",
"chan",
"notification",
")",
",",... | // NewQueue wraps a service with a queue for sending notifications asynchronously. | [
"NewQueue",
"wraps",
"a",
"service",
"with",
"a",
"queue",
"for",
"sending",
"notifications",
"asynchronously",
"."
] | 75d85f30d5ffbe02a1fa39cb15c7a526ee70ab31 | https://github.com/RobotsAndPencils/buford/blob/75d85f30d5ffbe02a1fa39cb15c7a526ee70ab31/push/queue.go#L25-L37 |
5,928 | RobotsAndPencils/buford | push/queue.go | Push | func (q *Queue) Push(deviceToken string, headers *Headers, payload []byte) {
n := notification{
DeviceToken: deviceToken,
Headers: headers,
Payload: payload,
}
q.notifications <- n
} | go | func (q *Queue) Push(deviceToken string, headers *Headers, payload []byte) {
n := notification{
DeviceToken: deviceToken,
Headers: headers,
Payload: payload,
}
q.notifications <- n
} | [
"func",
"(",
"q",
"*",
"Queue",
")",
"Push",
"(",
"deviceToken",
"string",
",",
"headers",
"*",
"Headers",
",",
"payload",
"[",
"]",
"byte",
")",
"{",
"n",
":=",
"notification",
"{",
"DeviceToken",
":",
"deviceToken",
",",
"Headers",
":",
"headers",
",... | // Push queues a notification to the APN service. | [
"Push",
"queues",
"a",
"notification",
"to",
"the",
"APN",
"service",
"."
] | 75d85f30d5ffbe02a1fa39cb15c7a526ee70ab31 | https://github.com/RobotsAndPencils/buford/blob/75d85f30d5ffbe02a1fa39cb15c7a526ee70ab31/push/queue.go#L40-L47 |
5,929 | RobotsAndPencils/buford | payload/aps.go | isSimple | func (a *Alert) isSimple() bool {
return len(a.Title) == 0 && len(a.Subtitle) == 0 &&
len(a.LaunchImage) == 0 &&
len(a.TitleLocKey) == 0 && len(a.TitleLocArgs) == 0 &&
len(a.LocKey) == 0 && len(a.LocArgs) == 0 && len(a.ActionLocKey) == 0
} | go | func (a *Alert) isSimple() bool {
return len(a.Title) == 0 && len(a.Subtitle) == 0 &&
len(a.LaunchImage) == 0 &&
len(a.TitleLocKey) == 0 && len(a.TitleLocArgs) == 0 &&
len(a.LocKey) == 0 && len(a.LocArgs) == 0 && len(a.ActionLocKey) == 0
} | [
"func",
"(",
"a",
"*",
"Alert",
")",
"isSimple",
"(",
")",
"bool",
"{",
"return",
"len",
"(",
"a",
".",
"Title",
")",
"==",
"0",
"&&",
"len",
"(",
"a",
".",
"Subtitle",
")",
"==",
"0",
"&&",
"len",
"(",
"a",
".",
"LaunchImage",
")",
"==",
"0"... | // isSimple alert with only Body set. | [
"isSimple",
"alert",
"with",
"only",
"Body",
"set",
"."
] | 75d85f30d5ffbe02a1fa39cb15c7a526ee70ab31 | https://github.com/RobotsAndPencils/buford/blob/75d85f30d5ffbe02a1fa39cb15c7a526ee70ab31/payload/aps.go#L60-L65 |
5,930 | RobotsAndPencils/buford | payload/aps.go | Map | func (a *APS) Map() map[string]interface{} {
aps := make(map[string]interface{}, 5)
if !a.Alert.isZero() {
if a.Alert.isSimple() {
aps["alert"] = a.Alert.Body
} else {
aps["alert"] = a.Alert
}
}
if n, ok := a.Badge.Number(); ok {
aps["badge"] = n
}
if a.Sound != "" {
aps["sound"] = a.Sound
}
if a.ContentAvailable {
aps["content-available"] = 1
}
if a.Category != "" {
aps["category"] = a.Category
}
if a.MutableContent {
aps["mutable-content"] = 1
}
if a.ThreadID != "" {
aps["thread-id"] = a.ThreadID
}
// wrap in "aps" to form the final payload
return map[string]interface{}{"aps": aps}
} | go | func (a *APS) Map() map[string]interface{} {
aps := make(map[string]interface{}, 5)
if !a.Alert.isZero() {
if a.Alert.isSimple() {
aps["alert"] = a.Alert.Body
} else {
aps["alert"] = a.Alert
}
}
if n, ok := a.Badge.Number(); ok {
aps["badge"] = n
}
if a.Sound != "" {
aps["sound"] = a.Sound
}
if a.ContentAvailable {
aps["content-available"] = 1
}
if a.Category != "" {
aps["category"] = a.Category
}
if a.MutableContent {
aps["mutable-content"] = 1
}
if a.ThreadID != "" {
aps["thread-id"] = a.ThreadID
}
// wrap in "aps" to form the final payload
return map[string]interface{}{"aps": aps}
} | [
"func",
"(",
"a",
"*",
"APS",
")",
"Map",
"(",
")",
"map",
"[",
"string",
"]",
"interface",
"{",
"}",
"{",
"aps",
":=",
"make",
"(",
"map",
"[",
"string",
"]",
"interface",
"{",
"}",
",",
"5",
")",
"\n\n",
"if",
"!",
"a",
".",
"Alert",
".",
... | // Map returns the payload as a map that you can customize
// before serializing it to JSON. | [
"Map",
"returns",
"the",
"payload",
"as",
"a",
"map",
"that",
"you",
"can",
"customize",
"before",
"serializing",
"it",
"to",
"JSON",
"."
] | 75d85f30d5ffbe02a1fa39cb15c7a526ee70ab31 | https://github.com/RobotsAndPencils/buford/blob/75d85f30d5ffbe02a1fa39cb15c7a526ee70ab31/payload/aps.go#L74-L105 |
5,931 | RobotsAndPencils/buford | payload/aps.go | Validate | func (a *APS) Validate() error {
if a == nil {
return ErrIncomplete
}
// must have a body or a badge (or custom data)
if len(a.Alert.Body) == 0 && a.Badge == badge.Preserve {
return ErrIncomplete
}
return nil
} | go | func (a *APS) Validate() error {
if a == nil {
return ErrIncomplete
}
// must have a body or a badge (or custom data)
if len(a.Alert.Body) == 0 && a.Badge == badge.Preserve {
return ErrIncomplete
}
return nil
} | [
"func",
"(",
"a",
"*",
"APS",
")",
"Validate",
"(",
")",
"error",
"{",
"if",
"a",
"==",
"nil",
"{",
"return",
"ErrIncomplete",
"\n",
"}",
"\n\n",
"// must have a body or a badge (or custom data)",
"if",
"len",
"(",
"a",
".",
"Alert",
".",
"Body",
")",
"=... | // Validate that a payload has the correct fields. | [
"Validate",
"that",
"a",
"payload",
"has",
"the",
"correct",
"fields",
"."
] | 75d85f30d5ffbe02a1fa39cb15c7a526ee70ab31 | https://github.com/RobotsAndPencils/buford/blob/75d85f30d5ffbe02a1fa39cb15c7a526ee70ab31/payload/aps.go#L113-L123 |
5,932 | RobotsAndPencils/buford | payload/browser.go | Validate | func (p *Browser) Validate() error {
if p == nil {
return ErrIncomplete
}
// must have both a title and body. action and url-args are optional.
if len(p.Alert.Title) == 0 || len(p.Alert.Body) == 0 {
return ErrIncomplete
}
return nil
} | go | func (p *Browser) Validate() error {
if p == nil {
return ErrIncomplete
}
// must have both a title and body. action and url-args are optional.
if len(p.Alert.Title) == 0 || len(p.Alert.Body) == 0 {
return ErrIncomplete
}
return nil
} | [
"func",
"(",
"p",
"*",
"Browser",
")",
"Validate",
"(",
")",
"error",
"{",
"if",
"p",
"==",
"nil",
"{",
"return",
"ErrIncomplete",
"\n",
"}",
"\n\n",
"// must have both a title and body. action and url-args are optional.",
"if",
"len",
"(",
"p",
".",
"Alert",
... | // Validate browser payload. | [
"Validate",
"browser",
"payload",
"."
] | 75d85f30d5ffbe02a1fa39cb15c7a526ee70ab31 | https://github.com/RobotsAndPencils/buford/blob/75d85f30d5ffbe02a1fa39cb15c7a526ee70ab31/payload/browser.go#L27-L37 |
5,933 | RobotsAndPencils/buford | push/header.go | set | func (h *Headers) set(reqHeader http.Header) {
// headers are optional
if h == nil {
return
}
if h.ID != "" {
reqHeader.Set("apns-id", h.ID)
} // when omitted, Apple will generate a UUID for you
if h.CollapseID != "" {
reqHeader.Set("apns-collapse-id", h.CollapseID)
}
if !h.Expiration.IsZero() {
reqHeader.Set("apns-expiration", strconv.FormatInt(h.Expiration.Unix(), 10))
}
if h.LowPriority {
reqHeader.Set("apns-priority", "5")
} // when omitted, the default priority is 10
if h.Topic != "" {
reqHeader.Set("apns-topic", h.Topic)
}
} | go | func (h *Headers) set(reqHeader http.Header) {
// headers are optional
if h == nil {
return
}
if h.ID != "" {
reqHeader.Set("apns-id", h.ID)
} // when omitted, Apple will generate a UUID for you
if h.CollapseID != "" {
reqHeader.Set("apns-collapse-id", h.CollapseID)
}
if !h.Expiration.IsZero() {
reqHeader.Set("apns-expiration", strconv.FormatInt(h.Expiration.Unix(), 10))
}
if h.LowPriority {
reqHeader.Set("apns-priority", "5")
} // when omitted, the default priority is 10
if h.Topic != "" {
reqHeader.Set("apns-topic", h.Topic)
}
} | [
"func",
"(",
"h",
"*",
"Headers",
")",
"set",
"(",
"reqHeader",
"http",
".",
"Header",
")",
"{",
"// headers are optional",
"if",
"h",
"==",
"nil",
"{",
"return",
"\n",
"}",
"\n\n",
"if",
"h",
".",
"ID",
"!=",
"\"",
"\"",
"{",
"reqHeader",
".",
"Se... | // set headers for an HTTP request | [
"set",
"headers",
"for",
"an",
"HTTP",
"request"
] | 75d85f30d5ffbe02a1fa39cb15c7a526ee70ab31 | https://github.com/RobotsAndPencils/buford/blob/75d85f30d5ffbe02a1fa39cb15c7a526ee70ab31/push/header.go#L31-L57 |
5,934 | RobotsAndPencils/buford | payload/mdm.go | Validate | func (p *MDM) Validate() error {
if p == nil {
return ErrIncomplete
}
// must have a token.
if len(p.Token) == 0 {
return ErrIncomplete
}
return nil
} | go | func (p *MDM) Validate() error {
if p == nil {
return ErrIncomplete
}
// must have a token.
if len(p.Token) == 0 {
return ErrIncomplete
}
return nil
} | [
"func",
"(",
"p",
"*",
"MDM",
")",
"Validate",
"(",
")",
"error",
"{",
"if",
"p",
"==",
"nil",
"{",
"return",
"ErrIncomplete",
"\n",
"}",
"\n\n",
"// must have a token.",
"if",
"len",
"(",
"p",
".",
"Token",
")",
"==",
"0",
"{",
"return",
"ErrIncompl... | // Validate MDM payload. | [
"Validate",
"MDM",
"payload",
"."
] | 75d85f30d5ffbe02a1fa39cb15c7a526ee70ab31 | https://github.com/RobotsAndPencils/buford/blob/75d85f30d5ffbe02a1fa39cb15c7a526ee70ab31/payload/mdm.go#L9-L19 |
5,935 | RobotsAndPencils/buford | certificate/cert.go | Load | func Load(filename, password string) (tls.Certificate, error) {
p12, err := ioutil.ReadFile(filename)
if err != nil {
return tls.Certificate{}, fmt.Errorf("Unable to load %s: %v", filename, err)
}
return Decode(p12, password)
} | go | func Load(filename, password string) (tls.Certificate, error) {
p12, err := ioutil.ReadFile(filename)
if err != nil {
return tls.Certificate{}, fmt.Errorf("Unable to load %s: %v", filename, err)
}
return Decode(p12, password)
} | [
"func",
"Load",
"(",
"filename",
",",
"password",
"string",
")",
"(",
"tls",
".",
"Certificate",
",",
"error",
")",
"{",
"p12",
",",
"err",
":=",
"ioutil",
".",
"ReadFile",
"(",
"filename",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"tls",
... | // Load a .p12 certificate from disk. | [
"Load",
"a",
".",
"p12",
"certificate",
"from",
"disk",
"."
] | 75d85f30d5ffbe02a1fa39cb15c7a526ee70ab31 | https://github.com/RobotsAndPencils/buford/blob/75d85f30d5ffbe02a1fa39cb15c7a526ee70ab31/certificate/cert.go#L25-L31 |
5,936 | RobotsAndPencils/buford | certificate/cert.go | TopicFromCert | func TopicFromCert(cert tls.Certificate) string {
commonName := cert.Leaf.Subject.CommonName
var topic string
// Apple Push Services: {bundle}
// Apple Development IOS Push Services: {bundle}
n := strings.Index(commonName, ":")
if n != -1 {
topic = strings.TrimSpace(commonName[n+1:])
}
return topic
} | go | func TopicFromCert(cert tls.Certificate) string {
commonName := cert.Leaf.Subject.CommonName
var topic string
// Apple Push Services: {bundle}
// Apple Development IOS Push Services: {bundle}
n := strings.Index(commonName, ":")
if n != -1 {
topic = strings.TrimSpace(commonName[n+1:])
}
return topic
} | [
"func",
"TopicFromCert",
"(",
"cert",
"tls",
".",
"Certificate",
")",
"string",
"{",
"commonName",
":=",
"cert",
".",
"Leaf",
".",
"Subject",
".",
"CommonName",
"\n\n",
"var",
"topic",
"string",
"\n",
"// Apple Push Services: {bundle}",
"// Apple Development IOS Pus... | // TopicFromCert extracts topic from a certificate's common name. | [
"TopicFromCert",
"extracts",
"topic",
"from",
"a",
"certificate",
"s",
"common",
"name",
"."
] | 75d85f30d5ffbe02a1fa39cb15c7a526ee70ab31 | https://github.com/RobotsAndPencils/buford/blob/75d85f30d5ffbe02a1fa39cb15c7a526ee70ab31/certificate/cert.go#L53-L64 |
5,937 | RobotsAndPencils/buford | certificate/cert.go | verify | func verify(cert *x509.Certificate) error {
_, err := cert.Verify(x509.VerifyOptions{})
if err == nil {
return nil
}
switch e := err.(type) {
case x509.CertificateInvalidError:
switch e.Reason {
case x509.Expired:
return ErrExpired
case x509.IncompatibleUsage:
// Apple cert fail on go 1.10
return nil
default:
return err
}
case x509.UnknownAuthorityError:
// Apple cert isn't in the cert pool
// ignoring this error
return nil
default:
return err
}
} | go | func verify(cert *x509.Certificate) error {
_, err := cert.Verify(x509.VerifyOptions{})
if err == nil {
return nil
}
switch e := err.(type) {
case x509.CertificateInvalidError:
switch e.Reason {
case x509.Expired:
return ErrExpired
case x509.IncompatibleUsage:
// Apple cert fail on go 1.10
return nil
default:
return err
}
case x509.UnknownAuthorityError:
// Apple cert isn't in the cert pool
// ignoring this error
return nil
default:
return err
}
} | [
"func",
"verify",
"(",
"cert",
"*",
"x509",
".",
"Certificate",
")",
"error",
"{",
"_",
",",
"err",
":=",
"cert",
".",
"Verify",
"(",
"x509",
".",
"VerifyOptions",
"{",
"}",
")",
"\n",
"if",
"err",
"==",
"nil",
"{",
"return",
"nil",
"\n",
"}",
"\... | // verify checks if a certificate has expired | [
"verify",
"checks",
"if",
"a",
"certificate",
"has",
"expired"
] | 75d85f30d5ffbe02a1fa39cb15c7a526ee70ab31 | https://github.com/RobotsAndPencils/buford/blob/75d85f30d5ffbe02a1fa39cb15c7a526ee70ab31/certificate/cert.go#L67-L91 |
5,938 | RobotsAndPencils/buford | pushpackage/checksum.go | copyAndChecksum | func copyAndChecksum(w io.Writer, r io.Reader) (string, error) {
h := sha1.New()
mw := io.MultiWriter(w, h)
if _, err := io.Copy(mw, r); err != nil {
return "", err
}
return hex.EncodeToString(h.Sum(nil)), nil
} | go | func copyAndChecksum(w io.Writer, r io.Reader) (string, error) {
h := sha1.New()
mw := io.MultiWriter(w, h)
if _, err := io.Copy(mw, r); err != nil {
return "", err
}
return hex.EncodeToString(h.Sum(nil)), nil
} | [
"func",
"copyAndChecksum",
"(",
"w",
"io",
".",
"Writer",
",",
"r",
"io",
".",
"Reader",
")",
"(",
"string",
",",
"error",
")",
"{",
"h",
":=",
"sha1",
".",
"New",
"(",
")",
"\n",
"mw",
":=",
"io",
".",
"MultiWriter",
"(",
"w",
",",
"h",
")",
... | // copyAndChecksum calculates a checksum while writing to another output | [
"copyAndChecksum",
"calculates",
"a",
"checksum",
"while",
"writing",
"to",
"another",
"output"
] | 75d85f30d5ffbe02a1fa39cb15c7a526ee70ab31 | https://github.com/RobotsAndPencils/buford/blob/75d85f30d5ffbe02a1fa39cb15c7a526ee70ab31/pushpackage/checksum.go#L10-L17 |
5,939 | RobotsAndPencils/buford | push/errors.go | mapErrorReason | func mapErrorReason(reason string) error {
var e error
switch reason {
case "PayloadEmpty":
e = ErrPayloadEmpty
case "PayloadTooLarge":
e = ErrPayloadTooLarge
case "BadTopic":
e = ErrBadTopic
case "TopicDisallowed":
e = ErrTopicDisallowed
case "BadMessageId":
e = ErrBadMessageID
case "BadExpirationDate":
e = ErrBadExpirationDate
case "BadPriority":
e = ErrBadPriority
case "MissingDeviceToken":
e = ErrMissingDeviceToken
case "BadDeviceToken":
e = ErrBadDeviceToken
case "DeviceTokenNotForTopic":
e = ErrDeviceTokenNotForTopic
case "Unregistered":
e = ErrUnregistered
case "DuplicateHeaders":
e = ErrDuplicateHeaders
case "BadCertificateEnvironment":
e = ErrBadCertificateEnvironment
case "BadCertificate":
e = ErrBadCertificate
case "Forbidden":
e = ErrForbidden
case "BadPath":
e = ErrBadPath
case "MethodNotAllowed":
e = ErrMethodNotAllowed
case "TooManyRequests":
e = ErrTooManyRequests
case "IdleTimeout":
e = ErrIdleTimeout
case "Shutdown":
e = ErrShutdown
case "InternalServerError":
e = ErrInternalServerError
case "ServiceUnavailable":
e = ErrServiceUnavailable
case "MissingTopic":
e = ErrMissingTopic
default:
e = errors.New(reason)
}
return e
} | go | func mapErrorReason(reason string) error {
var e error
switch reason {
case "PayloadEmpty":
e = ErrPayloadEmpty
case "PayloadTooLarge":
e = ErrPayloadTooLarge
case "BadTopic":
e = ErrBadTopic
case "TopicDisallowed":
e = ErrTopicDisallowed
case "BadMessageId":
e = ErrBadMessageID
case "BadExpirationDate":
e = ErrBadExpirationDate
case "BadPriority":
e = ErrBadPriority
case "MissingDeviceToken":
e = ErrMissingDeviceToken
case "BadDeviceToken":
e = ErrBadDeviceToken
case "DeviceTokenNotForTopic":
e = ErrDeviceTokenNotForTopic
case "Unregistered":
e = ErrUnregistered
case "DuplicateHeaders":
e = ErrDuplicateHeaders
case "BadCertificateEnvironment":
e = ErrBadCertificateEnvironment
case "BadCertificate":
e = ErrBadCertificate
case "Forbidden":
e = ErrForbidden
case "BadPath":
e = ErrBadPath
case "MethodNotAllowed":
e = ErrMethodNotAllowed
case "TooManyRequests":
e = ErrTooManyRequests
case "IdleTimeout":
e = ErrIdleTimeout
case "Shutdown":
e = ErrShutdown
case "InternalServerError":
e = ErrInternalServerError
case "ServiceUnavailable":
e = ErrServiceUnavailable
case "MissingTopic":
e = ErrMissingTopic
default:
e = errors.New(reason)
}
return e
} | [
"func",
"mapErrorReason",
"(",
"reason",
"string",
")",
"error",
"{",
"var",
"e",
"error",
"\n",
"switch",
"reason",
"{",
"case",
"\"",
"\"",
":",
"e",
"=",
"ErrPayloadEmpty",
"\n",
"case",
"\"",
"\"",
":",
"e",
"=",
"ErrPayloadTooLarge",
"\n",
"case",
... | // mapErrorReason converts Apple error responses into exported Err variables
// for comparisons. | [
"mapErrorReason",
"converts",
"Apple",
"error",
"responses",
"into",
"exported",
"Err",
"variables",
"for",
"comparisons",
"."
] | 75d85f30d5ffbe02a1fa39cb15c7a526ee70ab31 | https://github.com/RobotsAndPencils/buford/blob/75d85f30d5ffbe02a1fa39cb15c7a526ee70ab31/push/errors.go#L56-L109 |
5,940 | tsuru/docker-cluster | cluster/container.go | CreateContainer | func (c *Cluster) CreateContainer(opts docker.CreateContainerOptions, inactivityTimeout time.Duration, nodes ...string) (string, *docker.Container, error) {
return c.CreateContainerSchedulerOpts(opts, nil, inactivityTimeout, nodes...)
} | go | func (c *Cluster) CreateContainer(opts docker.CreateContainerOptions, inactivityTimeout time.Duration, nodes ...string) (string, *docker.Container, error) {
return c.CreateContainerSchedulerOpts(opts, nil, inactivityTimeout, nodes...)
} | [
"func",
"(",
"c",
"*",
"Cluster",
")",
"CreateContainer",
"(",
"opts",
"docker",
".",
"CreateContainerOptions",
",",
"inactivityTimeout",
"time",
".",
"Duration",
",",
"nodes",
"...",
"string",
")",
"(",
"string",
",",
"*",
"docker",
".",
"Container",
",",
... | // CreateContainer creates a container in the specified node. If no node is
// specified, it will create the container in a node selected by the scheduler.
//
// It returns the container, or an error, in case of failures. | [
"CreateContainer",
"creates",
"a",
"container",
"in",
"the",
"specified",
"node",
".",
"If",
"no",
"node",
"is",
"specified",
"it",
"will",
"create",
"the",
"container",
"in",
"a",
"node",
"selected",
"by",
"the",
"scheduler",
".",
"It",
"returns",
"the",
... | f372d8d4e3549863e8ca98c233f645bf3d2c1055 | https://github.com/tsuru/docker-cluster/blob/f372d8d4e3549863e8ca98c233f645bf3d2c1055/cluster/container.go#L29-L31 |
5,941 | tsuru/docker-cluster | cluster/container.go | CreateContainerSchedulerOpts | func (c *Cluster) CreateContainerSchedulerOpts(opts docker.CreateContainerOptions, schedulerOpts SchedulerOptions, inactivityTimeout time.Duration, nodes ...string) (string, *docker.Container, error) {
return c.CreateContainerPullOptsSchedulerOpts(opts, docker.PullImageOptions{
Repository: opts.Config.Image,
InactivityTimeout: inactivityTimeout,
Context: opts.Context,
}, docker.AuthConfiguration{}, schedulerOpts, nodes...)
} | go | func (c *Cluster) CreateContainerSchedulerOpts(opts docker.CreateContainerOptions, schedulerOpts SchedulerOptions, inactivityTimeout time.Duration, nodes ...string) (string, *docker.Container, error) {
return c.CreateContainerPullOptsSchedulerOpts(opts, docker.PullImageOptions{
Repository: opts.Config.Image,
InactivityTimeout: inactivityTimeout,
Context: opts.Context,
}, docker.AuthConfiguration{}, schedulerOpts, nodes...)
} | [
"func",
"(",
"c",
"*",
"Cluster",
")",
"CreateContainerSchedulerOpts",
"(",
"opts",
"docker",
".",
"CreateContainerOptions",
",",
"schedulerOpts",
"SchedulerOptions",
",",
"inactivityTimeout",
"time",
".",
"Duration",
",",
"nodes",
"...",
"string",
")",
"(",
"stri... | // Similar to CreateContainer but allows arbritary options to be passed to
// the scheduler. | [
"Similar",
"to",
"CreateContainer",
"but",
"allows",
"arbritary",
"options",
"to",
"be",
"passed",
"to",
"the",
"scheduler",
"."
] | f372d8d4e3549863e8ca98c233f645bf3d2c1055 | https://github.com/tsuru/docker-cluster/blob/f372d8d4e3549863e8ca98c233f645bf3d2c1055/cluster/container.go#L35-L41 |
5,942 | tsuru/docker-cluster | cluster/container.go | CreateContainerPullOptsSchedulerOpts | func (c *Cluster) CreateContainerPullOptsSchedulerOpts(opts docker.CreateContainerOptions, pullOpts docker.PullImageOptions, pullAuth docker.AuthConfiguration, schedulerOpts SchedulerOptions, nodes ...string) (string, *docker.Container, error) {
var (
addr string
container *docker.Container
err error
)
useScheduler := len(nodes) == 0
maxTries := 5
for ; maxTries > 0; maxTries-- {
if opts.Context != nil {
select {
case <-opts.Context.Done():
return "", nil, opts.Context.Err()
default:
}
}
if useScheduler {
node, scheduleErr := c.scheduler.Schedule(c, &opts, schedulerOpts)
if scheduleErr != nil {
if err != nil {
scheduleErr = fmt.Errorf("Error in scheduler after previous errors (%s) trying to create container: %s", err.Error(), scheduleErr.Error())
}
return addr, nil, scheduleErr
}
addr = node.Address
} else {
addr = nodes[rand.Intn(len(nodes))]
}
if addr == "" {
return addr, nil, errors.New("CreateContainer needs a non empty node addr")
}
err = c.runHookForAddr(HookEventBeforeContainerCreate, addr)
if err != nil {
log.Errorf("Error in before create container hook in node %q: %s. Trying again in another node...", addr, err)
}
if err == nil {
container, err = c.createContainerInNode(opts, pullOpts, pullAuth, addr)
if err == nil {
c.handleNodeSuccess(addr)
break
}
log.Errorf("Error trying to create container in node %q: %s. Trying again in another node...", addr, err.Error())
}
shouldIncrementFailures := false
isCreateContainerErr := false
baseErr := err
if nodeErr, ok := baseErr.(DockerNodeError); ok {
isCreateContainerErr = nodeErr.cmd == "createContainer"
baseErr = nodeErr.BaseError()
}
if urlErr, ok := baseErr.(*url.Error); ok {
baseErr = urlErr.Err
}
_, isNetErr := baseErr.(net.Error)
if isNetErr || isCreateContainerErr || baseErr == docker.ErrConnectionRefused {
shouldIncrementFailures = true
}
c.handleNodeError(addr, err, shouldIncrementFailures)
if !useScheduler {
return addr, nil, err
}
}
if err != nil {
return addr, nil, fmt.Errorf("CreateContainer: maximum number of tries exceeded, last error: %s", err.Error())
}
err = c.storage().StoreContainer(container.ID, addr)
return addr, container, err
} | go | func (c *Cluster) CreateContainerPullOptsSchedulerOpts(opts docker.CreateContainerOptions, pullOpts docker.PullImageOptions, pullAuth docker.AuthConfiguration, schedulerOpts SchedulerOptions, nodes ...string) (string, *docker.Container, error) {
var (
addr string
container *docker.Container
err error
)
useScheduler := len(nodes) == 0
maxTries := 5
for ; maxTries > 0; maxTries-- {
if opts.Context != nil {
select {
case <-opts.Context.Done():
return "", nil, opts.Context.Err()
default:
}
}
if useScheduler {
node, scheduleErr := c.scheduler.Schedule(c, &opts, schedulerOpts)
if scheduleErr != nil {
if err != nil {
scheduleErr = fmt.Errorf("Error in scheduler after previous errors (%s) trying to create container: %s", err.Error(), scheduleErr.Error())
}
return addr, nil, scheduleErr
}
addr = node.Address
} else {
addr = nodes[rand.Intn(len(nodes))]
}
if addr == "" {
return addr, nil, errors.New("CreateContainer needs a non empty node addr")
}
err = c.runHookForAddr(HookEventBeforeContainerCreate, addr)
if err != nil {
log.Errorf("Error in before create container hook in node %q: %s. Trying again in another node...", addr, err)
}
if err == nil {
container, err = c.createContainerInNode(opts, pullOpts, pullAuth, addr)
if err == nil {
c.handleNodeSuccess(addr)
break
}
log.Errorf("Error trying to create container in node %q: %s. Trying again in another node...", addr, err.Error())
}
shouldIncrementFailures := false
isCreateContainerErr := false
baseErr := err
if nodeErr, ok := baseErr.(DockerNodeError); ok {
isCreateContainerErr = nodeErr.cmd == "createContainer"
baseErr = nodeErr.BaseError()
}
if urlErr, ok := baseErr.(*url.Error); ok {
baseErr = urlErr.Err
}
_, isNetErr := baseErr.(net.Error)
if isNetErr || isCreateContainerErr || baseErr == docker.ErrConnectionRefused {
shouldIncrementFailures = true
}
c.handleNodeError(addr, err, shouldIncrementFailures)
if !useScheduler {
return addr, nil, err
}
}
if err != nil {
return addr, nil, fmt.Errorf("CreateContainer: maximum number of tries exceeded, last error: %s", err.Error())
}
err = c.storage().StoreContainer(container.ID, addr)
return addr, container, err
} | [
"func",
"(",
"c",
"*",
"Cluster",
")",
"CreateContainerPullOptsSchedulerOpts",
"(",
"opts",
"docker",
".",
"CreateContainerOptions",
",",
"pullOpts",
"docker",
".",
"PullImageOptions",
",",
"pullAuth",
"docker",
".",
"AuthConfiguration",
",",
"schedulerOpts",
"Schedul... | // Similar to CreateContainer but allows arbritary options to be passed to
// the scheduler and to the pull image call. | [
"Similar",
"to",
"CreateContainer",
"but",
"allows",
"arbritary",
"options",
"to",
"be",
"passed",
"to",
"the",
"scheduler",
"and",
"to",
"the",
"pull",
"image",
"call",
"."
] | f372d8d4e3549863e8ca98c233f645bf3d2c1055 | https://github.com/tsuru/docker-cluster/blob/f372d8d4e3549863e8ca98c233f645bf3d2c1055/cluster/container.go#L45-L112 |
5,943 | tsuru/docker-cluster | cluster/container.go | InspectContainer | func (c *Cluster) InspectContainer(id string) (*docker.Container, error) {
node, err := c.getNodeForContainer(id)
if err != nil {
return nil, err
}
cont, err := node.InspectContainer(id)
return cont, wrapError(node, err)
} | go | func (c *Cluster) InspectContainer(id string) (*docker.Container, error) {
node, err := c.getNodeForContainer(id)
if err != nil {
return nil, err
}
cont, err := node.InspectContainer(id)
return cont, wrapError(node, err)
} | [
"func",
"(",
"c",
"*",
"Cluster",
")",
"InspectContainer",
"(",
"id",
"string",
")",
"(",
"*",
"docker",
".",
"Container",
",",
"error",
")",
"{",
"node",
",",
"err",
":=",
"c",
".",
"getNodeForContainer",
"(",
"id",
")",
"\n",
"if",
"err",
"!=",
"... | // InspectContainer returns information about a container by its ID, getting
// the information from the right node. | [
"InspectContainer",
"returns",
"information",
"about",
"a",
"container",
"by",
"its",
"ID",
"getting",
"the",
"information",
"from",
"the",
"right",
"node",
"."
] | f372d8d4e3549863e8ca98c233f645bf3d2c1055 | https://github.com/tsuru/docker-cluster/blob/f372d8d4e3549863e8ca98c233f645bf3d2c1055/cluster/container.go#L132-L139 |
5,944 | tsuru/docker-cluster | cluster/container.go | KillContainer | func (c *Cluster) KillContainer(opts docker.KillContainerOptions) error {
node, err := c.getNodeForContainer(opts.ID)
if err != nil {
return err
}
return wrapError(node, node.KillContainer(opts))
} | go | func (c *Cluster) KillContainer(opts docker.KillContainerOptions) error {
node, err := c.getNodeForContainer(opts.ID)
if err != nil {
return err
}
return wrapError(node, node.KillContainer(opts))
} | [
"func",
"(",
"c",
"*",
"Cluster",
")",
"KillContainer",
"(",
"opts",
"docker",
".",
"KillContainerOptions",
")",
"error",
"{",
"node",
",",
"err",
":=",
"c",
".",
"getNodeForContainer",
"(",
"opts",
".",
"ID",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
... | // KillContainer kills a container, returning an error in case of failure. | [
"KillContainer",
"kills",
"a",
"container",
"returning",
"an",
"error",
"in",
"case",
"of",
"failure",
"."
] | f372d8d4e3549863e8ca98c233f645bf3d2c1055 | https://github.com/tsuru/docker-cluster/blob/f372d8d4e3549863e8ca98c233f645bf3d2c1055/cluster/container.go#L142-L148 |
5,945 | tsuru/docker-cluster | cluster/container.go | ListContainers | func (c *Cluster) ListContainers(opts docker.ListContainersOptions) ([]docker.APIContainers, error) {
nodes, err := c.Nodes()
if err != nil {
return nil, err
}
var wg sync.WaitGroup
result := make(chan []docker.APIContainers, len(nodes))
errs := make(chan error, len(nodes))
for _, n := range nodes {
wg.Add(1)
client, _ := c.getNodeByAddr(n.Address)
go func(n node) {
defer wg.Done()
if containers, err := n.ListContainers(opts); err != nil {
errs <- wrapError(n, err)
} else {
result <- containers
}
}(client)
}
wg.Wait()
var group []docker.APIContainers
for {
select {
case containers := <-result:
group = append(group, containers...)
case err = <-errs:
default:
return group, err
}
}
} | go | func (c *Cluster) ListContainers(opts docker.ListContainersOptions) ([]docker.APIContainers, error) {
nodes, err := c.Nodes()
if err != nil {
return nil, err
}
var wg sync.WaitGroup
result := make(chan []docker.APIContainers, len(nodes))
errs := make(chan error, len(nodes))
for _, n := range nodes {
wg.Add(1)
client, _ := c.getNodeByAddr(n.Address)
go func(n node) {
defer wg.Done()
if containers, err := n.ListContainers(opts); err != nil {
errs <- wrapError(n, err)
} else {
result <- containers
}
}(client)
}
wg.Wait()
var group []docker.APIContainers
for {
select {
case containers := <-result:
group = append(group, containers...)
case err = <-errs:
default:
return group, err
}
}
} | [
"func",
"(",
"c",
"*",
"Cluster",
")",
"ListContainers",
"(",
"opts",
"docker",
".",
"ListContainersOptions",
")",
"(",
"[",
"]",
"docker",
".",
"APIContainers",
",",
"error",
")",
"{",
"nodes",
",",
"err",
":=",
"c",
".",
"Nodes",
"(",
")",
"\n",
"i... | // ListContainers returns a slice of all containers in the cluster matching the
// given criteria. | [
"ListContainers",
"returns",
"a",
"slice",
"of",
"all",
"containers",
"in",
"the",
"cluster",
"matching",
"the",
"given",
"criteria",
"."
] | f372d8d4e3549863e8ca98c233f645bf3d2c1055 | https://github.com/tsuru/docker-cluster/blob/f372d8d4e3549863e8ca98c233f645bf3d2c1055/cluster/container.go#L152-L183 |
5,946 | tsuru/docker-cluster | cluster/container.go | RemoveContainer | func (c *Cluster) RemoveContainer(opts docker.RemoveContainerOptions) error {
return c.removeFromStorage(opts)
} | go | func (c *Cluster) RemoveContainer(opts docker.RemoveContainerOptions) error {
return c.removeFromStorage(opts)
} | [
"func",
"(",
"c",
"*",
"Cluster",
")",
"RemoveContainer",
"(",
"opts",
"docker",
".",
"RemoveContainerOptions",
")",
"error",
"{",
"return",
"c",
".",
"removeFromStorage",
"(",
"opts",
")",
"\n",
"}"
] | // RemoveContainer removes a container from the cluster. | [
"RemoveContainer",
"removes",
"a",
"container",
"from",
"the",
"cluster",
"."
] | f372d8d4e3549863e8ca98c233f645bf3d2c1055 | https://github.com/tsuru/docker-cluster/blob/f372d8d4e3549863e8ca98c233f645bf3d2c1055/cluster/container.go#L186-L188 |
5,947 | tsuru/docker-cluster | cluster/container.go | StopContainer | func (c *Cluster) StopContainer(id string, timeout uint) error {
node, err := c.getNodeForContainer(id)
if err != nil {
return err
}
return wrapError(node, node.StopContainer(id, timeout))
} | go | func (c *Cluster) StopContainer(id string, timeout uint) error {
node, err := c.getNodeForContainer(id)
if err != nil {
return err
}
return wrapError(node, node.StopContainer(id, timeout))
} | [
"func",
"(",
"c",
"*",
"Cluster",
")",
"StopContainer",
"(",
"id",
"string",
",",
"timeout",
"uint",
")",
"error",
"{",
"node",
",",
"err",
":=",
"c",
".",
"getNodeForContainer",
"(",
"id",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
... | // StopContainer stops a container, killing it after the given timeout, if it
// fails to stop nicely. | [
"StopContainer",
"stops",
"a",
"container",
"killing",
"it",
"after",
"the",
"given",
"timeout",
"if",
"it",
"fails",
"to",
"stop",
"nicely",
"."
] | f372d8d4e3549863e8ca98c233f645bf3d2c1055 | https://github.com/tsuru/docker-cluster/blob/f372d8d4e3549863e8ca98c233f645bf3d2c1055/cluster/container.go#L224-L230 |
5,948 | tsuru/docker-cluster | cluster/container.go | PauseContainer | func (c *Cluster) PauseContainer(id string) error {
node, err := c.getNodeForContainer(id)
if err != nil {
return err
}
return wrapError(node, node.PauseContainer(id))
} | go | func (c *Cluster) PauseContainer(id string) error {
node, err := c.getNodeForContainer(id)
if err != nil {
return err
}
return wrapError(node, node.PauseContainer(id))
} | [
"func",
"(",
"c",
"*",
"Cluster",
")",
"PauseContainer",
"(",
"id",
"string",
")",
"error",
"{",
"node",
",",
"err",
":=",
"c",
".",
"getNodeForContainer",
"(",
"id",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"retu... | // PauseContainer changes the container to the paused state. | [
"PauseContainer",
"changes",
"the",
"container",
"to",
"the",
"paused",
"state",
"."
] | f372d8d4e3549863e8ca98c233f645bf3d2c1055 | https://github.com/tsuru/docker-cluster/blob/f372d8d4e3549863e8ca98c233f645bf3d2c1055/cluster/container.go#L243-L249 |
5,949 | tsuru/docker-cluster | cluster/container.go | WaitContainer | func (c *Cluster) WaitContainer(id string) (int, error) {
node, err := c.getNodeForContainer(id)
if err != nil {
return -1, err
}
node.setPersistentClient()
code, err := node.WaitContainer(id)
return code, wrapError(node, err)
} | go | func (c *Cluster) WaitContainer(id string) (int, error) {
node, err := c.getNodeForContainer(id)
if err != nil {
return -1, err
}
node.setPersistentClient()
code, err := node.WaitContainer(id)
return code, wrapError(node, err)
} | [
"func",
"(",
"c",
"*",
"Cluster",
")",
"WaitContainer",
"(",
"id",
"string",
")",
"(",
"int",
",",
"error",
")",
"{",
"node",
",",
"err",
":=",
"c",
".",
"getNodeForContainer",
"(",
"id",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"-",
"... | // WaitContainer blocks until the given container stops, returning the exit
// code of the container command. | [
"WaitContainer",
"blocks",
"until",
"the",
"given",
"container",
"stops",
"returning",
"the",
"exit",
"code",
"of",
"the",
"container",
"command",
"."
] | f372d8d4e3549863e8ca98c233f645bf3d2c1055 | https://github.com/tsuru/docker-cluster/blob/f372d8d4e3549863e8ca98c233f645bf3d2c1055/cluster/container.go#L262-L270 |
5,950 | tsuru/docker-cluster | cluster/container.go | AttachToContainer | func (c *Cluster) AttachToContainer(opts docker.AttachToContainerOptions) error {
node, err := c.getNodeForContainer(opts.Container)
if err != nil {
return err
}
node.setPersistentClient()
return wrapError(node, node.AttachToContainer(opts))
} | go | func (c *Cluster) AttachToContainer(opts docker.AttachToContainerOptions) error {
node, err := c.getNodeForContainer(opts.Container)
if err != nil {
return err
}
node.setPersistentClient()
return wrapError(node, node.AttachToContainer(opts))
} | [
"func",
"(",
"c",
"*",
"Cluster",
")",
"AttachToContainer",
"(",
"opts",
"docker",
".",
"AttachToContainerOptions",
")",
"error",
"{",
"node",
",",
"err",
":=",
"c",
".",
"getNodeForContainer",
"(",
"opts",
".",
"Container",
")",
"\n",
"if",
"err",
"!=",
... | // AttachToContainer attaches to a container, using the given options. | [
"AttachToContainer",
"attaches",
"to",
"a",
"container",
"using",
"the",
"given",
"options",
"."
] | f372d8d4e3549863e8ca98c233f645bf3d2c1055 | https://github.com/tsuru/docker-cluster/blob/f372d8d4e3549863e8ca98c233f645bf3d2c1055/cluster/container.go#L273-L280 |
5,951 | tsuru/docker-cluster | cluster/container.go | AttachToContainerNonBlocking | func (c *Cluster) AttachToContainerNonBlocking(opts docker.AttachToContainerOptions) (docker.CloseWaiter, error) {
node, err := c.getNodeForContainer(opts.Container)
if err != nil {
return nil, err
}
node.setPersistentClient()
return node.AttachToContainerNonBlocking(opts)
} | go | func (c *Cluster) AttachToContainerNonBlocking(opts docker.AttachToContainerOptions) (docker.CloseWaiter, error) {
node, err := c.getNodeForContainer(opts.Container)
if err != nil {
return nil, err
}
node.setPersistentClient()
return node.AttachToContainerNonBlocking(opts)
} | [
"func",
"(",
"c",
"*",
"Cluster",
")",
"AttachToContainerNonBlocking",
"(",
"opts",
"docker",
".",
"AttachToContainerOptions",
")",
"(",
"docker",
".",
"CloseWaiter",
",",
"error",
")",
"{",
"node",
",",
"err",
":=",
"c",
".",
"getNodeForContainer",
"(",
"op... | // AttachToContainerNonBlocking attaches to a container and returns a docker.CloseWaiter, using given options. | [
"AttachToContainerNonBlocking",
"attaches",
"to",
"a",
"container",
"and",
"returns",
"a",
"docker",
".",
"CloseWaiter",
"using",
"given",
"options",
"."
] | f372d8d4e3549863e8ca98c233f645bf3d2c1055 | https://github.com/tsuru/docker-cluster/blob/f372d8d4e3549863e8ca98c233f645bf3d2c1055/cluster/container.go#L283-L290 |
5,952 | tsuru/docker-cluster | cluster/container.go | Logs | func (c *Cluster) Logs(opts docker.LogsOptions) error {
node, err := c.getNodeForContainer(opts.Container)
if err != nil {
return err
}
return wrapError(node, node.Logs(opts))
} | go | func (c *Cluster) Logs(opts docker.LogsOptions) error {
node, err := c.getNodeForContainer(opts.Container)
if err != nil {
return err
}
return wrapError(node, node.Logs(opts))
} | [
"func",
"(",
"c",
"*",
"Cluster",
")",
"Logs",
"(",
"opts",
"docker",
".",
"LogsOptions",
")",
"error",
"{",
"node",
",",
"err",
":=",
"c",
".",
"getNodeForContainer",
"(",
"opts",
".",
"Container",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",... | // Logs retrieves the logs of the specified container. | [
"Logs",
"retrieves",
"the",
"logs",
"of",
"the",
"specified",
"container",
"."
] | f372d8d4e3549863e8ca98c233f645bf3d2c1055 | https://github.com/tsuru/docker-cluster/blob/f372d8d4e3549863e8ca98c233f645bf3d2c1055/cluster/container.go#L293-L299 |
5,953 | tsuru/docker-cluster | cluster/container.go | CommitContainer | func (c *Cluster) CommitContainer(opts docker.CommitContainerOptions) (*docker.Image, error) {
node, err := c.getNodeForContainer(opts.Container)
if err != nil {
return nil, err
}
node.setPersistentClient()
image, err := node.CommitContainer(opts)
if err != nil {
return nil, wrapError(node, err)
}
key := imageKey(opts.Repository, opts.Tag)
if key != "" {
err = c.storage().StoreImage(key, image.ID, node.addr)
if err != nil {
return nil, err
}
}
return image, nil
} | go | func (c *Cluster) CommitContainer(opts docker.CommitContainerOptions) (*docker.Image, error) {
node, err := c.getNodeForContainer(opts.Container)
if err != nil {
return nil, err
}
node.setPersistentClient()
image, err := node.CommitContainer(opts)
if err != nil {
return nil, wrapError(node, err)
}
key := imageKey(opts.Repository, opts.Tag)
if key != "" {
err = c.storage().StoreImage(key, image.ID, node.addr)
if err != nil {
return nil, err
}
}
return image, nil
} | [
"func",
"(",
"c",
"*",
"Cluster",
")",
"CommitContainer",
"(",
"opts",
"docker",
".",
"CommitContainerOptions",
")",
"(",
"*",
"docker",
".",
"Image",
",",
"error",
")",
"{",
"node",
",",
"err",
":=",
"c",
".",
"getNodeForContainer",
"(",
"opts",
".",
... | // CommitContainer commits a container and returns the image id. | [
"CommitContainer",
"commits",
"a",
"container",
"and",
"returns",
"the",
"image",
"id",
"."
] | f372d8d4e3549863e8ca98c233f645bf3d2c1055 | https://github.com/tsuru/docker-cluster/blob/f372d8d4e3549863e8ca98c233f645bf3d2c1055/cluster/container.go#L302-L320 |
5,954 | tsuru/docker-cluster | cluster/container.go | ExportContainer | func (c *Cluster) ExportContainer(opts docker.ExportContainerOptions) error {
node, err := c.getNodeForContainer(opts.ID)
if err != nil {
return err
}
return wrapError(node, node.ExportContainer(opts))
} | go | func (c *Cluster) ExportContainer(opts docker.ExportContainerOptions) error {
node, err := c.getNodeForContainer(opts.ID)
if err != nil {
return err
}
return wrapError(node, node.ExportContainer(opts))
} | [
"func",
"(",
"c",
"*",
"Cluster",
")",
"ExportContainer",
"(",
"opts",
"docker",
".",
"ExportContainerOptions",
")",
"error",
"{",
"node",
",",
"err",
":=",
"c",
".",
"getNodeForContainer",
"(",
"opts",
".",
"ID",
")",
"\n",
"if",
"err",
"!=",
"nil",
"... | // ExportContainer exports a container as a tar and writes
// the result in out. | [
"ExportContainer",
"exports",
"a",
"container",
"as",
"a",
"tar",
"and",
"writes",
"the",
"result",
"in",
"out",
"."
] | f372d8d4e3549863e8ca98c233f645bf3d2c1055 | https://github.com/tsuru/docker-cluster/blob/f372d8d4e3549863e8ca98c233f645bf3d2c1055/cluster/container.go#L324-L330 |
5,955 | tsuru/docker-cluster | cluster/container.go | TopContainer | func (c *Cluster) TopContainer(id string, psArgs string) (docker.TopResult, error) {
node, err := c.getNodeForContainer(id)
if err != nil {
return docker.TopResult{}, err
}
result, err := node.TopContainer(id, psArgs)
return result, wrapError(node, err)
} | go | func (c *Cluster) TopContainer(id string, psArgs string) (docker.TopResult, error) {
node, err := c.getNodeForContainer(id)
if err != nil {
return docker.TopResult{}, err
}
result, err := node.TopContainer(id, psArgs)
return result, wrapError(node, err)
} | [
"func",
"(",
"c",
"*",
"Cluster",
")",
"TopContainer",
"(",
"id",
"string",
",",
"psArgs",
"string",
")",
"(",
"docker",
".",
"TopResult",
",",
"error",
")",
"{",
"node",
",",
"err",
":=",
"c",
".",
"getNodeForContainer",
"(",
"id",
")",
"\n",
"if",
... | // TopContainer returns information about running processes inside a container
// by its ID, getting the information from the right node. | [
"TopContainer",
"returns",
"information",
"about",
"running",
"processes",
"inside",
"a",
"container",
"by",
"its",
"ID",
"getting",
"the",
"information",
"from",
"the",
"right",
"node",
"."
] | f372d8d4e3549863e8ca98c233f645bf3d2c1055 | https://github.com/tsuru/docker-cluster/blob/f372d8d4e3549863e8ca98c233f645bf3d2c1055/cluster/container.go#L334-L341 |
5,956 | tsuru/docker-cluster | cluster/cluster.go | New | func New(scheduler Scheduler, storage Storage, caPath string, nodes ...Node) (*Cluster, error) {
var (
c Cluster
err error
)
if storage == nil {
return nil, errStorageMandatory
}
c.stor = storage
c.scheduler = scheduler
if caPath != "" {
tlsConfig, errTLS := readTLSConfig(caPath)
if errTLS != nil {
return nil, errTLS
}
c.tlsConfig = tlsConfig
}
c.Healer = DefaultHealer{}
if scheduler == nil {
c.scheduler = &roundRobin{lastUsed: -1}
}
if len(nodes) > 0 {
for _, n := range nodes {
err = c.Register(n)
if err != nil {
return &c, err
}
}
}
return &c, err
} | go | func New(scheduler Scheduler, storage Storage, caPath string, nodes ...Node) (*Cluster, error) {
var (
c Cluster
err error
)
if storage == nil {
return nil, errStorageMandatory
}
c.stor = storage
c.scheduler = scheduler
if caPath != "" {
tlsConfig, errTLS := readTLSConfig(caPath)
if errTLS != nil {
return nil, errTLS
}
c.tlsConfig = tlsConfig
}
c.Healer = DefaultHealer{}
if scheduler == nil {
c.scheduler = &roundRobin{lastUsed: -1}
}
if len(nodes) > 0 {
for _, n := range nodes {
err = c.Register(n)
if err != nil {
return &c, err
}
}
}
return &c, err
} | [
"func",
"New",
"(",
"scheduler",
"Scheduler",
",",
"storage",
"Storage",
",",
"caPath",
"string",
",",
"nodes",
"...",
"Node",
")",
"(",
"*",
"Cluster",
",",
"error",
")",
"{",
"var",
"(",
"c",
"Cluster",
"\n",
"err",
"error",
"\n",
")",
"\n",
"if",
... | // New creates a new Cluster, initially composed by the given nodes.
//
// The scheduler parameter defines the scheduling strategy. It defaults
// to round robin if nil.
// The storage parameter is the storage the cluster instance will use. | [
"New",
"creates",
"a",
"new",
"Cluster",
"initially",
"composed",
"by",
"the",
"given",
"nodes",
".",
"The",
"scheduler",
"parameter",
"defines",
"the",
"scheduling",
"strategy",
".",
"It",
"defaults",
"to",
"round",
"robin",
"if",
"nil",
".",
"The",
"storag... | f372d8d4e3549863e8ca98c233f645bf3d2c1055 | https://github.com/tsuru/docker-cluster/blob/f372d8d4e3549863e8ca98c233f645bf3d2c1055/cluster/cluster.go#L163-L193 |
5,957 | tsuru/docker-cluster | cluster/cluster.go | Register | func (c *Cluster) Register(node Node) error {
if node.Address == "" {
return errors.New("Invalid address")
}
node.defTLSConfig = c.tlsConfig
err := c.runHooks(HookEventBeforeNodeRegister, &node)
if err != nil {
return err
}
return c.storage().StoreNode(node)
} | go | func (c *Cluster) Register(node Node) error {
if node.Address == "" {
return errors.New("Invalid address")
}
node.defTLSConfig = c.tlsConfig
err := c.runHooks(HookEventBeforeNodeRegister, &node)
if err != nil {
return err
}
return c.storage().StoreNode(node)
} | [
"func",
"(",
"c",
"*",
"Cluster",
")",
"Register",
"(",
"node",
"Node",
")",
"error",
"{",
"if",
"node",
".",
"Address",
"==",
"\"",
"\"",
"{",
"return",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"node",
".",
"defTLSConfig",
"=... | // Register adds new nodes to the cluster. | [
"Register",
"adds",
"new",
"nodes",
"to",
"the",
"cluster",
"."
] | f372d8d4e3549863e8ca98c233f645bf3d2c1055 | https://github.com/tsuru/docker-cluster/blob/f372d8d4e3549863e8ca98c233f645bf3d2c1055/cluster/cluster.go#L223-L233 |
5,958 | tsuru/docker-cluster | cluster/cluster.go | Unregister | func (c *Cluster) Unregister(address string) error {
err := c.runHookForAddr(HookEventBeforeNodeUnregister, address)
if err != nil {
return err
}
return c.storage().RemoveNode(address)
} | go | func (c *Cluster) Unregister(address string) error {
err := c.runHookForAddr(HookEventBeforeNodeUnregister, address)
if err != nil {
return err
}
return c.storage().RemoveNode(address)
} | [
"func",
"(",
"c",
"*",
"Cluster",
")",
"Unregister",
"(",
"address",
"string",
")",
"error",
"{",
"err",
":=",
"c",
".",
"runHookForAddr",
"(",
"HookEventBeforeNodeUnregister",
",",
"address",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\... | // Unregister removes nodes from the cluster. | [
"Unregister",
"removes",
"nodes",
"from",
"the",
"cluster",
"."
] | f372d8d4e3549863e8ca98c233f645bf3d2c1055 | https://github.com/tsuru/docker-cluster/blob/f372d8d4e3549863e8ca98c233f645bf3d2c1055/cluster/cluster.go#L274-L280 |
5,959 | tsuru/docker-cluster | cluster/image.go | RemoveImage | func (c *Cluster) RemoveImage(name string) error {
stor := c.storage()
image, err := stor.RetrieveImage(name)
if err != nil {
return err
}
hosts := []string{}
idMap := map[string][]string{}
for _, entry := range image.History {
_, isOld := idMap[entry.Node]
idMap[entry.Node] = append(idMap[entry.Node], entry.ImageId)
if !isOld {
hosts = append(hosts, entry.Node)
}
}
_, err = c.runOnNodes(func(n node) (interface{}, error) {
imgIds, _ := idMap[n.addr]
err = n.RemoveImage(name)
_, isNetErr := err.(net.Error)
if err == docker.ErrConnectionRefused {
isNetErr = true
}
if err != nil && err != docker.ErrNoSuchImage && !isNetErr {
return nil, err
}
for _, imgId := range imgIds {
// Errors are ignored here because we're just ensuring any
// remaining data that wasn't removed when calling remove with the
// image name is removed now, no big deal if there're errors here.
n.RemoveImage(imgId)
stor.RemoveImage(name, imgId, n.addr)
}
return nil, nil
}, docker.ErrNoSuchImage, true, hosts...)
return err
} | go | func (c *Cluster) RemoveImage(name string) error {
stor := c.storage()
image, err := stor.RetrieveImage(name)
if err != nil {
return err
}
hosts := []string{}
idMap := map[string][]string{}
for _, entry := range image.History {
_, isOld := idMap[entry.Node]
idMap[entry.Node] = append(idMap[entry.Node], entry.ImageId)
if !isOld {
hosts = append(hosts, entry.Node)
}
}
_, err = c.runOnNodes(func(n node) (interface{}, error) {
imgIds, _ := idMap[n.addr]
err = n.RemoveImage(name)
_, isNetErr := err.(net.Error)
if err == docker.ErrConnectionRefused {
isNetErr = true
}
if err != nil && err != docker.ErrNoSuchImage && !isNetErr {
return nil, err
}
for _, imgId := range imgIds {
// Errors are ignored here because we're just ensuring any
// remaining data that wasn't removed when calling remove with the
// image name is removed now, no big deal if there're errors here.
n.RemoveImage(imgId)
stor.RemoveImage(name, imgId, n.addr)
}
return nil, nil
}, docker.ErrNoSuchImage, true, hosts...)
return err
} | [
"func",
"(",
"c",
"*",
"Cluster",
")",
"RemoveImage",
"(",
"name",
"string",
")",
"error",
"{",
"stor",
":=",
"c",
".",
"storage",
"(",
")",
"\n",
"image",
",",
"err",
":=",
"stor",
".",
"RetrieveImage",
"(",
"name",
")",
"\n",
"if",
"err",
"!=",
... | // RemoveImage removes an image from the nodes where this images exists,
// returning an error in case of failure. Will wait for the image to be
// removed on all nodes. | [
"RemoveImage",
"removes",
"an",
"image",
"from",
"the",
"nodes",
"where",
"this",
"images",
"exists",
"returning",
"an",
"error",
"in",
"case",
"of",
"failure",
".",
"Will",
"wait",
"for",
"the",
"image",
"to",
"be",
"removed",
"on",
"all",
"nodes",
"."
] | f372d8d4e3549863e8ca98c233f645bf3d2c1055 | https://github.com/tsuru/docker-cluster/blob/f372d8d4e3549863e8ca98c233f645bf3d2c1055/cluster/image.go#L37-L72 |
5,960 | tsuru/docker-cluster | cluster/image.go | PullImage | func (c *Cluster) PullImage(opts docker.PullImageOptions, auth docker.AuthConfiguration, nodes ...string) error {
var w safe.Buffer
if opts.OutputStream != nil {
mw := io.MultiWriter(&w, opts.OutputStream)
opts.OutputStream = mw
} else {
opts.OutputStream = &w
}
key := imageKey(opts.Repository, opts.Tag)
_, err := c.runOnNodes(func(n node) (interface{}, error) {
n.setPersistentClient()
err := n.PullImage(opts, auth)
if err != nil {
return nil, err
}
img, err := n.InspectImage(key)
if err != nil {
return nil, err
}
return nil, c.storage().StoreImage(key, img.ID, n.addr)
}, docker.ErrNoSuchImage, true, nodes...)
if err != nil {
return err
}
digest, _ := fix.GetImageDigest(w.String())
return c.storage().SetImageDigest(key, digest)
} | go | func (c *Cluster) PullImage(opts docker.PullImageOptions, auth docker.AuthConfiguration, nodes ...string) error {
var w safe.Buffer
if opts.OutputStream != nil {
mw := io.MultiWriter(&w, opts.OutputStream)
opts.OutputStream = mw
} else {
opts.OutputStream = &w
}
key := imageKey(opts.Repository, opts.Tag)
_, err := c.runOnNodes(func(n node) (interface{}, error) {
n.setPersistentClient()
err := n.PullImage(opts, auth)
if err != nil {
return nil, err
}
img, err := n.InspectImage(key)
if err != nil {
return nil, err
}
return nil, c.storage().StoreImage(key, img.ID, n.addr)
}, docker.ErrNoSuchImage, true, nodes...)
if err != nil {
return err
}
digest, _ := fix.GetImageDigest(w.String())
return c.storage().SetImageDigest(key, digest)
} | [
"func",
"(",
"c",
"*",
"Cluster",
")",
"PullImage",
"(",
"opts",
"docker",
".",
"PullImageOptions",
",",
"auth",
"docker",
".",
"AuthConfiguration",
",",
"nodes",
"...",
"string",
")",
"error",
"{",
"var",
"w",
"safe",
".",
"Buffer",
"\n",
"if",
"opts",
... | // PullImage pulls an image from a remote registry server, returning an error
// in case of failure.
//
// It will pull all images in parallel, so users need to make sure that the
// given buffer is safe. | [
"PullImage",
"pulls",
"an",
"image",
"from",
"a",
"remote",
"registry",
"server",
"returning",
"an",
"error",
"in",
"case",
"of",
"failure",
".",
"It",
"will",
"pull",
"all",
"images",
"in",
"parallel",
"so",
"users",
"need",
"to",
"make",
"sure",
"that",
... | f372d8d4e3549863e8ca98c233f645bf3d2c1055 | https://github.com/tsuru/docker-cluster/blob/f372d8d4e3549863e8ca98c233f645bf3d2c1055/cluster/image.go#L90-L116 |
5,961 | tsuru/docker-cluster | cluster/image.go | TagImage | func (c *Cluster) TagImage(name string, opts docker.TagImageOptions) error {
img, err := c.storage().RetrieveImage(name)
if err != nil {
return err
}
node, err := c.getNodeByAddr(img.LastNode)
if err != nil {
return err
}
err = node.TagImage(name, opts)
if err != nil {
return wrapError(node, err)
}
key := imageKey(opts.Repo, opts.Tag)
return c.storage().StoreImage(key, img.LastId, node.addr)
} | go | func (c *Cluster) TagImage(name string, opts docker.TagImageOptions) error {
img, err := c.storage().RetrieveImage(name)
if err != nil {
return err
}
node, err := c.getNodeByAddr(img.LastNode)
if err != nil {
return err
}
err = node.TagImage(name, opts)
if err != nil {
return wrapError(node, err)
}
key := imageKey(opts.Repo, opts.Tag)
return c.storage().StoreImage(key, img.LastId, node.addr)
} | [
"func",
"(",
"c",
"*",
"Cluster",
")",
"TagImage",
"(",
"name",
"string",
",",
"opts",
"docker",
".",
"TagImageOptions",
")",
"error",
"{",
"img",
",",
"err",
":=",
"c",
".",
"storage",
"(",
")",
".",
"RetrieveImage",
"(",
"name",
")",
"\n",
"if",
... | // TagImage adds a tag to the given image, returning an error in case of
// failure. | [
"TagImage",
"adds",
"a",
"tag",
"to",
"the",
"given",
"image",
"returning",
"an",
"error",
"in",
"case",
"of",
"failure",
"."
] | f372d8d4e3549863e8ca98c233f645bf3d2c1055 | https://github.com/tsuru/docker-cluster/blob/f372d8d4e3549863e8ca98c233f645bf3d2c1055/cluster/image.go#L120-L135 |
5,962 | tsuru/docker-cluster | cluster/image.go | PushImage | func (c *Cluster) PushImage(opts docker.PushImageOptions, auth docker.AuthConfiguration) error {
key := imageKey(opts.Name, opts.Tag)
img, err := c.storage().RetrieveImage(key)
if err != nil {
return err
}
node, err := c.getNodeByAddr(img.LastNode)
if err != nil {
return err
}
node.setPersistentClient()
return wrapError(node, node.PushImage(opts, auth))
} | go | func (c *Cluster) PushImage(opts docker.PushImageOptions, auth docker.AuthConfiguration) error {
key := imageKey(opts.Name, opts.Tag)
img, err := c.storage().RetrieveImage(key)
if err != nil {
return err
}
node, err := c.getNodeByAddr(img.LastNode)
if err != nil {
return err
}
node.setPersistentClient()
return wrapError(node, node.PushImage(opts, auth))
} | [
"func",
"(",
"c",
"*",
"Cluster",
")",
"PushImage",
"(",
"opts",
"docker",
".",
"PushImageOptions",
",",
"auth",
"docker",
".",
"AuthConfiguration",
")",
"error",
"{",
"key",
":=",
"imageKey",
"(",
"opts",
".",
"Name",
",",
"opts",
".",
"Tag",
")",
"\n... | // PushImage pushes an image to a remote registry server, returning an error in
// case of failure. | [
"PushImage",
"pushes",
"an",
"image",
"to",
"a",
"remote",
"registry",
"server",
"returning",
"an",
"error",
"in",
"case",
"of",
"failure",
"."
] | f372d8d4e3549863e8ca98c233f645bf3d2c1055 | https://github.com/tsuru/docker-cluster/blob/f372d8d4e3549863e8ca98c233f645bf3d2c1055/cluster/image.go#L139-L151 |
5,963 | tsuru/docker-cluster | cluster/image.go | InspectImage | func (c *Cluster) InspectImage(repo string) (*docker.Image, error) {
img, err := c.storage().RetrieveImage(repo)
if err != nil {
return nil, err
}
node, err := c.getNodeByAddr(img.LastNode)
if err != nil {
return nil, err
}
dockerImg, err := node.InspectImage(repo)
return dockerImg, wrapError(node, err)
} | go | func (c *Cluster) InspectImage(repo string) (*docker.Image, error) {
img, err := c.storage().RetrieveImage(repo)
if err != nil {
return nil, err
}
node, err := c.getNodeByAddr(img.LastNode)
if err != nil {
return nil, err
}
dockerImg, err := node.InspectImage(repo)
return dockerImg, wrapError(node, err)
} | [
"func",
"(",
"c",
"*",
"Cluster",
")",
"InspectImage",
"(",
"repo",
"string",
")",
"(",
"*",
"docker",
".",
"Image",
",",
"error",
")",
"{",
"img",
",",
"err",
":=",
"c",
".",
"storage",
"(",
")",
".",
"RetrieveImage",
"(",
"repo",
")",
"\n",
"if... | // InspectImage inspects an image based on its repo name | [
"InspectImage",
"inspects",
"an",
"image",
"based",
"on",
"its",
"repo",
"name"
] | f372d8d4e3549863e8ca98c233f645bf3d2c1055 | https://github.com/tsuru/docker-cluster/blob/f372d8d4e3549863e8ca98c233f645bf3d2c1055/cluster/image.go#L154-L165 |
5,964 | tsuru/docker-cluster | cluster/image.go | ImageHistory | func (c *Cluster) ImageHistory(repo string) ([]docker.ImageHistory, error) {
img, err := c.storage().RetrieveImage(repo)
if err != nil {
return nil, err
}
node, err := c.getNodeByAddr(img.LastNode)
if err != nil {
return nil, err
}
imgHistory, err := node.ImageHistory(repo)
return imgHistory, wrapError(node, err)
} | go | func (c *Cluster) ImageHistory(repo string) ([]docker.ImageHistory, error) {
img, err := c.storage().RetrieveImage(repo)
if err != nil {
return nil, err
}
node, err := c.getNodeByAddr(img.LastNode)
if err != nil {
return nil, err
}
imgHistory, err := node.ImageHistory(repo)
return imgHistory, wrapError(node, err)
} | [
"func",
"(",
"c",
"*",
"Cluster",
")",
"ImageHistory",
"(",
"repo",
"string",
")",
"(",
"[",
"]",
"docker",
".",
"ImageHistory",
",",
"error",
")",
"{",
"img",
",",
"err",
":=",
"c",
".",
"storage",
"(",
")",
".",
"RetrieveImage",
"(",
"repo",
")",... | // ImageHistory returns the history of a given image | [
"ImageHistory",
"returns",
"the",
"history",
"of",
"a",
"given",
"image"
] | f372d8d4e3549863e8ca98c233f645bf3d2c1055 | https://github.com/tsuru/docker-cluster/blob/f372d8d4e3549863e8ca98c233f645bf3d2c1055/cluster/image.go#L168-L179 |
5,965 | tsuru/docker-cluster | cluster/image.go | ListImages | func (c *Cluster) ListImages(opts docker.ListImagesOptions) ([]docker.APIImages, error) {
nodes, err := c.UnfilteredNodes()
if err != nil {
return nil, err
}
resultChan := make(chan []docker.APIImages, len(nodes))
errChan := make(chan error, len(nodes))
var wg sync.WaitGroup
for _, node := range nodes {
wg.Add(1)
go func(addr string) {
defer wg.Done()
client, err := c.getNodeByAddr(addr)
if err != nil {
errChan <- err
}
nodeImages, err := client.ListImages(opts)
if err != nil {
errChan <- wrapError(client, err)
}
resultChan <- nodeImages
}(node.Address)
}
wg.Wait()
close(resultChan)
close(errChan)
var allImages []docker.APIImages
for images := range resultChan {
allImages = append(allImages, images...)
}
select {
case err := <-errChan:
return allImages, err
default:
}
return allImages, nil
} | go | func (c *Cluster) ListImages(opts docker.ListImagesOptions) ([]docker.APIImages, error) {
nodes, err := c.UnfilteredNodes()
if err != nil {
return nil, err
}
resultChan := make(chan []docker.APIImages, len(nodes))
errChan := make(chan error, len(nodes))
var wg sync.WaitGroup
for _, node := range nodes {
wg.Add(1)
go func(addr string) {
defer wg.Done()
client, err := c.getNodeByAddr(addr)
if err != nil {
errChan <- err
}
nodeImages, err := client.ListImages(opts)
if err != nil {
errChan <- wrapError(client, err)
}
resultChan <- nodeImages
}(node.Address)
}
wg.Wait()
close(resultChan)
close(errChan)
var allImages []docker.APIImages
for images := range resultChan {
allImages = append(allImages, images...)
}
select {
case err := <-errChan:
return allImages, err
default:
}
return allImages, nil
} | [
"func",
"(",
"c",
"*",
"Cluster",
")",
"ListImages",
"(",
"opts",
"docker",
".",
"ListImagesOptions",
")",
"(",
"[",
"]",
"docker",
".",
"APIImages",
",",
"error",
")",
"{",
"nodes",
",",
"err",
":=",
"c",
".",
"UnfilteredNodes",
"(",
")",
"\n",
"if"... | // ListImages lists images existing in each cluster node | [
"ListImages",
"lists",
"images",
"existing",
"in",
"each",
"cluster",
"node"
] | f372d8d4e3549863e8ca98c233f645bf3d2c1055 | https://github.com/tsuru/docker-cluster/blob/f372d8d4e3549863e8ca98c233f645bf3d2c1055/cluster/image.go#L182-L218 |
5,966 | tsuru/docker-cluster | cluster/image.go | ImportImage | func (c *Cluster) ImportImage(opts docker.ImportImageOptions) error {
_, err := c.runOnNodes(func(n node) (interface{}, error) {
return nil, n.ImportImage(opts)
}, docker.ErrNoSuchImage, false)
return err
} | go | func (c *Cluster) ImportImage(opts docker.ImportImageOptions) error {
_, err := c.runOnNodes(func(n node) (interface{}, error) {
return nil, n.ImportImage(opts)
}, docker.ErrNoSuchImage, false)
return err
} | [
"func",
"(",
"c",
"*",
"Cluster",
")",
"ImportImage",
"(",
"opts",
"docker",
".",
"ImportImageOptions",
")",
"error",
"{",
"_",
",",
"err",
":=",
"c",
".",
"runOnNodes",
"(",
"func",
"(",
"n",
"node",
")",
"(",
"interface",
"{",
"}",
",",
"error",
... | // ImportImage imports an image from a url or stdin | [
"ImportImage",
"imports",
"an",
"image",
"from",
"a",
"url",
"or",
"stdin"
] | f372d8d4e3549863e8ca98c233f645bf3d2c1055 | https://github.com/tsuru/docker-cluster/blob/f372d8d4e3549863e8ca98c233f645bf3d2c1055/cluster/image.go#L221-L226 |
5,967 | tsuru/docker-cluster | cluster/image.go | BuildImage | func (c *Cluster) BuildImage(buildOptions docker.BuildImageOptions) error {
nodes, err := c.Nodes()
if err != nil {
return err
}
if len(nodes) < 1 {
return errors.New("There is no docker node. Please list one in tsuru.conf or add one with `tsuru node-add`.")
}
nodeAddress := nodes[rand.Intn(len(nodes))].Address
node, err := c.getNodeByAddr(nodeAddress)
if err != nil {
return err
}
node.setPersistentClient()
err = node.BuildImage(buildOptions)
if err != nil {
return wrapError(node, err)
}
img, err := node.InspectImage(buildOptions.Name)
if err != nil {
return wrapError(node, err)
}
return c.storage().StoreImage(buildOptions.Name, img.ID, nodeAddress)
} | go | func (c *Cluster) BuildImage(buildOptions docker.BuildImageOptions) error {
nodes, err := c.Nodes()
if err != nil {
return err
}
if len(nodes) < 1 {
return errors.New("There is no docker node. Please list one in tsuru.conf or add one with `tsuru node-add`.")
}
nodeAddress := nodes[rand.Intn(len(nodes))].Address
node, err := c.getNodeByAddr(nodeAddress)
if err != nil {
return err
}
node.setPersistentClient()
err = node.BuildImage(buildOptions)
if err != nil {
return wrapError(node, err)
}
img, err := node.InspectImage(buildOptions.Name)
if err != nil {
return wrapError(node, err)
}
return c.storage().StoreImage(buildOptions.Name, img.ID, nodeAddress)
} | [
"func",
"(",
"c",
"*",
"Cluster",
")",
"BuildImage",
"(",
"buildOptions",
"docker",
".",
"BuildImageOptions",
")",
"error",
"{",
"nodes",
",",
"err",
":=",
"c",
".",
"Nodes",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
... | //BuildImage build an image and pushes it to registry | [
"BuildImage",
"build",
"an",
"image",
"and",
"pushes",
"it",
"to",
"registry"
] | f372d8d4e3549863e8ca98c233f645bf3d2c1055 | https://github.com/tsuru/docker-cluster/blob/f372d8d4e3549863e8ca98c233f645bf3d2c1055/cluster/image.go#L229-L252 |
5,968 | vrischmann/envconfig | envconfig.go | InitWithPrefix | func InitWithPrefix(conf interface{}, prefix string) error {
return InitWithOptions(conf, Options{Prefix: prefix})
} | go | func InitWithPrefix(conf interface{}, prefix string) error {
return InitWithOptions(conf, Options{Prefix: prefix})
} | [
"func",
"InitWithPrefix",
"(",
"conf",
"interface",
"{",
"}",
",",
"prefix",
"string",
")",
"error",
"{",
"return",
"InitWithOptions",
"(",
"conf",
",",
"Options",
"{",
"Prefix",
":",
"prefix",
"}",
")",
"\n",
"}"
] | // InitWithPrefix reads the configuration from environment variables and populates the conf object. conf must be a pointer.
// Each key read will be prefixed with the prefix string. | [
"InitWithPrefix",
"reads",
"the",
"configuration",
"from",
"environment",
"variables",
"and",
"populates",
"the",
"conf",
"object",
".",
"conf",
"must",
"be",
"a",
"pointer",
".",
"Each",
"key",
"read",
"will",
"be",
"prefixed",
"with",
"the",
"prefix",
"strin... | d647766a494a7182c05fa4ddd1702c2c307a770d | https://github.com/vrischmann/envconfig/blob/d647766a494a7182c05fa4ddd1702c2c307a770d/envconfig.go#L84-L86 |
5,969 | vrischmann/envconfig | envconfig.go | InitWithOptions | func InitWithOptions(conf interface{}, opts Options) error {
value := reflect.ValueOf(conf)
if value.Kind() != reflect.Ptr {
return ErrNotAPointer
}
elem := value.Elem()
ctx := context{
name: opts.Prefix,
optional: opts.AllOptional,
leaveNil: opts.LeaveNil,
allowUnexported: opts.AllowUnexported,
}
switch elem.Kind() {
case reflect.Ptr:
if elem.IsNil() {
elem.Set(reflect.New(elem.Type().Elem()))
}
_, err := readStruct(elem.Elem(), &ctx)
return err
case reflect.Struct:
_, err := readStruct(elem, &ctx)
return err
default:
return ErrInvalidValueKind
}
} | go | func InitWithOptions(conf interface{}, opts Options) error {
value := reflect.ValueOf(conf)
if value.Kind() != reflect.Ptr {
return ErrNotAPointer
}
elem := value.Elem()
ctx := context{
name: opts.Prefix,
optional: opts.AllOptional,
leaveNil: opts.LeaveNil,
allowUnexported: opts.AllowUnexported,
}
switch elem.Kind() {
case reflect.Ptr:
if elem.IsNil() {
elem.Set(reflect.New(elem.Type().Elem()))
}
_, err := readStruct(elem.Elem(), &ctx)
return err
case reflect.Struct:
_, err := readStruct(elem, &ctx)
return err
default:
return ErrInvalidValueKind
}
} | [
"func",
"InitWithOptions",
"(",
"conf",
"interface",
"{",
"}",
",",
"opts",
"Options",
")",
"error",
"{",
"value",
":=",
"reflect",
".",
"ValueOf",
"(",
"conf",
")",
"\n",
"if",
"value",
".",
"Kind",
"(",
")",
"!=",
"reflect",
".",
"Ptr",
"{",
"retur... | // InitWithOptions reads the configuration from environment variables and populates the conf object.
// conf must be a pointer. | [
"InitWithOptions",
"reads",
"the",
"configuration",
"from",
"environment",
"variables",
"and",
"populates",
"the",
"conf",
"object",
".",
"conf",
"must",
"be",
"a",
"pointer",
"."
] | d647766a494a7182c05fa4ddd1702c2c307a770d | https://github.com/vrischmann/envconfig/blob/d647766a494a7182c05fa4ddd1702c2c307a770d/envconfig.go#L90-L117 |
5,970 | mgutz/ansi | ansi.go | colorCode | func colorCode(style string) *bytes.Buffer {
buf := bytes.NewBufferString("")
if plain || style == "" {
return buf
}
if style == "reset" {
buf.WriteString(Reset)
return buf
} else if style == "off" {
return buf
}
foregroundBackground := strings.Split(style, ":")
foreground := strings.Split(foregroundBackground[0], "+")
fgKey := foreground[0]
fg := Colors[fgKey]
fgStyle := ""
if len(foreground) > 1 {
fgStyle = foreground[1]
}
bg, bgStyle := "", ""
if len(foregroundBackground) > 1 {
background := strings.Split(foregroundBackground[1], "+")
bg = background[0]
if len(background) > 1 {
bgStyle = background[1]
}
}
buf.WriteString(start)
base := normalIntensityFG
if len(fgStyle) > 0 {
if strings.Contains(fgStyle, "b") {
buf.WriteString(bold)
}
if strings.Contains(fgStyle, "B") {
buf.WriteString(blink)
}
if strings.Contains(fgStyle, "u") {
buf.WriteString(underline)
}
if strings.Contains(fgStyle, "i") {
buf.WriteString(inverse)
}
if strings.Contains(fgStyle, "s") {
buf.WriteString(strikethrough)
}
if strings.Contains(fgStyle, "h") {
base = highIntensityFG
}
}
// if 256-color
n, err := strconv.Atoi(fgKey)
if err == nil {
fmt.Fprintf(buf, "38;5;%d;", n)
} else {
fmt.Fprintf(buf, "%d;", base+fg)
}
base = normalIntensityBG
if len(bg) > 0 {
if strings.Contains(bgStyle, "h") {
base = highIntensityBG
}
// if 256-color
n, err := strconv.Atoi(bg)
if err == nil {
fmt.Fprintf(buf, "48;5;%d;", n)
} else {
fmt.Fprintf(buf, "%d;", base+Colors[bg])
}
}
// remove last ";"
buf.Truncate(buf.Len() - 1)
buf.WriteRune('m')
return buf
} | go | func colorCode(style string) *bytes.Buffer {
buf := bytes.NewBufferString("")
if plain || style == "" {
return buf
}
if style == "reset" {
buf.WriteString(Reset)
return buf
} else if style == "off" {
return buf
}
foregroundBackground := strings.Split(style, ":")
foreground := strings.Split(foregroundBackground[0], "+")
fgKey := foreground[0]
fg := Colors[fgKey]
fgStyle := ""
if len(foreground) > 1 {
fgStyle = foreground[1]
}
bg, bgStyle := "", ""
if len(foregroundBackground) > 1 {
background := strings.Split(foregroundBackground[1], "+")
bg = background[0]
if len(background) > 1 {
bgStyle = background[1]
}
}
buf.WriteString(start)
base := normalIntensityFG
if len(fgStyle) > 0 {
if strings.Contains(fgStyle, "b") {
buf.WriteString(bold)
}
if strings.Contains(fgStyle, "B") {
buf.WriteString(blink)
}
if strings.Contains(fgStyle, "u") {
buf.WriteString(underline)
}
if strings.Contains(fgStyle, "i") {
buf.WriteString(inverse)
}
if strings.Contains(fgStyle, "s") {
buf.WriteString(strikethrough)
}
if strings.Contains(fgStyle, "h") {
base = highIntensityFG
}
}
// if 256-color
n, err := strconv.Atoi(fgKey)
if err == nil {
fmt.Fprintf(buf, "38;5;%d;", n)
} else {
fmt.Fprintf(buf, "%d;", base+fg)
}
base = normalIntensityBG
if len(bg) > 0 {
if strings.Contains(bgStyle, "h") {
base = highIntensityBG
}
// if 256-color
n, err := strconv.Atoi(bg)
if err == nil {
fmt.Fprintf(buf, "48;5;%d;", n)
} else {
fmt.Fprintf(buf, "%d;", base+Colors[bg])
}
}
// remove last ";"
buf.Truncate(buf.Len() - 1)
buf.WriteRune('m')
return buf
} | [
"func",
"colorCode",
"(",
"style",
"string",
")",
"*",
"bytes",
".",
"Buffer",
"{",
"buf",
":=",
"bytes",
".",
"NewBufferString",
"(",
"\"",
"\"",
")",
"\n",
"if",
"plain",
"||",
"style",
"==",
"\"",
"\"",
"{",
"return",
"buf",
"\n",
"}",
"\n",
"if... | // Gets the ANSI color code for a style. | [
"Gets",
"the",
"ANSI",
"color",
"code",
"for",
"a",
"style",
"."
] | 9520e82c474b0a04dd04f8a40959027271bab992 | https://github.com/mgutz/ansi/blob/9520e82c474b0a04dd04f8a40959027271bab992/ansi.go#L134-L214 |
5,971 | mgutz/ansi | ansi.go | Color | func Color(s, style string) string {
if plain || len(style) < 1 {
return s
}
buf := colorCode(style)
buf.WriteString(s)
buf.WriteString(Reset)
return buf.String()
} | go | func Color(s, style string) string {
if plain || len(style) < 1 {
return s
}
buf := colorCode(style)
buf.WriteString(s)
buf.WriteString(Reset)
return buf.String()
} | [
"func",
"Color",
"(",
"s",
",",
"style",
"string",
")",
"string",
"{",
"if",
"plain",
"||",
"len",
"(",
"style",
")",
"<",
"1",
"{",
"return",
"s",
"\n",
"}",
"\n",
"buf",
":=",
"colorCode",
"(",
"style",
")",
"\n",
"buf",
".",
"WriteString",
"("... | // Color colors a string based on the ANSI color code for style. | [
"Color",
"colors",
"a",
"string",
"based",
"on",
"the",
"ANSI",
"color",
"code",
"for",
"style",
"."
] | 9520e82c474b0a04dd04f8a40959027271bab992 | https://github.com/mgutz/ansi/blob/9520e82c474b0a04dd04f8a40959027271bab992/ansi.go#L217-L225 |
5,972 | mgutz/ansi | ansi.go | ColorFunc | func ColorFunc(style string) func(string) string {
if style == "" {
return func(s string) string {
return s
}
}
color := ColorCode(style)
return func(s string) string {
if plain || s == "" {
return s
}
buf := bytes.NewBufferString(color)
buf.WriteString(s)
buf.WriteString(Reset)
result := buf.String()
return result
}
} | go | func ColorFunc(style string) func(string) string {
if style == "" {
return func(s string) string {
return s
}
}
color := ColorCode(style)
return func(s string) string {
if plain || s == "" {
return s
}
buf := bytes.NewBufferString(color)
buf.WriteString(s)
buf.WriteString(Reset)
result := buf.String()
return result
}
} | [
"func",
"ColorFunc",
"(",
"style",
"string",
")",
"func",
"(",
"string",
")",
"string",
"{",
"if",
"style",
"==",
"\"",
"\"",
"{",
"return",
"func",
"(",
"s",
"string",
")",
"string",
"{",
"return",
"s",
"\n",
"}",
"\n",
"}",
"\n",
"color",
":=",
... | // ColorFunc creates a closure to avoid computation ANSI color code. | [
"ColorFunc",
"creates",
"a",
"closure",
"to",
"avoid",
"computation",
"ANSI",
"color",
"code",
"."
] | 9520e82c474b0a04dd04f8a40959027271bab992 | https://github.com/mgutz/ansi/blob/9520e82c474b0a04dd04f8a40959027271bab992/ansi.go#L228-L245 |
5,973 | mgutz/ansi | print.go | PrintStyles | func PrintStyles() {
// for compatibility with Windows, not needed for *nix
stdout := colorable.NewColorableStdout()
bgColors := []string{
"",
":black",
":red",
":green",
":yellow",
":blue",
":magenta",
":cyan",
":white",
}
keys := make([]string, 0, len(Colors))
for k := range Colors {
keys = append(keys, k)
}
sort.Sort(sort.StringSlice(keys))
for _, fg := range keys {
for _, bg := range bgColors {
fmt.Fprintln(stdout, padColor(fg, []string{"" + bg, "+b" + bg, "+bh" + bg, "+u" + bg}))
fmt.Fprintln(stdout, padColor(fg, []string{"+s" + bg, "+i" + bg}))
fmt.Fprintln(stdout, padColor(fg, []string{"+uh" + bg, "+B" + bg, "+Bb" + bg /* backgrounds */, "" + bg + "+h"}))
fmt.Fprintln(stdout, padColor(fg, []string{"+b" + bg + "+h", "+bh" + bg + "+h", "+u" + bg + "+h", "+uh" + bg + "+h"}))
}
}
} | go | func PrintStyles() {
// for compatibility with Windows, not needed for *nix
stdout := colorable.NewColorableStdout()
bgColors := []string{
"",
":black",
":red",
":green",
":yellow",
":blue",
":magenta",
":cyan",
":white",
}
keys := make([]string, 0, len(Colors))
for k := range Colors {
keys = append(keys, k)
}
sort.Sort(sort.StringSlice(keys))
for _, fg := range keys {
for _, bg := range bgColors {
fmt.Fprintln(stdout, padColor(fg, []string{"" + bg, "+b" + bg, "+bh" + bg, "+u" + bg}))
fmt.Fprintln(stdout, padColor(fg, []string{"+s" + bg, "+i" + bg}))
fmt.Fprintln(stdout, padColor(fg, []string{"+uh" + bg, "+B" + bg, "+Bb" + bg /* backgrounds */, "" + bg + "+h"}))
fmt.Fprintln(stdout, padColor(fg, []string{"+b" + bg + "+h", "+bh" + bg + "+h", "+u" + bg + "+h", "+uh" + bg + "+h"}))
}
}
} | [
"func",
"PrintStyles",
"(",
")",
"{",
"// for compatibility with Windows, not needed for *nix",
"stdout",
":=",
"colorable",
".",
"NewColorableStdout",
"(",
")",
"\n\n",
"bgColors",
":=",
"[",
"]",
"string",
"{",
"\"",
"\"",
",",
"\"",
"\"",
",",
"\"",
"\"",
"... | // PrintStyles prints all style combinations to the terminal. | [
"PrintStyles",
"prints",
"all",
"style",
"combinations",
"to",
"the",
"terminal",
"."
] | 9520e82c474b0a04dd04f8a40959027271bab992 | https://github.com/mgutz/ansi/blob/9520e82c474b0a04dd04f8a40959027271bab992/print.go#L11-L42 |
5,974 | libp2p/go-tcp-transport | tcp.go | tryLinger | func tryLinger(conn net.Conn, sec int) {
type canLinger interface {
SetLinger(int) error
}
if lingerConn, ok := conn.(canLinger); ok {
_ = lingerConn.SetLinger(sec)
}
} | go | func tryLinger(conn net.Conn, sec int) {
type canLinger interface {
SetLinger(int) error
}
if lingerConn, ok := conn.(canLinger); ok {
_ = lingerConn.SetLinger(sec)
}
} | [
"func",
"tryLinger",
"(",
"conn",
"net",
".",
"Conn",
",",
"sec",
"int",
")",
"{",
"type",
"canLinger",
"interface",
"{",
"SetLinger",
"(",
"int",
")",
"error",
"\n",
"}",
"\n\n",
"if",
"lingerConn",
",",
"ok",
":=",
"conn",
".",
"(",
"canLinger",
")... | // try to set linger on the connection, if possible. | [
"try",
"to",
"set",
"linger",
"on",
"the",
"connection",
"if",
"possible",
"."
] | d3b107842331578fe29ed84341f9f30a421f3e20 | https://github.com/libp2p/go-tcp-transport/blob/d3b107842331578fe29ed84341f9f30a421f3e20/tcp.go#L25-L33 |
5,975 | libp2p/go-tcp-transport | tcp.go | CanDial | func (t *TcpTransport) CanDial(addr ma.Multiaddr) bool {
return mafmt.TCP.Matches(addr)
} | go | func (t *TcpTransport) CanDial(addr ma.Multiaddr) bool {
return mafmt.TCP.Matches(addr)
} | [
"func",
"(",
"t",
"*",
"TcpTransport",
")",
"CanDial",
"(",
"addr",
"ma",
".",
"Multiaddr",
")",
"bool",
"{",
"return",
"mafmt",
".",
"TCP",
".",
"Matches",
"(",
"addr",
")",
"\n",
"}"
] | // CanDial returns true if this transport believes it can dial the given
// multiaddr. | [
"CanDial",
"returns",
"true",
"if",
"this",
"transport",
"believes",
"it",
"can",
"dial",
"the",
"given",
"multiaddr",
"."
] | d3b107842331578fe29ed84341f9f30a421f3e20 | https://github.com/libp2p/go-tcp-transport/blob/d3b107842331578fe29ed84341f9f30a421f3e20/tcp.go#L74-L76 |
5,976 | libp2p/go-tcp-transport | tcp.go | Dial | func (t *TcpTransport) Dial(ctx context.Context, raddr ma.Multiaddr, p peer.ID) (tpt.Conn, error) {
conn, err := t.maDial(ctx, raddr)
if err != nil {
return nil, err
}
// Set linger to 0 so we never get stuck in the TIME-WAIT state. When
// linger is 0, connections are _reset_ instead of closed with a FIN.
// This means we can immediately reuse the 5-tuple and reconnect.
tryLinger(conn, 0)
return t.Upgrader.UpgradeOutbound(ctx, t, conn, p)
} | go | func (t *TcpTransport) Dial(ctx context.Context, raddr ma.Multiaddr, p peer.ID) (tpt.Conn, error) {
conn, err := t.maDial(ctx, raddr)
if err != nil {
return nil, err
}
// Set linger to 0 so we never get stuck in the TIME-WAIT state. When
// linger is 0, connections are _reset_ instead of closed with a FIN.
// This means we can immediately reuse the 5-tuple and reconnect.
tryLinger(conn, 0)
return t.Upgrader.UpgradeOutbound(ctx, t, conn, p)
} | [
"func",
"(",
"t",
"*",
"TcpTransport",
")",
"Dial",
"(",
"ctx",
"context",
".",
"Context",
",",
"raddr",
"ma",
".",
"Multiaddr",
",",
"p",
"peer",
".",
"ID",
")",
"(",
"tpt",
".",
"Conn",
",",
"error",
")",
"{",
"conn",
",",
"err",
":=",
"t",
"... | // Dial dials the peer at the remote address. | [
"Dial",
"dials",
"the",
"peer",
"at",
"the",
"remote",
"address",
"."
] | d3b107842331578fe29ed84341f9f30a421f3e20 | https://github.com/libp2p/go-tcp-transport/blob/d3b107842331578fe29ed84341f9f30a421f3e20/tcp.go#L97-L107 |
5,977 | libp2p/go-tcp-transport | tcp.go | Listen | func (t *TcpTransport) Listen(laddr ma.Multiaddr) (tpt.Listener, error) {
list, err := t.maListen(laddr)
if err != nil {
return nil, err
}
list = &lingerListener{list, 0}
return t.Upgrader.UpgradeListener(t, list), nil
} | go | func (t *TcpTransport) Listen(laddr ma.Multiaddr) (tpt.Listener, error) {
list, err := t.maListen(laddr)
if err != nil {
return nil, err
}
list = &lingerListener{list, 0}
return t.Upgrader.UpgradeListener(t, list), nil
} | [
"func",
"(",
"t",
"*",
"TcpTransport",
")",
"Listen",
"(",
"laddr",
"ma",
".",
"Multiaddr",
")",
"(",
"tpt",
".",
"Listener",
",",
"error",
")",
"{",
"list",
",",
"err",
":=",
"t",
".",
"maListen",
"(",
"laddr",
")",
"\n",
"if",
"err",
"!=",
"nil... | // Listen listens on the given multiaddr. | [
"Listen",
"listens",
"on",
"the",
"given",
"multiaddr",
"."
] | d3b107842331578fe29ed84341f9f30a421f3e20 | https://github.com/libp2p/go-tcp-transport/blob/d3b107842331578fe29ed84341f9f30a421f3e20/tcp.go#L122-L129 |
5,978 | cloudfoundry/bosh-init | ui/ui.go | PrintLinef | func (ui *ui) PrintLinef(pattern string, args ...interface{}) {
message := fmt.Sprintf(pattern, args...)
_, err := fmt.Fprintln(ui.outWriter, message)
if err != nil {
ui.logger.Error(ui.logTag, "UI.PrintLinef failed (message='%s'): %s", message, err)
}
} | go | func (ui *ui) PrintLinef(pattern string, args ...interface{}) {
message := fmt.Sprintf(pattern, args...)
_, err := fmt.Fprintln(ui.outWriter, message)
if err != nil {
ui.logger.Error(ui.logTag, "UI.PrintLinef failed (message='%s'): %s", message, err)
}
} | [
"func",
"(",
"ui",
"*",
"ui",
")",
"PrintLinef",
"(",
"pattern",
"string",
",",
"args",
"...",
"interface",
"{",
"}",
")",
"{",
"message",
":=",
"fmt",
".",
"Sprintf",
"(",
"pattern",
",",
"args",
"...",
")",
"\n",
"_",
",",
"err",
":=",
"fmt",
"... | // Printlnf starts and ends a text line | [
"Printlnf",
"starts",
"and",
"ends",
"a",
"text",
"line"
] | 25ef2dbc1de0e6bb7c49f3075eaa8d1999764de6 | https://github.com/cloudfoundry/bosh-init/blob/25ef2dbc1de0e6bb7c49f3075eaa8d1999764de6/ui/ui.go#L48-L54 |
5,979 | cloudfoundry/bosh-init | ui/ui.go | BeginLinef | func (ui *ui) BeginLinef(pattern string, args ...interface{}) {
message := fmt.Sprintf(pattern, args...)
_, err := fmt.Fprint(ui.outWriter, message)
if err != nil {
ui.logger.Error(ui.logTag, "UI.BeginLinef failed (message='%s'): %s", message, err)
}
} | go | func (ui *ui) BeginLinef(pattern string, args ...interface{}) {
message := fmt.Sprintf(pattern, args...)
_, err := fmt.Fprint(ui.outWriter, message)
if err != nil {
ui.logger.Error(ui.logTag, "UI.BeginLinef failed (message='%s'): %s", message, err)
}
} | [
"func",
"(",
"ui",
"*",
"ui",
")",
"BeginLinef",
"(",
"pattern",
"string",
",",
"args",
"...",
"interface",
"{",
"}",
")",
"{",
"message",
":=",
"fmt",
".",
"Sprintf",
"(",
"pattern",
",",
"args",
"...",
")",
"\n",
"_",
",",
"err",
":=",
"fmt",
"... | // PrintBeginf starts a text line | [
"PrintBeginf",
"starts",
"a",
"text",
"line"
] | 25ef2dbc1de0e6bb7c49f3075eaa8d1999764de6 | https://github.com/cloudfoundry/bosh-init/blob/25ef2dbc1de0e6bb7c49f3075eaa8d1999764de6/ui/ui.go#L57-L63 |
5,980 | cloudfoundry/bosh-init | release/pkg/sort.go | Sort | func Sort(releasePackages []*Package) ([]*Package, error) {
sortedPackages := []*Package{}
incomingEdges, outgoingEdges := getEdgeMaps(releasePackages)
noIncomingEdgesSet := []*Package{}
for pkg, edgeList := range incomingEdges {
if len(edgeList) == 0 {
noIncomingEdgesSet = append(noIncomingEdgesSet, pkg)
}
}
for len(noIncomingEdgesSet) > 0 {
elem := noIncomingEdgesSet[0]
noIncomingEdgesSet = noIncomingEdgesSet[1:]
sortedPackages = append([]*Package{elem}, sortedPackages...)
for _, pkg := range outgoingEdges[elem] {
incomingEdges[pkg] = removeFromList(incomingEdges[pkg], elem)
if len(incomingEdges[pkg]) == 0 {
noIncomingEdgesSet = append(noIncomingEdgesSet, pkg)
}
}
}
for _, edges := range incomingEdges {
if len(edges) > 0 {
return nil, errors.New("Circular dependency detected while sorting packages")
}
}
return sortedPackages, nil
} | go | func Sort(releasePackages []*Package) ([]*Package, error) {
sortedPackages := []*Package{}
incomingEdges, outgoingEdges := getEdgeMaps(releasePackages)
noIncomingEdgesSet := []*Package{}
for pkg, edgeList := range incomingEdges {
if len(edgeList) == 0 {
noIncomingEdgesSet = append(noIncomingEdgesSet, pkg)
}
}
for len(noIncomingEdgesSet) > 0 {
elem := noIncomingEdgesSet[0]
noIncomingEdgesSet = noIncomingEdgesSet[1:]
sortedPackages = append([]*Package{elem}, sortedPackages...)
for _, pkg := range outgoingEdges[elem] {
incomingEdges[pkg] = removeFromList(incomingEdges[pkg], elem)
if len(incomingEdges[pkg]) == 0 {
noIncomingEdgesSet = append(noIncomingEdgesSet, pkg)
}
}
}
for _, edges := range incomingEdges {
if len(edges) > 0 {
return nil, errors.New("Circular dependency detected while sorting packages")
}
}
return sortedPackages, nil
} | [
"func",
"Sort",
"(",
"releasePackages",
"[",
"]",
"*",
"Package",
")",
"(",
"[",
"]",
"*",
"Package",
",",
"error",
")",
"{",
"sortedPackages",
":=",
"[",
"]",
"*",
"Package",
"{",
"}",
"\n\n",
"incomingEdges",
",",
"outgoingEdges",
":=",
"getEdgeMaps",
... | // Topologically sorts an array of packages | [
"Topologically",
"sorts",
"an",
"array",
"of",
"packages"
] | 25ef2dbc1de0e6bb7c49f3075eaa8d1999764de6 | https://github.com/cloudfoundry/bosh-init/blob/25ef2dbc1de0e6bb7c49f3075eaa8d1999764de6/release/pkg/sort.go#L9-L39 |
5,981 | gorilla/pat | pat.go | Add | func (r *Router) Add(meth, pat string, h http.Handler) *mux.Route {
return r.NewRoute().PathPrefix(pat).Handler(h).Methods(meth)
} | go | func (r *Router) Add(meth, pat string, h http.Handler) *mux.Route {
return r.NewRoute().PathPrefix(pat).Handler(h).Methods(meth)
} | [
"func",
"(",
"r",
"*",
"Router",
")",
"Add",
"(",
"meth",
",",
"pat",
"string",
",",
"h",
"http",
".",
"Handler",
")",
"*",
"mux",
".",
"Route",
"{",
"return",
"r",
".",
"NewRoute",
"(",
")",
".",
"PathPrefix",
"(",
"pat",
")",
".",
"Handler",
... | // Add registers a pattern with a handler for the given request method. | [
"Add",
"registers",
"a",
"pattern",
"with",
"a",
"handler",
"for",
"the",
"given",
"request",
"method",
"."
] | 199c85a7f6d1ed2ecd6f071892d312c00d43b031 | https://github.com/gorilla/pat/blob/199c85a7f6d1ed2ecd6f071892d312c00d43b031/pat.go#L30-L32 |
5,982 | gorilla/pat | pat.go | Options | func (r *Router) Options(pat string, h http.HandlerFunc) *mux.Route {
return r.Add("OPTIONS", pat, h)
} | go | func (r *Router) Options(pat string, h http.HandlerFunc) *mux.Route {
return r.Add("OPTIONS", pat, h)
} | [
"func",
"(",
"r",
"*",
"Router",
")",
"Options",
"(",
"pat",
"string",
",",
"h",
"http",
".",
"HandlerFunc",
")",
"*",
"mux",
".",
"Route",
"{",
"return",
"r",
".",
"Add",
"(",
"\"",
"\"",
",",
"pat",
",",
"h",
")",
"\n",
"}"
] | // Options registers a pattern with a handler for OPTIONS requests. | [
"Options",
"registers",
"a",
"pattern",
"with",
"a",
"handler",
"for",
"OPTIONS",
"requests",
"."
] | 199c85a7f6d1ed2ecd6f071892d312c00d43b031 | https://github.com/gorilla/pat/blob/199c85a7f6d1ed2ecd6f071892d312c00d43b031/pat.go#L35-L37 |
5,983 | gorilla/pat | pat.go | ServeHTTP | func (r *Router) ServeHTTP(w http.ResponseWriter, req *http.Request) {
// Clean path to canonical form and redirect.
if p := cleanPath(req.URL.Path); p != req.URL.Path {
w.Header().Set("Location", p)
w.WriteHeader(http.StatusMovedPermanently)
return
}
var match mux.RouteMatch
var handler http.Handler
if matched := r.Match(req, &match); matched {
handler = match.Handler
registerVars(req, match.Vars)
}
if handler == nil {
if r.NotFoundHandler == nil {
r.NotFoundHandler = http.NotFoundHandler()
}
handler = r.NotFoundHandler
}
if !r.KeepContext {
defer context.Clear(req)
}
handler.ServeHTTP(w, req)
} | go | func (r *Router) ServeHTTP(w http.ResponseWriter, req *http.Request) {
// Clean path to canonical form and redirect.
if p := cleanPath(req.URL.Path); p != req.URL.Path {
w.Header().Set("Location", p)
w.WriteHeader(http.StatusMovedPermanently)
return
}
var match mux.RouteMatch
var handler http.Handler
if matched := r.Match(req, &match); matched {
handler = match.Handler
registerVars(req, match.Vars)
}
if handler == nil {
if r.NotFoundHandler == nil {
r.NotFoundHandler = http.NotFoundHandler()
}
handler = r.NotFoundHandler
}
if !r.KeepContext {
defer context.Clear(req)
}
handler.ServeHTTP(w, req)
} | [
"func",
"(",
"r",
"*",
"Router",
")",
"ServeHTTP",
"(",
"w",
"http",
".",
"ResponseWriter",
",",
"req",
"*",
"http",
".",
"Request",
")",
"{",
"// Clean path to canonical form and redirect.",
"if",
"p",
":=",
"cleanPath",
"(",
"req",
".",
"URL",
".",
"Path... | // ServeHTTP dispatches the handler registered in the matched route. | [
"ServeHTTP",
"dispatches",
"the",
"handler",
"registered",
"in",
"the",
"matched",
"route",
"."
] | 199c85a7f6d1ed2ecd6f071892d312c00d43b031 | https://github.com/gorilla/pat/blob/199c85a7f6d1ed2ecd6f071892d312c00d43b031/pat.go#L70-L93 |
5,984 | gorilla/pat | pat.go | registerVars | func registerVars(r *http.Request, vars map[string]string) {
parts, i := make([]string, len(vars)), 0
for key, value := range vars {
parts[i] = url.QueryEscape(":"+key) + "=" + url.QueryEscape(value)
i++
}
q := strings.Join(parts, "&")
if r.URL.RawQuery == "" {
r.URL.RawQuery = q
} else {
r.URL.RawQuery += "&" + q
}
} | go | func registerVars(r *http.Request, vars map[string]string) {
parts, i := make([]string, len(vars)), 0
for key, value := range vars {
parts[i] = url.QueryEscape(":"+key) + "=" + url.QueryEscape(value)
i++
}
q := strings.Join(parts, "&")
if r.URL.RawQuery == "" {
r.URL.RawQuery = q
} else {
r.URL.RawQuery += "&" + q
}
} | [
"func",
"registerVars",
"(",
"r",
"*",
"http",
".",
"Request",
",",
"vars",
"map",
"[",
"string",
"]",
"string",
")",
"{",
"parts",
",",
"i",
":=",
"make",
"(",
"[",
"]",
"string",
",",
"len",
"(",
"vars",
")",
")",
",",
"0",
"\n",
"for",
"key"... | // registerVars adds the matched route variables to the URL query. | [
"registerVars",
"adds",
"the",
"matched",
"route",
"variables",
"to",
"the",
"URL",
"query",
"."
] | 199c85a7f6d1ed2ecd6f071892d312c00d43b031 | https://github.com/gorilla/pat/blob/199c85a7f6d1ed2ecd6f071892d312c00d43b031/pat.go#L96-L108 |
5,985 | ivpusic/neo | router.go | apply | func (h handler) apply(ctx *Ctx, fns []appliable, current int) {
status, err := h(ctx)
if err != nil {
log.Errorf("Error returned from route handler. %s", err.Error())
ctx.Res.Status = 500
} else {
ctx.Res.Status = status
}
current++
if len(fns) > current {
fns[current].apply(ctx, fns, current)
}
} | go | func (h handler) apply(ctx *Ctx, fns []appliable, current int) {
status, err := h(ctx)
if err != nil {
log.Errorf("Error returned from route handler. %s", err.Error())
ctx.Res.Status = 500
} else {
ctx.Res.Status = status
}
current++
if len(fns) > current {
fns[current].apply(ctx, fns, current)
}
} | [
"func",
"(",
"h",
"handler",
")",
"apply",
"(",
"ctx",
"*",
"Ctx",
",",
"fns",
"[",
"]",
"appliable",
",",
"current",
"int",
")",
"{",
"status",
",",
"err",
":=",
"h",
"(",
"ctx",
")",
"\n\n",
"if",
"err",
"!=",
"nil",
"{",
"log",
".",
"Errorf"... | // composing route with middlewares. Will be called from ``compose`` fn. | [
"composing",
"route",
"with",
"middlewares",
".",
"Will",
"be",
"called",
"from",
"compose",
"fn",
"."
] | c81644170eed26e491487d0877d8642a0a84ea8d | https://github.com/ivpusic/neo/blob/c81644170eed26e491487d0877d8642a0a84ea8d/router.go#L17-L31 |
5,986 | ivpusic/neo | router.go | makeRegion | func (r *router) makeRegion() *Region {
m := &methods{}
i := &interceptor{[]appliable{}}
region := &Region{i, m.init()}
r.regions.PushBack(region)
return region
} | go | func (r *router) makeRegion() *Region {
m := &methods{}
i := &interceptor{[]appliable{}}
region := &Region{i, m.init()}
r.regions.PushBack(region)
return region
} | [
"func",
"(",
"r",
"*",
"router",
")",
"makeRegion",
"(",
")",
"*",
"Region",
"{",
"m",
":=",
"&",
"methods",
"{",
"}",
"\n",
"i",
":=",
"&",
"interceptor",
"{",
"[",
"]",
"appliable",
"{",
"}",
"}",
"\n\n",
"region",
":=",
"&",
"Region",
"{",
"... | // making new region instance | [
"making",
"new",
"region",
"instance"
] | c81644170eed26e491487d0877d8642a0a84ea8d | https://github.com/ivpusic/neo/blob/c81644170eed26e491487d0877d8642a0a84ea8d/router.go#L71-L79 |
5,987 | ivpusic/neo | router.go | flush | func (router *router) flush() {
// first copy all middlewares to top-level routes
for method, routesSlice := range router.routes {
for i, route := range routesSlice {
route.fnChain = compose(merge(
router.middlewares,
route.middlewares,
[]appliable{route.fn},
))
router.routes[method][i] = route
}
}
// then copy all middlewares for region level routes
// this will copy all b/a from router and region
// so at the end all b/a for route will be placed directly in route
//
// mr = maybeRegion
for mr := router.regions.Front(); mr != nil; mr = mr.Next() {
region, ok := mr.Value.(*Region)
if !ok {
log.Error("cannot convert element to region")
continue
}
for method, routesSlice := range region.routes {
for _, route := range routesSlice {
route.fnChain = compose(merge(
router.middlewares,
region.middlewares,
route.middlewares,
[]appliable{route.fn},
))
router.routes[method] = append(router.routes[method], route)
}
// remove method key from region (GET, POST,...)
delete(region.routes, method)
}
}
// remove regions, we don't need them anymore
router.regions.Init()
} | go | func (router *router) flush() {
// first copy all middlewares to top-level routes
for method, routesSlice := range router.routes {
for i, route := range routesSlice {
route.fnChain = compose(merge(
router.middlewares,
route.middlewares,
[]appliable{route.fn},
))
router.routes[method][i] = route
}
}
// then copy all middlewares for region level routes
// this will copy all b/a from router and region
// so at the end all b/a for route will be placed directly in route
//
// mr = maybeRegion
for mr := router.regions.Front(); mr != nil; mr = mr.Next() {
region, ok := mr.Value.(*Region)
if !ok {
log.Error("cannot convert element to region")
continue
}
for method, routesSlice := range region.routes {
for _, route := range routesSlice {
route.fnChain = compose(merge(
router.middlewares,
region.middlewares,
route.middlewares,
[]appliable{route.fn},
))
router.routes[method] = append(router.routes[method], route)
}
// remove method key from region (GET, POST,...)
delete(region.routes, method)
}
}
// remove regions, we don't need them anymore
router.regions.Init()
} | [
"func",
"(",
"router",
"*",
"router",
")",
"flush",
"(",
")",
"{",
"// first copy all middlewares to top-level routes",
"for",
"method",
",",
"routesSlice",
":=",
"range",
"router",
".",
"routes",
"{",
"for",
"i",
",",
"route",
":=",
"range",
"routesSlice",
"{... | // forcing all middlewares to copy to appropriate routes
// also cleans up intrnal structures | [
"forcing",
"all",
"middlewares",
"to",
"copy",
"to",
"appropriate",
"routes",
"also",
"cleans",
"up",
"intrnal",
"structures"
] | c81644170eed26e491487d0877d8642a0a84ea8d | https://github.com/ivpusic/neo/blob/c81644170eed26e491487d0877d8642a0a84ea8d/router.go#L83-L130 |
5,988 | ivpusic/neo | ctx.go | Error | func (c *Ctx) Error(err error) {
c.Errors = append(c.Errors, err)
} | go | func (c *Ctx) Error(err error) {
c.Errors = append(c.Errors, err)
} | [
"func",
"(",
"c",
"*",
"Ctx",
")",
"Error",
"(",
"err",
"error",
")",
"{",
"c",
".",
"Errors",
"=",
"append",
"(",
"c",
".",
"Errors",
",",
"err",
")",
"\n",
"}"
] | // Append error to list of errors for current http request.
// This function can be used from any part of your code which has access to current context | [
"Append",
"error",
"to",
"list",
"of",
"errors",
"for",
"current",
"http",
"request",
".",
"This",
"function",
"can",
"be",
"used",
"from",
"any",
"part",
"of",
"your",
"code",
"which",
"has",
"access",
"to",
"current",
"context"
] | c81644170eed26e491487d0877d8642a0a84ea8d | https://github.com/ivpusic/neo/blob/c81644170eed26e491487d0877d8642a0a84ea8d/ctx.go#L69-L71 |
5,989 | ivpusic/neo | ctx.go | makeCtx | func makeCtx(req *http.Request, w http.ResponseWriter) *Ctx {
request := makeRequest(req)
response := makeResponse(req, w)
// 404 - OK by default
// this can be overided by middlewares and handler fns
response.Status = 404
ctx := &Ctx{
Req: request,
Res: response,
Data: CtxData{},
Errors: []error{},
}
ctx.InitEBus()
return ctx
} | go | func makeCtx(req *http.Request, w http.ResponseWriter) *Ctx {
request := makeRequest(req)
response := makeResponse(req, w)
// 404 - OK by default
// this can be overided by middlewares and handler fns
response.Status = 404
ctx := &Ctx{
Req: request,
Res: response,
Data: CtxData{},
Errors: []error{},
}
ctx.InitEBus()
return ctx
} | [
"func",
"makeCtx",
"(",
"req",
"*",
"http",
".",
"Request",
",",
"w",
"http",
".",
"ResponseWriter",
")",
"*",
"Ctx",
"{",
"request",
":=",
"makeRequest",
"(",
"req",
")",
"\n",
"response",
":=",
"makeResponse",
"(",
"req",
",",
"w",
")",
"\n",
"// 4... | // Will make default contextual data based on provided request and ResponseWriter | [
"Will",
"make",
"default",
"contextual",
"data",
"based",
"on",
"provided",
"request",
"and",
"ResponseWriter"
] | c81644170eed26e491487d0877d8642a0a84ea8d | https://github.com/ivpusic/neo/blob/c81644170eed26e491487d0877d8642a0a84ea8d/ctx.go#L79-L95 |
5,990 | ivpusic/neo | interceptor.go | compose | func compose(fns []appliable) func(*Ctx) {
return func(ctx *Ctx) {
fns[0].apply(ctx, fns, 0)
}
} | go | func compose(fns []appliable) func(*Ctx) {
return func(ctx *Ctx) {
fns[0].apply(ctx, fns, 0)
}
} | [
"func",
"compose",
"(",
"fns",
"[",
"]",
"appliable",
")",
"func",
"(",
"*",
"Ctx",
")",
"{",
"return",
"func",
"(",
"ctx",
"*",
"Ctx",
")",
"{",
"fns",
"[",
"0",
"]",
".",
"apply",
"(",
"ctx",
",",
"fns",
",",
"0",
")",
"\n",
"}",
"\n",
"}... | // Composing multiple middlewares into one chained function. | [
"Composing",
"multiple",
"middlewares",
"into",
"one",
"chained",
"function",
"."
] | c81644170eed26e491487d0877d8642a0a84ea8d | https://github.com/ivpusic/neo/blob/c81644170eed26e491487d0877d8642a0a84ea8d/interceptor.go#L10-L14 |
5,991 | ivpusic/neo | interceptor.go | Use | func (m *interceptor) Use(fn Middleware) {
m.middlewares = append(m.middlewares, appliable(&fn))
} | go | func (m *interceptor) Use(fn Middleware) {
m.middlewares = append(m.middlewares, appliable(&fn))
} | [
"func",
"(",
"m",
"*",
"interceptor",
")",
"Use",
"(",
"fn",
"Middleware",
")",
"{",
"m",
".",
"middlewares",
"=",
"append",
"(",
"m",
".",
"middlewares",
",",
"appliable",
"(",
"&",
"fn",
")",
")",
"\n",
"}"
] | // Adding new middleware into chain of middlewares. | [
"Adding",
"new",
"middleware",
"into",
"chain",
"of",
"middlewares",
"."
] | c81644170eed26e491487d0877d8642a0a84ea8d | https://github.com/ivpusic/neo/blob/c81644170eed26e491487d0877d8642a0a84ea8d/interceptor.go#L35-L37 |
5,992 | ivpusic/neo | conf.go | Parse | func (c *Conf) Parse(path string) {
c.loadDefaults()
if path == "" {
log.Info("Loaded configuration defaults")
return
}
if _, err := toml.DecodeFile(path, c); err != nil {
panic(err)
}
} | go | func (c *Conf) Parse(path string) {
c.loadDefaults()
if path == "" {
log.Info("Loaded configuration defaults")
return
}
if _, err := toml.DecodeFile(path, c); err != nil {
panic(err)
}
} | [
"func",
"(",
"c",
"*",
"Conf",
")",
"Parse",
"(",
"path",
"string",
")",
"{",
"c",
".",
"loadDefaults",
"(",
")",
"\n\n",
"if",
"path",
"==",
"\"",
"\"",
"{",
"log",
".",
"Info",
"(",
"\"",
"\"",
")",
"\n",
"return",
"\n",
"}",
"\n\n",
"if",
... | // Will try to parse TOML configuration file. | [
"Will",
"try",
"to",
"parse",
"TOML",
"configuration",
"file",
"."
] | c81644170eed26e491487d0877d8642a0a84ea8d | https://github.com/ivpusic/neo/blob/c81644170eed26e491487d0877d8642a0a84ea8d/conf.go#L86-L97 |
5,993 | ivpusic/neo | utils.go | merge | func merge(appliabels ...[]appliable) []appliable {
all := []appliable{}
for _, appl := range appliabels {
all = append(all, appl...)
}
return all
} | go | func merge(appliabels ...[]appliable) []appliable {
all := []appliable{}
for _, appl := range appliabels {
all = append(all, appl...)
}
return all
} | [
"func",
"merge",
"(",
"appliabels",
"...",
"[",
"]",
"appliable",
")",
"[",
"]",
"appliable",
"{",
"all",
":=",
"[",
"]",
"appliable",
"{",
"}",
"\n\n",
"for",
"_",
",",
"appl",
":=",
"range",
"appliabels",
"{",
"all",
"=",
"append",
"(",
"all",
",... | // Merging multiple ``appliable`` slices into one. | [
"Merging",
"multiple",
"appliable",
"slices",
"into",
"one",
"."
] | c81644170eed26e491487d0877d8642a0a84ea8d | https://github.com/ivpusic/neo/blob/c81644170eed26e491487d0877d8642a0a84ea8d/utils.go#L22-L30 |
5,994 | ivpusic/neo | utils.go | parseLogLevel | func parseLogLevel(level string) (golog.Level, error) {
level = strings.ToLower(level)
switch level {
case "debug":
return golog.DEBUG, nil
case "info":
return golog.INFO, nil
case "warn":
return golog.WARN, nil
case "error":
return golog.ERROR, nil
case "panic":
return golog.PANIC, nil
}
return golog.Level{}, errors.New("Log level " + level + " not found!")
} | go | func parseLogLevel(level string) (golog.Level, error) {
level = strings.ToLower(level)
switch level {
case "debug":
return golog.DEBUG, nil
case "info":
return golog.INFO, nil
case "warn":
return golog.WARN, nil
case "error":
return golog.ERROR, nil
case "panic":
return golog.PANIC, nil
}
return golog.Level{}, errors.New("Log level " + level + " not found!")
} | [
"func",
"parseLogLevel",
"(",
"level",
"string",
")",
"(",
"golog",
".",
"Level",
",",
"error",
")",
"{",
"level",
"=",
"strings",
".",
"ToLower",
"(",
"level",
")",
"\n\n",
"switch",
"level",
"{",
"case",
"\"",
"\"",
":",
"return",
"golog",
".",
"DE... | // For given string representation of log level, return ``golog.Level`` instance. | [
"For",
"given",
"string",
"representation",
"of",
"log",
"level",
"return",
"golog",
".",
"Level",
"instance",
"."
] | c81644170eed26e491487d0877d8642a0a84ea8d | https://github.com/ivpusic/neo/blob/c81644170eed26e491487d0877d8642a0a84ea8d/utils.go#L33-L50 |
5,995 | ivpusic/neo | template.go | renderTpl | func renderTpl(writer io.Writer, name string, data interface{}) error {
if tpl == nil {
return errors.New("Rendering template error! Please compile your templates.")
}
return tpl.ExecuteTemplate(writer, name, data)
} | go | func renderTpl(writer io.Writer, name string, data interface{}) error {
if tpl == nil {
return errors.New("Rendering template error! Please compile your templates.")
}
return tpl.ExecuteTemplate(writer, name, data)
} | [
"func",
"renderTpl",
"(",
"writer",
"io",
".",
"Writer",
",",
"name",
"string",
",",
"data",
"interface",
"{",
"}",
")",
"error",
"{",
"if",
"tpl",
"==",
"nil",
"{",
"return",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"return",... | // Write result of ExecuteTemplate to provided writer. This is usually ResponseWriter. | [
"Write",
"result",
"of",
"ExecuteTemplate",
"to",
"provided",
"writer",
".",
"This",
"is",
"usually",
"ResponseWriter",
"."
] | c81644170eed26e491487d0877d8642a0a84ea8d | https://github.com/ivpusic/neo/blob/c81644170eed26e491487d0877d8642a0a84ea8d/template.go#L14-L20 |
5,996 | ivpusic/neo | template.go | collectFiles | func collectFiles(location string) ([]string, error) {
log.Debug("collecting templates from " + location)
result := []string{}
paths, err := filepath.Glob(location)
if err != nil {
log.Error(err.Error())
return nil, err
}
for _, path := range paths {
isDir, err := isDirectory(path)
if err != nil {
log.Error(err.Error())
return nil, err
}
if !isDir {
result = append(result, path)
}
}
return result, nil
} | go | func collectFiles(location string) ([]string, error) {
log.Debug("collecting templates from " + location)
result := []string{}
paths, err := filepath.Glob(location)
if err != nil {
log.Error(err.Error())
return nil, err
}
for _, path := range paths {
isDir, err := isDirectory(path)
if err != nil {
log.Error(err.Error())
return nil, err
}
if !isDir {
result = append(result, path)
}
}
return result, nil
} | [
"func",
"collectFiles",
"(",
"location",
"string",
")",
"(",
"[",
"]",
"string",
",",
"error",
")",
"{",
"log",
".",
"Debug",
"(",
"\"",
"\"",
"+",
"location",
")",
"\n",
"result",
":=",
"[",
"]",
"string",
"{",
"}",
"\n\n",
"paths",
",",
"err",
... | // Collect all files for come location. | [
"Collect",
"all",
"files",
"for",
"come",
"location",
"."
] | c81644170eed26e491487d0877d8642a0a84ea8d | https://github.com/ivpusic/neo/blob/c81644170eed26e491487d0877d8642a0a84ea8d/template.go#L23-L46 |
5,997 | ivpusic/neo | template.go | compileTpl | func compileTpl(paths ...string) {
locations := []string{}
var err error
for _, path := range paths {
pths, err := collectFiles(path)
if err != nil {
panic(err)
} else {
locations = append(locations, pths...)
}
}
tpl, err = template.ParseFiles(locations...)
if err != nil {
panic(err)
}
} | go | func compileTpl(paths ...string) {
locations := []string{}
var err error
for _, path := range paths {
pths, err := collectFiles(path)
if err != nil {
panic(err)
} else {
locations = append(locations, pths...)
}
}
tpl, err = template.ParseFiles(locations...)
if err != nil {
panic(err)
}
} | [
"func",
"compileTpl",
"(",
"paths",
"...",
"string",
")",
"{",
"locations",
":=",
"[",
"]",
"string",
"{",
"}",
"\n",
"var",
"err",
"error",
"\n\n",
"for",
"_",
",",
"path",
":=",
"range",
"paths",
"{",
"pths",
",",
"err",
":=",
"collectFiles",
"(",
... | // compile templates on provided locations
// method will panic if there is something wrong during template compilation
// this is intended to be called on application startup | [
"compile",
"templates",
"on",
"provided",
"locations",
"method",
"will",
"panic",
"if",
"there",
"is",
"something",
"wrong",
"during",
"template",
"compilation",
"this",
"is",
"intended",
"to",
"be",
"called",
"on",
"application",
"startup"
] | c81644170eed26e491487d0877d8642a0a84ea8d | https://github.com/ivpusic/neo/blob/c81644170eed26e491487d0877d8642a0a84ea8d/template.go#L51-L68 |
5,998 | ivpusic/neo | request.go | buildReqCookies | func buildReqCookies(cookies []*http.Cookie) Cookie {
result := Cookie{}
for _, cookie := range cookies {
result[cookie.Name] = cookie
}
return result
} | go | func buildReqCookies(cookies []*http.Cookie) Cookie {
result := Cookie{}
for _, cookie := range cookies {
result[cookie.Name] = cookie
}
return result
} | [
"func",
"buildReqCookies",
"(",
"cookies",
"[",
"]",
"*",
"http",
".",
"Cookie",
")",
"Cookie",
"{",
"result",
":=",
"Cookie",
"{",
"}",
"\n\n",
"for",
"_",
",",
"cookie",
":=",
"range",
"cookies",
"{",
"result",
"[",
"cookie",
".",
"Name",
"]",
"=",... | // Make cookie map. | [
"Make",
"cookie",
"map",
"."
] | c81644170eed26e491487d0877d8642a0a84ea8d | https://github.com/ivpusic/neo/blob/c81644170eed26e491487d0877d8642a0a84ea8d/request.go#L17-L25 |
5,999 | ivpusic/neo | request.go | makeRequest | func makeRequest(req *http.Request) *Request {
request := &Request{
Request: req,
}
return request
} | go | func makeRequest(req *http.Request) *Request {
request := &Request{
Request: req,
}
return request
} | [
"func",
"makeRequest",
"(",
"req",
"*",
"http",
".",
"Request",
")",
"*",
"Request",
"{",
"request",
":=",
"&",
"Request",
"{",
"Request",
":",
"req",
",",
"}",
"\n\n",
"return",
"request",
"\n",
"}"
] | // Make new Request instance | [
"Make",
"new",
"Request",
"instance"
] | c81644170eed26e491487d0877d8642a0a84ea8d | https://github.com/ivpusic/neo/blob/c81644170eed26e491487d0877d8642a0a84ea8d/request.go#L28-L34 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.