id
int32 0
167k
| repo
stringlengths 5
54
| path
stringlengths 4
155
| func_name
stringlengths 1
118
| original_string
stringlengths 52
85.5k
| language
stringclasses 1
value | code
stringlengths 52
85.5k
| code_tokens
listlengths 21
1.41k
| docstring
stringlengths 6
2.61k
| docstring_tokens
listlengths 3
215
| sha
stringlengths 40
40
| url
stringlengths 85
252
|
---|---|---|---|---|---|---|---|---|---|---|---|
11,400 | multiformats/go-multihash | multihash.go | Cast | func Cast(buf []byte) (Multihash, error) {
dm, err := Decode(buf)
if err != nil {
return Multihash{}, err
}
if !ValidCode(dm.Code) {
return Multihash{}, ErrUnknownCode
}
return Multihash(buf), nil
} | go | func Cast(buf []byte) (Multihash, error) {
dm, err := Decode(buf)
if err != nil {
return Multihash{}, err
}
if !ValidCode(dm.Code) {
return Multihash{}, ErrUnknownCode
}
return Multihash(buf), nil
} | [
"func",
"Cast",
"(",
"buf",
"[",
"]",
"byte",
")",
"(",
"Multihash",
",",
"error",
")",
"{",
"dm",
",",
"err",
":=",
"Decode",
"(",
"buf",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"Multihash",
"{",
"}",
",",
"err",
"\n",
"}",
"\n\n",
"if",
"!",
"ValidCode",
"(",
"dm",
".",
"Code",
")",
"{",
"return",
"Multihash",
"{",
"}",
",",
"ErrUnknownCode",
"\n",
"}",
"\n\n",
"return",
"Multihash",
"(",
"buf",
")",
",",
"nil",
"\n",
"}"
]
| // Cast casts a buffer onto a multihash, and returns an error
// if it does not work. | [
"Cast",
"casts",
"a",
"buffer",
"onto",
"a",
"multihash",
"and",
"returns",
"an",
"error",
"if",
"it",
"does",
"not",
"work",
"."
]
| c242156eec223a58ac13b8c114a2b31e87bbf558 | https://github.com/multiformats/go-multihash/blob/c242156eec223a58ac13b8c114a2b31e87bbf558/multihash.go#L220-L231 |
11,401 | multiformats/go-multihash | multihash.go | Decode | func Decode(buf []byte) (*DecodedMultihash, error) {
if len(buf) < 2 {
return nil, ErrTooShort
}
var err error
var code, length uint64
code, buf, err = uvarint(buf)
if err != nil {
return nil, err
}
length, buf, err = uvarint(buf)
if err != nil {
return nil, err
}
if length > math.MaxInt32 {
return nil, errors.New("digest too long, supporting only <= 2^31-1")
}
dm := &DecodedMultihash{
Code: code,
Name: Codes[code],
Length: int(length),
Digest: buf,
}
if len(dm.Digest) != dm.Length {
return nil, ErrInconsistentLen{dm}
}
return dm, nil
} | go | func Decode(buf []byte) (*DecodedMultihash, error) {
if len(buf) < 2 {
return nil, ErrTooShort
}
var err error
var code, length uint64
code, buf, err = uvarint(buf)
if err != nil {
return nil, err
}
length, buf, err = uvarint(buf)
if err != nil {
return nil, err
}
if length > math.MaxInt32 {
return nil, errors.New("digest too long, supporting only <= 2^31-1")
}
dm := &DecodedMultihash{
Code: code,
Name: Codes[code],
Length: int(length),
Digest: buf,
}
if len(dm.Digest) != dm.Length {
return nil, ErrInconsistentLen{dm}
}
return dm, nil
} | [
"func",
"Decode",
"(",
"buf",
"[",
"]",
"byte",
")",
"(",
"*",
"DecodedMultihash",
",",
"error",
")",
"{",
"if",
"len",
"(",
"buf",
")",
"<",
"2",
"{",
"return",
"nil",
",",
"ErrTooShort",
"\n",
"}",
"\n\n",
"var",
"err",
"error",
"\n",
"var",
"code",
",",
"length",
"uint64",
"\n\n",
"code",
",",
"buf",
",",
"err",
"=",
"uvarint",
"(",
"buf",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"length",
",",
"buf",
",",
"err",
"=",
"uvarint",
"(",
"buf",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"if",
"length",
">",
"math",
".",
"MaxInt32",
"{",
"return",
"nil",
",",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"dm",
":=",
"&",
"DecodedMultihash",
"{",
"Code",
":",
"code",
",",
"Name",
":",
"Codes",
"[",
"code",
"]",
",",
"Length",
":",
"int",
"(",
"length",
")",
",",
"Digest",
":",
"buf",
",",
"}",
"\n\n",
"if",
"len",
"(",
"dm",
".",
"Digest",
")",
"!=",
"dm",
".",
"Length",
"{",
"return",
"nil",
",",
"ErrInconsistentLen",
"{",
"dm",
"}",
"\n",
"}",
"\n\n",
"return",
"dm",
",",
"nil",
"\n",
"}"
]
| // Decode parses multihash bytes into a DecodedMultihash. | [
"Decode",
"parses",
"multihash",
"bytes",
"into",
"a",
"DecodedMultihash",
"."
]
| c242156eec223a58ac13b8c114a2b31e87bbf558 | https://github.com/multiformats/go-multihash/blob/c242156eec223a58ac13b8c114a2b31e87bbf558/multihash.go#L234-L269 |
11,402 | multiformats/go-multihash | sum.go | Sum | func Sum(data []byte, code uint64, length int) (Multihash, error) {
if !ValidCode(code) {
return nil, fmt.Errorf("invalid multihash code %d", code)
}
if length < 0 {
var ok bool
length, ok = DefaultLengths[code]
if !ok {
return nil, fmt.Errorf("no default length for code %d", code)
}
}
hashFunc, ok := funcTable[code]
if !ok {
return nil, ErrSumNotSupported
}
d, err := hashFunc(data, length)
if err != nil {
return nil, err
}
if length >= 0 {
d = d[:length]
}
return Encode(d, code)
} | go | func Sum(data []byte, code uint64, length int) (Multihash, error) {
if !ValidCode(code) {
return nil, fmt.Errorf("invalid multihash code %d", code)
}
if length < 0 {
var ok bool
length, ok = DefaultLengths[code]
if !ok {
return nil, fmt.Errorf("no default length for code %d", code)
}
}
hashFunc, ok := funcTable[code]
if !ok {
return nil, ErrSumNotSupported
}
d, err := hashFunc(data, length)
if err != nil {
return nil, err
}
if length >= 0 {
d = d[:length]
}
return Encode(d, code)
} | [
"func",
"Sum",
"(",
"data",
"[",
"]",
"byte",
",",
"code",
"uint64",
",",
"length",
"int",
")",
"(",
"Multihash",
",",
"error",
")",
"{",
"if",
"!",
"ValidCode",
"(",
"code",
")",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"code",
")",
"\n",
"}",
"\n\n",
"if",
"length",
"<",
"0",
"{",
"var",
"ok",
"bool",
"\n",
"length",
",",
"ok",
"=",
"DefaultLengths",
"[",
"code",
"]",
"\n",
"if",
"!",
"ok",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"code",
")",
"\n",
"}",
"\n",
"}",
"\n\n",
"hashFunc",
",",
"ok",
":=",
"funcTable",
"[",
"code",
"]",
"\n",
"if",
"!",
"ok",
"{",
"return",
"nil",
",",
"ErrSumNotSupported",
"\n",
"}",
"\n\n",
"d",
",",
"err",
":=",
"hashFunc",
"(",
"data",
",",
"length",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"if",
"length",
">=",
"0",
"{",
"d",
"=",
"d",
"[",
":",
"length",
"]",
"\n",
"}",
"\n",
"return",
"Encode",
"(",
"d",
",",
"code",
")",
"\n",
"}"
]
| // Sum obtains the cryptographic sum of a given buffer. The length parameter
// indicates the length of the resulting digest and passing a negative value
// use default length values for the selected hash function. | [
"Sum",
"obtains",
"the",
"cryptographic",
"sum",
"of",
"a",
"given",
"buffer",
".",
"The",
"length",
"parameter",
"indicates",
"the",
"length",
"of",
"the",
"resulting",
"digest",
"and",
"passing",
"a",
"negative",
"value",
"use",
"default",
"length",
"values",
"for",
"the",
"selected",
"hash",
"function",
"."
]
| c242156eec223a58ac13b8c114a2b31e87bbf558 | https://github.com/multiformats/go-multihash/blob/c242156eec223a58ac13b8c114a2b31e87bbf558/sum.go#L34-L60 |
11,403 | multiformats/go-multihash | sum.go | RegisterHashFunc | func RegisterHashFunc(code uint64, hashFunc HashFunc) error {
if !ValidCode(code) {
return fmt.Errorf("code %v not valid", code)
}
_, ok := funcTable[code]
if ok {
return fmt.Errorf("hash func for code %v already registered", code)
}
funcTable[code] = hashFunc
return nil
} | go | func RegisterHashFunc(code uint64, hashFunc HashFunc) error {
if !ValidCode(code) {
return fmt.Errorf("code %v not valid", code)
}
_, ok := funcTable[code]
if ok {
return fmt.Errorf("hash func for code %v already registered", code)
}
funcTable[code] = hashFunc
return nil
} | [
"func",
"RegisterHashFunc",
"(",
"code",
"uint64",
",",
"hashFunc",
"HashFunc",
")",
"error",
"{",
"if",
"!",
"ValidCode",
"(",
"code",
")",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"code",
")",
"\n",
"}",
"\n\n",
"_",
",",
"ok",
":=",
"funcTable",
"[",
"code",
"]",
"\n",
"if",
"ok",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"code",
")",
"\n",
"}",
"\n\n",
"funcTable",
"[",
"code",
"]",
"=",
"hashFunc",
"\n",
"return",
"nil",
"\n",
"}"
]
| // RegisterHashFunc adds an entry to the package-level code -> hash func map.
// The hash function must return at least the requested number of bytes. If it
// returns more, the hash will be truncated. | [
"RegisterHashFunc",
"adds",
"an",
"entry",
"to",
"the",
"package",
"-",
"level",
"code",
"-",
">",
"hash",
"func",
"map",
".",
"The",
"hash",
"function",
"must",
"return",
"at",
"least",
"the",
"requested",
"number",
"of",
"bytes",
".",
"If",
"it",
"returns",
"more",
"the",
"hash",
"will",
"be",
"truncated",
"."
]
| c242156eec223a58ac13b8c114a2b31e87bbf558 | https://github.com/multiformats/go-multihash/blob/c242156eec223a58ac13b8c114a2b31e87bbf558/sum.go#L218-L230 |
11,404 | drone/envsubst | parse/scan.go | init | func (s *scanner) init(buf string) {
s.buf = buf
s.pos = 0
s.start = 0
s.width = 0
s.accept = nil
} | go | func (s *scanner) init(buf string) {
s.buf = buf
s.pos = 0
s.start = 0
s.width = 0
s.accept = nil
} | [
"func",
"(",
"s",
"*",
"scanner",
")",
"init",
"(",
"buf",
"string",
")",
"{",
"s",
".",
"buf",
"=",
"buf",
"\n",
"s",
".",
"pos",
"=",
"0",
"\n",
"s",
".",
"start",
"=",
"0",
"\n",
"s",
".",
"width",
"=",
"0",
"\n",
"s",
".",
"accept",
"=",
"nil",
"\n",
"}"
]
| // init initializes a scanner with a new buffer. | [
"init",
"initializes",
"a",
"scanner",
"with",
"a",
"new",
"buffer",
"."
]
| 5a78055244d6b899c2a2eb158c8454f548af9ab2 | https://github.com/drone/envsubst/blob/5a78055244d6b899c2a2eb158c8454f548af9ab2/parse/scan.go#L53-L59 |
11,405 | drone/envsubst | parse/scan.go | read | func (s *scanner) read() rune {
if s.pos >= len(s.buf) {
s.width = 0
return eof
}
r, w := utf8.DecodeRuneInString(s.buf[s.pos:])
s.width = w
s.pos += s.width
return r
} | go | func (s *scanner) read() rune {
if s.pos >= len(s.buf) {
s.width = 0
return eof
}
r, w := utf8.DecodeRuneInString(s.buf[s.pos:])
s.width = w
s.pos += s.width
return r
} | [
"func",
"(",
"s",
"*",
"scanner",
")",
"read",
"(",
")",
"rune",
"{",
"if",
"s",
".",
"pos",
">=",
"len",
"(",
"s",
".",
"buf",
")",
"{",
"s",
".",
"width",
"=",
"0",
"\n",
"return",
"eof",
"\n",
"}",
"\n",
"r",
",",
"w",
":=",
"utf8",
".",
"DecodeRuneInString",
"(",
"s",
".",
"buf",
"[",
"s",
".",
"pos",
":",
"]",
")",
"\n",
"s",
".",
"width",
"=",
"w",
"\n",
"s",
".",
"pos",
"+=",
"s",
".",
"width",
"\n",
"return",
"r",
"\n",
"}"
]
| // read returns the next unicode character. It returns eof at
// the end of the string buffer. | [
"read",
"returns",
"the",
"next",
"unicode",
"character",
".",
"It",
"returns",
"eof",
"at",
"the",
"end",
"of",
"the",
"string",
"buffer",
"."
]
| 5a78055244d6b899c2a2eb158c8454f548af9ab2 | https://github.com/drone/envsubst/blob/5a78055244d6b899c2a2eb158c8454f548af9ab2/parse/scan.go#L63-L72 |
11,406 | drone/envsubst | parse/scan.go | skip | func (s *scanner) skip() {
l := s.buf[:s.pos-1]
r := s.buf[s.pos:]
s.buf = l + r
} | go | func (s *scanner) skip() {
l := s.buf[:s.pos-1]
r := s.buf[s.pos:]
s.buf = l + r
} | [
"func",
"(",
"s",
"*",
"scanner",
")",
"skip",
"(",
")",
"{",
"l",
":=",
"s",
".",
"buf",
"[",
":",
"s",
".",
"pos",
"-",
"1",
"]",
"\n",
"r",
":=",
"s",
".",
"buf",
"[",
"s",
".",
"pos",
":",
"]",
"\n",
"s",
".",
"buf",
"=",
"l",
"+",
"r",
"\n",
"}"
]
| // skip skips over the curring unicode character in the buffer
// by slicing and removing from the buffer. | [
"skip",
"skips",
"over",
"the",
"curring",
"unicode",
"character",
"in",
"the",
"buffer",
"by",
"slicing",
"and",
"removing",
"from",
"the",
"buffer",
"."
]
| 5a78055244d6b899c2a2eb158c8454f548af9ab2 | https://github.com/drone/envsubst/blob/5a78055244d6b899c2a2eb158c8454f548af9ab2/parse/scan.go#L80-L84 |
11,407 | drone/envsubst | parse/scan.go | scan | func (s *scanner) scan() token {
s.start = s.pos
r := s.read()
switch {
case r == eof:
return tokenEOF
case s.scanLbrack(r):
return tokenLbrack
case s.scanRbrack(r):
return tokenRbrack
case s.scanIdent(r):
return tokenIdent
}
return tokenIllegal
} | go | func (s *scanner) scan() token {
s.start = s.pos
r := s.read()
switch {
case r == eof:
return tokenEOF
case s.scanLbrack(r):
return tokenLbrack
case s.scanRbrack(r):
return tokenRbrack
case s.scanIdent(r):
return tokenIdent
}
return tokenIllegal
} | [
"func",
"(",
"s",
"*",
"scanner",
")",
"scan",
"(",
")",
"token",
"{",
"s",
".",
"start",
"=",
"s",
".",
"pos",
"\n",
"r",
":=",
"s",
".",
"read",
"(",
")",
"\n",
"switch",
"{",
"case",
"r",
"==",
"eof",
":",
"return",
"tokenEOF",
"\n",
"case",
"s",
".",
"scanLbrack",
"(",
"r",
")",
":",
"return",
"tokenLbrack",
"\n",
"case",
"s",
".",
"scanRbrack",
"(",
"r",
")",
":",
"return",
"tokenRbrack",
"\n",
"case",
"s",
".",
"scanIdent",
"(",
"r",
")",
":",
"return",
"tokenIdent",
"\n",
"}",
"\n",
"return",
"tokenIllegal",
"\n",
"}"
]
| // scan reads the next token or Unicode character from source and
// returns it. It returns EOF at the end of the source. | [
"scan",
"reads",
"the",
"next",
"token",
"or",
"Unicode",
"character",
"from",
"source",
"and",
"returns",
"it",
".",
"It",
"returns",
"EOF",
"at",
"the",
"end",
"of",
"the",
"source",
"."
]
| 5a78055244d6b899c2a2eb158c8454f548af9ab2 | https://github.com/drone/envsubst/blob/5a78055244d6b899c2a2eb158c8454f548af9ab2/parse/scan.go#L103-L117 |
11,408 | drone/envsubst | parse/scan.go | scanIdent | func (s *scanner) scanIdent(r rune) bool {
if s.mode&scanIdent == 0 {
return false
}
if s.scanEscaped(r) {
s.skip()
} else if !s.accept(r, s.pos-s.start) {
return false
}
loop:
for {
r := s.read()
switch {
case r == eof:
s.unread()
break loop
case s.scanLbrack(r):
s.unread()
s.unread()
break loop
}
if s.scanEscaped(r) {
s.skip()
continue
}
if !s.accept(r, s.pos-s.start) {
s.unread()
break loop
}
}
return true
} | go | func (s *scanner) scanIdent(r rune) bool {
if s.mode&scanIdent == 0 {
return false
}
if s.scanEscaped(r) {
s.skip()
} else if !s.accept(r, s.pos-s.start) {
return false
}
loop:
for {
r := s.read()
switch {
case r == eof:
s.unread()
break loop
case s.scanLbrack(r):
s.unread()
s.unread()
break loop
}
if s.scanEscaped(r) {
s.skip()
continue
}
if !s.accept(r, s.pos-s.start) {
s.unread()
break loop
}
}
return true
} | [
"func",
"(",
"s",
"*",
"scanner",
")",
"scanIdent",
"(",
"r",
"rune",
")",
"bool",
"{",
"if",
"s",
".",
"mode",
"&",
"scanIdent",
"==",
"0",
"{",
"return",
"false",
"\n",
"}",
"\n",
"if",
"s",
".",
"scanEscaped",
"(",
"r",
")",
"{",
"s",
".",
"skip",
"(",
")",
"\n",
"}",
"else",
"if",
"!",
"s",
".",
"accept",
"(",
"r",
",",
"s",
".",
"pos",
"-",
"s",
".",
"start",
")",
"{",
"return",
"false",
"\n",
"}",
"\n",
"loop",
":",
"for",
"{",
"r",
":=",
"s",
".",
"read",
"(",
")",
"\n",
"switch",
"{",
"case",
"r",
"==",
"eof",
":",
"s",
".",
"unread",
"(",
")",
"\n",
"break",
"loop",
"\n",
"case",
"s",
".",
"scanLbrack",
"(",
"r",
")",
":",
"s",
".",
"unread",
"(",
")",
"\n",
"s",
".",
"unread",
"(",
")",
"\n",
"break",
"loop",
"\n",
"}",
"\n",
"if",
"s",
".",
"scanEscaped",
"(",
"r",
")",
"{",
"s",
".",
"skip",
"(",
")",
"\n",
"continue",
"\n",
"}",
"\n",
"if",
"!",
"s",
".",
"accept",
"(",
"r",
",",
"s",
".",
"pos",
"-",
"s",
".",
"start",
")",
"{",
"s",
".",
"unread",
"(",
")",
"\n",
"break",
"loop",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"true",
"\n",
"}"
]
| // scanIdent reads the next token or Unicode character from source
// and returns true if the Ident character is accepted. | [
"scanIdent",
"reads",
"the",
"next",
"token",
"or",
"Unicode",
"character",
"from",
"source",
"and",
"returns",
"true",
"if",
"the",
"Ident",
"character",
"is",
"accepted",
"."
]
| 5a78055244d6b899c2a2eb158c8454f548af9ab2 | https://github.com/drone/envsubst/blob/5a78055244d6b899c2a2eb158c8454f548af9ab2/parse/scan.go#L121-L152 |
11,409 | drone/envsubst | parse/scan.go | scanLbrack | func (s *scanner) scanLbrack(r rune) bool {
if s.mode&scanLbrack == 0 {
return false
}
if r == '$' {
if s.read() == '{' {
return true
}
s.unread()
}
return false
} | go | func (s *scanner) scanLbrack(r rune) bool {
if s.mode&scanLbrack == 0 {
return false
}
if r == '$' {
if s.read() == '{' {
return true
}
s.unread()
}
return false
} | [
"func",
"(",
"s",
"*",
"scanner",
")",
"scanLbrack",
"(",
"r",
"rune",
")",
"bool",
"{",
"if",
"s",
".",
"mode",
"&",
"scanLbrack",
"==",
"0",
"{",
"return",
"false",
"\n",
"}",
"\n",
"if",
"r",
"==",
"'$'",
"{",
"if",
"s",
".",
"read",
"(",
")",
"==",
"'{'",
"{",
"return",
"true",
"\n",
"}",
"\n",
"s",
".",
"unread",
"(",
")",
"\n",
"}",
"\n",
"return",
"false",
"\n",
"}"
]
| // scanLbrack reads the next token or Unicode character from source
// and returns true if the open bracket is encountered. | [
"scanLbrack",
"reads",
"the",
"next",
"token",
"or",
"Unicode",
"character",
"from",
"source",
"and",
"returns",
"true",
"if",
"the",
"open",
"bracket",
"is",
"encountered",
"."
]
| 5a78055244d6b899c2a2eb158c8454f548af9ab2 | https://github.com/drone/envsubst/blob/5a78055244d6b899c2a2eb158c8454f548af9ab2/parse/scan.go#L156-L167 |
11,410 | drone/envsubst | parse/scan.go | scanRbrack | func (s *scanner) scanRbrack(r rune) bool {
if s.mode&scanRbrack == 0 {
return false
}
return r == '}'
} | go | func (s *scanner) scanRbrack(r rune) bool {
if s.mode&scanRbrack == 0 {
return false
}
return r == '}'
} | [
"func",
"(",
"s",
"*",
"scanner",
")",
"scanRbrack",
"(",
"r",
"rune",
")",
"bool",
"{",
"if",
"s",
".",
"mode",
"&",
"scanRbrack",
"==",
"0",
"{",
"return",
"false",
"\n",
"}",
"\n",
"return",
"r",
"==",
"'}'",
"\n",
"}"
]
| // scanRbrack reads the next token or Unicode character from source
// and returns true if the closing bracket is encountered. | [
"scanRbrack",
"reads",
"the",
"next",
"token",
"or",
"Unicode",
"character",
"from",
"source",
"and",
"returns",
"true",
"if",
"the",
"closing",
"bracket",
"is",
"encountered",
"."
]
| 5a78055244d6b899c2a2eb158c8454f548af9ab2 | https://github.com/drone/envsubst/blob/5a78055244d6b899c2a2eb158c8454f548af9ab2/parse/scan.go#L171-L176 |
11,411 | drone/envsubst | parse/scan.go | scanEscaped | func (s *scanner) scanEscaped(r rune) bool {
if s.mode&scanEscape == 0 {
return false
}
if r == '$' {
if s.peek() == '$' {
return true
}
}
if r != '\\' {
return false
}
switch s.peek() {
case '/', '\\':
return true
default:
return false
}
} | go | func (s *scanner) scanEscaped(r rune) bool {
if s.mode&scanEscape == 0 {
return false
}
if r == '$' {
if s.peek() == '$' {
return true
}
}
if r != '\\' {
return false
}
switch s.peek() {
case '/', '\\':
return true
default:
return false
}
} | [
"func",
"(",
"s",
"*",
"scanner",
")",
"scanEscaped",
"(",
"r",
"rune",
")",
"bool",
"{",
"if",
"s",
".",
"mode",
"&",
"scanEscape",
"==",
"0",
"{",
"return",
"false",
"\n",
"}",
"\n",
"if",
"r",
"==",
"'$'",
"{",
"if",
"s",
".",
"peek",
"(",
")",
"==",
"'$'",
"{",
"return",
"true",
"\n",
"}",
"\n",
"}",
"\n",
"if",
"r",
"!=",
"'\\\\'",
"{",
"return",
"false",
"\n",
"}",
"\n",
"switch",
"s",
".",
"peek",
"(",
")",
"{",
"case",
"'/'",
",",
"'\\\\'",
":",
"return",
"true",
"\n",
"default",
":",
"return",
"false",
"\n",
"}",
"\n",
"}"
]
| // scanEscaped reads the next token or Unicode character from source
// and returns true if it being escaped and should be sipped. | [
"scanEscaped",
"reads",
"the",
"next",
"token",
"or",
"Unicode",
"character",
"from",
"source",
"and",
"returns",
"true",
"if",
"it",
"being",
"escaped",
"and",
"should",
"be",
"sipped",
"."
]
| 5a78055244d6b899c2a2eb158c8454f548af9ab2 | https://github.com/drone/envsubst/blob/5a78055244d6b899c2a2eb158c8454f548af9ab2/parse/scan.go#L180-L198 |
11,412 | drone/envsubst | parse/parse.go | Parse | func Parse(buf string) (*Tree, error) {
t := new(Tree)
t.scanner = new(scanner)
return t.Parse(buf)
} | go | func Parse(buf string) (*Tree, error) {
t := new(Tree)
t.scanner = new(scanner)
return t.Parse(buf)
} | [
"func",
"Parse",
"(",
"buf",
"string",
")",
"(",
"*",
"Tree",
",",
"error",
")",
"{",
"t",
":=",
"new",
"(",
"Tree",
")",
"\n",
"t",
".",
"scanner",
"=",
"new",
"(",
"scanner",
")",
"\n",
"return",
"t",
".",
"Parse",
"(",
"buf",
")",
"\n",
"}"
]
| // Parse parses the string and returns a Tree. | [
"Parse",
"parses",
"the",
"string",
"and",
"returns",
"a",
"Tree",
"."
]
| 5a78055244d6b899c2a2eb158c8454f548af9ab2 | https://github.com/drone/envsubst/blob/5a78055244d6b899c2a2eb158c8454f548af9ab2/parse/parse.go#L17-L21 |
11,413 | drone/envsubst | parse/parse.go | Parse | func (t *Tree) Parse(buf string) (tree *Tree, err error) {
t.scanner.init(buf)
t.Root, err = t.parseAny()
return t, err
} | go | func (t *Tree) Parse(buf string) (tree *Tree, err error) {
t.scanner.init(buf)
t.Root, err = t.parseAny()
return t, err
} | [
"func",
"(",
"t",
"*",
"Tree",
")",
"Parse",
"(",
"buf",
"string",
")",
"(",
"tree",
"*",
"Tree",
",",
"err",
"error",
")",
"{",
"t",
".",
"scanner",
".",
"init",
"(",
"buf",
")",
"\n",
"t",
".",
"Root",
",",
"err",
"=",
"t",
".",
"parseAny",
"(",
")",
"\n",
"return",
"t",
",",
"err",
"\n",
"}"
]
| // Parse parses the string buffer to construct an ast
// representation for expansion. | [
"Parse",
"parses",
"the",
"string",
"buffer",
"to",
"construct",
"an",
"ast",
"representation",
"for",
"expansion",
"."
]
| 5a78055244d6b899c2a2eb158c8454f548af9ab2 | https://github.com/drone/envsubst/blob/5a78055244d6b899c2a2eb158c8454f548af9ab2/parse/parse.go#L25-L29 |
11,414 | drone/envsubst | parse/parse.go | parseParam | func (t *Tree) parseParam(accept acceptFunc, mode byte) (Node, error) {
t.scanner.accept = accept
t.scanner.mode = mode | scanLbrack
switch t.scanner.scan() {
case tokenLbrack:
return t.parseFunc()
case tokenIdent:
return newTextNode(
t.scanner.string(),
), nil
default:
return nil, ErrBadSubstitution
}
} | go | func (t *Tree) parseParam(accept acceptFunc, mode byte) (Node, error) {
t.scanner.accept = accept
t.scanner.mode = mode | scanLbrack
switch t.scanner.scan() {
case tokenLbrack:
return t.parseFunc()
case tokenIdent:
return newTextNode(
t.scanner.string(),
), nil
default:
return nil, ErrBadSubstitution
}
} | [
"func",
"(",
"t",
"*",
"Tree",
")",
"parseParam",
"(",
"accept",
"acceptFunc",
",",
"mode",
"byte",
")",
"(",
"Node",
",",
"error",
")",
"{",
"t",
".",
"scanner",
".",
"accept",
"=",
"accept",
"\n",
"t",
".",
"scanner",
".",
"mode",
"=",
"mode",
"|",
"scanLbrack",
"\n",
"switch",
"t",
".",
"scanner",
".",
"scan",
"(",
")",
"{",
"case",
"tokenLbrack",
":",
"return",
"t",
".",
"parseFunc",
"(",
")",
"\n",
"case",
"tokenIdent",
":",
"return",
"newTextNode",
"(",
"t",
".",
"scanner",
".",
"string",
"(",
")",
",",
")",
",",
"nil",
"\n",
"default",
":",
"return",
"nil",
",",
"ErrBadSubstitution",
"\n",
"}",
"\n",
"}"
]
| // parse a substitution function parameter. | [
"parse",
"a",
"substitution",
"function",
"parameter",
"."
]
| 5a78055244d6b899c2a2eb158c8454f548af9ab2 | https://github.com/drone/envsubst/blob/5a78055244d6b899c2a2eb158c8454f548af9ab2/parse/parse.go#L112-L125 |
11,415 | drone/envsubst | parse/parse.go | parseDefaultOrSubstr | func (t *Tree) parseDefaultOrSubstr(name string) (Node, error) {
t.scanner.read()
r := t.scanner.peek()
t.scanner.unread()
switch r {
case '=', '-', '?', '+':
return t.parseDefaultFunc(name)
default:
return t.parseSubstrFunc(name)
}
} | go | func (t *Tree) parseDefaultOrSubstr(name string) (Node, error) {
t.scanner.read()
r := t.scanner.peek()
t.scanner.unread()
switch r {
case '=', '-', '?', '+':
return t.parseDefaultFunc(name)
default:
return t.parseSubstrFunc(name)
}
} | [
"func",
"(",
"t",
"*",
"Tree",
")",
"parseDefaultOrSubstr",
"(",
"name",
"string",
")",
"(",
"Node",
",",
"error",
")",
"{",
"t",
".",
"scanner",
".",
"read",
"(",
")",
"\n",
"r",
":=",
"t",
".",
"scanner",
".",
"peek",
"(",
")",
"\n",
"t",
".",
"scanner",
".",
"unread",
"(",
")",
"\n",
"switch",
"r",
"{",
"case",
"'='",
",",
"'-'",
",",
"'?'",
",",
"'+'",
":",
"return",
"t",
".",
"parseDefaultFunc",
"(",
"name",
")",
"\n",
"default",
":",
"return",
"t",
".",
"parseSubstrFunc",
"(",
"name",
")",
"\n",
"}",
"\n",
"}"
]
| // parse either a default or substring substitution function. | [
"parse",
"either",
"a",
"default",
"or",
"substring",
"substitution",
"function",
"."
]
| 5a78055244d6b899c2a2eb158c8454f548af9ab2 | https://github.com/drone/envsubst/blob/5a78055244d6b899c2a2eb158c8454f548af9ab2/parse/parse.go#L128-L138 |
11,416 | drone/envsubst | parse/parse.go | consumeRbrack | func (t *Tree) consumeRbrack() error {
t.scanner.mode = scanRbrack
if t.scanner.scan() != tokenRbrack {
return ErrBadSubstitution
}
return nil
} | go | func (t *Tree) consumeRbrack() error {
t.scanner.mode = scanRbrack
if t.scanner.scan() != tokenRbrack {
return ErrBadSubstitution
}
return nil
} | [
"func",
"(",
"t",
"*",
"Tree",
")",
"consumeRbrack",
"(",
")",
"error",
"{",
"t",
".",
"scanner",
".",
"mode",
"=",
"scanRbrack",
"\n",
"if",
"t",
".",
"scanner",
".",
"scan",
"(",
")",
"!=",
"tokenRbrack",
"{",
"return",
"ErrBadSubstitution",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
]
| // consumeRbrack consumes a right closing bracket. If a closing
// bracket token is not consumed an ErrBadSubstitution is returned. | [
"consumeRbrack",
"consumes",
"a",
"right",
"closing",
"bracket",
".",
"If",
"a",
"closing",
"bracket",
"token",
"is",
"not",
"consumed",
"an",
"ErrBadSubstitution",
"is",
"returned",
"."
]
| 5a78055244d6b899c2a2eb158c8454f548af9ab2 | https://github.com/drone/envsubst/blob/5a78055244d6b899c2a2eb158c8454f548af9ab2/parse/parse.go#L357-L363 |
11,417 | drone/envsubst | funcs.go | toLen | func toLen(s string, args ...string) string {
return strconv.Itoa(len(s))
} | go | func toLen(s string, args ...string) string {
return strconv.Itoa(len(s))
} | [
"func",
"toLen",
"(",
"s",
"string",
",",
"args",
"...",
"string",
")",
"string",
"{",
"return",
"strconv",
".",
"Itoa",
"(",
"len",
"(",
"s",
")",
")",
"\n",
"}"
]
| // toLen returns the length of string s. | [
"toLen",
"returns",
"the",
"length",
"of",
"string",
"s",
"."
]
| 5a78055244d6b899c2a2eb158c8454f548af9ab2 | https://github.com/drone/envsubst/blob/5a78055244d6b899c2a2eb158c8454f548af9ab2/funcs.go#L16-L18 |
11,418 | drone/envsubst | funcs.go | toLowerFirst | func toLowerFirst(s string, args ...string) string {
if s == "" {
return s
}
r, n := utf8.DecodeRuneInString(s)
return string(unicode.ToLower(r)) + s[n:]
} | go | func toLowerFirst(s string, args ...string) string {
if s == "" {
return s
}
r, n := utf8.DecodeRuneInString(s)
return string(unicode.ToLower(r)) + s[n:]
} | [
"func",
"toLowerFirst",
"(",
"s",
"string",
",",
"args",
"...",
"string",
")",
"string",
"{",
"if",
"s",
"==",
"\"",
"\"",
"{",
"return",
"s",
"\n",
"}",
"\n",
"r",
",",
"n",
":=",
"utf8",
".",
"DecodeRuneInString",
"(",
"s",
")",
"\n",
"return",
"string",
"(",
"unicode",
".",
"ToLower",
"(",
"r",
")",
")",
"+",
"s",
"[",
"n",
":",
"]",
"\n",
"}"
]
| // toLowerFirst returns a copy of the string s with the first
// character mapped to its lower case. | [
"toLowerFirst",
"returns",
"a",
"copy",
"of",
"the",
"string",
"s",
"with",
"the",
"first",
"character",
"mapped",
"to",
"its",
"lower",
"case",
"."
]
| 5a78055244d6b899c2a2eb158c8454f548af9ab2 | https://github.com/drone/envsubst/blob/5a78055244d6b899c2a2eb158c8454f548af9ab2/funcs.go#L34-L40 |
11,419 | drone/envsubst | funcs.go | toUpperFirst | func toUpperFirst(s string, args ...string) string {
if s == "" {
return s
}
r, n := utf8.DecodeRuneInString(s)
return string(unicode.ToUpper(r)) + s[n:]
} | go | func toUpperFirst(s string, args ...string) string {
if s == "" {
return s
}
r, n := utf8.DecodeRuneInString(s)
return string(unicode.ToUpper(r)) + s[n:]
} | [
"func",
"toUpperFirst",
"(",
"s",
"string",
",",
"args",
"...",
"string",
")",
"string",
"{",
"if",
"s",
"==",
"\"",
"\"",
"{",
"return",
"s",
"\n",
"}",
"\n",
"r",
",",
"n",
":=",
"utf8",
".",
"DecodeRuneInString",
"(",
"s",
")",
"\n",
"return",
"string",
"(",
"unicode",
".",
"ToUpper",
"(",
"r",
")",
")",
"+",
"s",
"[",
"n",
":",
"]",
"\n",
"}"
]
| // toUpperFirst returns a copy of the string s with the first
// character mapped to its upper case. | [
"toUpperFirst",
"returns",
"a",
"copy",
"of",
"the",
"string",
"s",
"with",
"the",
"first",
"character",
"mapped",
"to",
"its",
"upper",
"case",
"."
]
| 5a78055244d6b899c2a2eb158c8454f548af9ab2 | https://github.com/drone/envsubst/blob/5a78055244d6b899c2a2eb158c8454f548af9ab2/funcs.go#L44-L50 |
11,420 | drone/envsubst | funcs.go | toDefault | func toDefault(s string, args ...string) string {
if len(s) == 0 && len(args) == 1 {
s = args[0]
}
return s
} | go | func toDefault(s string, args ...string) string {
if len(s) == 0 && len(args) == 1 {
s = args[0]
}
return s
} | [
"func",
"toDefault",
"(",
"s",
"string",
",",
"args",
"...",
"string",
")",
"string",
"{",
"if",
"len",
"(",
"s",
")",
"==",
"0",
"&&",
"len",
"(",
"args",
")",
"==",
"1",
"{",
"s",
"=",
"args",
"[",
"0",
"]",
"\n",
"}",
"\n",
"return",
"s",
"\n",
"}"
]
| // toDefault returns a copy of the string s if not empty, else
// returns a copy of the first string arugment. | [
"toDefault",
"returns",
"a",
"copy",
"of",
"the",
"string",
"s",
"if",
"not",
"empty",
"else",
"returns",
"a",
"copy",
"of",
"the",
"first",
"string",
"arugment",
"."
]
| 5a78055244d6b899c2a2eb158c8454f548af9ab2 | https://github.com/drone/envsubst/blob/5a78055244d6b899c2a2eb158c8454f548af9ab2/funcs.go#L54-L59 |
11,421 | drone/envsubst | funcs.go | toSubstr | func toSubstr(s string, args ...string) string {
if len(args) == 0 {
return s // should never happen
}
pos, err := strconv.Atoi(args[0])
if err != nil {
// bash returns the string if the position
// cannot be parsed.
return s
}
if len(args) == 1 {
if pos < len(s) {
return s[pos:]
}
// if the position exceeds the length of the
// string an empty string is returned
return ""
}
length, err := strconv.Atoi(args[1])
if err != nil {
// bash returns the string if the length
// cannot be parsed.
return s
}
if pos+length >= len(s) {
// if the position exceeds the length of the
// string just return the rest of it like bash
return s[pos:]
}
return s[pos : pos+length]
} | go | func toSubstr(s string, args ...string) string {
if len(args) == 0 {
return s // should never happen
}
pos, err := strconv.Atoi(args[0])
if err != nil {
// bash returns the string if the position
// cannot be parsed.
return s
}
if len(args) == 1 {
if pos < len(s) {
return s[pos:]
}
// if the position exceeds the length of the
// string an empty string is returned
return ""
}
length, err := strconv.Atoi(args[1])
if err != nil {
// bash returns the string if the length
// cannot be parsed.
return s
}
if pos+length >= len(s) {
// if the position exceeds the length of the
// string just return the rest of it like bash
return s[pos:]
}
return s[pos : pos+length]
} | [
"func",
"toSubstr",
"(",
"s",
"string",
",",
"args",
"...",
"string",
")",
"string",
"{",
"if",
"len",
"(",
"args",
")",
"==",
"0",
"{",
"return",
"s",
"// should never happen",
"\n",
"}",
"\n\n",
"pos",
",",
"err",
":=",
"strconv",
".",
"Atoi",
"(",
"args",
"[",
"0",
"]",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"// bash returns the string if the position",
"// cannot be parsed.",
"return",
"s",
"\n",
"}",
"\n\n",
"if",
"len",
"(",
"args",
")",
"==",
"1",
"{",
"if",
"pos",
"<",
"len",
"(",
"s",
")",
"{",
"return",
"s",
"[",
"pos",
":",
"]",
"\n",
"}",
"\n",
"// if the position exceeds the length of the",
"// string an empty string is returned",
"return",
"\"",
"\"",
"\n",
"}",
"\n\n",
"length",
",",
"err",
":=",
"strconv",
".",
"Atoi",
"(",
"args",
"[",
"1",
"]",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"// bash returns the string if the length",
"// cannot be parsed.",
"return",
"s",
"\n",
"}",
"\n\n",
"if",
"pos",
"+",
"length",
">=",
"len",
"(",
"s",
")",
"{",
"// if the position exceeds the length of the",
"// string just return the rest of it like bash",
"return",
"s",
"[",
"pos",
":",
"]",
"\n",
"}",
"\n\n",
"return",
"s",
"[",
"pos",
":",
"pos",
"+",
"length",
"]",
"\n",
"}"
]
| // toSubstr returns a slice of the string s at the specified
// length and position. | [
"toSubstr",
"returns",
"a",
"slice",
"of",
"the",
"string",
"s",
"at",
"the",
"specified",
"length",
"and",
"position",
"."
]
| 5a78055244d6b899c2a2eb158c8454f548af9ab2 | https://github.com/drone/envsubst/blob/5a78055244d6b899c2a2eb158c8454f548af9ab2/funcs.go#L63-L98 |
11,422 | drone/envsubst | funcs.go | replaceAll | func replaceAll(s string, args ...string) string {
switch len(args) {
case 0:
return s
case 1:
return strings.Replace(s, args[0], "", -1)
default:
return strings.Replace(s, args[0], args[1], -1)
}
} | go | func replaceAll(s string, args ...string) string {
switch len(args) {
case 0:
return s
case 1:
return strings.Replace(s, args[0], "", -1)
default:
return strings.Replace(s, args[0], args[1], -1)
}
} | [
"func",
"replaceAll",
"(",
"s",
"string",
",",
"args",
"...",
"string",
")",
"string",
"{",
"switch",
"len",
"(",
"args",
")",
"{",
"case",
"0",
":",
"return",
"s",
"\n",
"case",
"1",
":",
"return",
"strings",
".",
"Replace",
"(",
"s",
",",
"args",
"[",
"0",
"]",
",",
"\"",
"\"",
",",
"-",
"1",
")",
"\n",
"default",
":",
"return",
"strings",
".",
"Replace",
"(",
"s",
",",
"args",
"[",
"0",
"]",
",",
"args",
"[",
"1",
"]",
",",
"-",
"1",
")",
"\n",
"}",
"\n",
"}"
]
| // replaceAll returns a copy of the string s with all instances
// of the substring replaced with the replacement string. | [
"replaceAll",
"returns",
"a",
"copy",
"of",
"the",
"string",
"s",
"with",
"all",
"instances",
"of",
"the",
"substring",
"replaced",
"with",
"the",
"replacement",
"string",
"."
]
| 5a78055244d6b899c2a2eb158c8454f548af9ab2 | https://github.com/drone/envsubst/blob/5a78055244d6b899c2a2eb158c8454f548af9ab2/funcs.go#L102-L111 |
11,423 | drone/envsubst | funcs.go | replaceFirst | func replaceFirst(s string, args ...string) string {
switch len(args) {
case 0:
return s
case 1:
return strings.Replace(s, args[0], "", 1)
default:
return strings.Replace(s, args[0], args[1], 1)
}
} | go | func replaceFirst(s string, args ...string) string {
switch len(args) {
case 0:
return s
case 1:
return strings.Replace(s, args[0], "", 1)
default:
return strings.Replace(s, args[0], args[1], 1)
}
} | [
"func",
"replaceFirst",
"(",
"s",
"string",
",",
"args",
"...",
"string",
")",
"string",
"{",
"switch",
"len",
"(",
"args",
")",
"{",
"case",
"0",
":",
"return",
"s",
"\n",
"case",
"1",
":",
"return",
"strings",
".",
"Replace",
"(",
"s",
",",
"args",
"[",
"0",
"]",
",",
"\"",
"\"",
",",
"1",
")",
"\n",
"default",
":",
"return",
"strings",
".",
"Replace",
"(",
"s",
",",
"args",
"[",
"0",
"]",
",",
"args",
"[",
"1",
"]",
",",
"1",
")",
"\n",
"}",
"\n",
"}"
]
| // replaceFirst returns a copy of the string s with the first
// instance of the substring replaced with the replacement string. | [
"replaceFirst",
"returns",
"a",
"copy",
"of",
"the",
"string",
"s",
"with",
"the",
"first",
"instance",
"of",
"the",
"substring",
"replaced",
"with",
"the",
"replacement",
"string",
"."
]
| 5a78055244d6b899c2a2eb158c8454f548af9ab2 | https://github.com/drone/envsubst/blob/5a78055244d6b899c2a2eb158c8454f548af9ab2/funcs.go#L115-L124 |
11,424 | drone/envsubst | funcs.go | replacePrefix | func replacePrefix(s string, args ...string) string {
if len(args) != 2 {
return s
}
if strings.HasPrefix(s, args[0]) {
return strings.Replace(s, args[0], args[1], 1)
}
return s
} | go | func replacePrefix(s string, args ...string) string {
if len(args) != 2 {
return s
}
if strings.HasPrefix(s, args[0]) {
return strings.Replace(s, args[0], args[1], 1)
}
return s
} | [
"func",
"replacePrefix",
"(",
"s",
"string",
",",
"args",
"...",
"string",
")",
"string",
"{",
"if",
"len",
"(",
"args",
")",
"!=",
"2",
"{",
"return",
"s",
"\n",
"}",
"\n",
"if",
"strings",
".",
"HasPrefix",
"(",
"s",
",",
"args",
"[",
"0",
"]",
")",
"{",
"return",
"strings",
".",
"Replace",
"(",
"s",
",",
"args",
"[",
"0",
"]",
",",
"args",
"[",
"1",
"]",
",",
"1",
")",
"\n",
"}",
"\n",
"return",
"s",
"\n",
"}"
]
| // replacePrefix returns a copy of the string s with the matching
// prefix replaced with the replacement string. | [
"replacePrefix",
"returns",
"a",
"copy",
"of",
"the",
"string",
"s",
"with",
"the",
"matching",
"prefix",
"replaced",
"with",
"the",
"replacement",
"string",
"."
]
| 5a78055244d6b899c2a2eb158c8454f548af9ab2 | https://github.com/drone/envsubst/blob/5a78055244d6b899c2a2eb158c8454f548af9ab2/funcs.go#L128-L136 |
11,425 | drone/envsubst | funcs.go | replaceSuffix | func replaceSuffix(s string, args ...string) string {
if len(args) != 2 {
return s
}
if strings.HasSuffix(s, args[0]) {
s = strings.TrimSuffix(s, args[0])
s = s + args[1]
}
return s
} | go | func replaceSuffix(s string, args ...string) string {
if len(args) != 2 {
return s
}
if strings.HasSuffix(s, args[0]) {
s = strings.TrimSuffix(s, args[0])
s = s + args[1]
}
return s
} | [
"func",
"replaceSuffix",
"(",
"s",
"string",
",",
"args",
"...",
"string",
")",
"string",
"{",
"if",
"len",
"(",
"args",
")",
"!=",
"2",
"{",
"return",
"s",
"\n",
"}",
"\n",
"if",
"strings",
".",
"HasSuffix",
"(",
"s",
",",
"args",
"[",
"0",
"]",
")",
"{",
"s",
"=",
"strings",
".",
"TrimSuffix",
"(",
"s",
",",
"args",
"[",
"0",
"]",
")",
"\n",
"s",
"=",
"s",
"+",
"args",
"[",
"1",
"]",
"\n",
"}",
"\n",
"return",
"s",
"\n",
"}"
]
| // replaceSuffix returns a copy of the string s with the matching
// suffix replaced with the replacement string. | [
"replaceSuffix",
"returns",
"a",
"copy",
"of",
"the",
"string",
"s",
"with",
"the",
"matching",
"suffix",
"replaced",
"with",
"the",
"replacement",
"string",
"."
]
| 5a78055244d6b899c2a2eb158c8454f548af9ab2 | https://github.com/drone/envsubst/blob/5a78055244d6b899c2a2eb158c8454f548af9ab2/funcs.go#L140-L149 |
11,426 | drone/envsubst | template.go | Parse | func Parse(s string) (t *Template, err error) {
t = new(Template)
t.tree, err = parse.Parse(s)
if err != nil {
return nil, err
}
return t, nil
} | go | func Parse(s string) (t *Template, err error) {
t = new(Template)
t.tree, err = parse.Parse(s)
if err != nil {
return nil, err
}
return t, nil
} | [
"func",
"Parse",
"(",
"s",
"string",
")",
"(",
"t",
"*",
"Template",
",",
"err",
"error",
")",
"{",
"t",
"=",
"new",
"(",
"Template",
")",
"\n",
"t",
".",
"tree",
",",
"err",
"=",
"parse",
".",
"Parse",
"(",
"s",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"return",
"t",
",",
"nil",
"\n",
"}"
]
| // Parse creates a new shell format template and parses the template
// definition from string s. | [
"Parse",
"creates",
"a",
"new",
"shell",
"format",
"template",
"and",
"parses",
"the",
"template",
"definition",
"from",
"string",
"s",
"."
]
| 5a78055244d6b899c2a2eb158c8454f548af9ab2 | https://github.com/drone/envsubst/blob/5a78055244d6b899c2a2eb158c8454f548af9ab2/template.go#L29-L36 |
11,427 | drone/envsubst | template.go | Execute | func (t *Template) Execute(mapping func(string) string) (str string, err error) {
b := new(bytes.Buffer)
s := new(state)
s.node = t.tree.Root
s.mapper = mapping
s.writer = b
err = t.eval(s)
if err != nil {
return
}
return b.String(), nil
} | go | func (t *Template) Execute(mapping func(string) string) (str string, err error) {
b := new(bytes.Buffer)
s := new(state)
s.node = t.tree.Root
s.mapper = mapping
s.writer = b
err = t.eval(s)
if err != nil {
return
}
return b.String(), nil
} | [
"func",
"(",
"t",
"*",
"Template",
")",
"Execute",
"(",
"mapping",
"func",
"(",
"string",
")",
"string",
")",
"(",
"str",
"string",
",",
"err",
"error",
")",
"{",
"b",
":=",
"new",
"(",
"bytes",
".",
"Buffer",
")",
"\n",
"s",
":=",
"new",
"(",
"state",
")",
"\n",
"s",
".",
"node",
"=",
"t",
".",
"tree",
".",
"Root",
"\n",
"s",
".",
"mapper",
"=",
"mapping",
"\n",
"s",
".",
"writer",
"=",
"b",
"\n",
"err",
"=",
"t",
".",
"eval",
"(",
"s",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\n",
"}",
"\n",
"return",
"b",
".",
"String",
"(",
")",
",",
"nil",
"\n",
"}"
]
| // Execute applies a parsed template to the specified data mapping. | [
"Execute",
"applies",
"a",
"parsed",
"template",
"to",
"the",
"specified",
"data",
"mapping",
"."
]
| 5a78055244d6b899c2a2eb158c8454f548af9ab2 | https://github.com/drone/envsubst/blob/5a78055244d6b899c2a2eb158c8454f548af9ab2/template.go#L49-L60 |
11,428 | drone/envsubst | template.go | lookupFunc | func lookupFunc(name string, args int) substituteFunc {
switch name {
case ",":
return toLowerFirst
case ",,":
return toLower
case "^":
return toUpperFirst
case "^^":
return toUpper
case "#":
if args == 0 {
return toLen
}
return trimShortestPrefix
case "##":
return trimLongestPrefix
case "%":
return trimShortestSuffix
case "%%":
return trimLongestSuffix
case ":":
return toSubstr
case "/#":
return replacePrefix
case "/%":
return replaceSuffix
case "/":
return replaceFirst
case "//":
return replaceAll
case "=", ":=", ":-":
return toDefault
case ":?", ":+", "-", "+":
return toDefault
default:
return toDefault
}
} | go | func lookupFunc(name string, args int) substituteFunc {
switch name {
case ",":
return toLowerFirst
case ",,":
return toLower
case "^":
return toUpperFirst
case "^^":
return toUpper
case "#":
if args == 0 {
return toLen
}
return trimShortestPrefix
case "##":
return trimLongestPrefix
case "%":
return trimShortestSuffix
case "%%":
return trimLongestSuffix
case ":":
return toSubstr
case "/#":
return replacePrefix
case "/%":
return replaceSuffix
case "/":
return replaceFirst
case "//":
return replaceAll
case "=", ":=", ":-":
return toDefault
case ":?", ":+", "-", "+":
return toDefault
default:
return toDefault
}
} | [
"func",
"lookupFunc",
"(",
"name",
"string",
",",
"args",
"int",
")",
"substituteFunc",
"{",
"switch",
"name",
"{",
"case",
"\"",
"\"",
":",
"return",
"toLowerFirst",
"\n",
"case",
"\"",
"\"",
":",
"return",
"toLower",
"\n",
"case",
"\"",
"\"",
":",
"return",
"toUpperFirst",
"\n",
"case",
"\"",
"\"",
":",
"return",
"toUpper",
"\n",
"case",
"\"",
"\"",
":",
"if",
"args",
"==",
"0",
"{",
"return",
"toLen",
"\n",
"}",
"\n",
"return",
"trimShortestPrefix",
"\n",
"case",
"\"",
"\"",
":",
"return",
"trimLongestPrefix",
"\n",
"case",
"\"",
"\"",
":",
"return",
"trimShortestSuffix",
"\n",
"case",
"\"",
"\"",
":",
"return",
"trimLongestSuffix",
"\n",
"case",
"\"",
"\"",
":",
"return",
"toSubstr",
"\n",
"case",
"\"",
"\"",
":",
"return",
"replacePrefix",
"\n",
"case",
"\"",
"\"",
":",
"return",
"replaceSuffix",
"\n",
"case",
"\"",
"\"",
":",
"return",
"replaceFirst",
"\n",
"case",
"\"",
"\"",
":",
"return",
"replaceAll",
"\n",
"case",
"\"",
"\"",
",",
"\"",
"\"",
",",
"\"",
"\"",
":",
"return",
"toDefault",
"\n",
"case",
"\"",
"\"",
",",
"\"",
"\"",
",",
"\"",
"\"",
",",
"\"",
"\"",
":",
"return",
"toDefault",
"\n",
"default",
":",
"return",
"toDefault",
"\n",
"}",
"\n",
"}"
]
| // lookupFunc returns the parameters substitution function by name. If the
// named function does not exists, a default function is returned. | [
"lookupFunc",
"returns",
"the",
"parameters",
"substitution",
"function",
"by",
"name",
".",
"If",
"the",
"named",
"function",
"does",
"not",
"exists",
"a",
"default",
"function",
"is",
"returned",
"."
]
| 5a78055244d6b899c2a2eb158c8454f548af9ab2 | https://github.com/drone/envsubst/blob/5a78055244d6b899c2a2eb158c8454f548af9ab2/template.go#L119-L157 |
11,429 | libp2p/go-libp2p-swarm | swarm_dial.go | Backoff | func (db *DialBackoff) Backoff(p peer.ID) (backoff bool) {
db.lock.Lock()
defer db.lock.Unlock()
db.init()
bp, found := db.entries[p]
if found && time.Now().Before(bp.until) {
return true
}
return false
} | go | func (db *DialBackoff) Backoff(p peer.ID) (backoff bool) {
db.lock.Lock()
defer db.lock.Unlock()
db.init()
bp, found := db.entries[p]
if found && time.Now().Before(bp.until) {
return true
}
return false
} | [
"func",
"(",
"db",
"*",
"DialBackoff",
")",
"Backoff",
"(",
"p",
"peer",
".",
"ID",
")",
"(",
"backoff",
"bool",
")",
"{",
"db",
".",
"lock",
".",
"Lock",
"(",
")",
"\n",
"defer",
"db",
".",
"lock",
".",
"Unlock",
"(",
")",
"\n",
"db",
".",
"init",
"(",
")",
"\n",
"bp",
",",
"found",
":=",
"db",
".",
"entries",
"[",
"p",
"]",
"\n",
"if",
"found",
"&&",
"time",
".",
"Now",
"(",
")",
".",
"Before",
"(",
"bp",
".",
"until",
")",
"{",
"return",
"true",
"\n",
"}",
"\n\n",
"return",
"false",
"\n",
"}"
]
| // Backoff returns whether the client should backoff from dialing
// peer p | [
"Backoff",
"returns",
"whether",
"the",
"client",
"should",
"backoff",
"from",
"dialing",
"peer",
"p"
]
| 0fc01368da4ae9ce28fc261131494af3eda9aace | https://github.com/libp2p/go-libp2p-swarm/blob/0fc01368da4ae9ce28fc261131494af3eda9aace/swarm_dial.go#L116-L126 |
11,430 | libp2p/go-libp2p-swarm | swarm_dial.go | Clear | func (db *DialBackoff) Clear(p peer.ID) {
db.lock.Lock()
defer db.lock.Unlock()
db.init()
delete(db.entries, p)
} | go | func (db *DialBackoff) Clear(p peer.ID) {
db.lock.Lock()
defer db.lock.Unlock()
db.init()
delete(db.entries, p)
} | [
"func",
"(",
"db",
"*",
"DialBackoff",
")",
"Clear",
"(",
"p",
"peer",
".",
"ID",
")",
"{",
"db",
".",
"lock",
".",
"Lock",
"(",
")",
"\n",
"defer",
"db",
".",
"lock",
".",
"Unlock",
"(",
")",
"\n",
"db",
".",
"init",
"(",
")",
"\n",
"delete",
"(",
"db",
".",
"entries",
",",
"p",
")",
"\n",
"}"
]
| // Clear removes a backoff record. Clients should call this after a
// successful Dial. | [
"Clear",
"removes",
"a",
"backoff",
"record",
".",
"Clients",
"should",
"call",
"this",
"after",
"a",
"successful",
"Dial",
"."
]
| 0fc01368da4ae9ce28fc261131494af3eda9aace | https://github.com/libp2p/go-libp2p-swarm/blob/0fc01368da4ae9ce28fc261131494af3eda9aace/swarm_dial.go#L170-L175 |
11,431 | libp2p/go-libp2p-swarm | swarm_dial.go | doDial | func (s *Swarm) doDial(ctx context.Context, p peer.ID) (*Conn, error) {
// Short circuit.
// By the time we take the dial lock, we may already *have* a connection
// to the peer.
c := s.bestConnToPeer(p)
if c != nil {
return c, nil
}
logdial := lgbl.Dial("swarm", s.LocalPeer(), p, nil, nil)
// ok, we have been charged to dial! let's do it.
// if it succeeds, dial will add the conn to the swarm itself.
defer log.EventBegin(ctx, "swarmDialAttemptStart", logdial).Done()
conn, err := s.dial(ctx, p)
if err != nil {
conn = s.bestConnToPeer(p)
if conn != nil {
// Hm? What error?
// Could have canceled the dial because we received a
// connection or some other random reason.
// Just ignore the error and return the connection.
log.Debugf("ignoring dial error because we have a connection: %s", err)
return conn, nil
}
if err != context.Canceled {
log.Event(ctx, "swarmDialBackoffAdd", logdial)
s.backf.AddBackoff(p) // let others know to backoff
}
// ok, we failed.
return nil, err
}
return conn, nil
} | go | func (s *Swarm) doDial(ctx context.Context, p peer.ID) (*Conn, error) {
// Short circuit.
// By the time we take the dial lock, we may already *have* a connection
// to the peer.
c := s.bestConnToPeer(p)
if c != nil {
return c, nil
}
logdial := lgbl.Dial("swarm", s.LocalPeer(), p, nil, nil)
// ok, we have been charged to dial! let's do it.
// if it succeeds, dial will add the conn to the swarm itself.
defer log.EventBegin(ctx, "swarmDialAttemptStart", logdial).Done()
conn, err := s.dial(ctx, p)
if err != nil {
conn = s.bestConnToPeer(p)
if conn != nil {
// Hm? What error?
// Could have canceled the dial because we received a
// connection or some other random reason.
// Just ignore the error and return the connection.
log.Debugf("ignoring dial error because we have a connection: %s", err)
return conn, nil
}
if err != context.Canceled {
log.Event(ctx, "swarmDialBackoffAdd", logdial)
s.backf.AddBackoff(p) // let others know to backoff
}
// ok, we failed.
return nil, err
}
return conn, nil
} | [
"func",
"(",
"s",
"*",
"Swarm",
")",
"doDial",
"(",
"ctx",
"context",
".",
"Context",
",",
"p",
"peer",
".",
"ID",
")",
"(",
"*",
"Conn",
",",
"error",
")",
"{",
"// Short circuit.",
"// By the time we take the dial lock, we may already *have* a connection",
"// to the peer.",
"c",
":=",
"s",
".",
"bestConnToPeer",
"(",
"p",
")",
"\n",
"if",
"c",
"!=",
"nil",
"{",
"return",
"c",
",",
"nil",
"\n",
"}",
"\n\n",
"logdial",
":=",
"lgbl",
".",
"Dial",
"(",
"\"",
"\"",
",",
"s",
".",
"LocalPeer",
"(",
")",
",",
"p",
",",
"nil",
",",
"nil",
")",
"\n\n",
"// ok, we have been charged to dial! let's do it.",
"// if it succeeds, dial will add the conn to the swarm itself.",
"defer",
"log",
".",
"EventBegin",
"(",
"ctx",
",",
"\"",
"\"",
",",
"logdial",
")",
".",
"Done",
"(",
")",
"\n\n",
"conn",
",",
"err",
":=",
"s",
".",
"dial",
"(",
"ctx",
",",
"p",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"conn",
"=",
"s",
".",
"bestConnToPeer",
"(",
"p",
")",
"\n",
"if",
"conn",
"!=",
"nil",
"{",
"// Hm? What error?",
"// Could have canceled the dial because we received a",
"// connection or some other random reason.",
"// Just ignore the error and return the connection.",
"log",
".",
"Debugf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"return",
"conn",
",",
"nil",
"\n",
"}",
"\n",
"if",
"err",
"!=",
"context",
".",
"Canceled",
"{",
"log",
".",
"Event",
"(",
"ctx",
",",
"\"",
"\"",
",",
"logdial",
")",
"\n",
"s",
".",
"backf",
".",
"AddBackoff",
"(",
"p",
")",
"// let others know to backoff",
"\n",
"}",
"\n\n",
"// ok, we failed.",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"return",
"conn",
",",
"nil",
"\n",
"}"
]
| // doDial is an ugly shim method to retain all the logging and backoff logic
// of the old dialsync code | [
"doDial",
"is",
"an",
"ugly",
"shim",
"method",
"to",
"retain",
"all",
"the",
"logging",
"and",
"backoff",
"logic",
"of",
"the",
"old",
"dialsync",
"code"
]
| 0fc01368da4ae9ce28fc261131494af3eda9aace | https://github.com/libp2p/go-libp2p-swarm/blob/0fc01368da4ae9ce28fc261131494af3eda9aace/swarm_dial.go#L233-L268 |
11,432 | libp2p/go-libp2p-swarm | swarm_dial.go | dial | func (s *Swarm) dial(ctx context.Context, p peer.ID) (*Conn, error) {
var logdial = lgbl.Dial("swarm", s.LocalPeer(), p, nil, nil)
if p == s.local {
log.Event(ctx, "swarmDialDoDialSelf", logdial)
return nil, ErrDialToSelf
}
defer log.EventBegin(ctx, "swarmDialDo", logdial).Done()
logdial["dial"] = "failure" // start off with failure. set to "success" at the end.
sk := s.peers.PrivKey(s.local)
logdial["encrypted"] = sk != nil // log whether this will be an encrypted dial or not.
if sk == nil {
// fine for sk to be nil, just log.
log.Debug("Dial not given PrivateKey, so WILL NOT SECURE conn.")
}
//////
/*
This slice-to-chan code is temporary, the peerstore can currently provide
a channel as an interface for receiving addresses, but more thought
needs to be put into the execution. For now, this allows us to use
the improved rate limiter, while maintaining the outward behaviour
that we previously had (halting a dial when we run out of addrs)
*/
peerAddrs := s.peers.Addrs(p)
if len(peerAddrs) == 0 {
return nil, &DialError{Peer: p, Cause: ErrNoAddresses}
}
goodAddrs := s.filterKnownUndialables(peerAddrs)
if len(goodAddrs) == 0 {
return nil, &DialError{Peer: p, Cause: ErrNoGoodAddresses}
}
goodAddrsChan := make(chan ma.Multiaddr, len(goodAddrs))
for _, a := range goodAddrs {
goodAddrsChan <- a
}
close(goodAddrsChan)
/////////
// try to get a connection to any addr
connC, dialErr := s.dialAddrs(ctx, p, goodAddrsChan)
if dialErr != nil {
logdial["error"] = dialErr.Cause.Error()
if dialErr.Cause == context.Canceled {
// always prefer the "context canceled" error.
// we rely on behing able to check `err == context.Canceled`
//
// Removing this will BREAK backoff (causing us to
// backoff when canceling dials).
return nil, context.Canceled
}
return nil, dialErr
}
logdial["conn"] = logging.Metadata{
"localAddr": connC.LocalMultiaddr(),
"remoteAddr": connC.RemoteMultiaddr(),
}
swarmC, err := s.addConn(connC, inet.DirOutbound)
if err != nil {
logdial["error"] = err.Error()
connC.Close() // close the connection. didn't work out :(
return nil, &DialError{Peer: p, Cause: err}
}
logdial["dial"] = "success"
return swarmC, nil
} | go | func (s *Swarm) dial(ctx context.Context, p peer.ID) (*Conn, error) {
var logdial = lgbl.Dial("swarm", s.LocalPeer(), p, nil, nil)
if p == s.local {
log.Event(ctx, "swarmDialDoDialSelf", logdial)
return nil, ErrDialToSelf
}
defer log.EventBegin(ctx, "swarmDialDo", logdial).Done()
logdial["dial"] = "failure" // start off with failure. set to "success" at the end.
sk := s.peers.PrivKey(s.local)
logdial["encrypted"] = sk != nil // log whether this will be an encrypted dial or not.
if sk == nil {
// fine for sk to be nil, just log.
log.Debug("Dial not given PrivateKey, so WILL NOT SECURE conn.")
}
//////
/*
This slice-to-chan code is temporary, the peerstore can currently provide
a channel as an interface for receiving addresses, but more thought
needs to be put into the execution. For now, this allows us to use
the improved rate limiter, while maintaining the outward behaviour
that we previously had (halting a dial when we run out of addrs)
*/
peerAddrs := s.peers.Addrs(p)
if len(peerAddrs) == 0 {
return nil, &DialError{Peer: p, Cause: ErrNoAddresses}
}
goodAddrs := s.filterKnownUndialables(peerAddrs)
if len(goodAddrs) == 0 {
return nil, &DialError{Peer: p, Cause: ErrNoGoodAddresses}
}
goodAddrsChan := make(chan ma.Multiaddr, len(goodAddrs))
for _, a := range goodAddrs {
goodAddrsChan <- a
}
close(goodAddrsChan)
/////////
// try to get a connection to any addr
connC, dialErr := s.dialAddrs(ctx, p, goodAddrsChan)
if dialErr != nil {
logdial["error"] = dialErr.Cause.Error()
if dialErr.Cause == context.Canceled {
// always prefer the "context canceled" error.
// we rely on behing able to check `err == context.Canceled`
//
// Removing this will BREAK backoff (causing us to
// backoff when canceling dials).
return nil, context.Canceled
}
return nil, dialErr
}
logdial["conn"] = logging.Metadata{
"localAddr": connC.LocalMultiaddr(),
"remoteAddr": connC.RemoteMultiaddr(),
}
swarmC, err := s.addConn(connC, inet.DirOutbound)
if err != nil {
logdial["error"] = err.Error()
connC.Close() // close the connection. didn't work out :(
return nil, &DialError{Peer: p, Cause: err}
}
logdial["dial"] = "success"
return swarmC, nil
} | [
"func",
"(",
"s",
"*",
"Swarm",
")",
"dial",
"(",
"ctx",
"context",
".",
"Context",
",",
"p",
"peer",
".",
"ID",
")",
"(",
"*",
"Conn",
",",
"error",
")",
"{",
"var",
"logdial",
"=",
"lgbl",
".",
"Dial",
"(",
"\"",
"\"",
",",
"s",
".",
"LocalPeer",
"(",
")",
",",
"p",
",",
"nil",
",",
"nil",
")",
"\n",
"if",
"p",
"==",
"s",
".",
"local",
"{",
"log",
".",
"Event",
"(",
"ctx",
",",
"\"",
"\"",
",",
"logdial",
")",
"\n",
"return",
"nil",
",",
"ErrDialToSelf",
"\n",
"}",
"\n",
"defer",
"log",
".",
"EventBegin",
"(",
"ctx",
",",
"\"",
"\"",
",",
"logdial",
")",
".",
"Done",
"(",
")",
"\n",
"logdial",
"[",
"\"",
"\"",
"]",
"=",
"\"",
"\"",
"// start off with failure. set to \"success\" at the end.",
"\n\n",
"sk",
":=",
"s",
".",
"peers",
".",
"PrivKey",
"(",
"s",
".",
"local",
")",
"\n",
"logdial",
"[",
"\"",
"\"",
"]",
"=",
"sk",
"!=",
"nil",
"// log whether this will be an encrypted dial or not.",
"\n",
"if",
"sk",
"==",
"nil",
"{",
"// fine for sk to be nil, just log.",
"log",
".",
"Debug",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"//////",
"/*\n\t\tThis slice-to-chan code is temporary, the peerstore can currently provide\n\t\ta channel as an interface for receiving addresses, but more thought\n\t\tneeds to be put into the execution. For now, this allows us to use\n\t\tthe improved rate limiter, while maintaining the outward behaviour\n\t\tthat we previously had (halting a dial when we run out of addrs)\n\t*/",
"peerAddrs",
":=",
"s",
".",
"peers",
".",
"Addrs",
"(",
"p",
")",
"\n",
"if",
"len",
"(",
"peerAddrs",
")",
"==",
"0",
"{",
"return",
"nil",
",",
"&",
"DialError",
"{",
"Peer",
":",
"p",
",",
"Cause",
":",
"ErrNoAddresses",
"}",
"\n",
"}",
"\n",
"goodAddrs",
":=",
"s",
".",
"filterKnownUndialables",
"(",
"peerAddrs",
")",
"\n",
"if",
"len",
"(",
"goodAddrs",
")",
"==",
"0",
"{",
"return",
"nil",
",",
"&",
"DialError",
"{",
"Peer",
":",
"p",
",",
"Cause",
":",
"ErrNoGoodAddresses",
"}",
"\n",
"}",
"\n",
"goodAddrsChan",
":=",
"make",
"(",
"chan",
"ma",
".",
"Multiaddr",
",",
"len",
"(",
"goodAddrs",
")",
")",
"\n",
"for",
"_",
",",
"a",
":=",
"range",
"goodAddrs",
"{",
"goodAddrsChan",
"<-",
"a",
"\n",
"}",
"\n",
"close",
"(",
"goodAddrsChan",
")",
"\n",
"/////////",
"// try to get a connection to any addr",
"connC",
",",
"dialErr",
":=",
"s",
".",
"dialAddrs",
"(",
"ctx",
",",
"p",
",",
"goodAddrsChan",
")",
"\n",
"if",
"dialErr",
"!=",
"nil",
"{",
"logdial",
"[",
"\"",
"\"",
"]",
"=",
"dialErr",
".",
"Cause",
".",
"Error",
"(",
")",
"\n",
"if",
"dialErr",
".",
"Cause",
"==",
"context",
".",
"Canceled",
"{",
"// always prefer the \"context canceled\" error.",
"// we rely on behing able to check `err == context.Canceled`",
"//",
"// Removing this will BREAK backoff (causing us to",
"// backoff when canceling dials).",
"return",
"nil",
",",
"context",
".",
"Canceled",
"\n",
"}",
"\n",
"return",
"nil",
",",
"dialErr",
"\n",
"}",
"\n",
"logdial",
"[",
"\"",
"\"",
"]",
"=",
"logging",
".",
"Metadata",
"{",
"\"",
"\"",
":",
"connC",
".",
"LocalMultiaddr",
"(",
")",
",",
"\"",
"\"",
":",
"connC",
".",
"RemoteMultiaddr",
"(",
")",
",",
"}",
"\n",
"swarmC",
",",
"err",
":=",
"s",
".",
"addConn",
"(",
"connC",
",",
"inet",
".",
"DirOutbound",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"logdial",
"[",
"\"",
"\"",
"]",
"=",
"err",
".",
"Error",
"(",
")",
"\n",
"connC",
".",
"Close",
"(",
")",
"// close the connection. didn't work out :(",
"\n",
"return",
"nil",
",",
"&",
"DialError",
"{",
"Peer",
":",
"p",
",",
"Cause",
":",
"err",
"}",
"\n",
"}",
"\n\n",
"logdial",
"[",
"\"",
"\"",
"]",
"=",
"\"",
"\"",
"\n",
"return",
"swarmC",
",",
"nil",
"\n",
"}"
]
| // dial is the actual swarm's dial logic, gated by Dial. | [
"dial",
"is",
"the",
"actual",
"swarm",
"s",
"dial",
"logic",
"gated",
"by",
"Dial",
"."
]
| 0fc01368da4ae9ce28fc261131494af3eda9aace | https://github.com/libp2p/go-libp2p-swarm/blob/0fc01368da4ae9ce28fc261131494af3eda9aace/swarm_dial.go#L276-L342 |
11,433 | libp2p/go-libp2p-swarm | swarm_dial.go | limitedDial | func (s *Swarm) limitedDial(ctx context.Context, p peer.ID, a ma.Multiaddr, resp chan dialResult) {
s.limiter.AddDialJob(&dialJob{
addr: a,
peer: p,
resp: resp,
ctx: ctx,
})
} | go | func (s *Swarm) limitedDial(ctx context.Context, p peer.ID, a ma.Multiaddr, resp chan dialResult) {
s.limiter.AddDialJob(&dialJob{
addr: a,
peer: p,
resp: resp,
ctx: ctx,
})
} | [
"func",
"(",
"s",
"*",
"Swarm",
")",
"limitedDial",
"(",
"ctx",
"context",
".",
"Context",
",",
"p",
"peer",
".",
"ID",
",",
"a",
"ma",
".",
"Multiaddr",
",",
"resp",
"chan",
"dialResult",
")",
"{",
"s",
".",
"limiter",
".",
"AddDialJob",
"(",
"&",
"dialJob",
"{",
"addr",
":",
"a",
",",
"peer",
":",
"p",
",",
"resp",
":",
"resp",
",",
"ctx",
":",
"ctx",
",",
"}",
")",
"\n",
"}"
]
| // limitedDial will start a dial to the given peer when
// it is able, respecting the various different types of rate
// limiting that occur without using extra goroutines per addr | [
"limitedDial",
"will",
"start",
"a",
"dial",
"to",
"the",
"given",
"peer",
"when",
"it",
"is",
"able",
"respecting",
"the",
"various",
"different",
"types",
"of",
"rate",
"limiting",
"that",
"occur",
"without",
"using",
"extra",
"goroutines",
"per",
"addr"
]
| 0fc01368da4ae9ce28fc261131494af3eda9aace | https://github.com/libp2p/go-libp2p-swarm/blob/0fc01368da4ae9ce28fc261131494af3eda9aace/swarm_dial.go#L440-L447 |
11,434 | libp2p/go-libp2p-swarm | limiter.go | freeFDToken | func (dl *dialLimiter) freeFDToken() {
log.Debugf("[limiter] freeing FD token; waiting: %d; consuming: %d", len(dl.waitingOnFd), dl.fdConsuming)
dl.fdConsuming--
for len(dl.waitingOnFd) > 0 {
next := dl.waitingOnFd[0]
dl.waitingOnFd[0] = nil // clear out memory
dl.waitingOnFd = dl.waitingOnFd[1:]
if len(dl.waitingOnFd) == 0 {
// clear out memory.
dl.waitingOnFd = nil
}
// Skip over canceled dials instead of queuing up a goroutine.
if next.cancelled() {
dl.freePeerToken(next)
continue
}
dl.fdConsuming++
// we already have activePerPeer token at this point so we can just dial
go dl.executeDial(next)
return
}
} | go | func (dl *dialLimiter) freeFDToken() {
log.Debugf("[limiter] freeing FD token; waiting: %d; consuming: %d", len(dl.waitingOnFd), dl.fdConsuming)
dl.fdConsuming--
for len(dl.waitingOnFd) > 0 {
next := dl.waitingOnFd[0]
dl.waitingOnFd[0] = nil // clear out memory
dl.waitingOnFd = dl.waitingOnFd[1:]
if len(dl.waitingOnFd) == 0 {
// clear out memory.
dl.waitingOnFd = nil
}
// Skip over canceled dials instead of queuing up a goroutine.
if next.cancelled() {
dl.freePeerToken(next)
continue
}
dl.fdConsuming++
// we already have activePerPeer token at this point so we can just dial
go dl.executeDial(next)
return
}
} | [
"func",
"(",
"dl",
"*",
"dialLimiter",
")",
"freeFDToken",
"(",
")",
"{",
"log",
".",
"Debugf",
"(",
"\"",
"\"",
",",
"len",
"(",
"dl",
".",
"waitingOnFd",
")",
",",
"dl",
".",
"fdConsuming",
")",
"\n",
"dl",
".",
"fdConsuming",
"--",
"\n\n",
"for",
"len",
"(",
"dl",
".",
"waitingOnFd",
")",
">",
"0",
"{",
"next",
":=",
"dl",
".",
"waitingOnFd",
"[",
"0",
"]",
"\n",
"dl",
".",
"waitingOnFd",
"[",
"0",
"]",
"=",
"nil",
"// clear out memory",
"\n",
"dl",
".",
"waitingOnFd",
"=",
"dl",
".",
"waitingOnFd",
"[",
"1",
":",
"]",
"\n\n",
"if",
"len",
"(",
"dl",
".",
"waitingOnFd",
")",
"==",
"0",
"{",
"// clear out memory.",
"dl",
".",
"waitingOnFd",
"=",
"nil",
"\n",
"}",
"\n\n",
"// Skip over canceled dials instead of queuing up a goroutine.",
"if",
"next",
".",
"cancelled",
"(",
")",
"{",
"dl",
".",
"freePeerToken",
"(",
"next",
")",
"\n",
"continue",
"\n",
"}",
"\n",
"dl",
".",
"fdConsuming",
"++",
"\n\n",
"// we already have activePerPeer token at this point so we can just dial",
"go",
"dl",
".",
"executeDial",
"(",
"next",
")",
"\n",
"return",
"\n",
"}",
"\n",
"}"
]
| // freeFDToken frees FD token and if there are any schedules another waiting dialJob
// in it's place | [
"freeFDToken",
"frees",
"FD",
"token",
"and",
"if",
"there",
"are",
"any",
"schedules",
"another",
"waiting",
"dialJob",
"in",
"it",
"s",
"place"
]
| 0fc01368da4ae9ce28fc261131494af3eda9aace | https://github.com/libp2p/go-libp2p-swarm/blob/0fc01368da4ae9ce28fc261131494af3eda9aace/limiter.go#L80-L105 |
11,435 | libp2p/go-libp2p-swarm | limiter.go | AddDialJob | func (dl *dialLimiter) AddDialJob(dj *dialJob) {
dl.lk.Lock()
defer dl.lk.Unlock()
log.Debugf("[limiter] adding a dial job through limiter: %v", dj.addr)
dl.addCheckPeerLimit(dj)
} | go | func (dl *dialLimiter) AddDialJob(dj *dialJob) {
dl.lk.Lock()
defer dl.lk.Unlock()
log.Debugf("[limiter] adding a dial job through limiter: %v", dj.addr)
dl.addCheckPeerLimit(dj)
} | [
"func",
"(",
"dl",
"*",
"dialLimiter",
")",
"AddDialJob",
"(",
"dj",
"*",
"dialJob",
")",
"{",
"dl",
".",
"lk",
".",
"Lock",
"(",
")",
"\n",
"defer",
"dl",
".",
"lk",
".",
"Unlock",
"(",
")",
"\n\n",
"log",
".",
"Debugf",
"(",
"\"",
"\"",
",",
"dj",
".",
"addr",
")",
"\n",
"dl",
".",
"addCheckPeerLimit",
"(",
"dj",
")",
"\n",
"}"
]
| // AddDialJob tries to take the needed tokens for starting the given dial job.
// If it acquires all needed tokens, it immediately starts the dial, otherwise
// it will put it on the waitlist for the requested token. | [
"AddDialJob",
"tries",
"to",
"take",
"the",
"needed",
"tokens",
"for",
"starting",
"the",
"given",
"dial",
"job",
".",
"If",
"it",
"acquires",
"all",
"needed",
"tokens",
"it",
"immediately",
"starts",
"the",
"dial",
"otherwise",
"it",
"will",
"put",
"it",
"on",
"the",
"waitlist",
"for",
"the",
"requested",
"token",
"."
]
| 0fc01368da4ae9ce28fc261131494af3eda9aace | https://github.com/libp2p/go-libp2p-swarm/blob/0fc01368da4ae9ce28fc261131494af3eda9aace/limiter.go#L187-L193 |
11,436 | libp2p/go-libp2p-swarm | limiter.go | executeDial | func (dl *dialLimiter) executeDial(j *dialJob) {
defer dl.finishedDial(j)
if j.cancelled() {
return
}
dctx, cancel := context.WithTimeout(j.ctx, j.dialTimeout())
defer cancel()
con, err := dl.dialFunc(dctx, j.peer, j.addr)
select {
case j.resp <- dialResult{Conn: con, Addr: j.addr, Err: err}:
case <-j.ctx.Done():
if err == nil {
con.Close()
}
}
} | go | func (dl *dialLimiter) executeDial(j *dialJob) {
defer dl.finishedDial(j)
if j.cancelled() {
return
}
dctx, cancel := context.WithTimeout(j.ctx, j.dialTimeout())
defer cancel()
con, err := dl.dialFunc(dctx, j.peer, j.addr)
select {
case j.resp <- dialResult{Conn: con, Addr: j.addr, Err: err}:
case <-j.ctx.Done():
if err == nil {
con.Close()
}
}
} | [
"func",
"(",
"dl",
"*",
"dialLimiter",
")",
"executeDial",
"(",
"j",
"*",
"dialJob",
")",
"{",
"defer",
"dl",
".",
"finishedDial",
"(",
"j",
")",
"\n",
"if",
"j",
".",
"cancelled",
"(",
")",
"{",
"return",
"\n",
"}",
"\n\n",
"dctx",
",",
"cancel",
":=",
"context",
".",
"WithTimeout",
"(",
"j",
".",
"ctx",
",",
"j",
".",
"dialTimeout",
"(",
")",
")",
"\n",
"defer",
"cancel",
"(",
")",
"\n\n",
"con",
",",
"err",
":=",
"dl",
".",
"dialFunc",
"(",
"dctx",
",",
"j",
".",
"peer",
",",
"j",
".",
"addr",
")",
"\n",
"select",
"{",
"case",
"j",
".",
"resp",
"<-",
"dialResult",
"{",
"Conn",
":",
"con",
",",
"Addr",
":",
"j",
".",
"addr",
",",
"Err",
":",
"err",
"}",
":",
"case",
"<-",
"j",
".",
"ctx",
".",
"Done",
"(",
")",
":",
"if",
"err",
"==",
"nil",
"{",
"con",
".",
"Close",
"(",
")",
"\n",
"}",
"\n",
"}",
"\n",
"}"
]
| // executeDial calls the dialFunc, and reports the result through the response
// channel when finished. Once the response is sent it also releases all tokens
// it held during the dial. | [
"executeDial",
"calls",
"the",
"dialFunc",
"and",
"reports",
"the",
"result",
"through",
"the",
"response",
"channel",
"when",
"finished",
".",
"Once",
"the",
"response",
"is",
"sent",
"it",
"also",
"releases",
"all",
"tokens",
"it",
"held",
"during",
"the",
"dial",
"."
]
| 0fc01368da4ae9ce28fc261131494af3eda9aace | https://github.com/libp2p/go-libp2p-swarm/blob/0fc01368da4ae9ce28fc261131494af3eda9aace/limiter.go#L208-L225 |
11,437 | libp2p/go-libp2p-swarm | swarm_transport.go | TransportForDialing | func (s *Swarm) TransportForDialing(a ma.Multiaddr) transport.Transport {
protocols := a.Protocols()
if len(protocols) == 0 {
return nil
}
s.transports.RLock()
defer s.transports.RUnlock()
if len(s.transports.m) == 0 {
log.Error("you have no transports configured")
return nil
}
for _, p := range protocols {
transport, ok := s.transports.m[p.Code]
if !ok {
continue
}
if transport.Proxy() {
return transport
}
}
return s.transports.m[protocols[len(protocols)-1].Code]
} | go | func (s *Swarm) TransportForDialing(a ma.Multiaddr) transport.Transport {
protocols := a.Protocols()
if len(protocols) == 0 {
return nil
}
s.transports.RLock()
defer s.transports.RUnlock()
if len(s.transports.m) == 0 {
log.Error("you have no transports configured")
return nil
}
for _, p := range protocols {
transport, ok := s.transports.m[p.Code]
if !ok {
continue
}
if transport.Proxy() {
return transport
}
}
return s.transports.m[protocols[len(protocols)-1].Code]
} | [
"func",
"(",
"s",
"*",
"Swarm",
")",
"TransportForDialing",
"(",
"a",
"ma",
".",
"Multiaddr",
")",
"transport",
".",
"Transport",
"{",
"protocols",
":=",
"a",
".",
"Protocols",
"(",
")",
"\n",
"if",
"len",
"(",
"protocols",
")",
"==",
"0",
"{",
"return",
"nil",
"\n",
"}",
"\n\n",
"s",
".",
"transports",
".",
"RLock",
"(",
")",
"\n",
"defer",
"s",
".",
"transports",
".",
"RUnlock",
"(",
")",
"\n",
"if",
"len",
"(",
"s",
".",
"transports",
".",
"m",
")",
"==",
"0",
"{",
"log",
".",
"Error",
"(",
"\"",
"\"",
")",
"\n",
"return",
"nil",
"\n",
"}",
"\n\n",
"for",
"_",
",",
"p",
":=",
"range",
"protocols",
"{",
"transport",
",",
"ok",
":=",
"s",
".",
"transports",
".",
"m",
"[",
"p",
".",
"Code",
"]",
"\n",
"if",
"!",
"ok",
"{",
"continue",
"\n",
"}",
"\n",
"if",
"transport",
".",
"Proxy",
"(",
")",
"{",
"return",
"transport",
"\n",
"}",
"\n",
"}",
"\n\n",
"return",
"s",
".",
"transports",
".",
"m",
"[",
"protocols",
"[",
"len",
"(",
"protocols",
")",
"-",
"1",
"]",
".",
"Code",
"]",
"\n",
"}"
]
| // TransportForDialing retrieves the appropriate transport for dialing the given
// multiaddr. | [
"TransportForDialing",
"retrieves",
"the",
"appropriate",
"transport",
"for",
"dialing",
"the",
"given",
"multiaddr",
"."
]
| 0fc01368da4ae9ce28fc261131494af3eda9aace | https://github.com/libp2p/go-libp2p-swarm/blob/0fc01368da4ae9ce28fc261131494af3eda9aace/swarm_transport.go#L13-L37 |
11,438 | libp2p/go-libp2p-swarm | swarm_transport.go | AddTransport | func (s *Swarm) AddTransport(t transport.Transport) error {
protocols := t.Protocols()
if len(protocols) == 0 {
return fmt.Errorf("useless transport handles no protocols: %T", t)
}
s.transports.Lock()
defer s.transports.Unlock()
var registered []string
for _, p := range protocols {
if _, ok := s.transports.m[p]; ok {
proto := ma.ProtocolWithCode(p)
name := proto.Name
if name == "" {
name = fmt.Sprintf("unknown (%d)", p)
}
registered = append(registered, name)
}
}
if len(registered) > 0 {
return fmt.Errorf(
"transports already registered for protocol(s): %s",
strings.Join(registered, ", "),
)
}
for _, p := range protocols {
s.transports.m[p] = t
}
return nil
} | go | func (s *Swarm) AddTransport(t transport.Transport) error {
protocols := t.Protocols()
if len(protocols) == 0 {
return fmt.Errorf("useless transport handles no protocols: %T", t)
}
s.transports.Lock()
defer s.transports.Unlock()
var registered []string
for _, p := range protocols {
if _, ok := s.transports.m[p]; ok {
proto := ma.ProtocolWithCode(p)
name := proto.Name
if name == "" {
name = fmt.Sprintf("unknown (%d)", p)
}
registered = append(registered, name)
}
}
if len(registered) > 0 {
return fmt.Errorf(
"transports already registered for protocol(s): %s",
strings.Join(registered, ", "),
)
}
for _, p := range protocols {
s.transports.m[p] = t
}
return nil
} | [
"func",
"(",
"s",
"*",
"Swarm",
")",
"AddTransport",
"(",
"t",
"transport",
".",
"Transport",
")",
"error",
"{",
"protocols",
":=",
"t",
".",
"Protocols",
"(",
")",
"\n\n",
"if",
"len",
"(",
"protocols",
")",
"==",
"0",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"t",
")",
"\n",
"}",
"\n\n",
"s",
".",
"transports",
".",
"Lock",
"(",
")",
"\n",
"defer",
"s",
".",
"transports",
".",
"Unlock",
"(",
")",
"\n",
"var",
"registered",
"[",
"]",
"string",
"\n",
"for",
"_",
",",
"p",
":=",
"range",
"protocols",
"{",
"if",
"_",
",",
"ok",
":=",
"s",
".",
"transports",
".",
"m",
"[",
"p",
"]",
";",
"ok",
"{",
"proto",
":=",
"ma",
".",
"ProtocolWithCode",
"(",
"p",
")",
"\n",
"name",
":=",
"proto",
".",
"Name",
"\n",
"if",
"name",
"==",
"\"",
"\"",
"{",
"name",
"=",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"p",
")",
"\n",
"}",
"\n",
"registered",
"=",
"append",
"(",
"registered",
",",
"name",
")",
"\n",
"}",
"\n",
"}",
"\n",
"if",
"len",
"(",
"registered",
")",
">",
"0",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"strings",
".",
"Join",
"(",
"registered",
",",
"\"",
"\"",
")",
",",
")",
"\n",
"}",
"\n\n",
"for",
"_",
",",
"p",
":=",
"range",
"protocols",
"{",
"s",
".",
"transports",
".",
"m",
"[",
"p",
"]",
"=",
"t",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
]
| // AddTransport adds a transport to this swarm.
//
// Satisfies the Network interface from go-libp2p-transport. | [
"AddTransport",
"adds",
"a",
"transport",
"to",
"this",
"swarm",
".",
"Satisfies",
"the",
"Network",
"interface",
"from",
"go",
"-",
"libp2p",
"-",
"transport",
"."
]
| 0fc01368da4ae9ce28fc261131494af3eda9aace | https://github.com/libp2p/go-libp2p-swarm/blob/0fc01368da4ae9ce28fc261131494af3eda9aace/swarm_transport.go#L70-L101 |
11,439 | libp2p/go-libp2p-swarm | swarm_listen.go | AddListenAddr | func (s *Swarm) AddListenAddr(a ma.Multiaddr) error {
tpt := s.TransportForListening(a)
if tpt == nil {
return ErrNoTransport
}
list, err := tpt.Listen(a)
if err != nil {
return err
}
s.listeners.Lock()
if s.listeners.m == nil {
s.listeners.Unlock()
list.Close()
return ErrSwarmClosed
}
s.refs.Add(1)
s.listeners.m[list] = struct{}{}
s.listeners.Unlock()
maddr := list.Multiaddr()
// signal to our notifiees on successful conn.
s.notifyAll(func(n inet.Notifiee) {
n.Listen(s, maddr)
})
go func() {
defer func() {
list.Close()
s.listeners.Lock()
delete(s.listeners.m, list)
s.listeners.Unlock()
s.refs.Done()
}()
for {
c, err := list.Accept()
if err != nil {
if s.ctx.Err() == nil {
log.Errorf("swarm listener accept error: %s", err)
}
return
}
log.Debugf("swarm listener accepted connection: %s", c)
s.refs.Add(1)
go func() {
defer s.refs.Done()
_, err := s.addConn(c, inet.DirInbound)
if err != nil {
// Probably just means that the swarm has been closed.
log.Warningf("add conn failed: ", err)
return
}
}()
}
}()
return nil
} | go | func (s *Swarm) AddListenAddr(a ma.Multiaddr) error {
tpt := s.TransportForListening(a)
if tpt == nil {
return ErrNoTransport
}
list, err := tpt.Listen(a)
if err != nil {
return err
}
s.listeners.Lock()
if s.listeners.m == nil {
s.listeners.Unlock()
list.Close()
return ErrSwarmClosed
}
s.refs.Add(1)
s.listeners.m[list] = struct{}{}
s.listeners.Unlock()
maddr := list.Multiaddr()
// signal to our notifiees on successful conn.
s.notifyAll(func(n inet.Notifiee) {
n.Listen(s, maddr)
})
go func() {
defer func() {
list.Close()
s.listeners.Lock()
delete(s.listeners.m, list)
s.listeners.Unlock()
s.refs.Done()
}()
for {
c, err := list.Accept()
if err != nil {
if s.ctx.Err() == nil {
log.Errorf("swarm listener accept error: %s", err)
}
return
}
log.Debugf("swarm listener accepted connection: %s", c)
s.refs.Add(1)
go func() {
defer s.refs.Done()
_, err := s.addConn(c, inet.DirInbound)
if err != nil {
// Probably just means that the swarm has been closed.
log.Warningf("add conn failed: ", err)
return
}
}()
}
}()
return nil
} | [
"func",
"(",
"s",
"*",
"Swarm",
")",
"AddListenAddr",
"(",
"a",
"ma",
".",
"Multiaddr",
")",
"error",
"{",
"tpt",
":=",
"s",
".",
"TransportForListening",
"(",
"a",
")",
"\n",
"if",
"tpt",
"==",
"nil",
"{",
"return",
"ErrNoTransport",
"\n",
"}",
"\n\n",
"list",
",",
"err",
":=",
"tpt",
".",
"Listen",
"(",
"a",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"s",
".",
"listeners",
".",
"Lock",
"(",
")",
"\n",
"if",
"s",
".",
"listeners",
".",
"m",
"==",
"nil",
"{",
"s",
".",
"listeners",
".",
"Unlock",
"(",
")",
"\n",
"list",
".",
"Close",
"(",
")",
"\n",
"return",
"ErrSwarmClosed",
"\n",
"}",
"\n",
"s",
".",
"refs",
".",
"Add",
"(",
"1",
")",
"\n",
"s",
".",
"listeners",
".",
"m",
"[",
"list",
"]",
"=",
"struct",
"{",
"}",
"{",
"}",
"\n",
"s",
".",
"listeners",
".",
"Unlock",
"(",
")",
"\n\n",
"maddr",
":=",
"list",
".",
"Multiaddr",
"(",
")",
"\n\n",
"// signal to our notifiees on successful conn.",
"s",
".",
"notifyAll",
"(",
"func",
"(",
"n",
"inet",
".",
"Notifiee",
")",
"{",
"n",
".",
"Listen",
"(",
"s",
",",
"maddr",
")",
"\n",
"}",
")",
"\n\n",
"go",
"func",
"(",
")",
"{",
"defer",
"func",
"(",
")",
"{",
"list",
".",
"Close",
"(",
")",
"\n",
"s",
".",
"listeners",
".",
"Lock",
"(",
")",
"\n",
"delete",
"(",
"s",
".",
"listeners",
".",
"m",
",",
"list",
")",
"\n",
"s",
".",
"listeners",
".",
"Unlock",
"(",
")",
"\n",
"s",
".",
"refs",
".",
"Done",
"(",
")",
"\n",
"}",
"(",
")",
"\n",
"for",
"{",
"c",
",",
"err",
":=",
"list",
".",
"Accept",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"if",
"s",
".",
"ctx",
".",
"Err",
"(",
")",
"==",
"nil",
"{",
"log",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n",
"return",
"\n",
"}",
"\n",
"log",
".",
"Debugf",
"(",
"\"",
"\"",
",",
"c",
")",
"\n",
"s",
".",
"refs",
".",
"Add",
"(",
"1",
")",
"\n",
"go",
"func",
"(",
")",
"{",
"defer",
"s",
".",
"refs",
".",
"Done",
"(",
")",
"\n",
"_",
",",
"err",
":=",
"s",
".",
"addConn",
"(",
"c",
",",
"inet",
".",
"DirInbound",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"// Probably just means that the swarm has been closed.",
"log",
".",
"Warningf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"return",
"\n",
"}",
"\n",
"}",
"(",
")",
"\n",
"}",
"\n",
"}",
"(",
")",
"\n",
"return",
"nil",
"\n",
"}"
]
| // AddListenAddr tells the swarm to listen on a single address. Unlike Listen,
// this method does not attempt to filter out bad addresses. | [
"AddListenAddr",
"tells",
"the",
"swarm",
"to",
"listen",
"on",
"a",
"single",
"address",
".",
"Unlike",
"Listen",
"this",
"method",
"does",
"not",
"attempt",
"to",
"filter",
"out",
"bad",
"addresses",
"."
]
| 0fc01368da4ae9ce28fc261131494af3eda9aace | https://github.com/libp2p/go-libp2p-swarm/blob/0fc01368da4ae9ce28fc261131494af3eda9aace/swarm_listen.go#L38-L96 |
11,440 | libp2p/go-libp2p-swarm | dial_sync.go | NewDialSync | func NewDialSync(dfn DialFunc) *DialSync {
return &DialSync{
dials: make(map[peer.ID]*activeDial),
dialFunc: dfn,
}
} | go | func NewDialSync(dfn DialFunc) *DialSync {
return &DialSync{
dials: make(map[peer.ID]*activeDial),
dialFunc: dfn,
}
} | [
"func",
"NewDialSync",
"(",
"dfn",
"DialFunc",
")",
"*",
"DialSync",
"{",
"return",
"&",
"DialSync",
"{",
"dials",
":",
"make",
"(",
"map",
"[",
"peer",
".",
"ID",
"]",
"*",
"activeDial",
")",
",",
"dialFunc",
":",
"dfn",
",",
"}",
"\n",
"}"
]
| // NewDialSync constructs a new DialSync | [
"NewDialSync",
"constructs",
"a",
"new",
"DialSync"
]
| 0fc01368da4ae9ce28fc261131494af3eda9aace | https://github.com/libp2p/go-libp2p-swarm/blob/0fc01368da4ae9ce28fc261131494af3eda9aace/dial_sync.go#L14-L19 |
11,441 | libp2p/go-libp2p-swarm | dial_sync.go | DialLock | func (ds *DialSync) DialLock(ctx context.Context, p peer.ID) (*Conn, error) {
return ds.getActiveDial(p).wait(ctx)
} | go | func (ds *DialSync) DialLock(ctx context.Context, p peer.ID) (*Conn, error) {
return ds.getActiveDial(p).wait(ctx)
} | [
"func",
"(",
"ds",
"*",
"DialSync",
")",
"DialLock",
"(",
"ctx",
"context",
".",
"Context",
",",
"p",
"peer",
".",
"ID",
")",
"(",
"*",
"Conn",
",",
"error",
")",
"{",
"return",
"ds",
".",
"getActiveDial",
"(",
"p",
")",
".",
"wait",
"(",
"ctx",
")",
"\n",
"}"
]
| // DialLock initiates a dial to the given peer if there are none in progress
// then waits for the dial to that peer to complete. | [
"DialLock",
"initiates",
"a",
"dial",
"to",
"the",
"given",
"peer",
"if",
"there",
"are",
"none",
"in",
"progress",
"then",
"waits",
"for",
"the",
"dial",
"to",
"that",
"peer",
"to",
"complete",
"."
]
| 0fc01368da4ae9ce28fc261131494af3eda9aace | https://github.com/libp2p/go-libp2p-swarm/blob/0fc01368da4ae9ce28fc261131494af3eda9aace/dial_sync.go#L111-L113 |
11,442 | libp2p/go-libp2p-swarm | dial_sync.go | CancelDial | func (ds *DialSync) CancelDial(p peer.ID) {
ds.dialsLk.Lock()
defer ds.dialsLk.Unlock()
if ad, ok := ds.dials[p]; ok {
ad.cancel()
}
} | go | func (ds *DialSync) CancelDial(p peer.ID) {
ds.dialsLk.Lock()
defer ds.dialsLk.Unlock()
if ad, ok := ds.dials[p]; ok {
ad.cancel()
}
} | [
"func",
"(",
"ds",
"*",
"DialSync",
")",
"CancelDial",
"(",
"p",
"peer",
".",
"ID",
")",
"{",
"ds",
".",
"dialsLk",
".",
"Lock",
"(",
")",
"\n",
"defer",
"ds",
".",
"dialsLk",
".",
"Unlock",
"(",
")",
"\n",
"if",
"ad",
",",
"ok",
":=",
"ds",
".",
"dials",
"[",
"p",
"]",
";",
"ok",
"{",
"ad",
".",
"cancel",
"(",
")",
"\n",
"}",
"\n",
"}"
]
| // CancelDial cancels all in-progress dials to the given peer. | [
"CancelDial",
"cancels",
"all",
"in",
"-",
"progress",
"dials",
"to",
"the",
"given",
"peer",
"."
]
| 0fc01368da4ae9ce28fc261131494af3eda9aace | https://github.com/libp2p/go-libp2p-swarm/blob/0fc01368da4ae9ce28fc261131494af3eda9aace/dial_sync.go#L116-L122 |
11,443 | libp2p/go-libp2p-swarm | swarm_conn.go | start | func (c *Conn) start() {
go func() {
defer c.swarm.refs.Done()
defer c.Close()
for {
ts, err := c.conn.AcceptStream()
if err != nil {
return
}
c.swarm.refs.Add(1)
go func() {
s, err := c.addStream(ts, inet.DirInbound)
// Don't defer this. We don't want to block
// swarm shutdown on the connection handler.
c.swarm.refs.Done()
// We only get an error here when the swarm is closed or closing.
if err != nil {
return
}
if h := c.swarm.StreamHandler(); h != nil {
h(s)
}
}()
}
}()
} | go | func (c *Conn) start() {
go func() {
defer c.swarm.refs.Done()
defer c.Close()
for {
ts, err := c.conn.AcceptStream()
if err != nil {
return
}
c.swarm.refs.Add(1)
go func() {
s, err := c.addStream(ts, inet.DirInbound)
// Don't defer this. We don't want to block
// swarm shutdown on the connection handler.
c.swarm.refs.Done()
// We only get an error here when the swarm is closed or closing.
if err != nil {
return
}
if h := c.swarm.StreamHandler(); h != nil {
h(s)
}
}()
}
}()
} | [
"func",
"(",
"c",
"*",
"Conn",
")",
"start",
"(",
")",
"{",
"go",
"func",
"(",
")",
"{",
"defer",
"c",
".",
"swarm",
".",
"refs",
".",
"Done",
"(",
")",
"\n",
"defer",
"c",
".",
"Close",
"(",
")",
"\n\n",
"for",
"{",
"ts",
",",
"err",
":=",
"c",
".",
"conn",
".",
"AcceptStream",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\n",
"}",
"\n",
"c",
".",
"swarm",
".",
"refs",
".",
"Add",
"(",
"1",
")",
"\n",
"go",
"func",
"(",
")",
"{",
"s",
",",
"err",
":=",
"c",
".",
"addStream",
"(",
"ts",
",",
"inet",
".",
"DirInbound",
")",
"\n\n",
"// Don't defer this. We don't want to block",
"// swarm shutdown on the connection handler.",
"c",
".",
"swarm",
".",
"refs",
".",
"Done",
"(",
")",
"\n\n",
"// We only get an error here when the swarm is closed or closing.",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\n",
"}",
"\n\n",
"if",
"h",
":=",
"c",
".",
"swarm",
".",
"StreamHandler",
"(",
")",
";",
"h",
"!=",
"nil",
"{",
"h",
"(",
"s",
")",
"\n",
"}",
"\n",
"}",
"(",
")",
"\n",
"}",
"\n",
"}",
"(",
")",
"\n",
"}"
]
| // listens for new streams.
//
// The caller must take a swarm ref before calling. This function decrements the
// swarm ref count. | [
"listens",
"for",
"new",
"streams",
".",
"The",
"caller",
"must",
"take",
"a",
"swarm",
"ref",
"before",
"calling",
".",
"This",
"function",
"decrements",
"the",
"swarm",
"ref",
"count",
"."
]
| 0fc01368da4ae9ce28fc261131494af3eda9aace | https://github.com/libp2p/go-libp2p-swarm/blob/0fc01368da4ae9ce28fc261131494af3eda9aace/swarm_conn.go#L91-L120 |
11,444 | libp2p/go-libp2p-swarm | swarm_conn.go | NewStream | func (c *Conn) NewStream() (inet.Stream, error) {
ts, err := c.conn.OpenStream()
if err != nil {
return nil, err
}
return c.addStream(ts, inet.DirOutbound)
} | go | func (c *Conn) NewStream() (inet.Stream, error) {
ts, err := c.conn.OpenStream()
if err != nil {
return nil, err
}
return c.addStream(ts, inet.DirOutbound)
} | [
"func",
"(",
"c",
"*",
"Conn",
")",
"NewStream",
"(",
")",
"(",
"inet",
".",
"Stream",
",",
"error",
")",
"{",
"ts",
",",
"err",
":=",
"c",
".",
"conn",
".",
"OpenStream",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"return",
"c",
".",
"addStream",
"(",
"ts",
",",
"inet",
".",
"DirOutbound",
")",
"\n",
"}"
]
| // NewStream returns a new Stream from this connection | [
"NewStream",
"returns",
"a",
"new",
"Stream",
"from",
"this",
"connection"
]
| 0fc01368da4ae9ce28fc261131494af3eda9aace | https://github.com/libp2p/go-libp2p-swarm/blob/0fc01368da4ae9ce28fc261131494af3eda9aace/swarm_conn.go#L169-L175 |
11,445 | libp2p/go-libp2p-swarm | swarm_conn.go | GetStreams | func (c *Conn) GetStreams() []inet.Stream {
c.streams.Lock()
defer c.streams.Unlock()
streams := make([]inet.Stream, 0, len(c.streams.m))
for s := range c.streams.m {
streams = append(streams, s)
}
return streams
} | go | func (c *Conn) GetStreams() []inet.Stream {
c.streams.Lock()
defer c.streams.Unlock()
streams := make([]inet.Stream, 0, len(c.streams.m))
for s := range c.streams.m {
streams = append(streams, s)
}
return streams
} | [
"func",
"(",
"c",
"*",
"Conn",
")",
"GetStreams",
"(",
")",
"[",
"]",
"inet",
".",
"Stream",
"{",
"c",
".",
"streams",
".",
"Lock",
"(",
")",
"\n",
"defer",
"c",
".",
"streams",
".",
"Unlock",
"(",
")",
"\n",
"streams",
":=",
"make",
"(",
"[",
"]",
"inet",
".",
"Stream",
",",
"0",
",",
"len",
"(",
"c",
".",
"streams",
".",
"m",
")",
")",
"\n",
"for",
"s",
":=",
"range",
"c",
".",
"streams",
".",
"m",
"{",
"streams",
"=",
"append",
"(",
"streams",
",",
"s",
")",
"\n",
"}",
"\n",
"return",
"streams",
"\n",
"}"
]
| // GetStreams returns the streams associated with this connection. | [
"GetStreams",
"returns",
"the",
"streams",
"associated",
"with",
"this",
"connection",
"."
]
| 0fc01368da4ae9ce28fc261131494af3eda9aace | https://github.com/libp2p/go-libp2p-swarm/blob/0fc01368da4ae9ce28fc261131494af3eda9aace/swarm_conn.go#L214-L222 |
11,446 | libp2p/go-libp2p-swarm | swarm_stream.go | Read | func (s *Stream) Read(p []byte) (int, error) {
n, err := s.stream.Read(p)
// TODO: push this down to a lower level for better accuracy.
if s.conn.swarm.bwc != nil {
s.conn.swarm.bwc.LogRecvMessage(int64(n))
s.conn.swarm.bwc.LogRecvMessageStream(int64(n), s.Protocol(), s.Conn().RemotePeer())
}
// If we observe an EOF, this stream is now closed for reading.
// If we're already closed for writing, this stream is now fully closed.
if err == io.EOF {
s.state.Lock()
switch s.state.v {
case streamCloseWrite:
s.state.v = streamCloseBoth
s.remove()
case streamOpen:
s.state.v = streamCloseRead
}
s.state.Unlock()
}
return n, err
} | go | func (s *Stream) Read(p []byte) (int, error) {
n, err := s.stream.Read(p)
// TODO: push this down to a lower level for better accuracy.
if s.conn.swarm.bwc != nil {
s.conn.swarm.bwc.LogRecvMessage(int64(n))
s.conn.swarm.bwc.LogRecvMessageStream(int64(n), s.Protocol(), s.Conn().RemotePeer())
}
// If we observe an EOF, this stream is now closed for reading.
// If we're already closed for writing, this stream is now fully closed.
if err == io.EOF {
s.state.Lock()
switch s.state.v {
case streamCloseWrite:
s.state.v = streamCloseBoth
s.remove()
case streamOpen:
s.state.v = streamCloseRead
}
s.state.Unlock()
}
return n, err
} | [
"func",
"(",
"s",
"*",
"Stream",
")",
"Read",
"(",
"p",
"[",
"]",
"byte",
")",
"(",
"int",
",",
"error",
")",
"{",
"n",
",",
"err",
":=",
"s",
".",
"stream",
".",
"Read",
"(",
"p",
")",
"\n",
"// TODO: push this down to a lower level for better accuracy.",
"if",
"s",
".",
"conn",
".",
"swarm",
".",
"bwc",
"!=",
"nil",
"{",
"s",
".",
"conn",
".",
"swarm",
".",
"bwc",
".",
"LogRecvMessage",
"(",
"int64",
"(",
"n",
")",
")",
"\n",
"s",
".",
"conn",
".",
"swarm",
".",
"bwc",
".",
"LogRecvMessageStream",
"(",
"int64",
"(",
"n",
")",
",",
"s",
".",
"Protocol",
"(",
")",
",",
"s",
".",
"Conn",
"(",
")",
".",
"RemotePeer",
"(",
")",
")",
"\n",
"}",
"\n",
"// If we observe an EOF, this stream is now closed for reading.",
"// If we're already closed for writing, this stream is now fully closed.",
"if",
"err",
"==",
"io",
".",
"EOF",
"{",
"s",
".",
"state",
".",
"Lock",
"(",
")",
"\n",
"switch",
"s",
".",
"state",
".",
"v",
"{",
"case",
"streamCloseWrite",
":",
"s",
".",
"state",
".",
"v",
"=",
"streamCloseBoth",
"\n",
"s",
".",
"remove",
"(",
")",
"\n",
"case",
"streamOpen",
":",
"s",
".",
"state",
".",
"v",
"=",
"streamCloseRead",
"\n",
"}",
"\n",
"s",
".",
"state",
".",
"Unlock",
"(",
")",
"\n",
"}",
"\n",
"return",
"n",
",",
"err",
"\n",
"}"
]
| // Read reads bytes from a stream. | [
"Read",
"reads",
"bytes",
"from",
"a",
"stream",
"."
]
| 0fc01368da4ae9ce28fc261131494af3eda9aace | https://github.com/libp2p/go-libp2p-swarm/blob/0fc01368da4ae9ce28fc261131494af3eda9aace/swarm_stream.go#L63-L84 |
11,447 | libp2p/go-libp2p-swarm | swarm_stream.go | Write | func (s *Stream) Write(p []byte) (int, error) {
n, err := s.stream.Write(p)
// TODO: push this down to a lower level for better accuracy.
if s.conn.swarm.bwc != nil {
s.conn.swarm.bwc.LogSentMessage(int64(n))
s.conn.swarm.bwc.LogSentMessageStream(int64(n), s.Protocol(), s.Conn().RemotePeer())
}
return n, err
} | go | func (s *Stream) Write(p []byte) (int, error) {
n, err := s.stream.Write(p)
// TODO: push this down to a lower level for better accuracy.
if s.conn.swarm.bwc != nil {
s.conn.swarm.bwc.LogSentMessage(int64(n))
s.conn.swarm.bwc.LogSentMessageStream(int64(n), s.Protocol(), s.Conn().RemotePeer())
}
return n, err
} | [
"func",
"(",
"s",
"*",
"Stream",
")",
"Write",
"(",
"p",
"[",
"]",
"byte",
")",
"(",
"int",
",",
"error",
")",
"{",
"n",
",",
"err",
":=",
"s",
".",
"stream",
".",
"Write",
"(",
"p",
")",
"\n",
"// TODO: push this down to a lower level for better accuracy.",
"if",
"s",
".",
"conn",
".",
"swarm",
".",
"bwc",
"!=",
"nil",
"{",
"s",
".",
"conn",
".",
"swarm",
".",
"bwc",
".",
"LogSentMessage",
"(",
"int64",
"(",
"n",
")",
")",
"\n",
"s",
".",
"conn",
".",
"swarm",
".",
"bwc",
".",
"LogSentMessageStream",
"(",
"int64",
"(",
"n",
")",
",",
"s",
".",
"Protocol",
"(",
")",
",",
"s",
".",
"Conn",
"(",
")",
".",
"RemotePeer",
"(",
")",
")",
"\n",
"}",
"\n",
"return",
"n",
",",
"err",
"\n",
"}"
]
| // Write writes bytes to a stream, flushing for each call. | [
"Write",
"writes",
"bytes",
"to",
"a",
"stream",
"flushing",
"for",
"each",
"call",
"."
]
| 0fc01368da4ae9ce28fc261131494af3eda9aace | https://github.com/libp2p/go-libp2p-swarm/blob/0fc01368da4ae9ce28fc261131494af3eda9aace/swarm_stream.go#L87-L95 |
11,448 | libp2p/go-libp2p-swarm | swarm_stream.go | Close | func (s *Stream) Close() error {
err := s.stream.Close()
s.state.Lock()
switch s.state.v {
case streamCloseRead:
s.state.v = streamCloseBoth
s.remove()
case streamOpen:
s.state.v = streamCloseWrite
}
s.state.Unlock()
return err
} | go | func (s *Stream) Close() error {
err := s.stream.Close()
s.state.Lock()
switch s.state.v {
case streamCloseRead:
s.state.v = streamCloseBoth
s.remove()
case streamOpen:
s.state.v = streamCloseWrite
}
s.state.Unlock()
return err
} | [
"func",
"(",
"s",
"*",
"Stream",
")",
"Close",
"(",
")",
"error",
"{",
"err",
":=",
"s",
".",
"stream",
".",
"Close",
"(",
")",
"\n\n",
"s",
".",
"state",
".",
"Lock",
"(",
")",
"\n",
"switch",
"s",
".",
"state",
".",
"v",
"{",
"case",
"streamCloseRead",
":",
"s",
".",
"state",
".",
"v",
"=",
"streamCloseBoth",
"\n",
"s",
".",
"remove",
"(",
")",
"\n",
"case",
"streamOpen",
":",
"s",
".",
"state",
".",
"v",
"=",
"streamCloseWrite",
"\n",
"}",
"\n",
"s",
".",
"state",
".",
"Unlock",
"(",
")",
"\n",
"return",
"err",
"\n",
"}"
]
| // Close closes the stream, indicating this side is finished
// with the stream. | [
"Close",
"closes",
"the",
"stream",
"indicating",
"this",
"side",
"is",
"finished",
"with",
"the",
"stream",
"."
]
| 0fc01368da4ae9ce28fc261131494af3eda9aace | https://github.com/libp2p/go-libp2p-swarm/blob/0fc01368da4ae9ce28fc261131494af3eda9aace/swarm_stream.go#L99-L112 |
11,449 | libp2p/go-libp2p-swarm | swarm_stream.go | Reset | func (s *Stream) Reset() error {
err := s.stream.Reset()
s.state.Lock()
switch s.state.v {
case streamOpen, streamCloseRead, streamCloseWrite:
s.state.v = streamReset
s.remove()
}
s.state.Unlock()
return err
} | go | func (s *Stream) Reset() error {
err := s.stream.Reset()
s.state.Lock()
switch s.state.v {
case streamOpen, streamCloseRead, streamCloseWrite:
s.state.v = streamReset
s.remove()
}
s.state.Unlock()
return err
} | [
"func",
"(",
"s",
"*",
"Stream",
")",
"Reset",
"(",
")",
"error",
"{",
"err",
":=",
"s",
".",
"stream",
".",
"Reset",
"(",
")",
"\n",
"s",
".",
"state",
".",
"Lock",
"(",
")",
"\n",
"switch",
"s",
".",
"state",
".",
"v",
"{",
"case",
"streamOpen",
",",
"streamCloseRead",
",",
"streamCloseWrite",
":",
"s",
".",
"state",
".",
"v",
"=",
"streamReset",
"\n",
"s",
".",
"remove",
"(",
")",
"\n",
"}",
"\n",
"s",
".",
"state",
".",
"Unlock",
"(",
")",
"\n",
"return",
"err",
"\n",
"}"
]
| // Reset resets the stream, closing both ends. | [
"Reset",
"resets",
"the",
"stream",
"closing",
"both",
"ends",
"."
]
| 0fc01368da4ae9ce28fc261131494af3eda9aace | https://github.com/libp2p/go-libp2p-swarm/blob/0fc01368da4ae9ce28fc261131494af3eda9aace/swarm_stream.go#L115-L125 |
11,450 | libp2p/go-libp2p-swarm | swarm.go | NewSwarm | func NewSwarm(ctx context.Context, local peer.ID, peers pstore.Peerstore, bwc metrics.Reporter) *Swarm {
s := &Swarm{
local: local,
peers: peers,
bwc: bwc,
Filters: filter.NewFilters(),
}
s.conns.m = make(map[peer.ID][]*Conn)
s.listeners.m = make(map[transport.Listener]struct{})
s.transports.m = make(map[int]transport.Transport)
s.notifs.m = make(map[inet.Notifiee]struct{})
s.dsync = NewDialSync(s.doDial)
s.limiter = newDialLimiter(s.dialAddr)
s.proc = goprocessctx.WithContextAndTeardown(ctx, s.teardown)
s.ctx = goprocessctx.OnClosingContext(s.proc)
return s
} | go | func NewSwarm(ctx context.Context, local peer.ID, peers pstore.Peerstore, bwc metrics.Reporter) *Swarm {
s := &Swarm{
local: local,
peers: peers,
bwc: bwc,
Filters: filter.NewFilters(),
}
s.conns.m = make(map[peer.ID][]*Conn)
s.listeners.m = make(map[transport.Listener]struct{})
s.transports.m = make(map[int]transport.Transport)
s.notifs.m = make(map[inet.Notifiee]struct{})
s.dsync = NewDialSync(s.doDial)
s.limiter = newDialLimiter(s.dialAddr)
s.proc = goprocessctx.WithContextAndTeardown(ctx, s.teardown)
s.ctx = goprocessctx.OnClosingContext(s.proc)
return s
} | [
"func",
"NewSwarm",
"(",
"ctx",
"context",
".",
"Context",
",",
"local",
"peer",
".",
"ID",
",",
"peers",
"pstore",
".",
"Peerstore",
",",
"bwc",
"metrics",
".",
"Reporter",
")",
"*",
"Swarm",
"{",
"s",
":=",
"&",
"Swarm",
"{",
"local",
":",
"local",
",",
"peers",
":",
"peers",
",",
"bwc",
":",
"bwc",
",",
"Filters",
":",
"filter",
".",
"NewFilters",
"(",
")",
",",
"}",
"\n\n",
"s",
".",
"conns",
".",
"m",
"=",
"make",
"(",
"map",
"[",
"peer",
".",
"ID",
"]",
"[",
"]",
"*",
"Conn",
")",
"\n",
"s",
".",
"listeners",
".",
"m",
"=",
"make",
"(",
"map",
"[",
"transport",
".",
"Listener",
"]",
"struct",
"{",
"}",
")",
"\n",
"s",
".",
"transports",
".",
"m",
"=",
"make",
"(",
"map",
"[",
"int",
"]",
"transport",
".",
"Transport",
")",
"\n",
"s",
".",
"notifs",
".",
"m",
"=",
"make",
"(",
"map",
"[",
"inet",
".",
"Notifiee",
"]",
"struct",
"{",
"}",
")",
"\n\n",
"s",
".",
"dsync",
"=",
"NewDialSync",
"(",
"s",
".",
"doDial",
")",
"\n",
"s",
".",
"limiter",
"=",
"newDialLimiter",
"(",
"s",
".",
"dialAddr",
")",
"\n",
"s",
".",
"proc",
"=",
"goprocessctx",
".",
"WithContextAndTeardown",
"(",
"ctx",
",",
"s",
".",
"teardown",
")",
"\n",
"s",
".",
"ctx",
"=",
"goprocessctx",
".",
"OnClosingContext",
"(",
"s",
".",
"proc",
")",
"\n\n",
"return",
"s",
"\n",
"}"
]
| // NewSwarm constructs a Swarm | [
"NewSwarm",
"constructs",
"a",
"Swarm"
]
| 0fc01368da4ae9ce28fc261131494af3eda9aace | https://github.com/libp2p/go-libp2p-swarm/blob/0fc01368da4ae9ce28fc261131494af3eda9aace/swarm.go#L90-L109 |
11,451 | libp2p/go-libp2p-swarm | swarm.go | AddAddrFilter | func (s *Swarm) AddAddrFilter(f string) error {
m, err := mafilter.NewMask(f)
if err != nil {
return err
}
s.Filters.AddDialFilter(m)
return nil
} | go | func (s *Swarm) AddAddrFilter(f string) error {
m, err := mafilter.NewMask(f)
if err != nil {
return err
}
s.Filters.AddDialFilter(m)
return nil
} | [
"func",
"(",
"s",
"*",
"Swarm",
")",
"AddAddrFilter",
"(",
"f",
"string",
")",
"error",
"{",
"m",
",",
"err",
":=",
"mafilter",
".",
"NewMask",
"(",
"f",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"s",
".",
"Filters",
".",
"AddDialFilter",
"(",
"m",
")",
"\n",
"return",
"nil",
"\n",
"}"
]
| // AddAddrFilter adds a multiaddr filter to the set of filters the swarm will use to determine which
// addresses not to dial to. | [
"AddAddrFilter",
"adds",
"a",
"multiaddr",
"filter",
"to",
"the",
"set",
"of",
"filters",
"the",
"swarm",
"will",
"use",
"to",
"determine",
"which",
"addresses",
"not",
"to",
"dial",
"to",
"."
]
| 0fc01368da4ae9ce28fc261131494af3eda9aace | https://github.com/libp2p/go-libp2p-swarm/blob/0fc01368da4ae9ce28fc261131494af3eda9aace/swarm.go#L153-L161 |
11,452 | libp2p/go-libp2p-swarm | swarm.go | ConnHandler | func (s *Swarm) ConnHandler() inet.ConnHandler {
handler, _ := s.connh.Load().(inet.ConnHandler)
return handler
} | go | func (s *Swarm) ConnHandler() inet.ConnHandler {
handler, _ := s.connh.Load().(inet.ConnHandler)
return handler
} | [
"func",
"(",
"s",
"*",
"Swarm",
")",
"ConnHandler",
"(",
")",
"inet",
".",
"ConnHandler",
"{",
"handler",
",",
"_",
":=",
"s",
".",
"connh",
".",
"Load",
"(",
")",
".",
"(",
"inet",
".",
"ConnHandler",
")",
"\n",
"return",
"handler",
"\n",
"}"
]
| // ConnHandler gets the handler for new connections. | [
"ConnHandler",
"gets",
"the",
"handler",
"for",
"new",
"connections",
"."
]
| 0fc01368da4ae9ce28fc261131494af3eda9aace | https://github.com/libp2p/go-libp2p-swarm/blob/0fc01368da4ae9ce28fc261131494af3eda9aace/swarm.go#L261-L264 |
11,453 | libp2p/go-libp2p-swarm | swarm.go | SetStreamHandler | func (s *Swarm) SetStreamHandler(handler inet.StreamHandler) {
s.streamh.Store(handler)
} | go | func (s *Swarm) SetStreamHandler(handler inet.StreamHandler) {
s.streamh.Store(handler)
} | [
"func",
"(",
"s",
"*",
"Swarm",
")",
"SetStreamHandler",
"(",
"handler",
"inet",
".",
"StreamHandler",
")",
"{",
"s",
".",
"streamh",
".",
"Store",
"(",
"handler",
")",
"\n",
"}"
]
| // SetStreamHandler assigns the handler for new streams. | [
"SetStreamHandler",
"assigns",
"the",
"handler",
"for",
"new",
"streams",
"."
]
| 0fc01368da4ae9ce28fc261131494af3eda9aace | https://github.com/libp2p/go-libp2p-swarm/blob/0fc01368da4ae9ce28fc261131494af3eda9aace/swarm.go#L267-L269 |
11,454 | libp2p/go-libp2p-swarm | swarm.go | StreamHandler | func (s *Swarm) StreamHandler() inet.StreamHandler {
handler, _ := s.streamh.Load().(inet.StreamHandler)
return handler
} | go | func (s *Swarm) StreamHandler() inet.StreamHandler {
handler, _ := s.streamh.Load().(inet.StreamHandler)
return handler
} | [
"func",
"(",
"s",
"*",
"Swarm",
")",
"StreamHandler",
"(",
")",
"inet",
".",
"StreamHandler",
"{",
"handler",
",",
"_",
":=",
"s",
".",
"streamh",
".",
"Load",
"(",
")",
".",
"(",
"inet",
".",
"StreamHandler",
")",
"\n",
"return",
"handler",
"\n",
"}"
]
| // StreamHandler gets the handler for new streams. | [
"StreamHandler",
"gets",
"the",
"handler",
"for",
"new",
"streams",
"."
]
| 0fc01368da4ae9ce28fc261131494af3eda9aace | https://github.com/libp2p/go-libp2p-swarm/blob/0fc01368da4ae9ce28fc261131494af3eda9aace/swarm.go#L272-L275 |
11,455 | libp2p/go-libp2p-swarm | swarm.go | NewStream | func (s *Swarm) NewStream(ctx context.Context, p peer.ID) (inet.Stream, error) {
log.Debugf("[%s] opening stream to peer [%s]", s.local, p)
// Algorithm:
// 1. Find the best connection, otherwise, dial.
// 2. Try opening a stream.
// 3. If the underlying connection is, in fact, closed, close the outer
// connection and try again. We do this in case we have a closed
// connection but don't notice it until we actually try to open a
// stream.
//
// Note: We only dial once.
//
// TODO: Try all connections even if we get an error opening a stream on
// a non-closed connection.
dials := 0
for {
c := s.bestConnToPeer(p)
if c == nil {
if nodial, _ := inet.GetNoDial(ctx); nodial {
return nil, inet.ErrNoConn
}
if dials >= DialAttempts {
return nil, errors.New("max dial attempts exceeded")
}
dials++
var err error
c, err = s.dialPeer(ctx, p)
if err != nil {
return nil, err
}
}
s, err := c.NewStream()
if err != nil {
if c.conn.IsClosed() {
continue
}
return nil, err
}
return s, nil
}
} | go | func (s *Swarm) NewStream(ctx context.Context, p peer.ID) (inet.Stream, error) {
log.Debugf("[%s] opening stream to peer [%s]", s.local, p)
// Algorithm:
// 1. Find the best connection, otherwise, dial.
// 2. Try opening a stream.
// 3. If the underlying connection is, in fact, closed, close the outer
// connection and try again. We do this in case we have a closed
// connection but don't notice it until we actually try to open a
// stream.
//
// Note: We only dial once.
//
// TODO: Try all connections even if we get an error opening a stream on
// a non-closed connection.
dials := 0
for {
c := s.bestConnToPeer(p)
if c == nil {
if nodial, _ := inet.GetNoDial(ctx); nodial {
return nil, inet.ErrNoConn
}
if dials >= DialAttempts {
return nil, errors.New("max dial attempts exceeded")
}
dials++
var err error
c, err = s.dialPeer(ctx, p)
if err != nil {
return nil, err
}
}
s, err := c.NewStream()
if err != nil {
if c.conn.IsClosed() {
continue
}
return nil, err
}
return s, nil
}
} | [
"func",
"(",
"s",
"*",
"Swarm",
")",
"NewStream",
"(",
"ctx",
"context",
".",
"Context",
",",
"p",
"peer",
".",
"ID",
")",
"(",
"inet",
".",
"Stream",
",",
"error",
")",
"{",
"log",
".",
"Debugf",
"(",
"\"",
"\"",
",",
"s",
".",
"local",
",",
"p",
")",
"\n\n",
"// Algorithm:",
"// 1. Find the best connection, otherwise, dial.",
"// 2. Try opening a stream.",
"// 3. If the underlying connection is, in fact, closed, close the outer",
"// connection and try again. We do this in case we have a closed",
"// connection but don't notice it until we actually try to open a",
"// stream.",
"//",
"// Note: We only dial once.",
"//",
"// TODO: Try all connections even if we get an error opening a stream on",
"// a non-closed connection.",
"dials",
":=",
"0",
"\n",
"for",
"{",
"c",
":=",
"s",
".",
"bestConnToPeer",
"(",
"p",
")",
"\n",
"if",
"c",
"==",
"nil",
"{",
"if",
"nodial",
",",
"_",
":=",
"inet",
".",
"GetNoDial",
"(",
"ctx",
")",
";",
"nodial",
"{",
"return",
"nil",
",",
"inet",
".",
"ErrNoConn",
"\n",
"}",
"\n\n",
"if",
"dials",
">=",
"DialAttempts",
"{",
"return",
"nil",
",",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"dials",
"++",
"\n\n",
"var",
"err",
"error",
"\n",
"c",
",",
"err",
"=",
"s",
".",
"dialPeer",
"(",
"ctx",
",",
"p",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"}",
"\n",
"s",
",",
"err",
":=",
"c",
".",
"NewStream",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"if",
"c",
".",
"conn",
".",
"IsClosed",
"(",
")",
"{",
"continue",
"\n",
"}",
"\n",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"return",
"s",
",",
"nil",
"\n",
"}",
"\n",
"}"
]
| // NewStream creates a new stream on any available connection to peer, dialing
// if necessary. | [
"NewStream",
"creates",
"a",
"new",
"stream",
"on",
"any",
"available",
"connection",
"to",
"peer",
"dialing",
"if",
"necessary",
"."
]
| 0fc01368da4ae9ce28fc261131494af3eda9aace | https://github.com/libp2p/go-libp2p-swarm/blob/0fc01368da4ae9ce28fc261131494af3eda9aace/swarm.go#L279-L322 |
11,456 | libp2p/go-libp2p-swarm | swarm.go | ConnsToPeer | func (s *Swarm) ConnsToPeer(p peer.ID) []inet.Conn {
// TODO: Consider sorting the connection list best to worst. Currently,
// it's sorted oldest to newest.
s.conns.RLock()
defer s.conns.RUnlock()
conns := s.conns.m[p]
output := make([]inet.Conn, len(conns))
for i, c := range conns {
output[i] = c
}
return output
} | go | func (s *Swarm) ConnsToPeer(p peer.ID) []inet.Conn {
// TODO: Consider sorting the connection list best to worst. Currently,
// it's sorted oldest to newest.
s.conns.RLock()
defer s.conns.RUnlock()
conns := s.conns.m[p]
output := make([]inet.Conn, len(conns))
for i, c := range conns {
output[i] = c
}
return output
} | [
"func",
"(",
"s",
"*",
"Swarm",
")",
"ConnsToPeer",
"(",
"p",
"peer",
".",
"ID",
")",
"[",
"]",
"inet",
".",
"Conn",
"{",
"// TODO: Consider sorting the connection list best to worst. Currently,",
"// it's sorted oldest to newest.",
"s",
".",
"conns",
".",
"RLock",
"(",
")",
"\n",
"defer",
"s",
".",
"conns",
".",
"RUnlock",
"(",
")",
"\n",
"conns",
":=",
"s",
".",
"conns",
".",
"m",
"[",
"p",
"]",
"\n",
"output",
":=",
"make",
"(",
"[",
"]",
"inet",
".",
"Conn",
",",
"len",
"(",
"conns",
")",
")",
"\n",
"for",
"i",
",",
"c",
":=",
"range",
"conns",
"{",
"output",
"[",
"i",
"]",
"=",
"c",
"\n",
"}",
"\n",
"return",
"output",
"\n",
"}"
]
| // ConnsToPeer returns all the live connections to peer. | [
"ConnsToPeer",
"returns",
"all",
"the",
"live",
"connections",
"to",
"peer",
"."
]
| 0fc01368da4ae9ce28fc261131494af3eda9aace | https://github.com/libp2p/go-libp2p-swarm/blob/0fc01368da4ae9ce28fc261131494af3eda9aace/swarm.go#L325-L336 |
11,457 | libp2p/go-libp2p-swarm | swarm.go | bestConnToPeer | func (s *Swarm) bestConnToPeer(p peer.ID) *Conn {
// Selects the best connection we have to the peer.
// TODO: Prefer some transports over others. Currently, we just select
// the newest non-closed connection with the most streams.
s.conns.RLock()
defer s.conns.RUnlock()
var best *Conn
bestLen := 0
for _, c := range s.conns.m[p] {
if c.conn.IsClosed() {
// We *will* garbage collect this soon anyways.
continue
}
c.streams.Lock()
cLen := len(c.streams.m)
c.streams.Unlock()
if cLen >= bestLen {
best = c
bestLen = cLen
}
}
return best
} | go | func (s *Swarm) bestConnToPeer(p peer.ID) *Conn {
// Selects the best connection we have to the peer.
// TODO: Prefer some transports over others. Currently, we just select
// the newest non-closed connection with the most streams.
s.conns.RLock()
defer s.conns.RUnlock()
var best *Conn
bestLen := 0
for _, c := range s.conns.m[p] {
if c.conn.IsClosed() {
// We *will* garbage collect this soon anyways.
continue
}
c.streams.Lock()
cLen := len(c.streams.m)
c.streams.Unlock()
if cLen >= bestLen {
best = c
bestLen = cLen
}
}
return best
} | [
"func",
"(",
"s",
"*",
"Swarm",
")",
"bestConnToPeer",
"(",
"p",
"peer",
".",
"ID",
")",
"*",
"Conn",
"{",
"// Selects the best connection we have to the peer.",
"// TODO: Prefer some transports over others. Currently, we just select",
"// the newest non-closed connection with the most streams.",
"s",
".",
"conns",
".",
"RLock",
"(",
")",
"\n",
"defer",
"s",
".",
"conns",
".",
"RUnlock",
"(",
")",
"\n\n",
"var",
"best",
"*",
"Conn",
"\n",
"bestLen",
":=",
"0",
"\n",
"for",
"_",
",",
"c",
":=",
"range",
"s",
".",
"conns",
".",
"m",
"[",
"p",
"]",
"{",
"if",
"c",
".",
"conn",
".",
"IsClosed",
"(",
")",
"{",
"// We *will* garbage collect this soon anyways.",
"continue",
"\n",
"}",
"\n",
"c",
".",
"streams",
".",
"Lock",
"(",
")",
"\n",
"cLen",
":=",
"len",
"(",
"c",
".",
"streams",
".",
"m",
")",
"\n",
"c",
".",
"streams",
".",
"Unlock",
"(",
")",
"\n\n",
"if",
"cLen",
">=",
"bestLen",
"{",
"best",
"=",
"c",
"\n",
"bestLen",
"=",
"cLen",
"\n",
"}",
"\n\n",
"}",
"\n",
"return",
"best",
"\n",
"}"
]
| // bestConnToPeer returns the best connection to peer. | [
"bestConnToPeer",
"returns",
"the",
"best",
"connection",
"to",
"peer",
"."
]
| 0fc01368da4ae9ce28fc261131494af3eda9aace | https://github.com/libp2p/go-libp2p-swarm/blob/0fc01368da4ae9ce28fc261131494af3eda9aace/swarm.go#L339-L364 |
11,458 | libp2p/go-libp2p-swarm | swarm.go | Conns | func (s *Swarm) Conns() []inet.Conn {
s.conns.RLock()
defer s.conns.RUnlock()
conns := make([]inet.Conn, 0, len(s.conns.m))
for _, cs := range s.conns.m {
for _, c := range cs {
conns = append(conns, c)
}
}
return conns
} | go | func (s *Swarm) Conns() []inet.Conn {
s.conns.RLock()
defer s.conns.RUnlock()
conns := make([]inet.Conn, 0, len(s.conns.m))
for _, cs := range s.conns.m {
for _, c := range cs {
conns = append(conns, c)
}
}
return conns
} | [
"func",
"(",
"s",
"*",
"Swarm",
")",
"Conns",
"(",
")",
"[",
"]",
"inet",
".",
"Conn",
"{",
"s",
".",
"conns",
".",
"RLock",
"(",
")",
"\n",
"defer",
"s",
".",
"conns",
".",
"RUnlock",
"(",
")",
"\n\n",
"conns",
":=",
"make",
"(",
"[",
"]",
"inet",
".",
"Conn",
",",
"0",
",",
"len",
"(",
"s",
".",
"conns",
".",
"m",
")",
")",
"\n",
"for",
"_",
",",
"cs",
":=",
"range",
"s",
".",
"conns",
".",
"m",
"{",
"for",
"_",
",",
"c",
":=",
"range",
"cs",
"{",
"conns",
"=",
"append",
"(",
"conns",
",",
"c",
")",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"conns",
"\n",
"}"
]
| // Conns returns a slice of all connections. | [
"Conns",
"returns",
"a",
"slice",
"of",
"all",
"connections",
"."
]
| 0fc01368da4ae9ce28fc261131494af3eda9aace | https://github.com/libp2p/go-libp2p-swarm/blob/0fc01368da4ae9ce28fc261131494af3eda9aace/swarm.go#L378-L389 |
11,459 | libp2p/go-libp2p-swarm | swarm.go | ClosePeer | func (s *Swarm) ClosePeer(p peer.ID) error {
conns := s.ConnsToPeer(p)
switch len(conns) {
case 0:
return nil
case 1:
return conns[0].Close()
default:
errCh := make(chan error)
for _, c := range conns {
go func(c inet.Conn) {
errCh <- c.Close()
}(c)
}
var errs []string
for _ = range conns {
err := <-errCh
if err != nil {
errs = append(errs, err.Error())
}
}
if len(errs) > 0 {
return fmt.Errorf("when disconnecting from peer %s: %s", p, strings.Join(errs, ", "))
}
return nil
}
} | go | func (s *Swarm) ClosePeer(p peer.ID) error {
conns := s.ConnsToPeer(p)
switch len(conns) {
case 0:
return nil
case 1:
return conns[0].Close()
default:
errCh := make(chan error)
for _, c := range conns {
go func(c inet.Conn) {
errCh <- c.Close()
}(c)
}
var errs []string
for _ = range conns {
err := <-errCh
if err != nil {
errs = append(errs, err.Error())
}
}
if len(errs) > 0 {
return fmt.Errorf("when disconnecting from peer %s: %s", p, strings.Join(errs, ", "))
}
return nil
}
} | [
"func",
"(",
"s",
"*",
"Swarm",
")",
"ClosePeer",
"(",
"p",
"peer",
".",
"ID",
")",
"error",
"{",
"conns",
":=",
"s",
".",
"ConnsToPeer",
"(",
"p",
")",
"\n",
"switch",
"len",
"(",
"conns",
")",
"{",
"case",
"0",
":",
"return",
"nil",
"\n",
"case",
"1",
":",
"return",
"conns",
"[",
"0",
"]",
".",
"Close",
"(",
")",
"\n",
"default",
":",
"errCh",
":=",
"make",
"(",
"chan",
"error",
")",
"\n",
"for",
"_",
",",
"c",
":=",
"range",
"conns",
"{",
"go",
"func",
"(",
"c",
"inet",
".",
"Conn",
")",
"{",
"errCh",
"<-",
"c",
".",
"Close",
"(",
")",
"\n",
"}",
"(",
"c",
")",
"\n",
"}",
"\n\n",
"var",
"errs",
"[",
"]",
"string",
"\n",
"for",
"_",
"=",
"range",
"conns",
"{",
"err",
":=",
"<-",
"errCh",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"errs",
"=",
"append",
"(",
"errs",
",",
"err",
".",
"Error",
"(",
")",
")",
"\n",
"}",
"\n",
"}",
"\n",
"if",
"len",
"(",
"errs",
")",
">",
"0",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"p",
",",
"strings",
".",
"Join",
"(",
"errs",
",",
"\"",
"\"",
")",
")",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}",
"\n",
"}"
]
| // ClosePeer closes all connections to the given peer. | [
"ClosePeer",
"closes",
"all",
"connections",
"to",
"the",
"given",
"peer",
"."
]
| 0fc01368da4ae9ce28fc261131494af3eda9aace | https://github.com/libp2p/go-libp2p-swarm/blob/0fc01368da4ae9ce28fc261131494af3eda9aace/swarm.go#L392-L419 |
11,460 | libp2p/go-libp2p-swarm | swarm.go | Peers | func (s *Swarm) Peers() []peer.ID {
s.conns.RLock()
defer s.conns.RUnlock()
peers := make([]peer.ID, 0, len(s.conns.m))
for p := range s.conns.m {
peers = append(peers, p)
}
return peers
} | go | func (s *Swarm) Peers() []peer.ID {
s.conns.RLock()
defer s.conns.RUnlock()
peers := make([]peer.ID, 0, len(s.conns.m))
for p := range s.conns.m {
peers = append(peers, p)
}
return peers
} | [
"func",
"(",
"s",
"*",
"Swarm",
")",
"Peers",
"(",
")",
"[",
"]",
"peer",
".",
"ID",
"{",
"s",
".",
"conns",
".",
"RLock",
"(",
")",
"\n",
"defer",
"s",
".",
"conns",
".",
"RUnlock",
"(",
")",
"\n",
"peers",
":=",
"make",
"(",
"[",
"]",
"peer",
".",
"ID",
",",
"0",
",",
"len",
"(",
"s",
".",
"conns",
".",
"m",
")",
")",
"\n",
"for",
"p",
":=",
"range",
"s",
".",
"conns",
".",
"m",
"{",
"peers",
"=",
"append",
"(",
"peers",
",",
"p",
")",
"\n",
"}",
"\n\n",
"return",
"peers",
"\n",
"}"
]
| // Peers returns a copy of the set of peers swarm is connected to. | [
"Peers",
"returns",
"a",
"copy",
"of",
"the",
"set",
"of",
"peers",
"swarm",
"is",
"connected",
"to",
"."
]
| 0fc01368da4ae9ce28fc261131494af3eda9aace | https://github.com/libp2p/go-libp2p-swarm/blob/0fc01368da4ae9ce28fc261131494af3eda9aace/swarm.go#L422-L431 |
11,461 | libp2p/go-libp2p-swarm | swarm.go | notifyAll | func (s *Swarm) notifyAll(notify func(inet.Notifiee)) {
var wg sync.WaitGroup
s.notifs.RLock()
wg.Add(len(s.notifs.m))
for f := range s.notifs.m {
go func(f inet.Notifiee) {
defer wg.Done()
notify(f)
}(f)
}
wg.Wait()
s.notifs.RUnlock()
} | go | func (s *Swarm) notifyAll(notify func(inet.Notifiee)) {
var wg sync.WaitGroup
s.notifs.RLock()
wg.Add(len(s.notifs.m))
for f := range s.notifs.m {
go func(f inet.Notifiee) {
defer wg.Done()
notify(f)
}(f)
}
wg.Wait()
s.notifs.RUnlock()
} | [
"func",
"(",
"s",
"*",
"Swarm",
")",
"notifyAll",
"(",
"notify",
"func",
"(",
"inet",
".",
"Notifiee",
")",
")",
"{",
"var",
"wg",
"sync",
".",
"WaitGroup",
"\n\n",
"s",
".",
"notifs",
".",
"RLock",
"(",
")",
"\n",
"wg",
".",
"Add",
"(",
"len",
"(",
"s",
".",
"notifs",
".",
"m",
")",
")",
"\n",
"for",
"f",
":=",
"range",
"s",
".",
"notifs",
".",
"m",
"{",
"go",
"func",
"(",
"f",
"inet",
".",
"Notifiee",
")",
"{",
"defer",
"wg",
".",
"Done",
"(",
")",
"\n",
"notify",
"(",
"f",
")",
"\n",
"}",
"(",
"f",
")",
"\n",
"}",
"\n\n",
"wg",
".",
"Wait",
"(",
")",
"\n",
"s",
".",
"notifs",
".",
"RUnlock",
"(",
")",
"\n",
"}"
]
| // notifyAll sends a signal to all Notifiees | [
"notifyAll",
"sends",
"a",
"signal",
"to",
"all",
"Notifiees"
]
| 0fc01368da4ae9ce28fc261131494af3eda9aace | https://github.com/libp2p/go-libp2p-swarm/blob/0fc01368da4ae9ce28fc261131494af3eda9aace/swarm.go#L444-L458 |
11,462 | libp2p/go-libp2p-swarm | swarm_addr.go | ListenAddresses | func (s *Swarm) ListenAddresses() []ma.Multiaddr {
s.listeners.RLock()
defer s.listeners.RUnlock()
addrs := make([]ma.Multiaddr, 0, len(s.listeners.m))
for l := range s.listeners.m {
addrs = append(addrs, l.Multiaddr())
}
return addrs
} | go | func (s *Swarm) ListenAddresses() []ma.Multiaddr {
s.listeners.RLock()
defer s.listeners.RUnlock()
addrs := make([]ma.Multiaddr, 0, len(s.listeners.m))
for l := range s.listeners.m {
addrs = append(addrs, l.Multiaddr())
}
return addrs
} | [
"func",
"(",
"s",
"*",
"Swarm",
")",
"ListenAddresses",
"(",
")",
"[",
"]",
"ma",
".",
"Multiaddr",
"{",
"s",
".",
"listeners",
".",
"RLock",
"(",
")",
"\n",
"defer",
"s",
".",
"listeners",
".",
"RUnlock",
"(",
")",
"\n",
"addrs",
":=",
"make",
"(",
"[",
"]",
"ma",
".",
"Multiaddr",
",",
"0",
",",
"len",
"(",
"s",
".",
"listeners",
".",
"m",
")",
")",
"\n",
"for",
"l",
":=",
"range",
"s",
".",
"listeners",
".",
"m",
"{",
"addrs",
"=",
"append",
"(",
"addrs",
",",
"l",
".",
"Multiaddr",
"(",
")",
")",
"\n",
"}",
"\n",
"return",
"addrs",
"\n",
"}"
]
| // ListenAddresses returns a list of addresses at which this swarm listens. | [
"ListenAddresses",
"returns",
"a",
"list",
"of",
"addresses",
"at",
"which",
"this",
"swarm",
"listens",
"."
]
| 0fc01368da4ae9ce28fc261131494af3eda9aace | https://github.com/libp2p/go-libp2p-swarm/blob/0fc01368da4ae9ce28fc261131494af3eda9aace/swarm_addr.go#L9-L17 |
11,463 | braintree/manners | server.go | NewWithServer | func NewWithServer(s *http.Server) *GracefulServer {
return &GracefulServer{
Server: s,
shutdown: make(chan bool),
shutdownFinished: make(chan bool, 1),
wg: new(sync.WaitGroup),
routinesCount: 0,
connections: make(map[net.Conn]bool),
}
} | go | func NewWithServer(s *http.Server) *GracefulServer {
return &GracefulServer{
Server: s,
shutdown: make(chan bool),
shutdownFinished: make(chan bool, 1),
wg: new(sync.WaitGroup),
routinesCount: 0,
connections: make(map[net.Conn]bool),
}
} | [
"func",
"NewWithServer",
"(",
"s",
"*",
"http",
".",
"Server",
")",
"*",
"GracefulServer",
"{",
"return",
"&",
"GracefulServer",
"{",
"Server",
":",
"s",
",",
"shutdown",
":",
"make",
"(",
"chan",
"bool",
")",
",",
"shutdownFinished",
":",
"make",
"(",
"chan",
"bool",
",",
"1",
")",
",",
"wg",
":",
"new",
"(",
"sync",
".",
"WaitGroup",
")",
",",
"routinesCount",
":",
"0",
",",
"connections",
":",
"make",
"(",
"map",
"[",
"net",
".",
"Conn",
"]",
"bool",
")",
",",
"}",
"\n",
"}"
]
| // NewWithServer wraps an existing http.Server object and returns a
// GracefulServer that supports all of the original Server operations. | [
"NewWithServer",
"wraps",
"an",
"existing",
"http",
".",
"Server",
"object",
"and",
"returns",
"a",
"GracefulServer",
"that",
"supports",
"all",
"of",
"the",
"original",
"Server",
"operations",
"."
]
| 82a8879fc5fd0381fa8b2d8033b19bf255252088 | https://github.com/braintree/manners/blob/82a8879fc5fd0381fa8b2d8033b19bf255252088/server.go#L81-L90 |
11,464 | braintree/manners | server.go | RoutinesCount | func (s *GracefulServer) RoutinesCount() int {
s.lcsmu.RLock()
defer s.lcsmu.RUnlock()
return s.routinesCount
} | go | func (s *GracefulServer) RoutinesCount() int {
s.lcsmu.RLock()
defer s.lcsmu.RUnlock()
return s.routinesCount
} | [
"func",
"(",
"s",
"*",
"GracefulServer",
")",
"RoutinesCount",
"(",
")",
"int",
"{",
"s",
".",
"lcsmu",
".",
"RLock",
"(",
")",
"\n",
"defer",
"s",
".",
"lcsmu",
".",
"RUnlock",
"(",
")",
"\n",
"return",
"s",
".",
"routinesCount",
"\n",
"}"
]
| // RoutinesCount returns the number of currently running routines | [
"RoutinesCount",
"returns",
"the",
"number",
"of",
"currently",
"running",
"routines"
]
| 82a8879fc5fd0381fa8b2d8033b19bf255252088 | https://github.com/braintree/manners/blob/82a8879fc5fd0381fa8b2d8033b19bf255252088/server.go#L256-L260 |
11,465 | cyberark/summon | internal/command/subcommand_default.go | runSubcommand | func runSubcommand(command []string, env []string) error {
binary, lookupErr := exec.LookPath(command[0])
if lookupErr != nil {
return lookupErr
}
return syscall.Exec(binary, command, env)
} | go | func runSubcommand(command []string, env []string) error {
binary, lookupErr := exec.LookPath(command[0])
if lookupErr != nil {
return lookupErr
}
return syscall.Exec(binary, command, env)
} | [
"func",
"runSubcommand",
"(",
"command",
"[",
"]",
"string",
",",
"env",
"[",
"]",
"string",
")",
"error",
"{",
"binary",
",",
"lookupErr",
":=",
"exec",
".",
"LookPath",
"(",
"command",
"[",
"0",
"]",
")",
"\n",
"if",
"lookupErr",
"!=",
"nil",
"{",
"return",
"lookupErr",
"\n",
"}",
"\n\n",
"return",
"syscall",
".",
"Exec",
"(",
"binary",
",",
"command",
",",
"env",
")",
"\n",
"}"
]
| // runSubcommand executes a command with arguments in the context
// of an environment populated with secret values. | [
"runSubcommand",
"executes",
"a",
"command",
"with",
"arguments",
"in",
"the",
"context",
"of",
"an",
"environment",
"populated",
"with",
"secret",
"values",
"."
]
| ac8ed58b292b5bf999273988cff4716be1402dca | https://github.com/cyberark/summon/blob/ac8ed58b292b5bf999273988cff4716be1402dca/internal/command/subcommand_default.go#L12-L19 |
11,466 | cyberark/summon | provider/provider.go | Resolve | func Resolve(providerArg string) (string, error) {
provider := providerArg
if provider == "" {
provider = os.Getenv("SUMMON_PROVIDER")
}
if provider == "" {
providers, _ := ioutil.ReadDir(DefaultPath)
if len(providers) == 1 {
provider = providers[0].Name()
} else if len(providers) > 1 {
return "", fmt.Errorf("More than one provider found in %s, please specify one\n", DefaultPath)
}
}
provider = expandPath(provider)
if provider == "" {
return "", fmt.Errorf("Could not resolve a provider!")
}
_, err := os.Stat(provider)
if err != nil {
return "", err
}
return provider, nil
} | go | func Resolve(providerArg string) (string, error) {
provider := providerArg
if provider == "" {
provider = os.Getenv("SUMMON_PROVIDER")
}
if provider == "" {
providers, _ := ioutil.ReadDir(DefaultPath)
if len(providers) == 1 {
provider = providers[0].Name()
} else if len(providers) > 1 {
return "", fmt.Errorf("More than one provider found in %s, please specify one\n", DefaultPath)
}
}
provider = expandPath(provider)
if provider == "" {
return "", fmt.Errorf("Could not resolve a provider!")
}
_, err := os.Stat(provider)
if err != nil {
return "", err
}
return provider, nil
} | [
"func",
"Resolve",
"(",
"providerArg",
"string",
")",
"(",
"string",
",",
"error",
")",
"{",
"provider",
":=",
"providerArg",
"\n\n",
"if",
"provider",
"==",
"\"",
"\"",
"{",
"provider",
"=",
"os",
".",
"Getenv",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"if",
"provider",
"==",
"\"",
"\"",
"{",
"providers",
",",
"_",
":=",
"ioutil",
".",
"ReadDir",
"(",
"DefaultPath",
")",
"\n",
"if",
"len",
"(",
"providers",
")",
"==",
"1",
"{",
"provider",
"=",
"providers",
"[",
"0",
"]",
".",
"Name",
"(",
")",
"\n",
"}",
"else",
"if",
"len",
"(",
"providers",
")",
">",
"1",
"{",
"return",
"\"",
"\"",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\\n",
"\"",
",",
"DefaultPath",
")",
"\n",
"}",
"\n",
"}",
"\n\n",
"provider",
"=",
"expandPath",
"(",
"provider",
")",
"\n\n",
"if",
"provider",
"==",
"\"",
"\"",
"{",
"return",
"\"",
"\"",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"_",
",",
"err",
":=",
"os",
".",
"Stat",
"(",
"provider",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\"",
"\"",
",",
"err",
"\n",
"}",
"\n\n",
"return",
"provider",
",",
"nil",
"\n",
"}"
]
| // Resolve resolves a filepath to a provider
// Checks the CLI arg, environment and then default path | [
"Resolve",
"resolves",
"a",
"filepath",
"to",
"a",
"provider",
"Checks",
"the",
"CLI",
"arg",
"environment",
"and",
"then",
"default",
"path"
]
| ac8ed58b292b5bf999273988cff4716be1402dca | https://github.com/cyberark/summon/blob/ac8ed58b292b5bf999273988cff4716be1402dca/provider/provider.go#L18-L46 |
11,467 | cyberark/summon | provider/provider.go | Call | func Call(provider, specPath string) (string, error) {
var (
stdOut bytes.Buffer
stdErr bytes.Buffer
)
cmd := exec.Command(provider, specPath)
cmd.Stdout = &stdOut
cmd.Stderr = &stdErr
err := cmd.Run()
if err != nil {
errstr := err.Error()
if stdErr.Len() > 0 {
errstr += ": " + strings.TrimSpace(stdErr.String())
}
return "", fmt.Errorf(errstr)
}
return strings.TrimSpace(stdOut.String()), nil
} | go | func Call(provider, specPath string) (string, error) {
var (
stdOut bytes.Buffer
stdErr bytes.Buffer
)
cmd := exec.Command(provider, specPath)
cmd.Stdout = &stdOut
cmd.Stderr = &stdErr
err := cmd.Run()
if err != nil {
errstr := err.Error()
if stdErr.Len() > 0 {
errstr += ": " + strings.TrimSpace(stdErr.String())
}
return "", fmt.Errorf(errstr)
}
return strings.TrimSpace(stdOut.String()), nil
} | [
"func",
"Call",
"(",
"provider",
",",
"specPath",
"string",
")",
"(",
"string",
",",
"error",
")",
"{",
"var",
"(",
"stdOut",
"bytes",
".",
"Buffer",
"\n",
"stdErr",
"bytes",
".",
"Buffer",
"\n",
")",
"\n",
"cmd",
":=",
"exec",
".",
"Command",
"(",
"provider",
",",
"specPath",
")",
"\n",
"cmd",
".",
"Stdout",
"=",
"&",
"stdOut",
"\n",
"cmd",
".",
"Stderr",
"=",
"&",
"stdErr",
"\n",
"err",
":=",
"cmd",
".",
"Run",
"(",
")",
"\n\n",
"if",
"err",
"!=",
"nil",
"{",
"errstr",
":=",
"err",
".",
"Error",
"(",
")",
"\n",
"if",
"stdErr",
".",
"Len",
"(",
")",
">",
"0",
"{",
"errstr",
"+=",
"\"",
"\"",
"+",
"strings",
".",
"TrimSpace",
"(",
"stdErr",
".",
"String",
"(",
")",
")",
"\n",
"}",
"\n",
"return",
"\"",
"\"",
",",
"fmt",
".",
"Errorf",
"(",
"errstr",
")",
"\n",
"}",
"\n\n",
"return",
"strings",
".",
"TrimSpace",
"(",
"stdOut",
".",
"String",
"(",
")",
")",
",",
"nil",
"\n",
"}"
]
| // Call shells out to a provider and return its output
// If call succeeds, stdout is returned with no error
// If call fails, "" is return with error containing stderr | [
"Call",
"shells",
"out",
"to",
"a",
"provider",
"and",
"return",
"its",
"output",
"If",
"call",
"succeeds",
"stdout",
"is",
"returned",
"with",
"no",
"error",
"If",
"call",
"fails",
"is",
"return",
"with",
"error",
"containing",
"stderr"
]
| ac8ed58b292b5bf999273988cff4716be1402dca | https://github.com/cyberark/summon/blob/ac8ed58b292b5bf999273988cff4716be1402dca/provider/provider.go#L51-L70 |
11,468 | cyberark/summon | internal/command/temp_factory.go | Push | func (tf *TempFactory) Push(value string) string {
f, _ := ioutil.TempFile(tf.path, ".summon")
defer f.Close()
f.Write([]byte(value))
name := f.Name()
tf.files = append(tf.files, name)
return name
} | go | func (tf *TempFactory) Push(value string) string {
f, _ := ioutil.TempFile(tf.path, ".summon")
defer f.Close()
f.Write([]byte(value))
name := f.Name()
tf.files = append(tf.files, name)
return name
} | [
"func",
"(",
"tf",
"*",
"TempFactory",
")",
"Push",
"(",
"value",
"string",
")",
"string",
"{",
"f",
",",
"_",
":=",
"ioutil",
".",
"TempFile",
"(",
"tf",
".",
"path",
",",
"\"",
"\"",
")",
"\n",
"defer",
"f",
".",
"Close",
"(",
")",
"\n\n",
"f",
".",
"Write",
"(",
"[",
"]",
"byte",
"(",
"value",
")",
")",
"\n",
"name",
":=",
"f",
".",
"Name",
"(",
")",
"\n",
"tf",
".",
"files",
"=",
"append",
"(",
"tf",
".",
"files",
",",
"name",
")",
"\n",
"return",
"name",
"\n",
"}"
]
| // Create a temp file with given value. Returns the path. | [
"Create",
"a",
"temp",
"file",
"with",
"given",
"value",
".",
"Returns",
"the",
"path",
"."
]
| ac8ed58b292b5bf999273988cff4716be1402dca | https://github.com/cyberark/summon/blob/ac8ed58b292b5bf999273988cff4716be1402dca/internal/command/temp_factory.go#L43-L51 |
11,469 | cyberark/summon | internal/command/temp_factory.go | Cleanup | func (tf *TempFactory) Cleanup() {
for _, file := range tf.files {
os.Remove(file)
}
// Also remove the tempdir if it's not DEVSHM
if !strings.Contains(tf.path, DEVSHM) {
os.Remove(tf.path)
}
tf = nil
} | go | func (tf *TempFactory) Cleanup() {
for _, file := range tf.files {
os.Remove(file)
}
// Also remove the tempdir if it's not DEVSHM
if !strings.Contains(tf.path, DEVSHM) {
os.Remove(tf.path)
}
tf = nil
} | [
"func",
"(",
"tf",
"*",
"TempFactory",
")",
"Cleanup",
"(",
")",
"{",
"for",
"_",
",",
"file",
":=",
"range",
"tf",
".",
"files",
"{",
"os",
".",
"Remove",
"(",
"file",
")",
"\n",
"}",
"\n",
"// Also remove the tempdir if it's not DEVSHM",
"if",
"!",
"strings",
".",
"Contains",
"(",
"tf",
".",
"path",
",",
"DEVSHM",
")",
"{",
"os",
".",
"Remove",
"(",
"tf",
".",
"path",
")",
"\n",
"}",
"\n",
"tf",
"=",
"nil",
"\n",
"}"
]
| // Cleanup removes the temporary files created with this factory. | [
"Cleanup",
"removes",
"the",
"temporary",
"files",
"created",
"with",
"this",
"factory",
"."
]
| ac8ed58b292b5bf999273988cff4716be1402dca | https://github.com/cyberark/summon/blob/ac8ed58b292b5bf999273988cff4716be1402dca/internal/command/temp_factory.go#L54-L63 |
11,470 | cyberark/summon | internal/command/action.go | runAction | func runAction(ac *ActionConfig) error {
var (
secrets secretsyml.SecretsMap
err error
)
switch ac.YamlInline {
case "":
secrets, err = secretsyml.ParseFromFile(ac.Filepath, ac.Environment, ac.Subs)
default:
secrets, err = secretsyml.ParseFromString(ac.YamlInline, ac.Environment, ac.Subs)
}
if err != nil {
return err
}
var env []string
tempFactory := NewTempFactory("")
defer tempFactory.Cleanup()
type Result struct {
string
error
}
// Run provider calls concurrently
results := make(chan Result, len(secrets))
var wg sync.WaitGroup
for key, spec := range secrets {
wg.Add(1)
go func(key string, spec secretsyml.SecretSpec) {
var value string
if spec.IsVar() {
value, err = prov.Call(ac.Provider, spec.Path)
if err != nil {
results <- Result{key, err}
wg.Done()
return
}
} else {
// If the spec isn't a variable, use its value as-is
value = spec.Path
}
envvar := formatForEnv(key, value, spec, &tempFactory)
results <- Result{envvar, nil}
wg.Done()
}(key, spec)
}
wg.Wait()
close(results)
EnvLoop:
for envvar := range results {
if envvar.error == nil {
env = append(env, envvar.string)
} else {
if ac.IgnoreAll {
continue EnvLoop
}
for i := range ac.Ignores {
if ac.Ignores[i] == envvar.string {
continue EnvLoop
}
}
return fmt.Errorf("Error fetching variable %v: %v", envvar.string, envvar.error.Error())
}
}
// Append environment variable if one is specified
if ac.Environment != "" {
env = append(env, fmt.Sprintf("%s=%s", SUMMON_ENV_KEY_NAME, ac.Environment))
}
setupEnvFile(ac.Args, env, &tempFactory)
return runSubcommand(ac.Args, append(os.Environ(), env...))
} | go | func runAction(ac *ActionConfig) error {
var (
secrets secretsyml.SecretsMap
err error
)
switch ac.YamlInline {
case "":
secrets, err = secretsyml.ParseFromFile(ac.Filepath, ac.Environment, ac.Subs)
default:
secrets, err = secretsyml.ParseFromString(ac.YamlInline, ac.Environment, ac.Subs)
}
if err != nil {
return err
}
var env []string
tempFactory := NewTempFactory("")
defer tempFactory.Cleanup()
type Result struct {
string
error
}
// Run provider calls concurrently
results := make(chan Result, len(secrets))
var wg sync.WaitGroup
for key, spec := range secrets {
wg.Add(1)
go func(key string, spec secretsyml.SecretSpec) {
var value string
if spec.IsVar() {
value, err = prov.Call(ac.Provider, spec.Path)
if err != nil {
results <- Result{key, err}
wg.Done()
return
}
} else {
// If the spec isn't a variable, use its value as-is
value = spec.Path
}
envvar := formatForEnv(key, value, spec, &tempFactory)
results <- Result{envvar, nil}
wg.Done()
}(key, spec)
}
wg.Wait()
close(results)
EnvLoop:
for envvar := range results {
if envvar.error == nil {
env = append(env, envvar.string)
} else {
if ac.IgnoreAll {
continue EnvLoop
}
for i := range ac.Ignores {
if ac.Ignores[i] == envvar.string {
continue EnvLoop
}
}
return fmt.Errorf("Error fetching variable %v: %v", envvar.string, envvar.error.Error())
}
}
// Append environment variable if one is specified
if ac.Environment != "" {
env = append(env, fmt.Sprintf("%s=%s", SUMMON_ENV_KEY_NAME, ac.Environment))
}
setupEnvFile(ac.Args, env, &tempFactory)
return runSubcommand(ac.Args, append(os.Environ(), env...))
} | [
"func",
"runAction",
"(",
"ac",
"*",
"ActionConfig",
")",
"error",
"{",
"var",
"(",
"secrets",
"secretsyml",
".",
"SecretsMap",
"\n",
"err",
"error",
"\n",
")",
"\n\n",
"switch",
"ac",
".",
"YamlInline",
"{",
"case",
"\"",
"\"",
":",
"secrets",
",",
"err",
"=",
"secretsyml",
".",
"ParseFromFile",
"(",
"ac",
".",
"Filepath",
",",
"ac",
".",
"Environment",
",",
"ac",
".",
"Subs",
")",
"\n",
"default",
":",
"secrets",
",",
"err",
"=",
"secretsyml",
".",
"ParseFromString",
"(",
"ac",
".",
"YamlInline",
",",
"ac",
".",
"Environment",
",",
"ac",
".",
"Subs",
")",
"\n",
"}",
"\n\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"var",
"env",
"[",
"]",
"string",
"\n",
"tempFactory",
":=",
"NewTempFactory",
"(",
"\"",
"\"",
")",
"\n",
"defer",
"tempFactory",
".",
"Cleanup",
"(",
")",
"\n\n",
"type",
"Result",
"struct",
"{",
"string",
"\n",
"error",
"\n",
"}",
"\n\n",
"// Run provider calls concurrently",
"results",
":=",
"make",
"(",
"chan",
"Result",
",",
"len",
"(",
"secrets",
")",
")",
"\n",
"var",
"wg",
"sync",
".",
"WaitGroup",
"\n\n",
"for",
"key",
",",
"spec",
":=",
"range",
"secrets",
"{",
"wg",
".",
"Add",
"(",
"1",
")",
"\n",
"go",
"func",
"(",
"key",
"string",
",",
"spec",
"secretsyml",
".",
"SecretSpec",
")",
"{",
"var",
"value",
"string",
"\n",
"if",
"spec",
".",
"IsVar",
"(",
")",
"{",
"value",
",",
"err",
"=",
"prov",
".",
"Call",
"(",
"ac",
".",
"Provider",
",",
"spec",
".",
"Path",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"results",
"<-",
"Result",
"{",
"key",
",",
"err",
"}",
"\n",
"wg",
".",
"Done",
"(",
")",
"\n",
"return",
"\n",
"}",
"\n",
"}",
"else",
"{",
"// If the spec isn't a variable, use its value as-is",
"value",
"=",
"spec",
".",
"Path",
"\n",
"}",
"\n\n",
"envvar",
":=",
"formatForEnv",
"(",
"key",
",",
"value",
",",
"spec",
",",
"&",
"tempFactory",
")",
"\n",
"results",
"<-",
"Result",
"{",
"envvar",
",",
"nil",
"}",
"\n",
"wg",
".",
"Done",
"(",
")",
"\n",
"}",
"(",
"key",
",",
"spec",
")",
"\n",
"}",
"\n",
"wg",
".",
"Wait",
"(",
")",
"\n",
"close",
"(",
"results",
")",
"\n\n",
"EnvLoop",
":",
"for",
"envvar",
":=",
"range",
"results",
"{",
"if",
"envvar",
".",
"error",
"==",
"nil",
"{",
"env",
"=",
"append",
"(",
"env",
",",
"envvar",
".",
"string",
")",
"\n",
"}",
"else",
"{",
"if",
"ac",
".",
"IgnoreAll",
"{",
"continue",
"EnvLoop",
"\n",
"}",
"\n\n",
"for",
"i",
":=",
"range",
"ac",
".",
"Ignores",
"{",
"if",
"ac",
".",
"Ignores",
"[",
"i",
"]",
"==",
"envvar",
".",
"string",
"{",
"continue",
"EnvLoop",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"envvar",
".",
"string",
",",
"envvar",
".",
"error",
".",
"Error",
"(",
")",
")",
"\n",
"}",
"\n",
"}",
"\n\n",
"// Append environment variable if one is specified",
"if",
"ac",
".",
"Environment",
"!=",
"\"",
"\"",
"{",
"env",
"=",
"append",
"(",
"env",
",",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"SUMMON_ENV_KEY_NAME",
",",
"ac",
".",
"Environment",
")",
")",
"\n",
"}",
"\n\n",
"setupEnvFile",
"(",
"ac",
".",
"Args",
",",
"env",
",",
"&",
"tempFactory",
")",
"\n\n",
"return",
"runSubcommand",
"(",
"ac",
".",
"Args",
",",
"append",
"(",
"os",
".",
"Environ",
"(",
")",
",",
"env",
"...",
")",
")",
"\n",
"}"
]
| // runAction encapsulates the logic of Action without cli Context for easier testing | [
"runAction",
"encapsulates",
"the",
"logic",
"of",
"Action",
"without",
"cli",
"Context",
"for",
"easier",
"testing"
]
| ac8ed58b292b5bf999273988cff4716be1402dca | https://github.com/cyberark/summon/blob/ac8ed58b292b5bf999273988cff4716be1402dca/internal/command/action.go#L64-L144 |
11,471 | cyberark/summon | internal/command/action.go | formatForEnv | func formatForEnv(key string, value string, spec secretsyml.SecretSpec, tempFactory *TempFactory) string {
if spec.IsFile() {
fname := tempFactory.Push(value)
value = fname
}
return fmt.Sprintf("%s=%s", key, value)
} | go | func formatForEnv(key string, value string, spec secretsyml.SecretSpec, tempFactory *TempFactory) string {
if spec.IsFile() {
fname := tempFactory.Push(value)
value = fname
}
return fmt.Sprintf("%s=%s", key, value)
} | [
"func",
"formatForEnv",
"(",
"key",
"string",
",",
"value",
"string",
",",
"spec",
"secretsyml",
".",
"SecretSpec",
",",
"tempFactory",
"*",
"TempFactory",
")",
"string",
"{",
"if",
"spec",
".",
"IsFile",
"(",
")",
"{",
"fname",
":=",
"tempFactory",
".",
"Push",
"(",
"value",
")",
"\n",
"value",
"=",
"fname",
"\n",
"}",
"\n\n",
"return",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"key",
",",
"value",
")",
"\n",
"}"
]
| // formatForEnv returns a string in %k=%v format, where %k=namespace of the secret and
// %v=the secret value or path to a temporary file containing the secret | [
"formatForEnv",
"returns",
"a",
"string",
"in",
"%k",
"=",
"%v",
"format",
"where",
"%k",
"=",
"namespace",
"of",
"the",
"secret",
"and",
"%v",
"=",
"the",
"secret",
"value",
"or",
"path",
"to",
"a",
"temporary",
"file",
"containing",
"the",
"secret"
]
| ac8ed58b292b5bf999273988cff4716be1402dca | https://github.com/cyberark/summon/blob/ac8ed58b292b5bf999273988cff4716be1402dca/internal/command/action.go#L148-L155 |
11,472 | cyberark/summon | internal/command/action.go | setupEnvFile | func setupEnvFile(args []string, env []string, tempFactory *TempFactory) string {
var envFile = ""
for i, arg := range args {
idx := strings.Index(arg, ENV_FILE_MAGIC)
if idx >= 0 {
if envFile == "" {
envFile = tempFactory.Push(joinEnv(env))
}
args[i] = strings.Replace(arg, ENV_FILE_MAGIC, envFile, -1)
}
}
return envFile
} | go | func setupEnvFile(args []string, env []string, tempFactory *TempFactory) string {
var envFile = ""
for i, arg := range args {
idx := strings.Index(arg, ENV_FILE_MAGIC)
if idx >= 0 {
if envFile == "" {
envFile = tempFactory.Push(joinEnv(env))
}
args[i] = strings.Replace(arg, ENV_FILE_MAGIC, envFile, -1)
}
}
return envFile
} | [
"func",
"setupEnvFile",
"(",
"args",
"[",
"]",
"string",
",",
"env",
"[",
"]",
"string",
",",
"tempFactory",
"*",
"TempFactory",
")",
"string",
"{",
"var",
"envFile",
"=",
"\"",
"\"",
"\n\n",
"for",
"i",
",",
"arg",
":=",
"range",
"args",
"{",
"idx",
":=",
"strings",
".",
"Index",
"(",
"arg",
",",
"ENV_FILE_MAGIC",
")",
"\n",
"if",
"idx",
">=",
"0",
"{",
"if",
"envFile",
"==",
"\"",
"\"",
"{",
"envFile",
"=",
"tempFactory",
".",
"Push",
"(",
"joinEnv",
"(",
"env",
")",
")",
"\n",
"}",
"\n",
"args",
"[",
"i",
"]",
"=",
"strings",
".",
"Replace",
"(",
"arg",
",",
"ENV_FILE_MAGIC",
",",
"envFile",
",",
"-",
"1",
")",
"\n",
"}",
"\n",
"}",
"\n\n",
"return",
"envFile",
"\n",
"}"
]
| // scans arguments for the magic string; if found,
// creates a tempfile to which all the environment mappings are dumped
// and replaces the magic string with its path.
// Returns the path if so, returns an empty string otherwise. | [
"scans",
"arguments",
"for",
"the",
"magic",
"string",
";",
"if",
"found",
"creates",
"a",
"tempfile",
"to",
"which",
"all",
"the",
"environment",
"mappings",
"are",
"dumped",
"and",
"replaces",
"the",
"magic",
"string",
"with",
"its",
"path",
".",
"Returns",
"the",
"path",
"if",
"so",
"returns",
"an",
"empty",
"string",
"otherwise",
"."
]
| ac8ed58b292b5bf999273988cff4716be1402dca | https://github.com/cyberark/summon/blob/ac8ed58b292b5bf999273988cff4716be1402dca/internal/command/action.go#L165-L179 |
11,473 | cyberark/summon | internal/command/action.go | convertSubsToMap | func convertSubsToMap(subs []string) map[string]string {
out := make(map[string]string)
for _, sub := range subs {
s := strings.SplitN(sub, "=", 2)
key, val := s[0], s[1]
out[key] = val
}
return out
} | go | func convertSubsToMap(subs []string) map[string]string {
out := make(map[string]string)
for _, sub := range subs {
s := strings.SplitN(sub, "=", 2)
key, val := s[0], s[1]
out[key] = val
}
return out
} | [
"func",
"convertSubsToMap",
"(",
"subs",
"[",
"]",
"string",
")",
"map",
"[",
"string",
"]",
"string",
"{",
"out",
":=",
"make",
"(",
"map",
"[",
"string",
"]",
"string",
")",
"\n",
"for",
"_",
",",
"sub",
":=",
"range",
"subs",
"{",
"s",
":=",
"strings",
".",
"SplitN",
"(",
"sub",
",",
"\"",
"\"",
",",
"2",
")",
"\n",
"key",
",",
"val",
":=",
"s",
"[",
"0",
"]",
",",
"s",
"[",
"1",
"]",
"\n",
"out",
"[",
"key",
"]",
"=",
"val",
"\n",
"}",
"\n",
"return",
"out",
"\n",
"}"
]
| // convertSubsToMap converts the list of substitutions passed in via
// command line to a map | [
"convertSubsToMap",
"converts",
"the",
"list",
"of",
"substitutions",
"passed",
"in",
"via",
"command",
"line",
"to",
"a",
"map"
]
| ac8ed58b292b5bf999273988cff4716be1402dca | https://github.com/cyberark/summon/blob/ac8ed58b292b5bf999273988cff4716be1402dca/internal/command/action.go#L183-L191 |
11,474 | cyberark/summon | secretsyml/secretsyml.go | ParseFromString | func ParseFromString(content, env string, subs map[string]string) (SecretsMap, error) {
return parse(content, env, subs)
} | go | func ParseFromString(content, env string, subs map[string]string) (SecretsMap, error) {
return parse(content, env, subs)
} | [
"func",
"ParseFromString",
"(",
"content",
",",
"env",
"string",
",",
"subs",
"map",
"[",
"string",
"]",
"string",
")",
"(",
"SecretsMap",
",",
"error",
")",
"{",
"return",
"parse",
"(",
"content",
",",
"env",
",",
"subs",
")",
"\n",
"}"
]
| // ParseFromString parses a string in secrets.yml format to a map. | [
"ParseFromString",
"parses",
"a",
"string",
"in",
"secrets",
".",
"yml",
"format",
"to",
"a",
"map",
"."
]
| ac8ed58b292b5bf999273988cff4716be1402dca | https://github.com/cyberark/summon/blob/ac8ed58b292b5bf999273988cff4716be1402dca/secretsyml/secretsyml.go#L87-L89 |
11,475 | cyberark/summon | secretsyml/secretsyml.go | ParseFromFile | func ParseFromFile(filepath, env string, subs map[string]string) (SecretsMap, error) {
data, err := ioutil.ReadFile(filepath)
if err != nil {
return nil, err
}
return parse(string(data), env, subs)
} | go | func ParseFromFile(filepath, env string, subs map[string]string) (SecretsMap, error) {
data, err := ioutil.ReadFile(filepath)
if err != nil {
return nil, err
}
return parse(string(data), env, subs)
} | [
"func",
"ParseFromFile",
"(",
"filepath",
",",
"env",
"string",
",",
"subs",
"map",
"[",
"string",
"]",
"string",
")",
"(",
"SecretsMap",
",",
"error",
")",
"{",
"data",
",",
"err",
":=",
"ioutil",
".",
"ReadFile",
"(",
"filepath",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"return",
"parse",
"(",
"string",
"(",
"data",
")",
",",
"env",
",",
"subs",
")",
"\n",
"}"
]
| // ParseFromFile parses a file in secrets.yml format to a map. | [
"ParseFromFile",
"parses",
"a",
"file",
"in",
"secrets",
".",
"yml",
"format",
"to",
"a",
"map",
"."
]
| ac8ed58b292b5bf999273988cff4716be1402dca | https://github.com/cyberark/summon/blob/ac8ed58b292b5bf999273988cff4716be1402dca/secretsyml/secretsyml.go#L92-L98 |
11,476 | cyberark/summon | secretsyml/secretsyml.go | parse | func parse(ymlContent, env string, subs map[string]string) (SecretsMap, error) {
if env == "" {
return parseRegular(ymlContent, subs)
}
return parseEnvironment(ymlContent, env, subs)
} | go | func parse(ymlContent, env string, subs map[string]string) (SecretsMap, error) {
if env == "" {
return parseRegular(ymlContent, subs)
}
return parseEnvironment(ymlContent, env, subs)
} | [
"func",
"parse",
"(",
"ymlContent",
",",
"env",
"string",
",",
"subs",
"map",
"[",
"string",
"]",
"string",
")",
"(",
"SecretsMap",
",",
"error",
")",
"{",
"if",
"env",
"==",
"\"",
"\"",
"{",
"return",
"parseRegular",
"(",
"ymlContent",
",",
"subs",
")",
"\n",
"}",
"\n\n",
"return",
"parseEnvironment",
"(",
"ymlContent",
",",
"env",
",",
"subs",
")",
"\n",
"}"
]
| // Wrapper for parsing yaml contents | [
"Wrapper",
"for",
"parsing",
"yaml",
"contents"
]
| ac8ed58b292b5bf999273988cff4716be1402dca | https://github.com/cyberark/summon/blob/ac8ed58b292b5bf999273988cff4716be1402dca/secretsyml/secretsyml.go#L101-L107 |
11,477 | cyberark/summon | secretsyml/secretsyml.go | parseEnvironment | func parseEnvironment(ymlContent, env string, subs map[string]string) (SecretsMap, error) {
out := make(map[string]map[string]SecretSpec)
if err := yaml.Unmarshal([]byte(ymlContent), &out); err != nil {
return nil, err
}
if _, ok := out[env]; !ok {
return nil, fmt.Errorf("No such environment '%v' found in secrets file", env)
}
secretsMap := make(SecretsMap)
for i, spec := range out[env] {
err := spec.applySubstitutions(subs)
if err != nil {
return nil, err
}
secretsMap[i] = spec
}
// parse and merge optional 'common/default' section with secretsMap
for _, section := range COMMON_SECTIONS {
if _, ok := out[section]; ok {
return parseAndMergeCommon(out[section], secretsMap, subs)
}
}
return secretsMap, nil
} | go | func parseEnvironment(ymlContent, env string, subs map[string]string) (SecretsMap, error) {
out := make(map[string]map[string]SecretSpec)
if err := yaml.Unmarshal([]byte(ymlContent), &out); err != nil {
return nil, err
}
if _, ok := out[env]; !ok {
return nil, fmt.Errorf("No such environment '%v' found in secrets file", env)
}
secretsMap := make(SecretsMap)
for i, spec := range out[env] {
err := spec.applySubstitutions(subs)
if err != nil {
return nil, err
}
secretsMap[i] = spec
}
// parse and merge optional 'common/default' section with secretsMap
for _, section := range COMMON_SECTIONS {
if _, ok := out[section]; ok {
return parseAndMergeCommon(out[section], secretsMap, subs)
}
}
return secretsMap, nil
} | [
"func",
"parseEnvironment",
"(",
"ymlContent",
",",
"env",
"string",
",",
"subs",
"map",
"[",
"string",
"]",
"string",
")",
"(",
"SecretsMap",
",",
"error",
")",
"{",
"out",
":=",
"make",
"(",
"map",
"[",
"string",
"]",
"map",
"[",
"string",
"]",
"SecretSpec",
")",
"\n\n",
"if",
"err",
":=",
"yaml",
".",
"Unmarshal",
"(",
"[",
"]",
"byte",
"(",
"ymlContent",
")",
",",
"&",
"out",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"if",
"_",
",",
"ok",
":=",
"out",
"[",
"env",
"]",
";",
"!",
"ok",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"env",
")",
"\n",
"}",
"\n\n",
"secretsMap",
":=",
"make",
"(",
"SecretsMap",
")",
"\n\n",
"for",
"i",
",",
"spec",
":=",
"range",
"out",
"[",
"env",
"]",
"{",
"err",
":=",
"spec",
".",
"applySubstitutions",
"(",
"subs",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"secretsMap",
"[",
"i",
"]",
"=",
"spec",
"\n",
"}",
"\n\n",
"// parse and merge optional 'common/default' section with secretsMap",
"for",
"_",
",",
"section",
":=",
"range",
"COMMON_SECTIONS",
"{",
"if",
"_",
",",
"ok",
":=",
"out",
"[",
"section",
"]",
";",
"ok",
"{",
"return",
"parseAndMergeCommon",
"(",
"out",
"[",
"section",
"]",
",",
"secretsMap",
",",
"subs",
")",
"\n",
"}",
"\n",
"}",
"\n\n",
"return",
"secretsMap",
",",
"nil",
"\n",
"}"
]
| // Parse secrets yaml that has environment sections | [
"Parse",
"secrets",
"yaml",
"that",
"has",
"environment",
"sections"
]
| ac8ed58b292b5bf999273988cff4716be1402dca | https://github.com/cyberark/summon/blob/ac8ed58b292b5bf999273988cff4716be1402dca/secretsyml/secretsyml.go#L110-L140 |
11,478 | cyberark/summon | secretsyml/secretsyml.go | parseRegular | func parseRegular(ymlContent string, subs map[string]string) (SecretsMap, error) {
out := make(map[string]SecretSpec)
if err := yaml.Unmarshal([]byte(ymlContent), &out); err != nil {
return nil, err
}
for i, spec := range out {
err := spec.applySubstitutions(subs)
if err != nil {
return nil, err
}
out[i] = spec
}
return out, nil
} | go | func parseRegular(ymlContent string, subs map[string]string) (SecretsMap, error) {
out := make(map[string]SecretSpec)
if err := yaml.Unmarshal([]byte(ymlContent), &out); err != nil {
return nil, err
}
for i, spec := range out {
err := spec.applySubstitutions(subs)
if err != nil {
return nil, err
}
out[i] = spec
}
return out, nil
} | [
"func",
"parseRegular",
"(",
"ymlContent",
"string",
",",
"subs",
"map",
"[",
"string",
"]",
"string",
")",
"(",
"SecretsMap",
",",
"error",
")",
"{",
"out",
":=",
"make",
"(",
"map",
"[",
"string",
"]",
"SecretSpec",
")",
"\n\n",
"if",
"err",
":=",
"yaml",
".",
"Unmarshal",
"(",
"[",
"]",
"byte",
"(",
"ymlContent",
")",
",",
"&",
"out",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"for",
"i",
",",
"spec",
":=",
"range",
"out",
"{",
"err",
":=",
"spec",
".",
"applySubstitutions",
"(",
"subs",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"out",
"[",
"i",
"]",
"=",
"spec",
"\n",
"}",
"\n\n",
"return",
"out",
",",
"nil",
"\n",
"}"
]
| // Parse a secrets yaml that has no environment sections | [
"Parse",
"a",
"secrets",
"yaml",
"that",
"has",
"no",
"environment",
"sections"
]
| ac8ed58b292b5bf999273988cff4716be1402dca | https://github.com/cyberark/summon/blob/ac8ed58b292b5bf999273988cff4716be1402dca/secretsyml/secretsyml.go#L160-L177 |
11,479 | cyberark/summon | secretsyml/secretsyml.go | tagInSlice | func tagInSlice(a YamlTag, list []YamlTag) bool {
for _, b := range list {
if b == a {
return true
}
}
return false
} | go | func tagInSlice(a YamlTag, list []YamlTag) bool {
for _, b := range list {
if b == a {
return true
}
}
return false
} | [
"func",
"tagInSlice",
"(",
"a",
"YamlTag",
",",
"list",
"[",
"]",
"YamlTag",
")",
"bool",
"{",
"for",
"_",
",",
"b",
":=",
"range",
"list",
"{",
"if",
"b",
"==",
"a",
"{",
"return",
"true",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"false",
"\n",
"}"
]
| // tagInSlice determines whether a YamlTag is in a list of YamlTag | [
"tagInSlice",
"determines",
"whether",
"a",
"YamlTag",
"is",
"in",
"a",
"list",
"of",
"YamlTag"
]
| ac8ed58b292b5bf999273988cff4716be1402dca | https://github.com/cyberark/summon/blob/ac8ed58b292b5bf999273988cff4716be1402dca/secretsyml/secretsyml.go#L202-L209 |
11,480 | krolaw/dhcp4 | server.go | ListenAndServe | func ListenAndServe(handler Handler) error {
l, err := net.ListenPacket("udp4", ":67")
if err != nil {
return err
}
defer l.Close()
return Serve(l, handler)
} | go | func ListenAndServe(handler Handler) error {
l, err := net.ListenPacket("udp4", ":67")
if err != nil {
return err
}
defer l.Close()
return Serve(l, handler)
} | [
"func",
"ListenAndServe",
"(",
"handler",
"Handler",
")",
"error",
"{",
"l",
",",
"err",
":=",
"net",
".",
"ListenPacket",
"(",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"defer",
"l",
".",
"Close",
"(",
")",
"\n",
"return",
"Serve",
"(",
"l",
",",
"handler",
")",
"\n",
"}"
]
| // ListenAndServe listens on the UDP network address addr and then calls
// Serve with handler to handle requests on incoming packets. | [
"ListenAndServe",
"listens",
"on",
"the",
"UDP",
"network",
"address",
"addr",
"and",
"then",
"calls",
"Serve",
"with",
"handler",
"to",
"handle",
"requests",
"on",
"incoming",
"packets",
"."
]
| 7cead472c414711982509839c1a6a324d4c70ce6 | https://github.com/krolaw/dhcp4/blob/7cead472c414711982509839c1a6a324d4c70ce6/server.go#L83-L90 |
11,481 | beefsack/go-astar | astar.go | get | func (nm nodeMap) get(p Pather) *node {
n, ok := nm[p]
if !ok {
n = &node{
pather: p,
}
nm[p] = n
}
return n
} | go | func (nm nodeMap) get(p Pather) *node {
n, ok := nm[p]
if !ok {
n = &node{
pather: p,
}
nm[p] = n
}
return n
} | [
"func",
"(",
"nm",
"nodeMap",
")",
"get",
"(",
"p",
"Pather",
")",
"*",
"node",
"{",
"n",
",",
"ok",
":=",
"nm",
"[",
"p",
"]",
"\n",
"if",
"!",
"ok",
"{",
"n",
"=",
"&",
"node",
"{",
"pather",
":",
"p",
",",
"}",
"\n",
"nm",
"[",
"p",
"]",
"=",
"n",
"\n",
"}",
"\n",
"return",
"n",
"\n",
"}"
]
| // get gets the Pather object wrapped in a node, instantiating if required. | [
"get",
"gets",
"the",
"Pather",
"object",
"wrapped",
"in",
"a",
"node",
"instantiating",
"if",
"required",
"."
]
| f324bbb0d6f79849d76a6d94329152c6adfccee2 | https://github.com/beefsack/go-astar/blob/f324bbb0d6f79849d76a6d94329152c6adfccee2/astar.go#L35-L44 |
11,482 | beefsack/go-astar | astar.go | Path | func Path(from, to Pather) (path []Pather, distance float64, found bool) {
nm := nodeMap{}
nq := &priorityQueue{}
heap.Init(nq)
fromNode := nm.get(from)
fromNode.open = true
heap.Push(nq, fromNode)
for {
if nq.Len() == 0 {
// There's no path, return found false.
return
}
current := heap.Pop(nq).(*node)
current.open = false
current.closed = true
if current == nm.get(to) {
// Found a path to the goal.
p := []Pather{}
curr := current
for curr != nil {
p = append(p, curr.pather)
curr = curr.parent
}
return p, current.cost, true
}
for _, neighbor := range current.pather.PathNeighbors() {
cost := current.cost + current.pather.PathNeighborCost(neighbor)
neighborNode := nm.get(neighbor)
if cost < neighborNode.cost {
if neighborNode.open {
heap.Remove(nq, neighborNode.index)
}
neighborNode.open = false
neighborNode.closed = false
}
if !neighborNode.open && !neighborNode.closed {
neighborNode.cost = cost
neighborNode.open = true
neighborNode.rank = cost + neighbor.PathEstimatedCost(to)
neighborNode.parent = current
heap.Push(nq, neighborNode)
}
}
}
} | go | func Path(from, to Pather) (path []Pather, distance float64, found bool) {
nm := nodeMap{}
nq := &priorityQueue{}
heap.Init(nq)
fromNode := nm.get(from)
fromNode.open = true
heap.Push(nq, fromNode)
for {
if nq.Len() == 0 {
// There's no path, return found false.
return
}
current := heap.Pop(nq).(*node)
current.open = false
current.closed = true
if current == nm.get(to) {
// Found a path to the goal.
p := []Pather{}
curr := current
for curr != nil {
p = append(p, curr.pather)
curr = curr.parent
}
return p, current.cost, true
}
for _, neighbor := range current.pather.PathNeighbors() {
cost := current.cost + current.pather.PathNeighborCost(neighbor)
neighborNode := nm.get(neighbor)
if cost < neighborNode.cost {
if neighborNode.open {
heap.Remove(nq, neighborNode.index)
}
neighborNode.open = false
neighborNode.closed = false
}
if !neighborNode.open && !neighborNode.closed {
neighborNode.cost = cost
neighborNode.open = true
neighborNode.rank = cost + neighbor.PathEstimatedCost(to)
neighborNode.parent = current
heap.Push(nq, neighborNode)
}
}
}
} | [
"func",
"Path",
"(",
"from",
",",
"to",
"Pather",
")",
"(",
"path",
"[",
"]",
"Pather",
",",
"distance",
"float64",
",",
"found",
"bool",
")",
"{",
"nm",
":=",
"nodeMap",
"{",
"}",
"\n",
"nq",
":=",
"&",
"priorityQueue",
"{",
"}",
"\n",
"heap",
".",
"Init",
"(",
"nq",
")",
"\n",
"fromNode",
":=",
"nm",
".",
"get",
"(",
"from",
")",
"\n",
"fromNode",
".",
"open",
"=",
"true",
"\n",
"heap",
".",
"Push",
"(",
"nq",
",",
"fromNode",
")",
"\n",
"for",
"{",
"if",
"nq",
".",
"Len",
"(",
")",
"==",
"0",
"{",
"// There's no path, return found false.",
"return",
"\n",
"}",
"\n",
"current",
":=",
"heap",
".",
"Pop",
"(",
"nq",
")",
".",
"(",
"*",
"node",
")",
"\n",
"current",
".",
"open",
"=",
"false",
"\n",
"current",
".",
"closed",
"=",
"true",
"\n\n",
"if",
"current",
"==",
"nm",
".",
"get",
"(",
"to",
")",
"{",
"// Found a path to the goal.",
"p",
":=",
"[",
"]",
"Pather",
"{",
"}",
"\n",
"curr",
":=",
"current",
"\n",
"for",
"curr",
"!=",
"nil",
"{",
"p",
"=",
"append",
"(",
"p",
",",
"curr",
".",
"pather",
")",
"\n",
"curr",
"=",
"curr",
".",
"parent",
"\n",
"}",
"\n",
"return",
"p",
",",
"current",
".",
"cost",
",",
"true",
"\n",
"}",
"\n\n",
"for",
"_",
",",
"neighbor",
":=",
"range",
"current",
".",
"pather",
".",
"PathNeighbors",
"(",
")",
"{",
"cost",
":=",
"current",
".",
"cost",
"+",
"current",
".",
"pather",
".",
"PathNeighborCost",
"(",
"neighbor",
")",
"\n",
"neighborNode",
":=",
"nm",
".",
"get",
"(",
"neighbor",
")",
"\n",
"if",
"cost",
"<",
"neighborNode",
".",
"cost",
"{",
"if",
"neighborNode",
".",
"open",
"{",
"heap",
".",
"Remove",
"(",
"nq",
",",
"neighborNode",
".",
"index",
")",
"\n",
"}",
"\n",
"neighborNode",
".",
"open",
"=",
"false",
"\n",
"neighborNode",
".",
"closed",
"=",
"false",
"\n",
"}",
"\n",
"if",
"!",
"neighborNode",
".",
"open",
"&&",
"!",
"neighborNode",
".",
"closed",
"{",
"neighborNode",
".",
"cost",
"=",
"cost",
"\n",
"neighborNode",
".",
"open",
"=",
"true",
"\n",
"neighborNode",
".",
"rank",
"=",
"cost",
"+",
"neighbor",
".",
"PathEstimatedCost",
"(",
"to",
")",
"\n",
"neighborNode",
".",
"parent",
"=",
"current",
"\n",
"heap",
".",
"Push",
"(",
"nq",
",",
"neighborNode",
")",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n",
"}"
]
| // Path calculates a short path and the distance between the two Pather nodes.
//
// If no path is found, found will be false. | [
"Path",
"calculates",
"a",
"short",
"path",
"and",
"the",
"distance",
"between",
"the",
"two",
"Pather",
"nodes",
".",
"If",
"no",
"path",
"is",
"found",
"found",
"will",
"be",
"false",
"."
]
| f324bbb0d6f79849d76a6d94329152c6adfccee2 | https://github.com/beefsack/go-astar/blob/f324bbb0d6f79849d76a6d94329152c6adfccee2/astar.go#L49-L95 |
11,483 | beefsack/go-astar | goreland_example.go | PathNeighbors | func (t *Truck) PathNeighbors() []Pather {
neighbors := []Pather{}
for _, tube_element := range t.out_to {
neighbors = append(neighbors, Pather(tube_element.to))
}
return neighbors
} | go | func (t *Truck) PathNeighbors() []Pather {
neighbors := []Pather{}
for _, tube_element := range t.out_to {
neighbors = append(neighbors, Pather(tube_element.to))
}
return neighbors
} | [
"func",
"(",
"t",
"*",
"Truck",
")",
"PathNeighbors",
"(",
")",
"[",
"]",
"Pather",
"{",
"neighbors",
":=",
"[",
"]",
"Pather",
"{",
"}",
"\n\n",
"for",
"_",
",",
"tube_element",
":=",
"range",
"t",
".",
"out_to",
"{",
"neighbors",
"=",
"append",
"(",
"neighbors",
",",
"Pather",
"(",
"tube_element",
".",
"to",
")",
")",
"\n",
"}",
"\n",
"return",
"neighbors",
"\n",
"}"
]
| // PathNeighbors returns the neighbors of the Truck | [
"PathNeighbors",
"returns",
"the",
"neighbors",
"of",
"the",
"Truck"
]
| f324bbb0d6f79849d76a6d94329152c6adfccee2 | https://github.com/beefsack/go-astar/blob/f324bbb0d6f79849d76a6d94329152c6adfccee2/goreland_example.go#L48-L56 |
11,484 | beefsack/go-astar | goreland_example.go | PathNeighborCost | func (t *Truck) PathNeighborCost(to Pather) float64 {
for _, tube_element := range (t).out_to {
if Pather((tube_element.to)) == to {
return tube_element.Cost
}
}
return 10000000
} | go | func (t *Truck) PathNeighborCost(to Pather) float64 {
for _, tube_element := range (t).out_to {
if Pather((tube_element.to)) == to {
return tube_element.Cost
}
}
return 10000000
} | [
"func",
"(",
"t",
"*",
"Truck",
")",
"PathNeighborCost",
"(",
"to",
"Pather",
")",
"float64",
"{",
"for",
"_",
",",
"tube_element",
":=",
"range",
"(",
"t",
")",
".",
"out_to",
"{",
"if",
"Pather",
"(",
"(",
"tube_element",
".",
"to",
")",
")",
"==",
"to",
"{",
"return",
"tube_element",
".",
"Cost",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"10000000",
"\n",
"}"
]
| // PathNeighborCost returns the cost of the tube leading to Truck. | [
"PathNeighborCost",
"returns",
"the",
"cost",
"of",
"the",
"tube",
"leading",
"to",
"Truck",
"."
]
| f324bbb0d6f79849d76a6d94329152c6adfccee2 | https://github.com/beefsack/go-astar/blob/f324bbb0d6f79849d76a6d94329152c6adfccee2/goreland_example.go#L59-L67 |
11,485 | beefsack/go-astar | goreland_example.go | PathEstimatedCost | func (t *Truck) PathEstimatedCost(to Pather) float64 {
toT := to.(*Truck)
absX := toT.X - t.X
if absX < 0 {
absX = -absX
}
absY := toT.Y - t.Y
if absY < 0 {
absY = -absY
}
r := float64(absX + absY)
return r
} | go | func (t *Truck) PathEstimatedCost(to Pather) float64 {
toT := to.(*Truck)
absX := toT.X - t.X
if absX < 0 {
absX = -absX
}
absY := toT.Y - t.Y
if absY < 0 {
absY = -absY
}
r := float64(absX + absY)
return r
} | [
"func",
"(",
"t",
"*",
"Truck",
")",
"PathEstimatedCost",
"(",
"to",
"Pather",
")",
"float64",
"{",
"toT",
":=",
"to",
".",
"(",
"*",
"Truck",
")",
"\n",
"absX",
":=",
"toT",
".",
"X",
"-",
"t",
".",
"X",
"\n",
"if",
"absX",
"<",
"0",
"{",
"absX",
"=",
"-",
"absX",
"\n",
"}",
"\n",
"absY",
":=",
"toT",
".",
"Y",
"-",
"t",
".",
"Y",
"\n",
"if",
"absY",
"<",
"0",
"{",
"absY",
"=",
"-",
"absY",
"\n",
"}",
"\n",
"r",
":=",
"float64",
"(",
"absX",
"+",
"absY",
")",
"\n\n",
"return",
"r",
"\n",
"}"
]
| // PathEstimatedCost uses Manhattan distance to estimate orthogonal distance
// between non-adjacent nodes. | [
"PathEstimatedCost",
"uses",
"Manhattan",
"distance",
"to",
"estimate",
"orthogonal",
"distance",
"between",
"non",
"-",
"adjacent",
"nodes",
"."
]
| f324bbb0d6f79849d76a6d94329152c6adfccee2 | https://github.com/beefsack/go-astar/blob/f324bbb0d6f79849d76a6d94329152c6adfccee2/goreland_example.go#L71-L85 |
11,486 | beefsack/go-astar | goreland_example.go | RenderPath | func (w Goreland) RenderPath(path []Pather) string {
s := ""
for _, p := range path {
pT := p.(*Truck)
s = pT.label + " " + s
}
return s
} | go | func (w Goreland) RenderPath(path []Pather) string {
s := ""
for _, p := range path {
pT := p.(*Truck)
s = pT.label + " " + s
}
return s
} | [
"func",
"(",
"w",
"Goreland",
")",
"RenderPath",
"(",
"path",
"[",
"]",
"Pather",
")",
"string",
"{",
"s",
":=",
"\"",
"\"",
"\n",
"for",
"_",
",",
"p",
":=",
"range",
"path",
"{",
"pT",
":=",
"p",
".",
"(",
"*",
"Truck",
")",
"\n",
"s",
"=",
"pT",
".",
"label",
"+",
"\"",
"\"",
"+",
"s",
"\n",
"}",
"\n",
"return",
"s",
"\n",
"}"
]
| // RenderPath renders a path on top of a Goreland world. | [
"RenderPath",
"renders",
"a",
"path",
"on",
"top",
"of",
"a",
"Goreland",
"world",
"."
]
| f324bbb0d6f79849d76a6d94329152c6adfccee2 | https://github.com/beefsack/go-astar/blob/f324bbb0d6f79849d76a6d94329152c6adfccee2/goreland_example.go#L88-L96 |
11,487 | krolaw/dhcp4 | helpers.go | IPLess | func IPLess(a, b net.IP) bool {
b = b.To4()
for i, ai := range a.To4() {
if ai != b[i] {
return ai < b[i]
}
}
return false
} | go | func IPLess(a, b net.IP) bool {
b = b.To4()
for i, ai := range a.To4() {
if ai != b[i] {
return ai < b[i]
}
}
return false
} | [
"func",
"IPLess",
"(",
"a",
",",
"b",
"net",
".",
"IP",
")",
"bool",
"{",
"b",
"=",
"b",
".",
"To4",
"(",
")",
"\n",
"for",
"i",
",",
"ai",
":=",
"range",
"a",
".",
"To4",
"(",
")",
"{",
"if",
"ai",
"!=",
"b",
"[",
"i",
"]",
"{",
"return",
"ai",
"<",
"b",
"[",
"i",
"]",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"false",
"\n",
"}"
]
| // IPLess returns where IP a is less than IP b. | [
"IPLess",
"returns",
"where",
"IP",
"a",
"is",
"less",
"than",
"IP",
"b",
"."
]
| 7cead472c414711982509839c1a6a324d4c70ce6 | https://github.com/krolaw/dhcp4/blob/7cead472c414711982509839c1a6a324d4c70ce6/helpers.go#L50-L58 |
11,488 | krolaw/dhcp4 | helpers.go | OptionsLeaseTime | func OptionsLeaseTime(d time.Duration) []byte {
leaseBytes := make([]byte, 4)
binary.BigEndian.PutUint32(leaseBytes, uint32(d/time.Second))
return leaseBytes
} | go | func OptionsLeaseTime(d time.Duration) []byte {
leaseBytes := make([]byte, 4)
binary.BigEndian.PutUint32(leaseBytes, uint32(d/time.Second))
return leaseBytes
} | [
"func",
"OptionsLeaseTime",
"(",
"d",
"time",
".",
"Duration",
")",
"[",
"]",
"byte",
"{",
"leaseBytes",
":=",
"make",
"(",
"[",
"]",
"byte",
",",
"4",
")",
"\n",
"binary",
".",
"BigEndian",
".",
"PutUint32",
"(",
"leaseBytes",
",",
"uint32",
"(",
"d",
"/",
"time",
".",
"Second",
")",
")",
"\n",
"return",
"leaseBytes",
"\n",
"}"
]
| // OptionsLeaseTime - converts a time.Duration to a 4 byte slice, compatible
// with OptionIPAddressLeaseTime. | [
"OptionsLeaseTime",
"-",
"converts",
"a",
"time",
".",
"Duration",
"to",
"a",
"4",
"byte",
"slice",
"compatible",
"with",
"OptionIPAddressLeaseTime",
"."
]
| 7cead472c414711982509839c1a6a324d4c70ce6 | https://github.com/krolaw/dhcp4/blob/7cead472c414711982509839c1a6a324d4c70ce6/helpers.go#L67-L71 |
11,489 | krolaw/dhcp4 | helpers.go | JoinIPs | func JoinIPs(ips []net.IP) (b []byte) {
for _, v := range ips {
b = append(b, v.To4()...)
}
return
} | go | func JoinIPs(ips []net.IP) (b []byte) {
for _, v := range ips {
b = append(b, v.To4()...)
}
return
} | [
"func",
"JoinIPs",
"(",
"ips",
"[",
"]",
"net",
".",
"IP",
")",
"(",
"b",
"[",
"]",
"byte",
")",
"{",
"for",
"_",
",",
"v",
":=",
"range",
"ips",
"{",
"b",
"=",
"append",
"(",
"b",
",",
"v",
".",
"To4",
"(",
")",
"...",
")",
"\n",
"}",
"\n",
"return",
"\n",
"}"
]
| // JoinIPs returns a byte slice of IP addresses, one immediately after the other
// This may be useful for creating multiple IP options such as OptionRouter. | [
"JoinIPs",
"returns",
"a",
"byte",
"slice",
"of",
"IP",
"addresses",
"one",
"immediately",
"after",
"the",
"other",
"This",
"may",
"be",
"useful",
"for",
"creating",
"multiple",
"IP",
"options",
"such",
"as",
"OptionRouter",
"."
]
| 7cead472c414711982509839c1a6a324d4c70ce6 | https://github.com/krolaw/dhcp4/blob/7cead472c414711982509839c1a6a324d4c70ce6/helpers.go#L75-L80 |
11,490 | krolaw/dhcp4 | packet.go | ParseOptions | func (p Packet) ParseOptions() Options {
opts := p.Options()
options := make(Options, 10)
for len(opts) >= 2 && OptionCode(opts[0]) != End {
if OptionCode(opts[0]) == Pad {
opts = opts[1:]
continue
}
size := int(opts[1])
if len(opts) < 2+size {
break
}
options[OptionCode(opts[0])] = opts[2 : 2+size]
opts = opts[2+size:]
}
return options
} | go | func (p Packet) ParseOptions() Options {
opts := p.Options()
options := make(Options, 10)
for len(opts) >= 2 && OptionCode(opts[0]) != End {
if OptionCode(opts[0]) == Pad {
opts = opts[1:]
continue
}
size := int(opts[1])
if len(opts) < 2+size {
break
}
options[OptionCode(opts[0])] = opts[2 : 2+size]
opts = opts[2+size:]
}
return options
} | [
"func",
"(",
"p",
"Packet",
")",
"ParseOptions",
"(",
")",
"Options",
"{",
"opts",
":=",
"p",
".",
"Options",
"(",
")",
"\n",
"options",
":=",
"make",
"(",
"Options",
",",
"10",
")",
"\n",
"for",
"len",
"(",
"opts",
")",
">=",
"2",
"&&",
"OptionCode",
"(",
"opts",
"[",
"0",
"]",
")",
"!=",
"End",
"{",
"if",
"OptionCode",
"(",
"opts",
"[",
"0",
"]",
")",
"==",
"Pad",
"{",
"opts",
"=",
"opts",
"[",
"1",
":",
"]",
"\n",
"continue",
"\n",
"}",
"\n",
"size",
":=",
"int",
"(",
"opts",
"[",
"1",
"]",
")",
"\n",
"if",
"len",
"(",
"opts",
")",
"<",
"2",
"+",
"size",
"{",
"break",
"\n",
"}",
"\n",
"options",
"[",
"OptionCode",
"(",
"opts",
"[",
"0",
"]",
")",
"]",
"=",
"opts",
"[",
"2",
":",
"2",
"+",
"size",
"]",
"\n",
"opts",
"=",
"opts",
"[",
"2",
"+",
"size",
":",
"]",
"\n",
"}",
"\n",
"return",
"options",
"\n",
"}"
]
| // Parses the packet's options into an Options map | [
"Parses",
"the",
"packet",
"s",
"options",
"into",
"an",
"Options",
"map"
]
| 7cead472c414711982509839c1a6a324d4c70ce6 | https://github.com/krolaw/dhcp4/blob/7cead472c414711982509839c1a6a324d4c70ce6/packet.go#L112-L128 |
11,491 | krolaw/dhcp4 | packet.go | AddOption | func (p *Packet) AddOption(o OptionCode, value []byte) {
*p = append((*p)[:len(*p)-1], []byte{byte(o), byte(len(value))}...) // Strip off End, Add OptionCode and Length
*p = append(*p, value...) // Add Option Value
*p = append(*p, byte(End)) // Add on new End
} | go | func (p *Packet) AddOption(o OptionCode, value []byte) {
*p = append((*p)[:len(*p)-1], []byte{byte(o), byte(len(value))}...) // Strip off End, Add OptionCode and Length
*p = append(*p, value...) // Add Option Value
*p = append(*p, byte(End)) // Add on new End
} | [
"func",
"(",
"p",
"*",
"Packet",
")",
"AddOption",
"(",
"o",
"OptionCode",
",",
"value",
"[",
"]",
"byte",
")",
"{",
"*",
"p",
"=",
"append",
"(",
"(",
"*",
"p",
")",
"[",
":",
"len",
"(",
"*",
"p",
")",
"-",
"1",
"]",
",",
"[",
"]",
"byte",
"{",
"byte",
"(",
"o",
")",
",",
"byte",
"(",
"len",
"(",
"value",
")",
")",
"}",
"...",
")",
"// Strip off End, Add OptionCode and Length",
"\n",
"*",
"p",
"=",
"append",
"(",
"*",
"p",
",",
"value",
"...",
")",
"// Add Option Value",
"\n",
"*",
"p",
"=",
"append",
"(",
"*",
"p",
",",
"byte",
"(",
"End",
")",
")",
"// Add on new End",
"\n",
"}"
]
| // Appends a DHCP option to the end of a packet | [
"Appends",
"a",
"DHCP",
"option",
"to",
"the",
"end",
"of",
"a",
"packet"
]
| 7cead472c414711982509839c1a6a324d4c70ce6 | https://github.com/krolaw/dhcp4/blob/7cead472c414711982509839c1a6a324d4c70ce6/packet.go#L140-L144 |
11,492 | krolaw/dhcp4 | packet.go | RequestPacket | func RequestPacket(mt MessageType, chAddr net.HardwareAddr, cIAddr net.IP, xId []byte, broadcast bool, options []Option) Packet {
p := NewPacket(BootRequest)
p.SetCHAddr(chAddr)
p.SetXId(xId)
if cIAddr != nil {
p.SetCIAddr(cIAddr)
}
p.SetBroadcast(broadcast)
p.AddOption(OptionDHCPMessageType, []byte{byte(mt)})
for _, o := range options {
p.AddOption(o.Code, o.Value)
}
p.PadToMinSize()
return p
} | go | func RequestPacket(mt MessageType, chAddr net.HardwareAddr, cIAddr net.IP, xId []byte, broadcast bool, options []Option) Packet {
p := NewPacket(BootRequest)
p.SetCHAddr(chAddr)
p.SetXId(xId)
if cIAddr != nil {
p.SetCIAddr(cIAddr)
}
p.SetBroadcast(broadcast)
p.AddOption(OptionDHCPMessageType, []byte{byte(mt)})
for _, o := range options {
p.AddOption(o.Code, o.Value)
}
p.PadToMinSize()
return p
} | [
"func",
"RequestPacket",
"(",
"mt",
"MessageType",
",",
"chAddr",
"net",
".",
"HardwareAddr",
",",
"cIAddr",
"net",
".",
"IP",
",",
"xId",
"[",
"]",
"byte",
",",
"broadcast",
"bool",
",",
"options",
"[",
"]",
"Option",
")",
"Packet",
"{",
"p",
":=",
"NewPacket",
"(",
"BootRequest",
")",
"\n",
"p",
".",
"SetCHAddr",
"(",
"chAddr",
")",
"\n",
"p",
".",
"SetXId",
"(",
"xId",
")",
"\n",
"if",
"cIAddr",
"!=",
"nil",
"{",
"p",
".",
"SetCIAddr",
"(",
"cIAddr",
")",
"\n",
"}",
"\n",
"p",
".",
"SetBroadcast",
"(",
"broadcast",
")",
"\n",
"p",
".",
"AddOption",
"(",
"OptionDHCPMessageType",
",",
"[",
"]",
"byte",
"{",
"byte",
"(",
"mt",
")",
"}",
")",
"\n",
"for",
"_",
",",
"o",
":=",
"range",
"options",
"{",
"p",
".",
"AddOption",
"(",
"o",
".",
"Code",
",",
"o",
".",
"Value",
")",
"\n",
"}",
"\n",
"p",
".",
"PadToMinSize",
"(",
")",
"\n",
"return",
"p",
"\n",
"}"
]
| // Creates a request packet that a Client would send to a server. | [
"Creates",
"a",
"request",
"packet",
"that",
"a",
"Client",
"would",
"send",
"to",
"a",
"server",
"."
]
| 7cead472c414711982509839c1a6a324d4c70ce6 | https://github.com/krolaw/dhcp4/blob/7cead472c414711982509839c1a6a324d4c70ce6/packet.go#L152-L166 |
11,493 | krolaw/dhcp4 | conn/filter.go | NewUDP4FilterListener | func NewUDP4FilterListener(interfaceName, laddr string) (c *serveIfConn, e error) {
iface, err := net.InterfaceByName(interfaceName)
if err != nil {
return nil, err
}
l, err := net.ListenPacket("udp4", laddr)
if err != nil {
return nil, err
}
defer func() {
if e != nil {
l.Close()
}
}()
p := ipv4.NewPacketConn(l)
if err := p.SetControlMessage(ipv4.FlagInterface, true); err != nil {
return nil, err
}
return &serveIfConn{ifIndex: iface.Index, conn: p}, nil
} | go | func NewUDP4FilterListener(interfaceName, laddr string) (c *serveIfConn, e error) {
iface, err := net.InterfaceByName(interfaceName)
if err != nil {
return nil, err
}
l, err := net.ListenPacket("udp4", laddr)
if err != nil {
return nil, err
}
defer func() {
if e != nil {
l.Close()
}
}()
p := ipv4.NewPacketConn(l)
if err := p.SetControlMessage(ipv4.FlagInterface, true); err != nil {
return nil, err
}
return &serveIfConn{ifIndex: iface.Index, conn: p}, nil
} | [
"func",
"NewUDP4FilterListener",
"(",
"interfaceName",
",",
"laddr",
"string",
")",
"(",
"c",
"*",
"serveIfConn",
",",
"e",
"error",
")",
"{",
"iface",
",",
"err",
":=",
"net",
".",
"InterfaceByName",
"(",
"interfaceName",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"l",
",",
"err",
":=",
"net",
".",
"ListenPacket",
"(",
"\"",
"\"",
",",
"laddr",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"defer",
"func",
"(",
")",
"{",
"if",
"e",
"!=",
"nil",
"{",
"l",
".",
"Close",
"(",
")",
"\n",
"}",
"\n",
"}",
"(",
")",
"\n",
"p",
":=",
"ipv4",
".",
"NewPacketConn",
"(",
"l",
")",
"\n",
"if",
"err",
":=",
"p",
".",
"SetControlMessage",
"(",
"ipv4",
".",
"FlagInterface",
",",
"true",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"return",
"&",
"serveIfConn",
"{",
"ifIndex",
":",
"iface",
".",
"Index",
",",
"conn",
":",
"p",
"}",
",",
"nil",
"\n",
"}"
]
| // Creates listener on all interfaces and then filters packets not received by interfaceName | [
"Creates",
"listener",
"on",
"all",
"interfaces",
"and",
"then",
"filters",
"packets",
"not",
"received",
"by",
"interfaceName"
]
| 7cead472c414711982509839c1a6a324d4c70ce6 | https://github.com/krolaw/dhcp4/blob/7cead472c414711982509839c1a6a324d4c70ce6/conn/filter.go#L10-L29 |
11,494 | hashicorp/go-syslog | builtin.go | dialBuiltin | func dialBuiltin(network, raddr string, priority syslog.Priority, tag string) (*builtinWriter, error) {
if priority < 0 || priority > syslog.LOG_LOCAL7|syslog.LOG_DEBUG {
return nil, errors.New("log/syslog: invalid priority")
}
if tag == "" {
tag = os.Args[0]
}
hostname, _ := os.Hostname()
w := &builtinWriter{
priority: priority,
tag: tag,
hostname: hostname,
network: network,
raddr: raddr,
}
w.mu.Lock()
defer w.mu.Unlock()
err := w.connect()
if err != nil {
return nil, err
}
return w, err
} | go | func dialBuiltin(network, raddr string, priority syslog.Priority, tag string) (*builtinWriter, error) {
if priority < 0 || priority > syslog.LOG_LOCAL7|syslog.LOG_DEBUG {
return nil, errors.New("log/syslog: invalid priority")
}
if tag == "" {
tag = os.Args[0]
}
hostname, _ := os.Hostname()
w := &builtinWriter{
priority: priority,
tag: tag,
hostname: hostname,
network: network,
raddr: raddr,
}
w.mu.Lock()
defer w.mu.Unlock()
err := w.connect()
if err != nil {
return nil, err
}
return w, err
} | [
"func",
"dialBuiltin",
"(",
"network",
",",
"raddr",
"string",
",",
"priority",
"syslog",
".",
"Priority",
",",
"tag",
"string",
")",
"(",
"*",
"builtinWriter",
",",
"error",
")",
"{",
"if",
"priority",
"<",
"0",
"||",
"priority",
">",
"syslog",
".",
"LOG_LOCAL7",
"|",
"syslog",
".",
"LOG_DEBUG",
"{",
"return",
"nil",
",",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"if",
"tag",
"==",
"\"",
"\"",
"{",
"tag",
"=",
"os",
".",
"Args",
"[",
"0",
"]",
"\n",
"}",
"\n",
"hostname",
",",
"_",
":=",
"os",
".",
"Hostname",
"(",
")",
"\n\n",
"w",
":=",
"&",
"builtinWriter",
"{",
"priority",
":",
"priority",
",",
"tag",
":",
"tag",
",",
"hostname",
":",
"hostname",
",",
"network",
":",
"network",
",",
"raddr",
":",
"raddr",
",",
"}",
"\n\n",
"w",
".",
"mu",
".",
"Lock",
"(",
")",
"\n",
"defer",
"w",
".",
"mu",
".",
"Unlock",
"(",
")",
"\n\n",
"err",
":=",
"w",
".",
"connect",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"return",
"w",
",",
"err",
"\n",
"}"
]
| // Dial establishes a connection to a log daemon by connecting to
// address raddr on the specified network. Each write to the returned
// writer sends a log message with the given facility, severity and
// tag.
// If network is empty, Dial will connect to the local syslog server. | [
"Dial",
"establishes",
"a",
"connection",
"to",
"a",
"log",
"daemon",
"by",
"connecting",
"to",
"address",
"raddr",
"on",
"the",
"specified",
"network",
".",
"Each",
"write",
"to",
"the",
"returned",
"writer",
"sends",
"a",
"log",
"message",
"with",
"the",
"given",
"facility",
"severity",
"and",
"tag",
".",
"If",
"network",
"is",
"empty",
"Dial",
"will",
"connect",
"to",
"the",
"local",
"syslog",
"server",
"."
]
| 8d1874e3e8d1862b74e0536851e218c4571066a5 | https://github.com/hashicorp/go-syslog/blob/8d1874e3e8d1862b74e0536851e218c4571066a5/builtin.go#L65-L91 |
11,495 | hashicorp/go-syslog | builtin.go | unixSyslog | func unixSyslog() (conn serverConn, err error) {
logTypes := []string{"unixgram", "unix"}
logPaths := []string{"/dev/log", "/var/run/syslog", "/var/run/log"}
for _, network := range logTypes {
for _, path := range logPaths {
conn, err := net.DialTimeout(network, path, localDeadline)
if err != nil {
continue
} else {
return &netConn{conn: conn, local: true}, nil
}
}
}
return nil, errors.New("Unix syslog delivery error")
} | go | func unixSyslog() (conn serverConn, err error) {
logTypes := []string{"unixgram", "unix"}
logPaths := []string{"/dev/log", "/var/run/syslog", "/var/run/log"}
for _, network := range logTypes {
for _, path := range logPaths {
conn, err := net.DialTimeout(network, path, localDeadline)
if err != nil {
continue
} else {
return &netConn{conn: conn, local: true}, nil
}
}
}
return nil, errors.New("Unix syslog delivery error")
} | [
"func",
"unixSyslog",
"(",
")",
"(",
"conn",
"serverConn",
",",
"err",
"error",
")",
"{",
"logTypes",
":=",
"[",
"]",
"string",
"{",
"\"",
"\"",
",",
"\"",
"\"",
"}",
"\n",
"logPaths",
":=",
"[",
"]",
"string",
"{",
"\"",
"\"",
",",
"\"",
"\"",
",",
"\"",
"\"",
"}",
"\n",
"for",
"_",
",",
"network",
":=",
"range",
"logTypes",
"{",
"for",
"_",
",",
"path",
":=",
"range",
"logPaths",
"{",
"conn",
",",
"err",
":=",
"net",
".",
"DialTimeout",
"(",
"network",
",",
"path",
",",
"localDeadline",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"continue",
"\n",
"}",
"else",
"{",
"return",
"&",
"netConn",
"{",
"conn",
":",
"conn",
",",
"local",
":",
"true",
"}",
",",
"nil",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"nil",
",",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"}"
]
| // unixSyslog opens a connection to the syslog daemon running on the
// local machine using a Unix domain socket. | [
"unixSyslog",
"opens",
"a",
"connection",
"to",
"the",
"syslog",
"daemon",
"running",
"on",
"the",
"local",
"machine",
"using",
"a",
"Unix",
"domain",
"socket",
"."
]
| 8d1874e3e8d1862b74e0536851e218c4571066a5 | https://github.com/hashicorp/go-syslog/blob/8d1874e3e8d1862b74e0536851e218c4571066a5/builtin.go#L200-L214 |
11,496 | hashicorp/go-syslog | unix.go | WriteLevel | func (b *builtinLogger) WriteLevel(p Priority, buf []byte) error {
var err error
m := string(buf)
switch p {
case LOG_EMERG:
_, err = b.writeAndRetry(syslog.LOG_EMERG, m)
case LOG_ALERT:
_, err = b.writeAndRetry(syslog.LOG_ALERT, m)
case LOG_CRIT:
_, err = b.writeAndRetry(syslog.LOG_CRIT, m)
case LOG_ERR:
_, err = b.writeAndRetry(syslog.LOG_ERR, m)
case LOG_WARNING:
_, err = b.writeAndRetry(syslog.LOG_WARNING, m)
case LOG_NOTICE:
_, err = b.writeAndRetry(syslog.LOG_NOTICE, m)
case LOG_INFO:
_, err = b.writeAndRetry(syslog.LOG_INFO, m)
case LOG_DEBUG:
_, err = b.writeAndRetry(syslog.LOG_DEBUG, m)
default:
err = fmt.Errorf("Unknown priority: %v", p)
}
return err
} | go | func (b *builtinLogger) WriteLevel(p Priority, buf []byte) error {
var err error
m := string(buf)
switch p {
case LOG_EMERG:
_, err = b.writeAndRetry(syslog.LOG_EMERG, m)
case LOG_ALERT:
_, err = b.writeAndRetry(syslog.LOG_ALERT, m)
case LOG_CRIT:
_, err = b.writeAndRetry(syslog.LOG_CRIT, m)
case LOG_ERR:
_, err = b.writeAndRetry(syslog.LOG_ERR, m)
case LOG_WARNING:
_, err = b.writeAndRetry(syslog.LOG_WARNING, m)
case LOG_NOTICE:
_, err = b.writeAndRetry(syslog.LOG_NOTICE, m)
case LOG_INFO:
_, err = b.writeAndRetry(syslog.LOG_INFO, m)
case LOG_DEBUG:
_, err = b.writeAndRetry(syslog.LOG_DEBUG, m)
default:
err = fmt.Errorf("Unknown priority: %v", p)
}
return err
} | [
"func",
"(",
"b",
"*",
"builtinLogger",
")",
"WriteLevel",
"(",
"p",
"Priority",
",",
"buf",
"[",
"]",
"byte",
")",
"error",
"{",
"var",
"err",
"error",
"\n",
"m",
":=",
"string",
"(",
"buf",
")",
"\n",
"switch",
"p",
"{",
"case",
"LOG_EMERG",
":",
"_",
",",
"err",
"=",
"b",
".",
"writeAndRetry",
"(",
"syslog",
".",
"LOG_EMERG",
",",
"m",
")",
"\n",
"case",
"LOG_ALERT",
":",
"_",
",",
"err",
"=",
"b",
".",
"writeAndRetry",
"(",
"syslog",
".",
"LOG_ALERT",
",",
"m",
")",
"\n",
"case",
"LOG_CRIT",
":",
"_",
",",
"err",
"=",
"b",
".",
"writeAndRetry",
"(",
"syslog",
".",
"LOG_CRIT",
",",
"m",
")",
"\n",
"case",
"LOG_ERR",
":",
"_",
",",
"err",
"=",
"b",
".",
"writeAndRetry",
"(",
"syslog",
".",
"LOG_ERR",
",",
"m",
")",
"\n",
"case",
"LOG_WARNING",
":",
"_",
",",
"err",
"=",
"b",
".",
"writeAndRetry",
"(",
"syslog",
".",
"LOG_WARNING",
",",
"m",
")",
"\n",
"case",
"LOG_NOTICE",
":",
"_",
",",
"err",
"=",
"b",
".",
"writeAndRetry",
"(",
"syslog",
".",
"LOG_NOTICE",
",",
"m",
")",
"\n",
"case",
"LOG_INFO",
":",
"_",
",",
"err",
"=",
"b",
".",
"writeAndRetry",
"(",
"syslog",
".",
"LOG_INFO",
",",
"m",
")",
"\n",
"case",
"LOG_DEBUG",
":",
"_",
",",
"err",
"=",
"b",
".",
"writeAndRetry",
"(",
"syslog",
".",
"LOG_DEBUG",
",",
"m",
")",
"\n",
"default",
":",
"err",
"=",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"p",
")",
"\n",
"}",
"\n",
"return",
"err",
"\n",
"}"
]
| // WriteLevel writes out a message at the given priority | [
"WriteLevel",
"writes",
"out",
"a",
"message",
"at",
"the",
"given",
"priority"
]
| 8d1874e3e8d1862b74e0536851e218c4571066a5 | https://github.com/hashicorp/go-syslog/blob/8d1874e3e8d1862b74e0536851e218c4571066a5/unix.go#L49-L73 |
11,497 | hashicorp/go-syslog | unix.go | facilityPriority | func facilityPriority(facility string) (syslog.Priority, error) {
facility = strings.ToUpper(facility)
switch facility {
case "KERN":
return syslog.LOG_KERN, nil
case "USER":
return syslog.LOG_USER, nil
case "MAIL":
return syslog.LOG_MAIL, nil
case "DAEMON":
return syslog.LOG_DAEMON, nil
case "AUTH":
return syslog.LOG_AUTH, nil
case "SYSLOG":
return syslog.LOG_SYSLOG, nil
case "LPR":
return syslog.LOG_LPR, nil
case "NEWS":
return syslog.LOG_NEWS, nil
case "UUCP":
return syslog.LOG_UUCP, nil
case "CRON":
return syslog.LOG_CRON, nil
case "AUTHPRIV":
return syslog.LOG_AUTHPRIV, nil
case "FTP":
return syslog.LOG_FTP, nil
case "LOCAL0":
return syslog.LOG_LOCAL0, nil
case "LOCAL1":
return syslog.LOG_LOCAL1, nil
case "LOCAL2":
return syslog.LOG_LOCAL2, nil
case "LOCAL3":
return syslog.LOG_LOCAL3, nil
case "LOCAL4":
return syslog.LOG_LOCAL4, nil
case "LOCAL5":
return syslog.LOG_LOCAL5, nil
case "LOCAL6":
return syslog.LOG_LOCAL6, nil
case "LOCAL7":
return syslog.LOG_LOCAL7, nil
default:
return 0, fmt.Errorf("invalid syslog facility: %s", facility)
}
} | go | func facilityPriority(facility string) (syslog.Priority, error) {
facility = strings.ToUpper(facility)
switch facility {
case "KERN":
return syslog.LOG_KERN, nil
case "USER":
return syslog.LOG_USER, nil
case "MAIL":
return syslog.LOG_MAIL, nil
case "DAEMON":
return syslog.LOG_DAEMON, nil
case "AUTH":
return syslog.LOG_AUTH, nil
case "SYSLOG":
return syslog.LOG_SYSLOG, nil
case "LPR":
return syslog.LOG_LPR, nil
case "NEWS":
return syslog.LOG_NEWS, nil
case "UUCP":
return syslog.LOG_UUCP, nil
case "CRON":
return syslog.LOG_CRON, nil
case "AUTHPRIV":
return syslog.LOG_AUTHPRIV, nil
case "FTP":
return syslog.LOG_FTP, nil
case "LOCAL0":
return syslog.LOG_LOCAL0, nil
case "LOCAL1":
return syslog.LOG_LOCAL1, nil
case "LOCAL2":
return syslog.LOG_LOCAL2, nil
case "LOCAL3":
return syslog.LOG_LOCAL3, nil
case "LOCAL4":
return syslog.LOG_LOCAL4, nil
case "LOCAL5":
return syslog.LOG_LOCAL5, nil
case "LOCAL6":
return syslog.LOG_LOCAL6, nil
case "LOCAL7":
return syslog.LOG_LOCAL7, nil
default:
return 0, fmt.Errorf("invalid syslog facility: %s", facility)
}
} | [
"func",
"facilityPriority",
"(",
"facility",
"string",
")",
"(",
"syslog",
".",
"Priority",
",",
"error",
")",
"{",
"facility",
"=",
"strings",
".",
"ToUpper",
"(",
"facility",
")",
"\n",
"switch",
"facility",
"{",
"case",
"\"",
"\"",
":",
"return",
"syslog",
".",
"LOG_KERN",
",",
"nil",
"\n",
"case",
"\"",
"\"",
":",
"return",
"syslog",
".",
"LOG_USER",
",",
"nil",
"\n",
"case",
"\"",
"\"",
":",
"return",
"syslog",
".",
"LOG_MAIL",
",",
"nil",
"\n",
"case",
"\"",
"\"",
":",
"return",
"syslog",
".",
"LOG_DAEMON",
",",
"nil",
"\n",
"case",
"\"",
"\"",
":",
"return",
"syslog",
".",
"LOG_AUTH",
",",
"nil",
"\n",
"case",
"\"",
"\"",
":",
"return",
"syslog",
".",
"LOG_SYSLOG",
",",
"nil",
"\n",
"case",
"\"",
"\"",
":",
"return",
"syslog",
".",
"LOG_LPR",
",",
"nil",
"\n",
"case",
"\"",
"\"",
":",
"return",
"syslog",
".",
"LOG_NEWS",
",",
"nil",
"\n",
"case",
"\"",
"\"",
":",
"return",
"syslog",
".",
"LOG_UUCP",
",",
"nil",
"\n",
"case",
"\"",
"\"",
":",
"return",
"syslog",
".",
"LOG_CRON",
",",
"nil",
"\n",
"case",
"\"",
"\"",
":",
"return",
"syslog",
".",
"LOG_AUTHPRIV",
",",
"nil",
"\n",
"case",
"\"",
"\"",
":",
"return",
"syslog",
".",
"LOG_FTP",
",",
"nil",
"\n",
"case",
"\"",
"\"",
":",
"return",
"syslog",
".",
"LOG_LOCAL0",
",",
"nil",
"\n",
"case",
"\"",
"\"",
":",
"return",
"syslog",
".",
"LOG_LOCAL1",
",",
"nil",
"\n",
"case",
"\"",
"\"",
":",
"return",
"syslog",
".",
"LOG_LOCAL2",
",",
"nil",
"\n",
"case",
"\"",
"\"",
":",
"return",
"syslog",
".",
"LOG_LOCAL3",
",",
"nil",
"\n",
"case",
"\"",
"\"",
":",
"return",
"syslog",
".",
"LOG_LOCAL4",
",",
"nil",
"\n",
"case",
"\"",
"\"",
":",
"return",
"syslog",
".",
"LOG_LOCAL5",
",",
"nil",
"\n",
"case",
"\"",
"\"",
":",
"return",
"syslog",
".",
"LOG_LOCAL6",
",",
"nil",
"\n",
"case",
"\"",
"\"",
":",
"return",
"syslog",
".",
"LOG_LOCAL7",
",",
"nil",
"\n",
"default",
":",
"return",
"0",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"facility",
")",
"\n",
"}",
"\n",
"}"
]
| // facilityPriority converts a facility string into
// an appropriate priority level or returns an error | [
"facilityPriority",
"converts",
"a",
"facility",
"string",
"into",
"an",
"appropriate",
"priority",
"level",
"or",
"returns",
"an",
"error"
]
| 8d1874e3e8d1862b74e0536851e218c4571066a5 | https://github.com/hashicorp/go-syslog/blob/8d1874e3e8d1862b74e0536851e218c4571066a5/unix.go#L77-L123 |
11,498 | miekg/pkcs11 | p11/secret_key.go | Decrypt | func (secret SecretKey) Decrypt(mechanism pkcs11.Mechanism, ciphertext []byte) ([]byte, error) {
s := secret.session
s.Lock()
defer s.Unlock()
err := s.ctx.DecryptInit(s.handle, []*pkcs11.Mechanism{&mechanism}, secret.objectHandle)
if err != nil {
return nil, err
}
out, err := s.ctx.Decrypt(s.handle, ciphertext)
if err != nil {
return nil, err
}
return out, nil
} | go | func (secret SecretKey) Decrypt(mechanism pkcs11.Mechanism, ciphertext []byte) ([]byte, error) {
s := secret.session
s.Lock()
defer s.Unlock()
err := s.ctx.DecryptInit(s.handle, []*pkcs11.Mechanism{&mechanism}, secret.objectHandle)
if err != nil {
return nil, err
}
out, err := s.ctx.Decrypt(s.handle, ciphertext)
if err != nil {
return nil, err
}
return out, nil
} | [
"func",
"(",
"secret",
"SecretKey",
")",
"Decrypt",
"(",
"mechanism",
"pkcs11",
".",
"Mechanism",
",",
"ciphertext",
"[",
"]",
"byte",
")",
"(",
"[",
"]",
"byte",
",",
"error",
")",
"{",
"s",
":=",
"secret",
".",
"session",
"\n",
"s",
".",
"Lock",
"(",
")",
"\n",
"defer",
"s",
".",
"Unlock",
"(",
")",
"\n",
"err",
":=",
"s",
".",
"ctx",
".",
"DecryptInit",
"(",
"s",
".",
"handle",
",",
"[",
"]",
"*",
"pkcs11",
".",
"Mechanism",
"{",
"&",
"mechanism",
"}",
",",
"secret",
".",
"objectHandle",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"out",
",",
"err",
":=",
"s",
".",
"ctx",
".",
"Decrypt",
"(",
"s",
".",
"handle",
",",
"ciphertext",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"return",
"out",
",",
"nil",
"\n",
"}"
]
| // Decrypt decrypts the input with a given mechanism. | [
"Decrypt",
"decrypts",
"the",
"input",
"with",
"a",
"given",
"mechanism",
"."
]
| a667d056470f6e0da7facaff2466f0d2645e35d7 | https://github.com/miekg/pkcs11/blob/a667d056470f6e0da7facaff2466f0d2645e35d7/p11/secret_key.go#L29-L42 |
11,499 | miekg/pkcs11 | params.go | IV | func (p *GCMParams) IV() []byte {
if p == nil || p.params == nil {
return nil
}
newIv := C.GoBytes(unsafe.Pointer(p.params.pIv), C.int(p.params.ulIvLen))
iv := make([]byte, len(newIv))
copy(iv, newIv)
return iv
} | go | func (p *GCMParams) IV() []byte {
if p == nil || p.params == nil {
return nil
}
newIv := C.GoBytes(unsafe.Pointer(p.params.pIv), C.int(p.params.ulIvLen))
iv := make([]byte, len(newIv))
copy(iv, newIv)
return iv
} | [
"func",
"(",
"p",
"*",
"GCMParams",
")",
"IV",
"(",
")",
"[",
"]",
"byte",
"{",
"if",
"p",
"==",
"nil",
"||",
"p",
".",
"params",
"==",
"nil",
"{",
"return",
"nil",
"\n",
"}",
"\n",
"newIv",
":=",
"C",
".",
"GoBytes",
"(",
"unsafe",
".",
"Pointer",
"(",
"p",
".",
"params",
".",
"pIv",
")",
",",
"C",
".",
"int",
"(",
"p",
".",
"params",
".",
"ulIvLen",
")",
")",
"\n",
"iv",
":=",
"make",
"(",
"[",
"]",
"byte",
",",
"len",
"(",
"newIv",
")",
")",
"\n",
"copy",
"(",
"iv",
",",
"newIv",
")",
"\n",
"return",
"iv",
"\n",
"}"
]
| // IV returns a copy of the actual IV used for the operation.
//
// Some HSMs may ignore the user-specified IV and write their own at the end of
// the encryption operation; this method allows you to retrieve it. | [
"IV",
"returns",
"a",
"copy",
"of",
"the",
"actual",
"IV",
"used",
"for",
"the",
"operation",
".",
"Some",
"HSMs",
"may",
"ignore",
"the",
"user",
"-",
"specified",
"IV",
"and",
"write",
"their",
"own",
"at",
"the",
"end",
"of",
"the",
"encryption",
"operation",
";",
"this",
"method",
"allows",
"you",
"to",
"retrieve",
"it",
"."
]
| a667d056470f6e0da7facaff2466f0d2645e35d7 | https://github.com/miekg/pkcs11/blob/a667d056470f6e0da7facaff2466f0d2645e35d7/params.go#L94-L102 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.