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
sequence | docstring
stringlengths 6
2.61k
| docstring_tokens
sequence | sha
stringlengths 40
40
| url
stringlengths 85
252
| partition
stringclasses 1
value |
---|---|---|---|---|---|---|---|---|---|---|---|
hashicorp/hcl | json/scanner/scanner.go | err | func (s *Scanner) err(msg string) {
s.ErrorCount++
pos := s.recentPosition()
if s.Error != nil {
s.Error(pos, msg)
return
}
fmt.Fprintf(os.Stderr, "%s: %s\n", pos, msg)
} | go | func (s *Scanner) err(msg string) {
s.ErrorCount++
pos := s.recentPosition()
if s.Error != nil {
s.Error(pos, msg)
return
}
fmt.Fprintf(os.Stderr, "%s: %s\n", pos, msg)
} | [
"func",
"(",
"s",
"*",
"Scanner",
")",
"err",
"(",
"msg",
"string",
")",
"{",
"s",
".",
"ErrorCount",
"++",
"\n",
"pos",
":=",
"s",
".",
"recentPosition",
"(",
")",
"\n\n",
"if",
"s",
".",
"Error",
"!=",
"nil",
"{",
"s",
".",
"Error",
"(",
"pos",
",",
"msg",
")",
"\n",
"return",
"\n",
"}",
"\n\n",
"fmt",
".",
"Fprintf",
"(",
"os",
".",
"Stderr",
",",
"\"",
"\\n",
"\"",
",",
"pos",
",",
"msg",
")",
"\n",
"}"
] | // err prints the error of any scanning to s.Error function. If the function is
// not defined, by default it prints them to os.Stderr | [
"err",
"prints",
"the",
"error",
"of",
"any",
"scanning",
"to",
"s",
".",
"Error",
"function",
".",
"If",
"the",
"function",
"is",
"not",
"defined",
"by",
"default",
"it",
"prints",
"them",
"to",
"os",
".",
"Stderr"
] | 99e2f22d1c94b272184d97dd9d252866409100ab | https://github.com/hashicorp/hcl/blob/99e2f22d1c94b272184d97dd9d252866409100ab/json/scanner/scanner.go#L403-L413 | train |
hashicorp/hcl | json/scanner/scanner.go | isDigit | func isDigit(ch rune) bool {
return '0' <= ch && ch <= '9' || ch >= 0x80 && unicode.IsDigit(ch)
} | go | func isDigit(ch rune) bool {
return '0' <= ch && ch <= '9' || ch >= 0x80 && unicode.IsDigit(ch)
} | [
"func",
"isDigit",
"(",
"ch",
"rune",
")",
"bool",
"{",
"return",
"'0'",
"<=",
"ch",
"&&",
"ch",
"<=",
"'9'",
"||",
"ch",
">=",
"0x80",
"&&",
"unicode",
".",
"IsDigit",
"(",
"ch",
")",
"\n",
"}"
] | // isHexadecimal returns true if the given rune is a decimal digit | [
"isHexadecimal",
"returns",
"true",
"if",
"the",
"given",
"rune",
"is",
"a",
"decimal",
"digit"
] | 99e2f22d1c94b272184d97dd9d252866409100ab | https://github.com/hashicorp/hcl/blob/99e2f22d1c94b272184d97dd9d252866409100ab/json/scanner/scanner.go#L421-L423 | train |
hashicorp/hcl | json/scanner/scanner.go | isHexadecimal | func isHexadecimal(ch rune) bool {
return '0' <= ch && ch <= '9' || 'a' <= ch && ch <= 'f' || 'A' <= ch && ch <= 'F'
} | go | func isHexadecimal(ch rune) bool {
return '0' <= ch && ch <= '9' || 'a' <= ch && ch <= 'f' || 'A' <= ch && ch <= 'F'
} | [
"func",
"isHexadecimal",
"(",
"ch",
"rune",
")",
"bool",
"{",
"return",
"'0'",
"<=",
"ch",
"&&",
"ch",
"<=",
"'9'",
"||",
"'a'",
"<=",
"ch",
"&&",
"ch",
"<=",
"'f'",
"||",
"'A'",
"<=",
"ch",
"&&",
"ch",
"<=",
"'F'",
"\n",
"}"
] | // isHexadecimal returns true if the given rune is an hexadecimal number | [
"isHexadecimal",
"returns",
"true",
"if",
"the",
"given",
"rune",
"is",
"an",
"hexadecimal",
"number"
] | 99e2f22d1c94b272184d97dd9d252866409100ab | https://github.com/hashicorp/hcl/blob/99e2f22d1c94b272184d97dd9d252866409100ab/json/scanner/scanner.go#L431-L433 | train |
hashicorp/hcl | hcl/token/position.go | Before | func (p Pos) Before(u Pos) bool {
return u.Offset > p.Offset || u.Line > p.Line
} | go | func (p Pos) Before(u Pos) bool {
return u.Offset > p.Offset || u.Line > p.Line
} | [
"func",
"(",
"p",
"Pos",
")",
"Before",
"(",
"u",
"Pos",
")",
"bool",
"{",
"return",
"u",
".",
"Offset",
">",
"p",
".",
"Offset",
"||",
"u",
".",
"Line",
">",
"p",
".",
"Line",
"\n",
"}"
] | // Before reports whether the position p is before u. | [
"Before",
"reports",
"whether",
"the",
"position",
"p",
"is",
"before",
"u",
"."
] | 99e2f22d1c94b272184d97dd9d252866409100ab | https://github.com/hashicorp/hcl/blob/99e2f22d1c94b272184d97dd9d252866409100ab/hcl/token/position.go#L39-L41 | train |
hashicorp/hcl | hcl/token/position.go | After | func (p Pos) After(u Pos) bool {
return u.Offset < p.Offset || u.Line < p.Line
} | go | func (p Pos) After(u Pos) bool {
return u.Offset < p.Offset || u.Line < p.Line
} | [
"func",
"(",
"p",
"Pos",
")",
"After",
"(",
"u",
"Pos",
")",
"bool",
"{",
"return",
"u",
".",
"Offset",
"<",
"p",
".",
"Offset",
"||",
"u",
".",
"Line",
"<",
"p",
".",
"Line",
"\n",
"}"
] | // After reports whether the position p is after u. | [
"After",
"reports",
"whether",
"the",
"position",
"p",
"is",
"after",
"u",
"."
] | 99e2f22d1c94b272184d97dd9d252866409100ab | https://github.com/hashicorp/hcl/blob/99e2f22d1c94b272184d97dd9d252866409100ab/hcl/token/position.go#L44-L46 | train |
hashicorp/hcl | decoder.go | Unmarshal | func Unmarshal(bs []byte, v interface{}) error {
root, err := parse(bs)
if err != nil {
return err
}
return DecodeObject(v, root)
} | go | func Unmarshal(bs []byte, v interface{}) error {
root, err := parse(bs)
if err != nil {
return err
}
return DecodeObject(v, root)
} | [
"func",
"Unmarshal",
"(",
"bs",
"[",
"]",
"byte",
",",
"v",
"interface",
"{",
"}",
")",
"error",
"{",
"root",
",",
"err",
":=",
"parse",
"(",
"bs",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"return",
"DecodeObject",
"(",
"v",
",",
"root",
")",
"\n",
"}"
] | // Unmarshal accepts a byte slice as input and writes the
// data to the value pointed to by v. | [
"Unmarshal",
"accepts",
"a",
"byte",
"slice",
"as",
"input",
"and",
"writes",
"the",
"data",
"to",
"the",
"value",
"pointed",
"to",
"by",
"v",
"."
] | 99e2f22d1c94b272184d97dd9d252866409100ab | https://github.com/hashicorp/hcl/blob/99e2f22d1c94b272184d97dd9d252866409100ab/decoder.go#L26-L33 | train |
hashicorp/hcl | decoder.go | Decode | func Decode(out interface{}, in string) error {
obj, err := Parse(in)
if err != nil {
return err
}
return DecodeObject(out, obj)
} | go | func Decode(out interface{}, in string) error {
obj, err := Parse(in)
if err != nil {
return err
}
return DecodeObject(out, obj)
} | [
"func",
"Decode",
"(",
"out",
"interface",
"{",
"}",
",",
"in",
"string",
")",
"error",
"{",
"obj",
",",
"err",
":=",
"Parse",
"(",
"in",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"return",
"DecodeObject",
"(",
"out",
",",
"obj",
")",
"\n",
"}"
] | // Decode reads the given input and decodes it into the structure
// given by `out`. | [
"Decode",
"reads",
"the",
"given",
"input",
"and",
"decodes",
"it",
"into",
"the",
"structure",
"given",
"by",
"out",
"."
] | 99e2f22d1c94b272184d97dd9d252866409100ab | https://github.com/hashicorp/hcl/blob/99e2f22d1c94b272184d97dd9d252866409100ab/decoder.go#L37-L44 | train |
hashicorp/hcl | decoder.go | DecodeObject | func DecodeObject(out interface{}, n ast.Node) error {
val := reflect.ValueOf(out)
if val.Kind() != reflect.Ptr {
return errors.New("result must be a pointer")
}
// If we have the file, we really decode the root node
if f, ok := n.(*ast.File); ok {
n = f.Node
}
var d decoder
return d.decode("root", n, val.Elem())
} | go | func DecodeObject(out interface{}, n ast.Node) error {
val := reflect.ValueOf(out)
if val.Kind() != reflect.Ptr {
return errors.New("result must be a pointer")
}
// If we have the file, we really decode the root node
if f, ok := n.(*ast.File); ok {
n = f.Node
}
var d decoder
return d.decode("root", n, val.Elem())
} | [
"func",
"DecodeObject",
"(",
"out",
"interface",
"{",
"}",
",",
"n",
"ast",
".",
"Node",
")",
"error",
"{",
"val",
":=",
"reflect",
".",
"ValueOf",
"(",
"out",
")",
"\n",
"if",
"val",
".",
"Kind",
"(",
")",
"!=",
"reflect",
".",
"Ptr",
"{",
"return",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"// If we have the file, we really decode the root node",
"if",
"f",
",",
"ok",
":=",
"n",
".",
"(",
"*",
"ast",
".",
"File",
")",
";",
"ok",
"{",
"n",
"=",
"f",
".",
"Node",
"\n",
"}",
"\n\n",
"var",
"d",
"decoder",
"\n",
"return",
"d",
".",
"decode",
"(",
"\"",
"\"",
",",
"n",
",",
"val",
".",
"Elem",
"(",
")",
")",
"\n",
"}"
] | // DecodeObject is a lower-level version of Decode. It decodes a
// raw Object into the given output. | [
"DecodeObject",
"is",
"a",
"lower",
"-",
"level",
"version",
"of",
"Decode",
".",
"It",
"decodes",
"a",
"raw",
"Object",
"into",
"the",
"given",
"output",
"."
] | 99e2f22d1c94b272184d97dd9d252866409100ab | https://github.com/hashicorp/hcl/blob/99e2f22d1c94b272184d97dd9d252866409100ab/decoder.go#L48-L61 | train |
hashicorp/hcl | decoder.go | expandObject | func expandObject(node ast.Node, result reflect.Value) ast.Node {
item, ok := node.(*ast.ObjectItem)
if !ok {
return node
}
elemType := result.Type()
// our target type must be a struct
switch elemType.Kind() {
case reflect.Ptr:
switch elemType.Elem().Kind() {
case reflect.Struct:
//OK
default:
return node
}
case reflect.Struct:
//OK
default:
return node
}
// A list value will have a key and field name. If it had more fields,
// it wouldn't have been flattened.
if len(item.Keys) != 2 {
return node
}
keyToken := item.Keys[0].Token
item.Keys = item.Keys[1:]
// we need to un-flatten the ast enough to decode
newNode := &ast.ObjectItem{
Keys: []*ast.ObjectKey{
{
Token: keyToken,
},
},
Val: &ast.ObjectType{
List: &ast.ObjectList{
Items: []*ast.ObjectItem{item},
},
},
}
return newNode
} | go | func expandObject(node ast.Node, result reflect.Value) ast.Node {
item, ok := node.(*ast.ObjectItem)
if !ok {
return node
}
elemType := result.Type()
// our target type must be a struct
switch elemType.Kind() {
case reflect.Ptr:
switch elemType.Elem().Kind() {
case reflect.Struct:
//OK
default:
return node
}
case reflect.Struct:
//OK
default:
return node
}
// A list value will have a key and field name. If it had more fields,
// it wouldn't have been flattened.
if len(item.Keys) != 2 {
return node
}
keyToken := item.Keys[0].Token
item.Keys = item.Keys[1:]
// we need to un-flatten the ast enough to decode
newNode := &ast.ObjectItem{
Keys: []*ast.ObjectKey{
{
Token: keyToken,
},
},
Val: &ast.ObjectType{
List: &ast.ObjectList{
Items: []*ast.ObjectItem{item},
},
},
}
return newNode
} | [
"func",
"expandObject",
"(",
"node",
"ast",
".",
"Node",
",",
"result",
"reflect",
".",
"Value",
")",
"ast",
".",
"Node",
"{",
"item",
",",
"ok",
":=",
"node",
".",
"(",
"*",
"ast",
".",
"ObjectItem",
")",
"\n",
"if",
"!",
"ok",
"{",
"return",
"node",
"\n",
"}",
"\n\n",
"elemType",
":=",
"result",
".",
"Type",
"(",
")",
"\n\n",
"// our target type must be a struct",
"switch",
"elemType",
".",
"Kind",
"(",
")",
"{",
"case",
"reflect",
".",
"Ptr",
":",
"switch",
"elemType",
".",
"Elem",
"(",
")",
".",
"Kind",
"(",
")",
"{",
"case",
"reflect",
".",
"Struct",
":",
"//OK",
"default",
":",
"return",
"node",
"\n",
"}",
"\n",
"case",
"reflect",
".",
"Struct",
":",
"//OK",
"default",
":",
"return",
"node",
"\n",
"}",
"\n\n",
"// A list value will have a key and field name. If it had more fields,",
"// it wouldn't have been flattened.",
"if",
"len",
"(",
"item",
".",
"Keys",
")",
"!=",
"2",
"{",
"return",
"node",
"\n",
"}",
"\n\n",
"keyToken",
":=",
"item",
".",
"Keys",
"[",
"0",
"]",
".",
"Token",
"\n",
"item",
".",
"Keys",
"=",
"item",
".",
"Keys",
"[",
"1",
":",
"]",
"\n\n",
"// we need to un-flatten the ast enough to decode",
"newNode",
":=",
"&",
"ast",
".",
"ObjectItem",
"{",
"Keys",
":",
"[",
"]",
"*",
"ast",
".",
"ObjectKey",
"{",
"{",
"Token",
":",
"keyToken",
",",
"}",
",",
"}",
",",
"Val",
":",
"&",
"ast",
".",
"ObjectType",
"{",
"List",
":",
"&",
"ast",
".",
"ObjectList",
"{",
"Items",
":",
"[",
"]",
"*",
"ast",
".",
"ObjectItem",
"{",
"item",
"}",
",",
"}",
",",
"}",
",",
"}",
"\n\n",
"return",
"newNode",
"\n",
"}"
] | // expandObject detects if an ambiguous JSON object was flattened to a List which
// should be decoded into a struct, and expands the ast to properly deocode. | [
"expandObject",
"detects",
"if",
"an",
"ambiguous",
"JSON",
"object",
"was",
"flattened",
"to",
"a",
"List",
"which",
"should",
"be",
"decoded",
"into",
"a",
"struct",
"and",
"expands",
"the",
"ast",
"to",
"properly",
"deocode",
"."
] | 99e2f22d1c94b272184d97dd9d252866409100ab | https://github.com/hashicorp/hcl/blob/99e2f22d1c94b272184d97dd9d252866409100ab/decoder.go#L485-L532 | train |
hashicorp/hcl | decoder.go | findNodeType | func findNodeType() reflect.Type {
var nodeContainer struct {
Node ast.Node
}
value := reflect.ValueOf(nodeContainer).FieldByName("Node")
return value.Type()
} | go | func findNodeType() reflect.Type {
var nodeContainer struct {
Node ast.Node
}
value := reflect.ValueOf(nodeContainer).FieldByName("Node")
return value.Type()
} | [
"func",
"findNodeType",
"(",
")",
"reflect",
".",
"Type",
"{",
"var",
"nodeContainer",
"struct",
"{",
"Node",
"ast",
".",
"Node",
"\n",
"}",
"\n",
"value",
":=",
"reflect",
".",
"ValueOf",
"(",
"nodeContainer",
")",
".",
"FieldByName",
"(",
"\"",
"\"",
")",
"\n",
"return",
"value",
".",
"Type",
"(",
")",
"\n",
"}"
] | // findNodeType returns the type of ast.Node | [
"findNodeType",
"returns",
"the",
"type",
"of",
"ast",
".",
"Node"
] | 99e2f22d1c94b272184d97dd9d252866409100ab | https://github.com/hashicorp/hcl/blob/99e2f22d1c94b272184d97dd9d252866409100ab/decoder.go#L752-L758 | train |
hashicorp/hcl | hcl/scanner/scanner.go | scanHeredoc | func (s *Scanner) scanHeredoc() {
// Scan the second '<' in example: '<<EOF'
if s.next() != '<' {
s.err("heredoc expected second '<', didn't see it")
return
}
// Get the original offset so we can read just the heredoc ident
offs := s.srcPos.Offset
// Scan the identifier
ch := s.next()
// Indented heredoc syntax
if ch == '-' {
ch = s.next()
}
for isLetter(ch) || isDigit(ch) {
ch = s.next()
}
// If we reached an EOF then that is not good
if ch == eof {
s.err("heredoc not terminated")
return
}
// Ignore the '\r' in Windows line endings
if ch == '\r' {
if s.peek() == '\n' {
ch = s.next()
}
}
// If we didn't reach a newline then that is also not good
if ch != '\n' {
s.err("invalid characters in heredoc anchor")
return
}
// Read the identifier
identBytes := s.src[offs : s.srcPos.Offset-s.lastCharLen]
if len(identBytes) == 0 || (len(identBytes) == 1 && identBytes[0] == '-') {
s.err("zero-length heredoc anchor")
return
}
var identRegexp *regexp.Regexp
if identBytes[0] == '-' {
identRegexp = regexp.MustCompile(fmt.Sprintf(`^[[:space:]]*%s\r*\z`, identBytes[1:]))
} else {
identRegexp = regexp.MustCompile(fmt.Sprintf(`^[[:space:]]*%s\r*\z`, identBytes))
}
// Read the actual string value
lineStart := s.srcPos.Offset
for {
ch := s.next()
// Special newline handling.
if ch == '\n' {
// Math is fast, so we first compare the byte counts to see if we have a chance
// of seeing the same identifier - if the length is less than the number of bytes
// in the identifier, this cannot be a valid terminator.
lineBytesLen := s.srcPos.Offset - s.lastCharLen - lineStart
if lineBytesLen >= len(identBytes) && identRegexp.Match(s.src[lineStart:s.srcPos.Offset-s.lastCharLen]) {
break
}
// Not an anchor match, record the start of a new line
lineStart = s.srcPos.Offset
}
if ch == eof {
s.err("heredoc not terminated")
return
}
}
return
} | go | func (s *Scanner) scanHeredoc() {
// Scan the second '<' in example: '<<EOF'
if s.next() != '<' {
s.err("heredoc expected second '<', didn't see it")
return
}
// Get the original offset so we can read just the heredoc ident
offs := s.srcPos.Offset
// Scan the identifier
ch := s.next()
// Indented heredoc syntax
if ch == '-' {
ch = s.next()
}
for isLetter(ch) || isDigit(ch) {
ch = s.next()
}
// If we reached an EOF then that is not good
if ch == eof {
s.err("heredoc not terminated")
return
}
// Ignore the '\r' in Windows line endings
if ch == '\r' {
if s.peek() == '\n' {
ch = s.next()
}
}
// If we didn't reach a newline then that is also not good
if ch != '\n' {
s.err("invalid characters in heredoc anchor")
return
}
// Read the identifier
identBytes := s.src[offs : s.srcPos.Offset-s.lastCharLen]
if len(identBytes) == 0 || (len(identBytes) == 1 && identBytes[0] == '-') {
s.err("zero-length heredoc anchor")
return
}
var identRegexp *regexp.Regexp
if identBytes[0] == '-' {
identRegexp = regexp.MustCompile(fmt.Sprintf(`^[[:space:]]*%s\r*\z`, identBytes[1:]))
} else {
identRegexp = regexp.MustCompile(fmt.Sprintf(`^[[:space:]]*%s\r*\z`, identBytes))
}
// Read the actual string value
lineStart := s.srcPos.Offset
for {
ch := s.next()
// Special newline handling.
if ch == '\n' {
// Math is fast, so we first compare the byte counts to see if we have a chance
// of seeing the same identifier - if the length is less than the number of bytes
// in the identifier, this cannot be a valid terminator.
lineBytesLen := s.srcPos.Offset - s.lastCharLen - lineStart
if lineBytesLen >= len(identBytes) && identRegexp.Match(s.src[lineStart:s.srcPos.Offset-s.lastCharLen]) {
break
}
// Not an anchor match, record the start of a new line
lineStart = s.srcPos.Offset
}
if ch == eof {
s.err("heredoc not terminated")
return
}
}
return
} | [
"func",
"(",
"s",
"*",
"Scanner",
")",
"scanHeredoc",
"(",
")",
"{",
"// Scan the second '<' in example: '<<EOF'",
"if",
"s",
".",
"next",
"(",
")",
"!=",
"'<'",
"{",
"s",
".",
"err",
"(",
"\"",
"\"",
")",
"\n",
"return",
"\n",
"}",
"\n\n",
"// Get the original offset so we can read just the heredoc ident",
"offs",
":=",
"s",
".",
"srcPos",
".",
"Offset",
"\n\n",
"// Scan the identifier",
"ch",
":=",
"s",
".",
"next",
"(",
")",
"\n\n",
"// Indented heredoc syntax",
"if",
"ch",
"==",
"'-'",
"{",
"ch",
"=",
"s",
".",
"next",
"(",
")",
"\n",
"}",
"\n\n",
"for",
"isLetter",
"(",
"ch",
")",
"||",
"isDigit",
"(",
"ch",
")",
"{",
"ch",
"=",
"s",
".",
"next",
"(",
")",
"\n",
"}",
"\n\n",
"// If we reached an EOF then that is not good",
"if",
"ch",
"==",
"eof",
"{",
"s",
".",
"err",
"(",
"\"",
"\"",
")",
"\n",
"return",
"\n",
"}",
"\n\n",
"// Ignore the '\\r' in Windows line endings",
"if",
"ch",
"==",
"'\\r'",
"{",
"if",
"s",
".",
"peek",
"(",
")",
"==",
"'\\n'",
"{",
"ch",
"=",
"s",
".",
"next",
"(",
")",
"\n",
"}",
"\n",
"}",
"\n\n",
"// If we didn't reach a newline then that is also not good",
"if",
"ch",
"!=",
"'\\n'",
"{",
"s",
".",
"err",
"(",
"\"",
"\"",
")",
"\n",
"return",
"\n",
"}",
"\n\n",
"// Read the identifier",
"identBytes",
":=",
"s",
".",
"src",
"[",
"offs",
":",
"s",
".",
"srcPos",
".",
"Offset",
"-",
"s",
".",
"lastCharLen",
"]",
"\n",
"if",
"len",
"(",
"identBytes",
")",
"==",
"0",
"||",
"(",
"len",
"(",
"identBytes",
")",
"==",
"1",
"&&",
"identBytes",
"[",
"0",
"]",
"==",
"'-'",
")",
"{",
"s",
".",
"err",
"(",
"\"",
"\"",
")",
"\n",
"return",
"\n",
"}",
"\n\n",
"var",
"identRegexp",
"*",
"regexp",
".",
"Regexp",
"\n",
"if",
"identBytes",
"[",
"0",
"]",
"==",
"'-'",
"{",
"identRegexp",
"=",
"regexp",
".",
"MustCompile",
"(",
"fmt",
".",
"Sprintf",
"(",
"`^[[:space:]]*%s\\r*\\z`",
",",
"identBytes",
"[",
"1",
":",
"]",
")",
")",
"\n",
"}",
"else",
"{",
"identRegexp",
"=",
"regexp",
".",
"MustCompile",
"(",
"fmt",
".",
"Sprintf",
"(",
"`^[[:space:]]*%s\\r*\\z`",
",",
"identBytes",
")",
")",
"\n",
"}",
"\n\n",
"// Read the actual string value",
"lineStart",
":=",
"s",
".",
"srcPos",
".",
"Offset",
"\n",
"for",
"{",
"ch",
":=",
"s",
".",
"next",
"(",
")",
"\n\n",
"// Special newline handling.",
"if",
"ch",
"==",
"'\\n'",
"{",
"// Math is fast, so we first compare the byte counts to see if we have a chance",
"// of seeing the same identifier - if the length is less than the number of bytes",
"// in the identifier, this cannot be a valid terminator.",
"lineBytesLen",
":=",
"s",
".",
"srcPos",
".",
"Offset",
"-",
"s",
".",
"lastCharLen",
"-",
"lineStart",
"\n",
"if",
"lineBytesLen",
">=",
"len",
"(",
"identBytes",
")",
"&&",
"identRegexp",
".",
"Match",
"(",
"s",
".",
"src",
"[",
"lineStart",
":",
"s",
".",
"srcPos",
".",
"Offset",
"-",
"s",
".",
"lastCharLen",
"]",
")",
"{",
"break",
"\n",
"}",
"\n\n",
"// Not an anchor match, record the start of a new line",
"lineStart",
"=",
"s",
".",
"srcPos",
".",
"Offset",
"\n",
"}",
"\n\n",
"if",
"ch",
"==",
"eof",
"{",
"s",
".",
"err",
"(",
"\"",
"\"",
")",
"\n",
"return",
"\n",
"}",
"\n",
"}",
"\n\n",
"return",
"\n",
"}"
] | // scanHeredoc scans a heredoc string | [
"scanHeredoc",
"scans",
"a",
"heredoc",
"string"
] | 99e2f22d1c94b272184d97dd9d252866409100ab | https://github.com/hashicorp/hcl/blob/99e2f22d1c94b272184d97dd9d252866409100ab/hcl/scanner/scanner.go#L393-L474 | train |
hashicorp/hcl | hcl/scanner/scanner.go | scanString | func (s *Scanner) scanString() {
braces := 0
for {
// '"' opening already consumed
// read character after quote
ch := s.next()
if (ch == '\n' && braces == 0) || ch < 0 || ch == eof {
s.err("literal not terminated")
return
}
if ch == '"' && braces == 0 {
break
}
// If we're going into a ${} then we can ignore quotes for awhile
if braces == 0 && ch == '$' && s.peek() == '{' {
braces++
s.next()
} else if braces > 0 && ch == '{' {
braces++
}
if braces > 0 && ch == '}' {
braces--
}
if ch == '\\' {
s.scanEscape()
}
}
return
} | go | func (s *Scanner) scanString() {
braces := 0
for {
// '"' opening already consumed
// read character after quote
ch := s.next()
if (ch == '\n' && braces == 0) || ch < 0 || ch == eof {
s.err("literal not terminated")
return
}
if ch == '"' && braces == 0 {
break
}
// If we're going into a ${} then we can ignore quotes for awhile
if braces == 0 && ch == '$' && s.peek() == '{' {
braces++
s.next()
} else if braces > 0 && ch == '{' {
braces++
}
if braces > 0 && ch == '}' {
braces--
}
if ch == '\\' {
s.scanEscape()
}
}
return
} | [
"func",
"(",
"s",
"*",
"Scanner",
")",
"scanString",
"(",
")",
"{",
"braces",
":=",
"0",
"\n",
"for",
"{",
"// '\"' opening already consumed",
"// read character after quote",
"ch",
":=",
"s",
".",
"next",
"(",
")",
"\n\n",
"if",
"(",
"ch",
"==",
"'\\n'",
"&&",
"braces",
"==",
"0",
")",
"||",
"ch",
"<",
"0",
"||",
"ch",
"==",
"eof",
"{",
"s",
".",
"err",
"(",
"\"",
"\"",
")",
"\n",
"return",
"\n",
"}",
"\n\n",
"if",
"ch",
"==",
"'\"'",
"&&",
"braces",
"==",
"0",
"{",
"break",
"\n",
"}",
"\n\n",
"// If we're going into a ${} then we can ignore quotes for awhile",
"if",
"braces",
"==",
"0",
"&&",
"ch",
"==",
"'$'",
"&&",
"s",
".",
"peek",
"(",
")",
"==",
"'{'",
"{",
"braces",
"++",
"\n",
"s",
".",
"next",
"(",
")",
"\n",
"}",
"else",
"if",
"braces",
">",
"0",
"&&",
"ch",
"==",
"'{'",
"{",
"braces",
"++",
"\n",
"}",
"\n",
"if",
"braces",
">",
"0",
"&&",
"ch",
"==",
"'}'",
"{",
"braces",
"--",
"\n",
"}",
"\n\n",
"if",
"ch",
"==",
"'\\\\'",
"{",
"s",
".",
"scanEscape",
"(",
")",
"\n",
"}",
"\n",
"}",
"\n\n",
"return",
"\n",
"}"
] | // scanString scans a quoted string | [
"scanString",
"scans",
"a",
"quoted",
"string"
] | 99e2f22d1c94b272184d97dd9d252866409100ab | https://github.com/hashicorp/hcl/blob/99e2f22d1c94b272184d97dd9d252866409100ab/hcl/scanner/scanner.go#L477-L510 | train |
hashicorp/hcl | hcl/parser/parser.go | scan | func (p *Parser) scan() token.Token {
// If we have a token on the buffer, then return it.
if p.n != 0 {
p.n = 0
return p.tok
}
// Otherwise read the next token from the scanner and Save it to the buffer
// in case we unscan later.
prev := p.tok
p.tok = p.sc.Scan()
if p.tok.Type == token.COMMENT {
var comment *ast.CommentGroup
var endline int
// fmt.Printf("p.tok.Pos.Line = %+v prev: %d endline %d \n",
// p.tok.Pos.Line, prev.Pos.Line, endline)
if p.tok.Pos.Line == prev.Pos.Line {
// The comment is on same line as the previous token; it
// cannot be a lead comment but may be a line comment.
comment, endline = p.consumeCommentGroup(0)
if p.tok.Pos.Line != endline {
// The next token is on a different line, thus
// the last comment group is a line comment.
p.lineComment = comment
}
}
// consume successor comments, if any
endline = -1
for p.tok.Type == token.COMMENT {
comment, endline = p.consumeCommentGroup(1)
}
if endline+1 == p.tok.Pos.Line && p.tok.Type != token.RBRACE {
switch p.tok.Type {
case token.RBRACE, token.RBRACK:
// Do not count for these cases
default:
// The next token is following on the line immediately after the
// comment group, thus the last comment group is a lead comment.
p.leadComment = comment
}
}
}
return p.tok
} | go | func (p *Parser) scan() token.Token {
// If we have a token on the buffer, then return it.
if p.n != 0 {
p.n = 0
return p.tok
}
// Otherwise read the next token from the scanner and Save it to the buffer
// in case we unscan later.
prev := p.tok
p.tok = p.sc.Scan()
if p.tok.Type == token.COMMENT {
var comment *ast.CommentGroup
var endline int
// fmt.Printf("p.tok.Pos.Line = %+v prev: %d endline %d \n",
// p.tok.Pos.Line, prev.Pos.Line, endline)
if p.tok.Pos.Line == prev.Pos.Line {
// The comment is on same line as the previous token; it
// cannot be a lead comment but may be a line comment.
comment, endline = p.consumeCommentGroup(0)
if p.tok.Pos.Line != endline {
// The next token is on a different line, thus
// the last comment group is a line comment.
p.lineComment = comment
}
}
// consume successor comments, if any
endline = -1
for p.tok.Type == token.COMMENT {
comment, endline = p.consumeCommentGroup(1)
}
if endline+1 == p.tok.Pos.Line && p.tok.Type != token.RBRACE {
switch p.tok.Type {
case token.RBRACE, token.RBRACK:
// Do not count for these cases
default:
// The next token is following on the line immediately after the
// comment group, thus the last comment group is a lead comment.
p.leadComment = comment
}
}
}
return p.tok
} | [
"func",
"(",
"p",
"*",
"Parser",
")",
"scan",
"(",
")",
"token",
".",
"Token",
"{",
"// If we have a token on the buffer, then return it.",
"if",
"p",
".",
"n",
"!=",
"0",
"{",
"p",
".",
"n",
"=",
"0",
"\n",
"return",
"p",
".",
"tok",
"\n",
"}",
"\n\n",
"// Otherwise read the next token from the scanner and Save it to the buffer",
"// in case we unscan later.",
"prev",
":=",
"p",
".",
"tok",
"\n",
"p",
".",
"tok",
"=",
"p",
".",
"sc",
".",
"Scan",
"(",
")",
"\n\n",
"if",
"p",
".",
"tok",
".",
"Type",
"==",
"token",
".",
"COMMENT",
"{",
"var",
"comment",
"*",
"ast",
".",
"CommentGroup",
"\n",
"var",
"endline",
"int",
"\n\n",
"// fmt.Printf(\"p.tok.Pos.Line = %+v prev: %d endline %d \\n\",",
"// p.tok.Pos.Line, prev.Pos.Line, endline)",
"if",
"p",
".",
"tok",
".",
"Pos",
".",
"Line",
"==",
"prev",
".",
"Pos",
".",
"Line",
"{",
"// The comment is on same line as the previous token; it",
"// cannot be a lead comment but may be a line comment.",
"comment",
",",
"endline",
"=",
"p",
".",
"consumeCommentGroup",
"(",
"0",
")",
"\n",
"if",
"p",
".",
"tok",
".",
"Pos",
".",
"Line",
"!=",
"endline",
"{",
"// The next token is on a different line, thus",
"// the last comment group is a line comment.",
"p",
".",
"lineComment",
"=",
"comment",
"\n",
"}",
"\n",
"}",
"\n\n",
"// consume successor comments, if any",
"endline",
"=",
"-",
"1",
"\n",
"for",
"p",
".",
"tok",
".",
"Type",
"==",
"token",
".",
"COMMENT",
"{",
"comment",
",",
"endline",
"=",
"p",
".",
"consumeCommentGroup",
"(",
"1",
")",
"\n",
"}",
"\n\n",
"if",
"endline",
"+",
"1",
"==",
"p",
".",
"tok",
".",
"Pos",
".",
"Line",
"&&",
"p",
".",
"tok",
".",
"Type",
"!=",
"token",
".",
"RBRACE",
"{",
"switch",
"p",
".",
"tok",
".",
"Type",
"{",
"case",
"token",
".",
"RBRACE",
",",
"token",
".",
"RBRACK",
":",
"// Do not count for these cases",
"default",
":",
"// The next token is following on the line immediately after the",
"// comment group, thus the last comment group is a lead comment.",
"p",
".",
"leadComment",
"=",
"comment",
"\n",
"}",
"\n",
"}",
"\n\n",
"}",
"\n\n",
"return",
"p",
".",
"tok",
"\n",
"}"
] | // scan returns the next token from the underlying scanner. If a token has
// been unscanned then read that instead. In the process, it collects any
// comment groups encountered, and remembers the last lead and line comments. | [
"scan",
"returns",
"the",
"next",
"token",
"from",
"the",
"underlying",
"scanner",
".",
"If",
"a",
"token",
"has",
"been",
"unscanned",
"then",
"read",
"that",
"instead",
".",
"In",
"the",
"process",
"it",
"collects",
"any",
"comment",
"groups",
"encountered",
"and",
"remembers",
"the",
"last",
"lead",
"and",
"line",
"comments",
"."
] | 99e2f22d1c94b272184d97dd9d252866409100ab | https://github.com/hashicorp/hcl/blob/99e2f22d1c94b272184d97dd9d252866409100ab/hcl/parser/parser.go#L444-L493 | train |
hashicorp/hcl | json/parser/parser.go | literalType | func (p *Parser) literalType() (*ast.LiteralType, error) {
defer un(trace(p, "ParseLiteral"))
return &ast.LiteralType{
Token: p.tok.HCLToken(),
}, nil
} | go | func (p *Parser) literalType() (*ast.LiteralType, error) {
defer un(trace(p, "ParseLiteral"))
return &ast.LiteralType{
Token: p.tok.HCLToken(),
}, nil
} | [
"func",
"(",
"p",
"*",
"Parser",
")",
"literalType",
"(",
")",
"(",
"*",
"ast",
".",
"LiteralType",
",",
"error",
")",
"{",
"defer",
"un",
"(",
"trace",
"(",
"p",
",",
"\"",
"\"",
")",
")",
"\n\n",
"return",
"&",
"ast",
".",
"LiteralType",
"{",
"Token",
":",
"p",
".",
"tok",
".",
"HCLToken",
"(",
")",
",",
"}",
",",
"nil",
"\n",
"}"
] | // literalType parses a literal type and returns a LiteralType AST | [
"literalType",
"parses",
"a",
"literal",
"type",
"and",
"returns",
"a",
"LiteralType",
"AST"
] | 99e2f22d1c94b272184d97dd9d252866409100ab | https://github.com/hashicorp/hcl/blob/99e2f22d1c94b272184d97dd9d252866409100ab/json/parser/parser.go#L255-L261 | train |
hashicorp/hcl | json/parser/parser.go | scan | func (p *Parser) scan() token.Token {
// If we have a token on the buffer, then return it.
if p.n != 0 {
p.n = 0
return p.tok
}
p.tok = p.sc.Scan()
return p.tok
} | go | func (p *Parser) scan() token.Token {
// If we have a token on the buffer, then return it.
if p.n != 0 {
p.n = 0
return p.tok
}
p.tok = p.sc.Scan()
return p.tok
} | [
"func",
"(",
"p",
"*",
"Parser",
")",
"scan",
"(",
")",
"token",
".",
"Token",
"{",
"// If we have a token on the buffer, then return it.",
"if",
"p",
".",
"n",
"!=",
"0",
"{",
"p",
".",
"n",
"=",
"0",
"\n",
"return",
"p",
".",
"tok",
"\n",
"}",
"\n\n",
"p",
".",
"tok",
"=",
"p",
".",
"sc",
".",
"Scan",
"(",
")",
"\n",
"return",
"p",
".",
"tok",
"\n",
"}"
] | // scan returns the next token from the underlying scanner. If a token has
// been unscanned then read that instead. | [
"scan",
"returns",
"the",
"next",
"token",
"from",
"the",
"underlying",
"scanner",
".",
"If",
"a",
"token",
"has",
"been",
"unscanned",
"then",
"read",
"that",
"instead",
"."
] | 99e2f22d1c94b272184d97dd9d252866409100ab | https://github.com/hashicorp/hcl/blob/99e2f22d1c94b272184d97dd9d252866409100ab/json/parser/parser.go#L265-L274 | train |
hashicorp/hcl | hcl/fmtcmd/fmtcmd.go | processFile | func processFile(filename string, in io.Reader, out io.Writer, stdin bool, opts Options) error {
if in == nil {
f, err := os.Open(filename)
if err != nil {
return err
}
defer f.Close()
in = f
}
src, err := ioutil.ReadAll(in)
if err != nil {
return err
}
res, err := printer.Format(src)
if err != nil {
return fmt.Errorf("In %s: %s", filename, err)
}
if !bytes.Equal(src, res) {
// formatting has changed
if opts.List {
fmt.Fprintln(out, filename)
}
if opts.Write {
err = ioutil.WriteFile(filename, res, 0644)
if err != nil {
return err
}
}
if opts.Diff {
data, err := diff(src, res)
if err != nil {
return fmt.Errorf("computing diff: %s", err)
}
fmt.Fprintf(out, "diff a/%s b/%s\n", filename, filename)
out.Write(data)
}
}
if !opts.List && !opts.Write && !opts.Diff {
_, err = out.Write(res)
}
return err
} | go | func processFile(filename string, in io.Reader, out io.Writer, stdin bool, opts Options) error {
if in == nil {
f, err := os.Open(filename)
if err != nil {
return err
}
defer f.Close()
in = f
}
src, err := ioutil.ReadAll(in)
if err != nil {
return err
}
res, err := printer.Format(src)
if err != nil {
return fmt.Errorf("In %s: %s", filename, err)
}
if !bytes.Equal(src, res) {
// formatting has changed
if opts.List {
fmt.Fprintln(out, filename)
}
if opts.Write {
err = ioutil.WriteFile(filename, res, 0644)
if err != nil {
return err
}
}
if opts.Diff {
data, err := diff(src, res)
if err != nil {
return fmt.Errorf("computing diff: %s", err)
}
fmt.Fprintf(out, "diff a/%s b/%s\n", filename, filename)
out.Write(data)
}
}
if !opts.List && !opts.Write && !opts.Diff {
_, err = out.Write(res)
}
return err
} | [
"func",
"processFile",
"(",
"filename",
"string",
",",
"in",
"io",
".",
"Reader",
",",
"out",
"io",
".",
"Writer",
",",
"stdin",
"bool",
",",
"opts",
"Options",
")",
"error",
"{",
"if",
"in",
"==",
"nil",
"{",
"f",
",",
"err",
":=",
"os",
".",
"Open",
"(",
"filename",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"defer",
"f",
".",
"Close",
"(",
")",
"\n",
"in",
"=",
"f",
"\n",
"}",
"\n\n",
"src",
",",
"err",
":=",
"ioutil",
".",
"ReadAll",
"(",
"in",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"res",
",",
"err",
":=",
"printer",
".",
"Format",
"(",
"src",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"filename",
",",
"err",
")",
"\n",
"}",
"\n\n",
"if",
"!",
"bytes",
".",
"Equal",
"(",
"src",
",",
"res",
")",
"{",
"// formatting has changed",
"if",
"opts",
".",
"List",
"{",
"fmt",
".",
"Fprintln",
"(",
"out",
",",
"filename",
")",
"\n",
"}",
"\n",
"if",
"opts",
".",
"Write",
"{",
"err",
"=",
"ioutil",
".",
"WriteFile",
"(",
"filename",
",",
"res",
",",
"0644",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"}",
"\n",
"if",
"opts",
".",
"Diff",
"{",
"data",
",",
"err",
":=",
"diff",
"(",
"src",
",",
"res",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n",
"fmt",
".",
"Fprintf",
"(",
"out",
",",
"\"",
"\\n",
"\"",
",",
"filename",
",",
"filename",
")",
"\n",
"out",
".",
"Write",
"(",
"data",
")",
"\n",
"}",
"\n",
"}",
"\n\n",
"if",
"!",
"opts",
".",
"List",
"&&",
"!",
"opts",
".",
"Write",
"&&",
"!",
"opts",
".",
"Diff",
"{",
"_",
",",
"err",
"=",
"out",
".",
"Write",
"(",
"res",
")",
"\n",
"}",
"\n\n",
"return",
"err",
"\n",
"}"
] | // If in == nil, the source is the contents of the file with the given filename. | [
"If",
"in",
"==",
"nil",
"the",
"source",
"is",
"the",
"contents",
"of",
"the",
"file",
"with",
"the",
"given",
"filename",
"."
] | 99e2f22d1c94b272184d97dd9d252866409100ab | https://github.com/hashicorp/hcl/blob/99e2f22d1c94b272184d97dd9d252866409100ab/hcl/fmtcmd/fmtcmd.go#L44-L90 | train |
hashicorp/hcl | hcl/token/token.go | String | func (t Type) String() string {
s := ""
if 0 <= t && t < Type(len(tokens)) {
s = tokens[t]
}
if s == "" {
s = "token(" + strconv.Itoa(int(t)) + ")"
}
return s
} | go | func (t Type) String() string {
s := ""
if 0 <= t && t < Type(len(tokens)) {
s = tokens[t]
}
if s == "" {
s = "token(" + strconv.Itoa(int(t)) + ")"
}
return s
} | [
"func",
"(",
"t",
"Type",
")",
"String",
"(",
")",
"string",
"{",
"s",
":=",
"\"",
"\"",
"\n",
"if",
"0",
"<=",
"t",
"&&",
"t",
"<",
"Type",
"(",
"len",
"(",
"tokens",
")",
")",
"{",
"s",
"=",
"tokens",
"[",
"t",
"]",
"\n",
"}",
"\n",
"if",
"s",
"==",
"\"",
"\"",
"{",
"s",
"=",
"\"",
"\"",
"+",
"strconv",
".",
"Itoa",
"(",
"int",
"(",
"t",
")",
")",
"+",
"\"",
"\"",
"\n",
"}",
"\n",
"return",
"s",
"\n",
"}"
] | // String returns the string corresponding to the token tok. | [
"String",
"returns",
"the",
"string",
"corresponding",
"to",
"the",
"token",
"tok",
"."
] | 99e2f22d1c94b272184d97dd9d252866409100ab | https://github.com/hashicorp/hcl/blob/99e2f22d1c94b272184d97dd9d252866409100ab/hcl/token/token.go#L83-L92 | train |
hashicorp/hcl | hcl/token/token.go | String | func (t Token) String() string {
return fmt.Sprintf("%s %s %s", t.Pos.String(), t.Type.String(), t.Text)
} | go | func (t Token) String() string {
return fmt.Sprintf("%s %s %s", t.Pos.String(), t.Type.String(), t.Text)
} | [
"func",
"(",
"t",
"Token",
")",
"String",
"(",
")",
"string",
"{",
"return",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"t",
".",
"Pos",
".",
"String",
"(",
")",
",",
"t",
".",
"Type",
".",
"String",
"(",
")",
",",
"t",
".",
"Text",
")",
"\n",
"}"
] | // String returns the token's literal text. Note that this is only
// applicable for certain token types, such as token.IDENT,
// token.STRING, etc.. | [
"String",
"returns",
"the",
"token",
"s",
"literal",
"text",
".",
"Note",
"that",
"this",
"is",
"only",
"applicable",
"for",
"certain",
"token",
"types",
"such",
"as",
"token",
".",
"IDENT",
"token",
".",
"STRING",
"etc",
".."
] | 99e2f22d1c94b272184d97dd9d252866409100ab | https://github.com/hashicorp/hcl/blob/99e2f22d1c94b272184d97dd9d252866409100ab/hcl/token/token.go#L109-L111 | train |
hashicorp/hcl | hcl/token/token.go | unindentHeredoc | func unindentHeredoc(heredoc string) string {
// We need to find the end of the marker
idx := strings.IndexByte(heredoc, '\n')
if idx == -1 {
panic("heredoc doesn't contain newline")
}
unindent := heredoc[2] == '-'
// We can optimize if the heredoc isn't marked for indentation
if !unindent {
return string(heredoc[idx+1 : len(heredoc)-idx+1])
}
// We need to unindent each line based on the indentation level of the marker
lines := strings.Split(string(heredoc[idx+1:len(heredoc)-idx+2]), "\n")
whitespacePrefix := lines[len(lines)-1]
isIndented := true
for _, v := range lines {
if strings.HasPrefix(v, whitespacePrefix) {
continue
}
isIndented = false
break
}
// If all lines are not at least as indented as the terminating mark, return the
// heredoc as is, but trim the leading space from the marker on the final line.
if !isIndented {
return strings.TrimRight(string(heredoc[idx+1:len(heredoc)-idx+1]), " \t")
}
unindentedLines := make([]string, len(lines))
for k, v := range lines {
if k == len(lines)-1 {
unindentedLines[k] = ""
break
}
unindentedLines[k] = strings.TrimPrefix(v, whitespacePrefix)
}
return strings.Join(unindentedLines, "\n")
} | go | func unindentHeredoc(heredoc string) string {
// We need to find the end of the marker
idx := strings.IndexByte(heredoc, '\n')
if idx == -1 {
panic("heredoc doesn't contain newline")
}
unindent := heredoc[2] == '-'
// We can optimize if the heredoc isn't marked for indentation
if !unindent {
return string(heredoc[idx+1 : len(heredoc)-idx+1])
}
// We need to unindent each line based on the indentation level of the marker
lines := strings.Split(string(heredoc[idx+1:len(heredoc)-idx+2]), "\n")
whitespacePrefix := lines[len(lines)-1]
isIndented := true
for _, v := range lines {
if strings.HasPrefix(v, whitespacePrefix) {
continue
}
isIndented = false
break
}
// If all lines are not at least as indented as the terminating mark, return the
// heredoc as is, but trim the leading space from the marker on the final line.
if !isIndented {
return strings.TrimRight(string(heredoc[idx+1:len(heredoc)-idx+1]), " \t")
}
unindentedLines := make([]string, len(lines))
for k, v := range lines {
if k == len(lines)-1 {
unindentedLines[k] = ""
break
}
unindentedLines[k] = strings.TrimPrefix(v, whitespacePrefix)
}
return strings.Join(unindentedLines, "\n")
} | [
"func",
"unindentHeredoc",
"(",
"heredoc",
"string",
")",
"string",
"{",
"// We need to find the end of the marker",
"idx",
":=",
"strings",
".",
"IndexByte",
"(",
"heredoc",
",",
"'\\n'",
")",
"\n",
"if",
"idx",
"==",
"-",
"1",
"{",
"panic",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"unindent",
":=",
"heredoc",
"[",
"2",
"]",
"==",
"'-'",
"\n\n",
"// We can optimize if the heredoc isn't marked for indentation",
"if",
"!",
"unindent",
"{",
"return",
"string",
"(",
"heredoc",
"[",
"idx",
"+",
"1",
":",
"len",
"(",
"heredoc",
")",
"-",
"idx",
"+",
"1",
"]",
")",
"\n",
"}",
"\n\n",
"// We need to unindent each line based on the indentation level of the marker",
"lines",
":=",
"strings",
".",
"Split",
"(",
"string",
"(",
"heredoc",
"[",
"idx",
"+",
"1",
":",
"len",
"(",
"heredoc",
")",
"-",
"idx",
"+",
"2",
"]",
")",
",",
"\"",
"\\n",
"\"",
")",
"\n",
"whitespacePrefix",
":=",
"lines",
"[",
"len",
"(",
"lines",
")",
"-",
"1",
"]",
"\n\n",
"isIndented",
":=",
"true",
"\n",
"for",
"_",
",",
"v",
":=",
"range",
"lines",
"{",
"if",
"strings",
".",
"HasPrefix",
"(",
"v",
",",
"whitespacePrefix",
")",
"{",
"continue",
"\n",
"}",
"\n\n",
"isIndented",
"=",
"false",
"\n",
"break",
"\n",
"}",
"\n\n",
"// If all lines are not at least as indented as the terminating mark, return the",
"// heredoc as is, but trim the leading space from the marker on the final line.",
"if",
"!",
"isIndented",
"{",
"return",
"strings",
".",
"TrimRight",
"(",
"string",
"(",
"heredoc",
"[",
"idx",
"+",
"1",
":",
"len",
"(",
"heredoc",
")",
"-",
"idx",
"+",
"1",
"]",
")",
",",
"\"",
"\\t",
"\"",
")",
"\n",
"}",
"\n\n",
"unindentedLines",
":=",
"make",
"(",
"[",
"]",
"string",
",",
"len",
"(",
"lines",
")",
")",
"\n",
"for",
"k",
",",
"v",
":=",
"range",
"lines",
"{",
"if",
"k",
"==",
"len",
"(",
"lines",
")",
"-",
"1",
"{",
"unindentedLines",
"[",
"k",
"]",
"=",
"\"",
"\"",
"\n",
"break",
"\n",
"}",
"\n\n",
"unindentedLines",
"[",
"k",
"]",
"=",
"strings",
".",
"TrimPrefix",
"(",
"v",
",",
"whitespacePrefix",
")",
"\n",
"}",
"\n\n",
"return",
"strings",
".",
"Join",
"(",
"unindentedLines",
",",
"\"",
"\\n",
"\"",
")",
"\n",
"}"
] | // unindentHeredoc returns the string content of a HEREDOC if it is started with <<
// and the content of a HEREDOC with the hanging indent removed if it is started with
// a <<-, and the terminating line is at least as indented as the least indented line. | [
"unindentHeredoc",
"returns",
"the",
"string",
"content",
"of",
"a",
"HEREDOC",
"if",
"it",
"is",
"started",
"with",
"<<",
"and",
"the",
"content",
"of",
"a",
"HEREDOC",
"with",
"the",
"hanging",
"indent",
"removed",
"if",
"it",
"is",
"started",
"with",
"a",
"<<",
"-",
"and",
"the",
"terminating",
"line",
"is",
"at",
"least",
"as",
"indented",
"as",
"the",
"least",
"indented",
"line",
"."
] | 99e2f22d1c94b272184d97dd9d252866409100ab | https://github.com/hashicorp/hcl/blob/99e2f22d1c94b272184d97dd9d252866409100ab/hcl/token/token.go#L174-L219 | train |
hashicorp/hcl | hcl/printer/nodes.go | collectComments | func (p *printer) collectComments(node ast.Node) {
// first collect all comments. This is already stored in
// ast.File.(comments)
ast.Walk(node, func(nn ast.Node) (ast.Node, bool) {
switch t := nn.(type) {
case *ast.File:
p.comments = t.Comments
return nn, false
}
return nn, true
})
standaloneComments := make(map[token.Pos]*ast.CommentGroup, 0)
for _, c := range p.comments {
standaloneComments[c.Pos()] = c
}
// next remove all lead and line comments from the overall comment map.
// This will give us comments which are standalone, comments which are not
// assigned to any kind of node.
ast.Walk(node, func(nn ast.Node) (ast.Node, bool) {
switch t := nn.(type) {
case *ast.LiteralType:
if t.LeadComment != nil {
for _, comment := range t.LeadComment.List {
if _, ok := standaloneComments[comment.Pos()]; ok {
delete(standaloneComments, comment.Pos())
}
}
}
if t.LineComment != nil {
for _, comment := range t.LineComment.List {
if _, ok := standaloneComments[comment.Pos()]; ok {
delete(standaloneComments, comment.Pos())
}
}
}
case *ast.ObjectItem:
if t.LeadComment != nil {
for _, comment := range t.LeadComment.List {
if _, ok := standaloneComments[comment.Pos()]; ok {
delete(standaloneComments, comment.Pos())
}
}
}
if t.LineComment != nil {
for _, comment := range t.LineComment.List {
if _, ok := standaloneComments[comment.Pos()]; ok {
delete(standaloneComments, comment.Pos())
}
}
}
}
return nn, true
})
for _, c := range standaloneComments {
p.standaloneComments = append(p.standaloneComments, c)
}
sort.Sort(ByPosition(p.standaloneComments))
} | go | func (p *printer) collectComments(node ast.Node) {
// first collect all comments. This is already stored in
// ast.File.(comments)
ast.Walk(node, func(nn ast.Node) (ast.Node, bool) {
switch t := nn.(type) {
case *ast.File:
p.comments = t.Comments
return nn, false
}
return nn, true
})
standaloneComments := make(map[token.Pos]*ast.CommentGroup, 0)
for _, c := range p.comments {
standaloneComments[c.Pos()] = c
}
// next remove all lead and line comments from the overall comment map.
// This will give us comments which are standalone, comments which are not
// assigned to any kind of node.
ast.Walk(node, func(nn ast.Node) (ast.Node, bool) {
switch t := nn.(type) {
case *ast.LiteralType:
if t.LeadComment != nil {
for _, comment := range t.LeadComment.List {
if _, ok := standaloneComments[comment.Pos()]; ok {
delete(standaloneComments, comment.Pos())
}
}
}
if t.LineComment != nil {
for _, comment := range t.LineComment.List {
if _, ok := standaloneComments[comment.Pos()]; ok {
delete(standaloneComments, comment.Pos())
}
}
}
case *ast.ObjectItem:
if t.LeadComment != nil {
for _, comment := range t.LeadComment.List {
if _, ok := standaloneComments[comment.Pos()]; ok {
delete(standaloneComments, comment.Pos())
}
}
}
if t.LineComment != nil {
for _, comment := range t.LineComment.List {
if _, ok := standaloneComments[comment.Pos()]; ok {
delete(standaloneComments, comment.Pos())
}
}
}
}
return nn, true
})
for _, c := range standaloneComments {
p.standaloneComments = append(p.standaloneComments, c)
}
sort.Sort(ByPosition(p.standaloneComments))
} | [
"func",
"(",
"p",
"*",
"printer",
")",
"collectComments",
"(",
"node",
"ast",
".",
"Node",
")",
"{",
"// first collect all comments. This is already stored in",
"// ast.File.(comments)",
"ast",
".",
"Walk",
"(",
"node",
",",
"func",
"(",
"nn",
"ast",
".",
"Node",
")",
"(",
"ast",
".",
"Node",
",",
"bool",
")",
"{",
"switch",
"t",
":=",
"nn",
".",
"(",
"type",
")",
"{",
"case",
"*",
"ast",
".",
"File",
":",
"p",
".",
"comments",
"=",
"t",
".",
"Comments",
"\n",
"return",
"nn",
",",
"false",
"\n",
"}",
"\n",
"return",
"nn",
",",
"true",
"\n",
"}",
")",
"\n\n",
"standaloneComments",
":=",
"make",
"(",
"map",
"[",
"token",
".",
"Pos",
"]",
"*",
"ast",
".",
"CommentGroup",
",",
"0",
")",
"\n",
"for",
"_",
",",
"c",
":=",
"range",
"p",
".",
"comments",
"{",
"standaloneComments",
"[",
"c",
".",
"Pos",
"(",
")",
"]",
"=",
"c",
"\n",
"}",
"\n\n",
"// next remove all lead and line comments from the overall comment map.",
"// This will give us comments which are standalone, comments which are not",
"// assigned to any kind of node.",
"ast",
".",
"Walk",
"(",
"node",
",",
"func",
"(",
"nn",
"ast",
".",
"Node",
")",
"(",
"ast",
".",
"Node",
",",
"bool",
")",
"{",
"switch",
"t",
":=",
"nn",
".",
"(",
"type",
")",
"{",
"case",
"*",
"ast",
".",
"LiteralType",
":",
"if",
"t",
".",
"LeadComment",
"!=",
"nil",
"{",
"for",
"_",
",",
"comment",
":=",
"range",
"t",
".",
"LeadComment",
".",
"List",
"{",
"if",
"_",
",",
"ok",
":=",
"standaloneComments",
"[",
"comment",
".",
"Pos",
"(",
")",
"]",
";",
"ok",
"{",
"delete",
"(",
"standaloneComments",
",",
"comment",
".",
"Pos",
"(",
")",
")",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n\n",
"if",
"t",
".",
"LineComment",
"!=",
"nil",
"{",
"for",
"_",
",",
"comment",
":=",
"range",
"t",
".",
"LineComment",
".",
"List",
"{",
"if",
"_",
",",
"ok",
":=",
"standaloneComments",
"[",
"comment",
".",
"Pos",
"(",
")",
"]",
";",
"ok",
"{",
"delete",
"(",
"standaloneComments",
",",
"comment",
".",
"Pos",
"(",
")",
")",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n",
"case",
"*",
"ast",
".",
"ObjectItem",
":",
"if",
"t",
".",
"LeadComment",
"!=",
"nil",
"{",
"for",
"_",
",",
"comment",
":=",
"range",
"t",
".",
"LeadComment",
".",
"List",
"{",
"if",
"_",
",",
"ok",
":=",
"standaloneComments",
"[",
"comment",
".",
"Pos",
"(",
")",
"]",
";",
"ok",
"{",
"delete",
"(",
"standaloneComments",
",",
"comment",
".",
"Pos",
"(",
")",
")",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n\n",
"if",
"t",
".",
"LineComment",
"!=",
"nil",
"{",
"for",
"_",
",",
"comment",
":=",
"range",
"t",
".",
"LineComment",
".",
"List",
"{",
"if",
"_",
",",
"ok",
":=",
"standaloneComments",
"[",
"comment",
".",
"Pos",
"(",
")",
"]",
";",
"ok",
"{",
"delete",
"(",
"standaloneComments",
",",
"comment",
".",
"Pos",
"(",
")",
")",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n\n",
"return",
"nn",
",",
"true",
"\n",
"}",
")",
"\n\n",
"for",
"_",
",",
"c",
":=",
"range",
"standaloneComments",
"{",
"p",
".",
"standaloneComments",
"=",
"append",
"(",
"p",
".",
"standaloneComments",
",",
"c",
")",
"\n",
"}",
"\n\n",
"sort",
".",
"Sort",
"(",
"ByPosition",
"(",
"p",
".",
"standaloneComments",
")",
")",
"\n",
"}"
] | // collectComments comments all standalone comments which are not lead or line
// comment | [
"collectComments",
"comments",
"all",
"standalone",
"comments",
"which",
"are",
"not",
"lead",
"or",
"line",
"comment"
] | 99e2f22d1c94b272184d97dd9d252866409100ab | https://github.com/hashicorp/hcl/blob/99e2f22d1c94b272184d97dd9d252866409100ab/hcl/printer/nodes.go#L42-L106 | train |
hashicorp/hcl | hcl/printer/nodes.go | list | func (p *printer) list(l *ast.ListType) []byte {
if p.isSingleLineList(l) {
return p.singleLineList(l)
}
var buf bytes.Buffer
buf.WriteString("[")
buf.WriteByte(newline)
var longestLine int
for _, item := range l.List {
// for now we assume that the list only contains literal types
if lit, ok := item.(*ast.LiteralType); ok {
lineLen := len(lit.Token.Text)
if lineLen > longestLine {
longestLine = lineLen
}
}
}
haveEmptyLine := false
for i, item := range l.List {
// If we have a lead comment, then we want to write that first
leadComment := false
if lit, ok := item.(*ast.LiteralType); ok && lit.LeadComment != nil {
leadComment = true
// Ensure an empty line before every element with a
// lead comment (except the first item in a list).
if !haveEmptyLine && i != 0 {
buf.WriteByte(newline)
}
for _, comment := range lit.LeadComment.List {
buf.Write(p.indent([]byte(comment.Text)))
buf.WriteByte(newline)
}
}
// also indent each line
val := p.output(item)
curLen := len(val)
buf.Write(p.indent(val))
// if this item is a heredoc, then we output the comma on
// the next line. This is the only case this happens.
comma := []byte{','}
if lit, ok := item.(*ast.LiteralType); ok && lit.Token.Type == token.HEREDOC {
buf.WriteByte(newline)
comma = p.indent(comma)
}
buf.Write(comma)
if lit, ok := item.(*ast.LiteralType); ok && lit.LineComment != nil {
// if the next item doesn't have any comments, do not align
buf.WriteByte(blank) // align one space
for i := 0; i < longestLine-curLen; i++ {
buf.WriteByte(blank)
}
for _, comment := range lit.LineComment.List {
buf.WriteString(comment.Text)
}
}
buf.WriteByte(newline)
// Ensure an empty line after every element with a
// lead comment (except the first item in a list).
haveEmptyLine = leadComment && i != len(l.List)-1
if haveEmptyLine {
buf.WriteByte(newline)
}
}
buf.WriteString("]")
return buf.Bytes()
} | go | func (p *printer) list(l *ast.ListType) []byte {
if p.isSingleLineList(l) {
return p.singleLineList(l)
}
var buf bytes.Buffer
buf.WriteString("[")
buf.WriteByte(newline)
var longestLine int
for _, item := range l.List {
// for now we assume that the list only contains literal types
if lit, ok := item.(*ast.LiteralType); ok {
lineLen := len(lit.Token.Text)
if lineLen > longestLine {
longestLine = lineLen
}
}
}
haveEmptyLine := false
for i, item := range l.List {
// If we have a lead comment, then we want to write that first
leadComment := false
if lit, ok := item.(*ast.LiteralType); ok && lit.LeadComment != nil {
leadComment = true
// Ensure an empty line before every element with a
// lead comment (except the first item in a list).
if !haveEmptyLine && i != 0 {
buf.WriteByte(newline)
}
for _, comment := range lit.LeadComment.List {
buf.Write(p.indent([]byte(comment.Text)))
buf.WriteByte(newline)
}
}
// also indent each line
val := p.output(item)
curLen := len(val)
buf.Write(p.indent(val))
// if this item is a heredoc, then we output the comma on
// the next line. This is the only case this happens.
comma := []byte{','}
if lit, ok := item.(*ast.LiteralType); ok && lit.Token.Type == token.HEREDOC {
buf.WriteByte(newline)
comma = p.indent(comma)
}
buf.Write(comma)
if lit, ok := item.(*ast.LiteralType); ok && lit.LineComment != nil {
// if the next item doesn't have any comments, do not align
buf.WriteByte(blank) // align one space
for i := 0; i < longestLine-curLen; i++ {
buf.WriteByte(blank)
}
for _, comment := range lit.LineComment.List {
buf.WriteString(comment.Text)
}
}
buf.WriteByte(newline)
// Ensure an empty line after every element with a
// lead comment (except the first item in a list).
haveEmptyLine = leadComment && i != len(l.List)-1
if haveEmptyLine {
buf.WriteByte(newline)
}
}
buf.WriteString("]")
return buf.Bytes()
} | [
"func",
"(",
"p",
"*",
"printer",
")",
"list",
"(",
"l",
"*",
"ast",
".",
"ListType",
")",
"[",
"]",
"byte",
"{",
"if",
"p",
".",
"isSingleLineList",
"(",
"l",
")",
"{",
"return",
"p",
".",
"singleLineList",
"(",
"l",
")",
"\n",
"}",
"\n\n",
"var",
"buf",
"bytes",
".",
"Buffer",
"\n",
"buf",
".",
"WriteString",
"(",
"\"",
"\"",
")",
"\n",
"buf",
".",
"WriteByte",
"(",
"newline",
")",
"\n\n",
"var",
"longestLine",
"int",
"\n",
"for",
"_",
",",
"item",
":=",
"range",
"l",
".",
"List",
"{",
"// for now we assume that the list only contains literal types",
"if",
"lit",
",",
"ok",
":=",
"item",
".",
"(",
"*",
"ast",
".",
"LiteralType",
")",
";",
"ok",
"{",
"lineLen",
":=",
"len",
"(",
"lit",
".",
"Token",
".",
"Text",
")",
"\n",
"if",
"lineLen",
">",
"longestLine",
"{",
"longestLine",
"=",
"lineLen",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n\n",
"haveEmptyLine",
":=",
"false",
"\n",
"for",
"i",
",",
"item",
":=",
"range",
"l",
".",
"List",
"{",
"// If we have a lead comment, then we want to write that first",
"leadComment",
":=",
"false",
"\n",
"if",
"lit",
",",
"ok",
":=",
"item",
".",
"(",
"*",
"ast",
".",
"LiteralType",
")",
";",
"ok",
"&&",
"lit",
".",
"LeadComment",
"!=",
"nil",
"{",
"leadComment",
"=",
"true",
"\n\n",
"// Ensure an empty line before every element with a",
"// lead comment (except the first item in a list).",
"if",
"!",
"haveEmptyLine",
"&&",
"i",
"!=",
"0",
"{",
"buf",
".",
"WriteByte",
"(",
"newline",
")",
"\n",
"}",
"\n\n",
"for",
"_",
",",
"comment",
":=",
"range",
"lit",
".",
"LeadComment",
".",
"List",
"{",
"buf",
".",
"Write",
"(",
"p",
".",
"indent",
"(",
"[",
"]",
"byte",
"(",
"comment",
".",
"Text",
")",
")",
")",
"\n",
"buf",
".",
"WriteByte",
"(",
"newline",
")",
"\n",
"}",
"\n",
"}",
"\n\n",
"// also indent each line",
"val",
":=",
"p",
".",
"output",
"(",
"item",
")",
"\n",
"curLen",
":=",
"len",
"(",
"val",
")",
"\n",
"buf",
".",
"Write",
"(",
"p",
".",
"indent",
"(",
"val",
")",
")",
"\n\n",
"// if this item is a heredoc, then we output the comma on",
"// the next line. This is the only case this happens.",
"comma",
":=",
"[",
"]",
"byte",
"{",
"','",
"}",
"\n",
"if",
"lit",
",",
"ok",
":=",
"item",
".",
"(",
"*",
"ast",
".",
"LiteralType",
")",
";",
"ok",
"&&",
"lit",
".",
"Token",
".",
"Type",
"==",
"token",
".",
"HEREDOC",
"{",
"buf",
".",
"WriteByte",
"(",
"newline",
")",
"\n",
"comma",
"=",
"p",
".",
"indent",
"(",
"comma",
")",
"\n",
"}",
"\n\n",
"buf",
".",
"Write",
"(",
"comma",
")",
"\n\n",
"if",
"lit",
",",
"ok",
":=",
"item",
".",
"(",
"*",
"ast",
".",
"LiteralType",
")",
";",
"ok",
"&&",
"lit",
".",
"LineComment",
"!=",
"nil",
"{",
"// if the next item doesn't have any comments, do not align",
"buf",
".",
"WriteByte",
"(",
"blank",
")",
"// align one space",
"\n",
"for",
"i",
":=",
"0",
";",
"i",
"<",
"longestLine",
"-",
"curLen",
";",
"i",
"++",
"{",
"buf",
".",
"WriteByte",
"(",
"blank",
")",
"\n",
"}",
"\n\n",
"for",
"_",
",",
"comment",
":=",
"range",
"lit",
".",
"LineComment",
".",
"List",
"{",
"buf",
".",
"WriteString",
"(",
"comment",
".",
"Text",
")",
"\n",
"}",
"\n",
"}",
"\n\n",
"buf",
".",
"WriteByte",
"(",
"newline",
")",
"\n\n",
"// Ensure an empty line after every element with a",
"// lead comment (except the first item in a list).",
"haveEmptyLine",
"=",
"leadComment",
"&&",
"i",
"!=",
"len",
"(",
"l",
".",
"List",
")",
"-",
"1",
"\n",
"if",
"haveEmptyLine",
"{",
"buf",
".",
"WriteByte",
"(",
"newline",
")",
"\n",
"}",
"\n",
"}",
"\n\n",
"buf",
".",
"WriteString",
"(",
"\"",
"\"",
")",
"\n",
"return",
"buf",
".",
"Bytes",
"(",
")",
"\n",
"}"
] | // list returns the printable HCL form of an list type. | [
"list",
"returns",
"the",
"printable",
"HCL",
"form",
"of",
"an",
"list",
"type",
"."
] | 99e2f22d1c94b272184d97dd9d252866409100ab | https://github.com/hashicorp/hcl/blob/99e2f22d1c94b272184d97dd9d252866409100ab/hcl/printer/nodes.go#L519-L597 | train |
hashicorp/hcl | hcl/printer/nodes.go | singleLineList | func (p *printer) singleLineList(l *ast.ListType) []byte {
buf := &bytes.Buffer{}
buf.WriteString("[")
for i, item := range l.List {
if i != 0 {
buf.WriteString(", ")
}
// Output the item itself
buf.Write(p.output(item))
// The heredoc marker needs to be at the end of line.
if lit, ok := item.(*ast.LiteralType); ok && lit.Token.Type == token.HEREDOC {
buf.WriteByte(newline)
}
}
buf.WriteString("]")
return buf.Bytes()
} | go | func (p *printer) singleLineList(l *ast.ListType) []byte {
buf := &bytes.Buffer{}
buf.WriteString("[")
for i, item := range l.List {
if i != 0 {
buf.WriteString(", ")
}
// Output the item itself
buf.Write(p.output(item))
// The heredoc marker needs to be at the end of line.
if lit, ok := item.(*ast.LiteralType); ok && lit.Token.Type == token.HEREDOC {
buf.WriteByte(newline)
}
}
buf.WriteString("]")
return buf.Bytes()
} | [
"func",
"(",
"p",
"*",
"printer",
")",
"singleLineList",
"(",
"l",
"*",
"ast",
".",
"ListType",
")",
"[",
"]",
"byte",
"{",
"buf",
":=",
"&",
"bytes",
".",
"Buffer",
"{",
"}",
"\n\n",
"buf",
".",
"WriteString",
"(",
"\"",
"\"",
")",
"\n",
"for",
"i",
",",
"item",
":=",
"range",
"l",
".",
"List",
"{",
"if",
"i",
"!=",
"0",
"{",
"buf",
".",
"WriteString",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"// Output the item itself",
"buf",
".",
"Write",
"(",
"p",
".",
"output",
"(",
"item",
")",
")",
"\n\n",
"// The heredoc marker needs to be at the end of line.",
"if",
"lit",
",",
"ok",
":=",
"item",
".",
"(",
"*",
"ast",
".",
"LiteralType",
")",
";",
"ok",
"&&",
"lit",
".",
"Token",
".",
"Type",
"==",
"token",
".",
"HEREDOC",
"{",
"buf",
".",
"WriteByte",
"(",
"newline",
")",
"\n",
"}",
"\n",
"}",
"\n\n",
"buf",
".",
"WriteString",
"(",
"\"",
"\"",
")",
"\n",
"return",
"buf",
".",
"Bytes",
"(",
")",
"\n",
"}"
] | // singleLineList prints a simple single line list.
// For a definition of "simple", see isSingleLineList above. | [
"singleLineList",
"prints",
"a",
"simple",
"single",
"line",
"list",
".",
"For",
"a",
"definition",
"of",
"simple",
"see",
"isSingleLineList",
"above",
"."
] | 99e2f22d1c94b272184d97dd9d252866409100ab | https://github.com/hashicorp/hcl/blob/99e2f22d1c94b272184d97dd9d252866409100ab/hcl/printer/nodes.go#L629-L649 | train |
hashicorp/hcl | hcl/printer/nodes.go | indent | func (p *printer) indent(buf []byte) []byte {
var prefix []byte
if p.cfg.SpacesWidth != 0 {
for i := 0; i < p.cfg.SpacesWidth; i++ {
prefix = append(prefix, blank)
}
} else {
prefix = []byte{tab}
}
var res []byte
bol := true
for _, c := range buf {
if bol && c != '\n' {
res = append(res, prefix...)
}
res = append(res, c)
bol = c == '\n'
}
return res
} | go | func (p *printer) indent(buf []byte) []byte {
var prefix []byte
if p.cfg.SpacesWidth != 0 {
for i := 0; i < p.cfg.SpacesWidth; i++ {
prefix = append(prefix, blank)
}
} else {
prefix = []byte{tab}
}
var res []byte
bol := true
for _, c := range buf {
if bol && c != '\n' {
res = append(res, prefix...)
}
res = append(res, c)
bol = c == '\n'
}
return res
} | [
"func",
"(",
"p",
"*",
"printer",
")",
"indent",
"(",
"buf",
"[",
"]",
"byte",
")",
"[",
"]",
"byte",
"{",
"var",
"prefix",
"[",
"]",
"byte",
"\n",
"if",
"p",
".",
"cfg",
".",
"SpacesWidth",
"!=",
"0",
"{",
"for",
"i",
":=",
"0",
";",
"i",
"<",
"p",
".",
"cfg",
".",
"SpacesWidth",
";",
"i",
"++",
"{",
"prefix",
"=",
"append",
"(",
"prefix",
",",
"blank",
")",
"\n",
"}",
"\n",
"}",
"else",
"{",
"prefix",
"=",
"[",
"]",
"byte",
"{",
"tab",
"}",
"\n",
"}",
"\n\n",
"var",
"res",
"[",
"]",
"byte",
"\n",
"bol",
":=",
"true",
"\n",
"for",
"_",
",",
"c",
":=",
"range",
"buf",
"{",
"if",
"bol",
"&&",
"c",
"!=",
"'\\n'",
"{",
"res",
"=",
"append",
"(",
"res",
",",
"prefix",
"...",
")",
"\n",
"}",
"\n\n",
"res",
"=",
"append",
"(",
"res",
",",
"c",
")",
"\n",
"bol",
"=",
"c",
"==",
"'\\n'",
"\n",
"}",
"\n",
"return",
"res",
"\n",
"}"
] | // indent indents the lines of the given buffer for each non-empty line | [
"indent",
"indents",
"the",
"lines",
"of",
"the",
"given",
"buffer",
"for",
"each",
"non",
"-",
"empty",
"line"
] | 99e2f22d1c94b272184d97dd9d252866409100ab | https://github.com/hashicorp/hcl/blob/99e2f22d1c94b272184d97dd9d252866409100ab/hcl/printer/nodes.go#L652-L673 | train |
hashicorp/hcl | hcl/printer/nodes.go | unindent | func (p *printer) unindent(buf []byte) []byte {
var res []byte
for i := 0; i < len(buf); i++ {
skip := len(buf)-i <= len(unindent)
if !skip {
skip = !bytes.Equal(unindent, buf[i:i+len(unindent)])
}
if skip {
res = append(res, buf[i])
continue
}
// We have a marker. we have to backtrace here and clean out
// any whitespace ahead of our tombstone up to a \n
for j := len(res) - 1; j >= 0; j-- {
if res[j] == '\n' {
break
}
res = res[:j]
}
// Skip the entire unindent marker
i += len(unindent) - 1
}
return res
} | go | func (p *printer) unindent(buf []byte) []byte {
var res []byte
for i := 0; i < len(buf); i++ {
skip := len(buf)-i <= len(unindent)
if !skip {
skip = !bytes.Equal(unindent, buf[i:i+len(unindent)])
}
if skip {
res = append(res, buf[i])
continue
}
// We have a marker. we have to backtrace here and clean out
// any whitespace ahead of our tombstone up to a \n
for j := len(res) - 1; j >= 0; j-- {
if res[j] == '\n' {
break
}
res = res[:j]
}
// Skip the entire unindent marker
i += len(unindent) - 1
}
return res
} | [
"func",
"(",
"p",
"*",
"printer",
")",
"unindent",
"(",
"buf",
"[",
"]",
"byte",
")",
"[",
"]",
"byte",
"{",
"var",
"res",
"[",
"]",
"byte",
"\n",
"for",
"i",
":=",
"0",
";",
"i",
"<",
"len",
"(",
"buf",
")",
";",
"i",
"++",
"{",
"skip",
":=",
"len",
"(",
"buf",
")",
"-",
"i",
"<=",
"len",
"(",
"unindent",
")",
"\n",
"if",
"!",
"skip",
"{",
"skip",
"=",
"!",
"bytes",
".",
"Equal",
"(",
"unindent",
",",
"buf",
"[",
"i",
":",
"i",
"+",
"len",
"(",
"unindent",
")",
"]",
")",
"\n",
"}",
"\n",
"if",
"skip",
"{",
"res",
"=",
"append",
"(",
"res",
",",
"buf",
"[",
"i",
"]",
")",
"\n",
"continue",
"\n",
"}",
"\n\n",
"// We have a marker. we have to backtrace here and clean out",
"// any whitespace ahead of our tombstone up to a \\n",
"for",
"j",
":=",
"len",
"(",
"res",
")",
"-",
"1",
";",
"j",
">=",
"0",
";",
"j",
"--",
"{",
"if",
"res",
"[",
"j",
"]",
"==",
"'\\n'",
"{",
"break",
"\n",
"}",
"\n\n",
"res",
"=",
"res",
"[",
":",
"j",
"]",
"\n",
"}",
"\n\n",
"// Skip the entire unindent marker",
"i",
"+=",
"len",
"(",
"unindent",
")",
"-",
"1",
"\n",
"}",
"\n\n",
"return",
"res",
"\n",
"}"
] | // unindent removes all the indentation from the tombstoned lines | [
"unindent",
"removes",
"all",
"the",
"indentation",
"from",
"the",
"tombstoned",
"lines"
] | 99e2f22d1c94b272184d97dd9d252866409100ab | https://github.com/hashicorp/hcl/blob/99e2f22d1c94b272184d97dd9d252866409100ab/hcl/printer/nodes.go#L676-L703 | train |
hashicorp/hcl | hcl/printer/nodes.go | heredocIndent | func (p *printer) heredocIndent(buf []byte) []byte {
var res []byte
bol := false
for _, c := range buf {
if bol && c != '\n' {
res = append(res, unindent...)
}
res = append(res, c)
bol = c == '\n'
}
return res
} | go | func (p *printer) heredocIndent(buf []byte) []byte {
var res []byte
bol := false
for _, c := range buf {
if bol && c != '\n' {
res = append(res, unindent...)
}
res = append(res, c)
bol = c == '\n'
}
return res
} | [
"func",
"(",
"p",
"*",
"printer",
")",
"heredocIndent",
"(",
"buf",
"[",
"]",
"byte",
")",
"[",
"]",
"byte",
"{",
"var",
"res",
"[",
"]",
"byte",
"\n",
"bol",
":=",
"false",
"\n",
"for",
"_",
",",
"c",
":=",
"range",
"buf",
"{",
"if",
"bol",
"&&",
"c",
"!=",
"'\\n'",
"{",
"res",
"=",
"append",
"(",
"res",
",",
"unindent",
"...",
")",
"\n",
"}",
"\n",
"res",
"=",
"append",
"(",
"res",
",",
"c",
")",
"\n",
"bol",
"=",
"c",
"==",
"'\\n'",
"\n",
"}",
"\n",
"return",
"res",
"\n",
"}"
] | // heredocIndent marks all the 2nd and further lines as unindentable | [
"heredocIndent",
"marks",
"all",
"the",
"2nd",
"and",
"further",
"lines",
"as",
"unindentable"
] | 99e2f22d1c94b272184d97dd9d252866409100ab | https://github.com/hashicorp/hcl/blob/99e2f22d1c94b272184d97dd9d252866409100ab/hcl/printer/nodes.go#L706-L717 | train |
hashicorp/hcl | json/parser/flatten.go | flattenObjects | func flattenObjects(node ast.Node) {
ast.Walk(node, func(n ast.Node) (ast.Node, bool) {
// We only care about lists, because this is what we modify
list, ok := n.(*ast.ObjectList)
if !ok {
return n, true
}
// Rebuild the item list
items := make([]*ast.ObjectItem, 0, len(list.Items))
frontier := make([]*ast.ObjectItem, len(list.Items))
copy(frontier, list.Items)
for len(frontier) > 0 {
// Pop the current item
n := len(frontier)
item := frontier[n-1]
frontier = frontier[:n-1]
switch v := item.Val.(type) {
case *ast.ObjectType:
items, frontier = flattenObjectType(v, item, items, frontier)
case *ast.ListType:
items, frontier = flattenListType(v, item, items, frontier)
default:
items = append(items, item)
}
}
// Reverse the list since the frontier model runs things backwards
for i := len(items)/2 - 1; i >= 0; i-- {
opp := len(items) - 1 - i
items[i], items[opp] = items[opp], items[i]
}
// Done! Set the original items
list.Items = items
return n, true
})
} | go | func flattenObjects(node ast.Node) {
ast.Walk(node, func(n ast.Node) (ast.Node, bool) {
// We only care about lists, because this is what we modify
list, ok := n.(*ast.ObjectList)
if !ok {
return n, true
}
// Rebuild the item list
items := make([]*ast.ObjectItem, 0, len(list.Items))
frontier := make([]*ast.ObjectItem, len(list.Items))
copy(frontier, list.Items)
for len(frontier) > 0 {
// Pop the current item
n := len(frontier)
item := frontier[n-1]
frontier = frontier[:n-1]
switch v := item.Val.(type) {
case *ast.ObjectType:
items, frontier = flattenObjectType(v, item, items, frontier)
case *ast.ListType:
items, frontier = flattenListType(v, item, items, frontier)
default:
items = append(items, item)
}
}
// Reverse the list since the frontier model runs things backwards
for i := len(items)/2 - 1; i >= 0; i-- {
opp := len(items) - 1 - i
items[i], items[opp] = items[opp], items[i]
}
// Done! Set the original items
list.Items = items
return n, true
})
} | [
"func",
"flattenObjects",
"(",
"node",
"ast",
".",
"Node",
")",
"{",
"ast",
".",
"Walk",
"(",
"node",
",",
"func",
"(",
"n",
"ast",
".",
"Node",
")",
"(",
"ast",
".",
"Node",
",",
"bool",
")",
"{",
"// We only care about lists, because this is what we modify",
"list",
",",
"ok",
":=",
"n",
".",
"(",
"*",
"ast",
".",
"ObjectList",
")",
"\n",
"if",
"!",
"ok",
"{",
"return",
"n",
",",
"true",
"\n",
"}",
"\n\n",
"// Rebuild the item list",
"items",
":=",
"make",
"(",
"[",
"]",
"*",
"ast",
".",
"ObjectItem",
",",
"0",
",",
"len",
"(",
"list",
".",
"Items",
")",
")",
"\n",
"frontier",
":=",
"make",
"(",
"[",
"]",
"*",
"ast",
".",
"ObjectItem",
",",
"len",
"(",
"list",
".",
"Items",
")",
")",
"\n",
"copy",
"(",
"frontier",
",",
"list",
".",
"Items",
")",
"\n",
"for",
"len",
"(",
"frontier",
")",
">",
"0",
"{",
"// Pop the current item",
"n",
":=",
"len",
"(",
"frontier",
")",
"\n",
"item",
":=",
"frontier",
"[",
"n",
"-",
"1",
"]",
"\n",
"frontier",
"=",
"frontier",
"[",
":",
"n",
"-",
"1",
"]",
"\n\n",
"switch",
"v",
":=",
"item",
".",
"Val",
".",
"(",
"type",
")",
"{",
"case",
"*",
"ast",
".",
"ObjectType",
":",
"items",
",",
"frontier",
"=",
"flattenObjectType",
"(",
"v",
",",
"item",
",",
"items",
",",
"frontier",
")",
"\n",
"case",
"*",
"ast",
".",
"ListType",
":",
"items",
",",
"frontier",
"=",
"flattenListType",
"(",
"v",
",",
"item",
",",
"items",
",",
"frontier",
")",
"\n",
"default",
":",
"items",
"=",
"append",
"(",
"items",
",",
"item",
")",
"\n",
"}",
"\n",
"}",
"\n\n",
"// Reverse the list since the frontier model runs things backwards",
"for",
"i",
":=",
"len",
"(",
"items",
")",
"/",
"2",
"-",
"1",
";",
"i",
">=",
"0",
";",
"i",
"--",
"{",
"opp",
":=",
"len",
"(",
"items",
")",
"-",
"1",
"-",
"i",
"\n",
"items",
"[",
"i",
"]",
",",
"items",
"[",
"opp",
"]",
"=",
"items",
"[",
"opp",
"]",
",",
"items",
"[",
"i",
"]",
"\n",
"}",
"\n\n",
"// Done! Set the original items",
"list",
".",
"Items",
"=",
"items",
"\n",
"return",
"n",
",",
"true",
"\n",
"}",
")",
"\n",
"}"
] | // flattenObjects takes an AST node, walks it, and flattens | [
"flattenObjects",
"takes",
"an",
"AST",
"node",
"walks",
"it",
"and",
"flattens"
] | 99e2f22d1c94b272184d97dd9d252866409100ab | https://github.com/hashicorp/hcl/blob/99e2f22d1c94b272184d97dd9d252866409100ab/json/parser/flatten.go#L6-L44 | train |
hashicorp/hcl | lex.go | lexMode | func lexMode(v []byte) lexModeValue {
var (
r rune
w int
offset int
)
for {
r, w = utf8.DecodeRune(v[offset:])
offset += w
if unicode.IsSpace(r) {
continue
}
if r == '{' {
return lexModeJson
}
break
}
return lexModeHcl
} | go | func lexMode(v []byte) lexModeValue {
var (
r rune
w int
offset int
)
for {
r, w = utf8.DecodeRune(v[offset:])
offset += w
if unicode.IsSpace(r) {
continue
}
if r == '{' {
return lexModeJson
}
break
}
return lexModeHcl
} | [
"func",
"lexMode",
"(",
"v",
"[",
"]",
"byte",
")",
"lexModeValue",
"{",
"var",
"(",
"r",
"rune",
"\n",
"w",
"int",
"\n",
"offset",
"int",
"\n",
")",
"\n\n",
"for",
"{",
"r",
",",
"w",
"=",
"utf8",
".",
"DecodeRune",
"(",
"v",
"[",
"offset",
":",
"]",
")",
"\n",
"offset",
"+=",
"w",
"\n",
"if",
"unicode",
".",
"IsSpace",
"(",
"r",
")",
"{",
"continue",
"\n",
"}",
"\n",
"if",
"r",
"==",
"'{'",
"{",
"return",
"lexModeJson",
"\n",
"}",
"\n",
"break",
"\n",
"}",
"\n\n",
"return",
"lexModeHcl",
"\n",
"}"
] | // lexMode returns whether we're going to be parsing in JSON
// mode or HCL mode. | [
"lexMode",
"returns",
"whether",
"we",
"re",
"going",
"to",
"be",
"parsing",
"in",
"JSON",
"mode",
"or",
"HCL",
"mode",
"."
] | 99e2f22d1c94b272184d97dd9d252866409100ab | https://github.com/hashicorp/hcl/blob/99e2f22d1c94b272184d97dd9d252866409100ab/lex.go#L18-L38 | train |
hashicorp/hcl | hcl/printer/printer.go | Fprint | func Fprint(output io.Writer, node ast.Node) error {
return DefaultConfig.Fprint(output, node)
} | go | func Fprint(output io.Writer, node ast.Node) error {
return DefaultConfig.Fprint(output, node)
} | [
"func",
"Fprint",
"(",
"output",
"io",
".",
"Writer",
",",
"node",
"ast",
".",
"Node",
")",
"error",
"{",
"return",
"DefaultConfig",
".",
"Fprint",
"(",
"output",
",",
"node",
")",
"\n",
"}"
] | // Fprint "pretty-prints" an HCL node to output
// It calls Config.Fprint with default settings. | [
"Fprint",
"pretty",
"-",
"prints",
"an",
"HCL",
"node",
"to",
"output",
"It",
"calls",
"Config",
".",
"Fprint",
"with",
"default",
"settings",
"."
] | 99e2f22d1c94b272184d97dd9d252866409100ab | https://github.com/hashicorp/hcl/blob/99e2f22d1c94b272184d97dd9d252866409100ab/hcl/printer/printer.go#L47-L49 | train |
hashicorp/hcl | hcl/printer/printer.go | Format | func Format(src []byte) ([]byte, error) {
node, err := parser.Parse(src)
if err != nil {
return nil, err
}
var buf bytes.Buffer
if err := DefaultConfig.Fprint(&buf, node); err != nil {
return nil, err
}
// Add trailing newline to result
buf.WriteString("\n")
return buf.Bytes(), nil
} | go | func Format(src []byte) ([]byte, error) {
node, err := parser.Parse(src)
if err != nil {
return nil, err
}
var buf bytes.Buffer
if err := DefaultConfig.Fprint(&buf, node); err != nil {
return nil, err
}
// Add trailing newline to result
buf.WriteString("\n")
return buf.Bytes(), nil
} | [
"func",
"Format",
"(",
"src",
"[",
"]",
"byte",
")",
"(",
"[",
"]",
"byte",
",",
"error",
")",
"{",
"node",
",",
"err",
":=",
"parser",
".",
"Parse",
"(",
"src",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"var",
"buf",
"bytes",
".",
"Buffer",
"\n",
"if",
"err",
":=",
"DefaultConfig",
".",
"Fprint",
"(",
"&",
"buf",
",",
"node",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"// Add trailing newline to result",
"buf",
".",
"WriteString",
"(",
"\"",
"\\n",
"\"",
")",
"\n",
"return",
"buf",
".",
"Bytes",
"(",
")",
",",
"nil",
"\n",
"}"
] | // Format formats src HCL and returns the result. | [
"Format",
"formats",
"src",
"HCL",
"and",
"returns",
"the",
"result",
"."
] | 99e2f22d1c94b272184d97dd9d252866409100ab | https://github.com/hashicorp/hcl/blob/99e2f22d1c94b272184d97dd9d252866409100ab/hcl/printer/printer.go#L52-L66 | train |
hashicorp/hcl | json/token/token.go | HCLToken | func (t Token) HCLToken() hcltoken.Token {
switch t.Type {
case BOOL:
return hcltoken.Token{Type: hcltoken.BOOL, Text: t.Text}
case FLOAT:
return hcltoken.Token{Type: hcltoken.FLOAT, Text: t.Text}
case NULL:
return hcltoken.Token{Type: hcltoken.STRING, Text: ""}
case NUMBER:
return hcltoken.Token{Type: hcltoken.NUMBER, Text: t.Text}
case STRING:
return hcltoken.Token{Type: hcltoken.STRING, Text: t.Text, JSON: true}
default:
panic(fmt.Sprintf("unimplemented HCLToken for type: %s", t.Type))
}
} | go | func (t Token) HCLToken() hcltoken.Token {
switch t.Type {
case BOOL:
return hcltoken.Token{Type: hcltoken.BOOL, Text: t.Text}
case FLOAT:
return hcltoken.Token{Type: hcltoken.FLOAT, Text: t.Text}
case NULL:
return hcltoken.Token{Type: hcltoken.STRING, Text: ""}
case NUMBER:
return hcltoken.Token{Type: hcltoken.NUMBER, Text: t.Text}
case STRING:
return hcltoken.Token{Type: hcltoken.STRING, Text: t.Text, JSON: true}
default:
panic(fmt.Sprintf("unimplemented HCLToken for type: %s", t.Type))
}
} | [
"func",
"(",
"t",
"Token",
")",
"HCLToken",
"(",
")",
"hcltoken",
".",
"Token",
"{",
"switch",
"t",
".",
"Type",
"{",
"case",
"BOOL",
":",
"return",
"hcltoken",
".",
"Token",
"{",
"Type",
":",
"hcltoken",
".",
"BOOL",
",",
"Text",
":",
"t",
".",
"Text",
"}",
"\n",
"case",
"FLOAT",
":",
"return",
"hcltoken",
".",
"Token",
"{",
"Type",
":",
"hcltoken",
".",
"FLOAT",
",",
"Text",
":",
"t",
".",
"Text",
"}",
"\n",
"case",
"NULL",
":",
"return",
"hcltoken",
".",
"Token",
"{",
"Type",
":",
"hcltoken",
".",
"STRING",
",",
"Text",
":",
"\"",
"\"",
"}",
"\n",
"case",
"NUMBER",
":",
"return",
"hcltoken",
".",
"Token",
"{",
"Type",
":",
"hcltoken",
".",
"NUMBER",
",",
"Text",
":",
"t",
".",
"Text",
"}",
"\n",
"case",
"STRING",
":",
"return",
"hcltoken",
".",
"Token",
"{",
"Type",
":",
"hcltoken",
".",
"STRING",
",",
"Text",
":",
"t",
".",
"Text",
",",
"JSON",
":",
"true",
"}",
"\n",
"default",
":",
"panic",
"(",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"t",
".",
"Type",
")",
")",
"\n",
"}",
"\n",
"}"
] | // HCLToken converts this token to an HCL token.
//
// The token type must be a literal type or this will panic. | [
"HCLToken",
"converts",
"this",
"token",
"to",
"an",
"HCL",
"token",
".",
"The",
"token",
"type",
"must",
"be",
"a",
"literal",
"type",
"or",
"this",
"will",
"panic",
"."
] | 99e2f22d1c94b272184d97dd9d252866409100ab | https://github.com/hashicorp/hcl/blob/99e2f22d1c94b272184d97dd9d252866409100ab/json/token/token.go#L103-L118 | train |
42wim/matterbridge | bridge/bridge.go | SetChannelMembers | func (b *Bridge) SetChannelMembers(newMembers *config.ChannelMembers) {
b.Lock()
b.ChannelMembers = newMembers
b.Unlock()
} | go | func (b *Bridge) SetChannelMembers(newMembers *config.ChannelMembers) {
b.Lock()
b.ChannelMembers = newMembers
b.Unlock()
} | [
"func",
"(",
"b",
"*",
"Bridge",
")",
"SetChannelMembers",
"(",
"newMembers",
"*",
"config",
".",
"ChannelMembers",
")",
"{",
"b",
".",
"Lock",
"(",
")",
"\n",
"b",
".",
"ChannelMembers",
"=",
"newMembers",
"\n",
"b",
".",
"Unlock",
"(",
")",
"\n",
"}"
] | // SetChannelMembers sets the newMembers to the bridge ChannelMembers | [
"SetChannelMembers",
"sets",
"the",
"newMembers",
"to",
"the",
"bridge",
"ChannelMembers"
] | 1b2feb19e506bc24580d5d61422d0de68349c24e | https://github.com/42wim/matterbridge/blob/1b2feb19e506bc24580d5d61422d0de68349c24e/bridge/bridge.go#L62-L66 | train |
42wim/matterbridge | hook/rockethook/rockethook.go | New | func New(url string, config Config) *Client {
c := &Client{In: make(chan Message), Config: config}
tr := &http.Transport{
TLSClientConfig: &tls.Config{InsecureSkipVerify: config.InsecureSkipVerify}, //nolint:gosec
}
c.httpclient = &http.Client{Transport: tr}
_, _, err := net.SplitHostPort(c.BindAddress)
if err != nil {
log.Fatalf("incorrect bindaddress %s", c.BindAddress)
}
go c.StartServer()
return c
} | go | func New(url string, config Config) *Client {
c := &Client{In: make(chan Message), Config: config}
tr := &http.Transport{
TLSClientConfig: &tls.Config{InsecureSkipVerify: config.InsecureSkipVerify}, //nolint:gosec
}
c.httpclient = &http.Client{Transport: tr}
_, _, err := net.SplitHostPort(c.BindAddress)
if err != nil {
log.Fatalf("incorrect bindaddress %s", c.BindAddress)
}
go c.StartServer()
return c
} | [
"func",
"New",
"(",
"url",
"string",
",",
"config",
"Config",
")",
"*",
"Client",
"{",
"c",
":=",
"&",
"Client",
"{",
"In",
":",
"make",
"(",
"chan",
"Message",
")",
",",
"Config",
":",
"config",
"}",
"\n",
"tr",
":=",
"&",
"http",
".",
"Transport",
"{",
"TLSClientConfig",
":",
"&",
"tls",
".",
"Config",
"{",
"InsecureSkipVerify",
":",
"config",
".",
"InsecureSkipVerify",
"}",
",",
"//nolint:gosec",
"}",
"\n",
"c",
".",
"httpclient",
"=",
"&",
"http",
".",
"Client",
"{",
"Transport",
":",
"tr",
"}",
"\n",
"_",
",",
"_",
",",
"err",
":=",
"net",
".",
"SplitHostPort",
"(",
"c",
".",
"BindAddress",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"log",
".",
"Fatalf",
"(",
"\"",
"\"",
",",
"c",
".",
"BindAddress",
")",
"\n",
"}",
"\n",
"go",
"c",
".",
"StartServer",
"(",
")",
"\n",
"return",
"c",
"\n",
"}"
] | // New Rocketchat client. | [
"New",
"Rocketchat",
"client",
"."
] | 1b2feb19e506bc24580d5d61422d0de68349c24e | https://github.com/42wim/matterbridge/blob/1b2feb19e506bc24580d5d61422d0de68349c24e/hook/rockethook/rockethook.go#L38-L50 | train |
42wim/matterbridge | matterclient/users.go | GetTeamName | func (m *MMClient) GetTeamName(teamId string) string { //nolint:golint
m.RLock()
defer m.RUnlock()
for _, t := range m.OtherTeams {
if t.Id == teamId {
return t.Team.Name
}
}
return ""
} | go | func (m *MMClient) GetTeamName(teamId string) string { //nolint:golint
m.RLock()
defer m.RUnlock()
for _, t := range m.OtherTeams {
if t.Id == teamId {
return t.Team.Name
}
}
return ""
} | [
"func",
"(",
"m",
"*",
"MMClient",
")",
"GetTeamName",
"(",
"teamId",
"string",
")",
"string",
"{",
"//nolint:golint",
"m",
".",
"RLock",
"(",
")",
"\n",
"defer",
"m",
".",
"RUnlock",
"(",
")",
"\n",
"for",
"_",
",",
"t",
":=",
"range",
"m",
".",
"OtherTeams",
"{",
"if",
"t",
".",
"Id",
"==",
"teamId",
"{",
"return",
"t",
".",
"Team",
".",
"Name",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"\"",
"\"",
"\n",
"}"
] | // GetTeamName returns the name of the specified teamId | [
"GetTeamName",
"returns",
"the",
"name",
"of",
"the",
"specified",
"teamId"
] | 1b2feb19e506bc24580d5d61422d0de68349c24e | https://github.com/42wim/matterbridge/blob/1b2feb19e506bc24580d5d61422d0de68349c24e/matterclient/users.go#L59-L68 | train |
42wim/matterbridge | bridge/telegram/handlers.go | handleChannels | func (b *Btelegram) handleChannels(rmsg *config.Message, message *tgbotapi.Message, update tgbotapi.Update) *tgbotapi.Message {
return b.handleUpdate(rmsg, message, update.ChannelPost, update.EditedChannelPost)
} | go | func (b *Btelegram) handleChannels(rmsg *config.Message, message *tgbotapi.Message, update tgbotapi.Update) *tgbotapi.Message {
return b.handleUpdate(rmsg, message, update.ChannelPost, update.EditedChannelPost)
} | [
"func",
"(",
"b",
"*",
"Btelegram",
")",
"handleChannels",
"(",
"rmsg",
"*",
"config",
".",
"Message",
",",
"message",
"*",
"tgbotapi",
".",
"Message",
",",
"update",
"tgbotapi",
".",
"Update",
")",
"*",
"tgbotapi",
".",
"Message",
"{",
"return",
"b",
".",
"handleUpdate",
"(",
"rmsg",
",",
"message",
",",
"update",
".",
"ChannelPost",
",",
"update",
".",
"EditedChannelPost",
")",
"\n",
"}"
] | // handleChannels checks if it's a channel message and if the message is a new or edited messages | [
"handleChannels",
"checks",
"if",
"it",
"s",
"a",
"channel",
"message",
"and",
"if",
"the",
"message",
"is",
"a",
"new",
"or",
"edited",
"messages"
] | 1b2feb19e506bc24580d5d61422d0de68349c24e | https://github.com/42wim/matterbridge/blob/1b2feb19e506bc24580d5d61422d0de68349c24e/bridge/telegram/handlers.go#L30-L32 | train |
42wim/matterbridge | bridge/telegram/handlers.go | handleGroups | func (b *Btelegram) handleGroups(rmsg *config.Message, message *tgbotapi.Message, update tgbotapi.Update) *tgbotapi.Message {
return b.handleUpdate(rmsg, message, update.Message, update.EditedMessage)
} | go | func (b *Btelegram) handleGroups(rmsg *config.Message, message *tgbotapi.Message, update tgbotapi.Update) *tgbotapi.Message {
return b.handleUpdate(rmsg, message, update.Message, update.EditedMessage)
} | [
"func",
"(",
"b",
"*",
"Btelegram",
")",
"handleGroups",
"(",
"rmsg",
"*",
"config",
".",
"Message",
",",
"message",
"*",
"tgbotapi",
".",
"Message",
",",
"update",
"tgbotapi",
".",
"Update",
")",
"*",
"tgbotapi",
".",
"Message",
"{",
"return",
"b",
".",
"handleUpdate",
"(",
"rmsg",
",",
"message",
",",
"update",
".",
"Message",
",",
"update",
".",
"EditedMessage",
")",
"\n",
"}"
] | // handleGroups checks if it's a group message and if the message is a new or edited messages | [
"handleGroups",
"checks",
"if",
"it",
"s",
"a",
"group",
"message",
"and",
"if",
"the",
"message",
"is",
"a",
"new",
"or",
"edited",
"messages"
] | 1b2feb19e506bc24580d5d61422d0de68349c24e | https://github.com/42wim/matterbridge/blob/1b2feb19e506bc24580d5d61422d0de68349c24e/bridge/telegram/handlers.go#L35-L37 | train |
42wim/matterbridge | bridge/telegram/handlers.go | handleForwarded | func (b *Btelegram) handleForwarded(rmsg *config.Message, message *tgbotapi.Message) {
if message.ForwardFrom != nil {
usernameForward := ""
if b.GetBool("UseFirstName") {
usernameForward = message.ForwardFrom.FirstName
}
if usernameForward == "" {
usernameForward = message.ForwardFrom.UserName
if usernameForward == "" {
usernameForward = message.ForwardFrom.FirstName
}
}
if usernameForward == "" {
usernameForward = unknownUser
}
rmsg.Text = "Forwarded from " + usernameForward + ": " + rmsg.Text
}
} | go | func (b *Btelegram) handleForwarded(rmsg *config.Message, message *tgbotapi.Message) {
if message.ForwardFrom != nil {
usernameForward := ""
if b.GetBool("UseFirstName") {
usernameForward = message.ForwardFrom.FirstName
}
if usernameForward == "" {
usernameForward = message.ForwardFrom.UserName
if usernameForward == "" {
usernameForward = message.ForwardFrom.FirstName
}
}
if usernameForward == "" {
usernameForward = unknownUser
}
rmsg.Text = "Forwarded from " + usernameForward + ": " + rmsg.Text
}
} | [
"func",
"(",
"b",
"*",
"Btelegram",
")",
"handleForwarded",
"(",
"rmsg",
"*",
"config",
".",
"Message",
",",
"message",
"*",
"tgbotapi",
".",
"Message",
")",
"{",
"if",
"message",
".",
"ForwardFrom",
"!=",
"nil",
"{",
"usernameForward",
":=",
"\"",
"\"",
"\n",
"if",
"b",
".",
"GetBool",
"(",
"\"",
"\"",
")",
"{",
"usernameForward",
"=",
"message",
".",
"ForwardFrom",
".",
"FirstName",
"\n",
"}",
"\n",
"if",
"usernameForward",
"==",
"\"",
"\"",
"{",
"usernameForward",
"=",
"message",
".",
"ForwardFrom",
".",
"UserName",
"\n",
"if",
"usernameForward",
"==",
"\"",
"\"",
"{",
"usernameForward",
"=",
"message",
".",
"ForwardFrom",
".",
"FirstName",
"\n",
"}",
"\n",
"}",
"\n",
"if",
"usernameForward",
"==",
"\"",
"\"",
"{",
"usernameForward",
"=",
"unknownUser",
"\n",
"}",
"\n",
"rmsg",
".",
"Text",
"=",
"\"",
"\"",
"+",
"usernameForward",
"+",
"\"",
"\"",
"+",
"rmsg",
".",
"Text",
"\n",
"}",
"\n",
"}"
] | // handleForwarded handles forwarded messages | [
"handleForwarded",
"handles",
"forwarded",
"messages"
] | 1b2feb19e506bc24580d5d61422d0de68349c24e | https://github.com/42wim/matterbridge/blob/1b2feb19e506bc24580d5d61422d0de68349c24e/bridge/telegram/handlers.go#L40-L57 | train |
42wim/matterbridge | bridge/telegram/handlers.go | handleQuoting | func (b *Btelegram) handleQuoting(rmsg *config.Message, message *tgbotapi.Message) {
if message.ReplyToMessage != nil {
usernameReply := ""
if message.ReplyToMessage.From != nil {
if b.GetBool("UseFirstName") {
usernameReply = message.ReplyToMessage.From.FirstName
}
if usernameReply == "" {
usernameReply = message.ReplyToMessage.From.UserName
if usernameReply == "" {
usernameReply = message.ReplyToMessage.From.FirstName
}
}
}
if usernameReply == "" {
usernameReply = unknownUser
}
if !b.GetBool("QuoteDisable") {
rmsg.Text = b.handleQuote(rmsg.Text, usernameReply, message.ReplyToMessage.Text)
}
}
} | go | func (b *Btelegram) handleQuoting(rmsg *config.Message, message *tgbotapi.Message) {
if message.ReplyToMessage != nil {
usernameReply := ""
if message.ReplyToMessage.From != nil {
if b.GetBool("UseFirstName") {
usernameReply = message.ReplyToMessage.From.FirstName
}
if usernameReply == "" {
usernameReply = message.ReplyToMessage.From.UserName
if usernameReply == "" {
usernameReply = message.ReplyToMessage.From.FirstName
}
}
}
if usernameReply == "" {
usernameReply = unknownUser
}
if !b.GetBool("QuoteDisable") {
rmsg.Text = b.handleQuote(rmsg.Text, usernameReply, message.ReplyToMessage.Text)
}
}
} | [
"func",
"(",
"b",
"*",
"Btelegram",
")",
"handleQuoting",
"(",
"rmsg",
"*",
"config",
".",
"Message",
",",
"message",
"*",
"tgbotapi",
".",
"Message",
")",
"{",
"if",
"message",
".",
"ReplyToMessage",
"!=",
"nil",
"{",
"usernameReply",
":=",
"\"",
"\"",
"\n",
"if",
"message",
".",
"ReplyToMessage",
".",
"From",
"!=",
"nil",
"{",
"if",
"b",
".",
"GetBool",
"(",
"\"",
"\"",
")",
"{",
"usernameReply",
"=",
"message",
".",
"ReplyToMessage",
".",
"From",
".",
"FirstName",
"\n",
"}",
"\n",
"if",
"usernameReply",
"==",
"\"",
"\"",
"{",
"usernameReply",
"=",
"message",
".",
"ReplyToMessage",
".",
"From",
".",
"UserName",
"\n",
"if",
"usernameReply",
"==",
"\"",
"\"",
"{",
"usernameReply",
"=",
"message",
".",
"ReplyToMessage",
".",
"From",
".",
"FirstName",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n",
"if",
"usernameReply",
"==",
"\"",
"\"",
"{",
"usernameReply",
"=",
"unknownUser",
"\n",
"}",
"\n",
"if",
"!",
"b",
".",
"GetBool",
"(",
"\"",
"\"",
")",
"{",
"rmsg",
".",
"Text",
"=",
"b",
".",
"handleQuote",
"(",
"rmsg",
".",
"Text",
",",
"usernameReply",
",",
"message",
".",
"ReplyToMessage",
".",
"Text",
")",
"\n",
"}",
"\n",
"}",
"\n",
"}"
] | // handleQuoting handles quoting of previous messages | [
"handleQuoting",
"handles",
"quoting",
"of",
"previous",
"messages"
] | 1b2feb19e506bc24580d5d61422d0de68349c24e | https://github.com/42wim/matterbridge/blob/1b2feb19e506bc24580d5d61422d0de68349c24e/bridge/telegram/handlers.go#L60-L81 | train |
42wim/matterbridge | bridge/telegram/handlers.go | handleUsername | func (b *Btelegram) handleUsername(rmsg *config.Message, message *tgbotapi.Message) {
if message.From != nil {
rmsg.UserID = strconv.Itoa(message.From.ID)
if b.GetBool("UseFirstName") {
rmsg.Username = message.From.FirstName
}
if rmsg.Username == "" {
rmsg.Username = message.From.UserName
if rmsg.Username == "" {
rmsg.Username = message.From.FirstName
}
}
// only download avatars if we have a place to upload them (configured mediaserver)
if b.General.MediaServerUpload != "" {
b.handleDownloadAvatar(message.From.ID, rmsg.Channel)
}
}
// if we really didn't find a username, set it to unknown
if rmsg.Username == "" {
rmsg.Username = unknownUser
}
} | go | func (b *Btelegram) handleUsername(rmsg *config.Message, message *tgbotapi.Message) {
if message.From != nil {
rmsg.UserID = strconv.Itoa(message.From.ID)
if b.GetBool("UseFirstName") {
rmsg.Username = message.From.FirstName
}
if rmsg.Username == "" {
rmsg.Username = message.From.UserName
if rmsg.Username == "" {
rmsg.Username = message.From.FirstName
}
}
// only download avatars if we have a place to upload them (configured mediaserver)
if b.General.MediaServerUpload != "" {
b.handleDownloadAvatar(message.From.ID, rmsg.Channel)
}
}
// if we really didn't find a username, set it to unknown
if rmsg.Username == "" {
rmsg.Username = unknownUser
}
} | [
"func",
"(",
"b",
"*",
"Btelegram",
")",
"handleUsername",
"(",
"rmsg",
"*",
"config",
".",
"Message",
",",
"message",
"*",
"tgbotapi",
".",
"Message",
")",
"{",
"if",
"message",
".",
"From",
"!=",
"nil",
"{",
"rmsg",
".",
"UserID",
"=",
"strconv",
".",
"Itoa",
"(",
"message",
".",
"From",
".",
"ID",
")",
"\n",
"if",
"b",
".",
"GetBool",
"(",
"\"",
"\"",
")",
"{",
"rmsg",
".",
"Username",
"=",
"message",
".",
"From",
".",
"FirstName",
"\n",
"}",
"\n",
"if",
"rmsg",
".",
"Username",
"==",
"\"",
"\"",
"{",
"rmsg",
".",
"Username",
"=",
"message",
".",
"From",
".",
"UserName",
"\n",
"if",
"rmsg",
".",
"Username",
"==",
"\"",
"\"",
"{",
"rmsg",
".",
"Username",
"=",
"message",
".",
"From",
".",
"FirstName",
"\n",
"}",
"\n",
"}",
"\n",
"// only download avatars if we have a place to upload them (configured mediaserver)",
"if",
"b",
".",
"General",
".",
"MediaServerUpload",
"!=",
"\"",
"\"",
"{",
"b",
".",
"handleDownloadAvatar",
"(",
"message",
".",
"From",
".",
"ID",
",",
"rmsg",
".",
"Channel",
")",
"\n",
"}",
"\n",
"}",
"\n\n",
"// if we really didn't find a username, set it to unknown",
"if",
"rmsg",
".",
"Username",
"==",
"\"",
"\"",
"{",
"rmsg",
".",
"Username",
"=",
"unknownUser",
"\n",
"}",
"\n",
"}"
] | // handleUsername handles the correct setting of the username | [
"handleUsername",
"handles",
"the",
"correct",
"setting",
"of",
"the",
"username"
] | 1b2feb19e506bc24580d5d61422d0de68349c24e | https://github.com/42wim/matterbridge/blob/1b2feb19e506bc24580d5d61422d0de68349c24e/bridge/telegram/handlers.go#L84-L106 | train |
42wim/matterbridge | bridge/telegram/handlers.go | handleDelete | func (b *Btelegram) handleDelete(msg *config.Message, chatid int64) (string, error) {
if msg.ID == "" {
return "", nil
}
msgid, err := strconv.Atoi(msg.ID)
if err != nil {
return "", err
}
_, err = b.c.DeleteMessage(tgbotapi.DeleteMessageConfig{ChatID: chatid, MessageID: msgid})
return "", err
} | go | func (b *Btelegram) handleDelete(msg *config.Message, chatid int64) (string, error) {
if msg.ID == "" {
return "", nil
}
msgid, err := strconv.Atoi(msg.ID)
if err != nil {
return "", err
}
_, err = b.c.DeleteMessage(tgbotapi.DeleteMessageConfig{ChatID: chatid, MessageID: msgid})
return "", err
} | [
"func",
"(",
"b",
"*",
"Btelegram",
")",
"handleDelete",
"(",
"msg",
"*",
"config",
".",
"Message",
",",
"chatid",
"int64",
")",
"(",
"string",
",",
"error",
")",
"{",
"if",
"msg",
".",
"ID",
"==",
"\"",
"\"",
"{",
"return",
"\"",
"\"",
",",
"nil",
"\n",
"}",
"\n",
"msgid",
",",
"err",
":=",
"strconv",
".",
"Atoi",
"(",
"msg",
".",
"ID",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\"",
"\"",
",",
"err",
"\n",
"}",
"\n",
"_",
",",
"err",
"=",
"b",
".",
"c",
".",
"DeleteMessage",
"(",
"tgbotapi",
".",
"DeleteMessageConfig",
"{",
"ChatID",
":",
"chatid",
",",
"MessageID",
":",
"msgid",
"}",
")",
"\n",
"return",
"\"",
"\"",
",",
"err",
"\n",
"}"
] | // handleDelete handles message deleting | [
"handleDelete",
"handles",
"message",
"deleting"
] | 1b2feb19e506bc24580d5d61422d0de68349c24e | https://github.com/42wim/matterbridge/blob/1b2feb19e506bc24580d5d61422d0de68349c24e/bridge/telegram/handlers.go#L284-L294 | train |
42wim/matterbridge | bridge/telegram/handlers.go | handleEdit | func (b *Btelegram) handleEdit(msg *config.Message, chatid int64) (string, error) {
msgid, err := strconv.Atoi(msg.ID)
if err != nil {
return "", err
}
if strings.ToLower(b.GetString("MessageFormat")) == HTMLNick {
b.Log.Debug("Using mode HTML - nick only")
msg.Text = html.EscapeString(msg.Text)
}
m := tgbotapi.NewEditMessageText(chatid, msgid, msg.Username+msg.Text)
switch b.GetString("MessageFormat") {
case HTMLFormat:
b.Log.Debug("Using mode HTML")
m.ParseMode = tgbotapi.ModeHTML
case "Markdown":
b.Log.Debug("Using mode markdown")
m.ParseMode = tgbotapi.ModeMarkdown
}
if strings.ToLower(b.GetString("MessageFormat")) == HTMLNick {
b.Log.Debug("Using mode HTML - nick only")
m.ParseMode = tgbotapi.ModeHTML
}
_, err = b.c.Send(m)
if err != nil {
return "", err
}
return "", nil
} | go | func (b *Btelegram) handleEdit(msg *config.Message, chatid int64) (string, error) {
msgid, err := strconv.Atoi(msg.ID)
if err != nil {
return "", err
}
if strings.ToLower(b.GetString("MessageFormat")) == HTMLNick {
b.Log.Debug("Using mode HTML - nick only")
msg.Text = html.EscapeString(msg.Text)
}
m := tgbotapi.NewEditMessageText(chatid, msgid, msg.Username+msg.Text)
switch b.GetString("MessageFormat") {
case HTMLFormat:
b.Log.Debug("Using mode HTML")
m.ParseMode = tgbotapi.ModeHTML
case "Markdown":
b.Log.Debug("Using mode markdown")
m.ParseMode = tgbotapi.ModeMarkdown
}
if strings.ToLower(b.GetString("MessageFormat")) == HTMLNick {
b.Log.Debug("Using mode HTML - nick only")
m.ParseMode = tgbotapi.ModeHTML
}
_, err = b.c.Send(m)
if err != nil {
return "", err
}
return "", nil
} | [
"func",
"(",
"b",
"*",
"Btelegram",
")",
"handleEdit",
"(",
"msg",
"*",
"config",
".",
"Message",
",",
"chatid",
"int64",
")",
"(",
"string",
",",
"error",
")",
"{",
"msgid",
",",
"err",
":=",
"strconv",
".",
"Atoi",
"(",
"msg",
".",
"ID",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\"",
"\"",
",",
"err",
"\n",
"}",
"\n",
"if",
"strings",
".",
"ToLower",
"(",
"b",
".",
"GetString",
"(",
"\"",
"\"",
")",
")",
"==",
"HTMLNick",
"{",
"b",
".",
"Log",
".",
"Debug",
"(",
"\"",
"\"",
")",
"\n",
"msg",
".",
"Text",
"=",
"html",
".",
"EscapeString",
"(",
"msg",
".",
"Text",
")",
"\n",
"}",
"\n",
"m",
":=",
"tgbotapi",
".",
"NewEditMessageText",
"(",
"chatid",
",",
"msgid",
",",
"msg",
".",
"Username",
"+",
"msg",
".",
"Text",
")",
"\n",
"switch",
"b",
".",
"GetString",
"(",
"\"",
"\"",
")",
"{",
"case",
"HTMLFormat",
":",
"b",
".",
"Log",
".",
"Debug",
"(",
"\"",
"\"",
")",
"\n",
"m",
".",
"ParseMode",
"=",
"tgbotapi",
".",
"ModeHTML",
"\n",
"case",
"\"",
"\"",
":",
"b",
".",
"Log",
".",
"Debug",
"(",
"\"",
"\"",
")",
"\n",
"m",
".",
"ParseMode",
"=",
"tgbotapi",
".",
"ModeMarkdown",
"\n",
"}",
"\n",
"if",
"strings",
".",
"ToLower",
"(",
"b",
".",
"GetString",
"(",
"\"",
"\"",
")",
")",
"==",
"HTMLNick",
"{",
"b",
".",
"Log",
".",
"Debug",
"(",
"\"",
"\"",
")",
"\n",
"m",
".",
"ParseMode",
"=",
"tgbotapi",
".",
"ModeHTML",
"\n",
"}",
"\n",
"_",
",",
"err",
"=",
"b",
".",
"c",
".",
"Send",
"(",
"m",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\"",
"\"",
",",
"err",
"\n",
"}",
"\n",
"return",
"\"",
"\"",
",",
"nil",
"\n",
"}"
] | // handleEdit handles message editing. | [
"handleEdit",
"handles",
"message",
"editing",
"."
] | 1b2feb19e506bc24580d5d61422d0de68349c24e | https://github.com/42wim/matterbridge/blob/1b2feb19e506bc24580d5d61422d0de68349c24e/bridge/telegram/handlers.go#L297-L324 | train |
42wim/matterbridge | bridge/telegram/handlers.go | handleEntities | func (b *Btelegram) handleEntities(rmsg *config.Message, message *tgbotapi.Message) {
if message.Entities == nil {
return
}
// for now only do URL replacements
for _, e := range *message.Entities {
if e.Type == "text_link" {
url, err := e.ParseURL()
if err != nil {
b.Log.Errorf("entity text_link url parse failed: %s", err)
continue
}
link := rmsg.Text[e.Offset : e.Offset+e.Length]
rmsg.Text = strings.Replace(rmsg.Text, link, url.String(), 1)
}
}
} | go | func (b *Btelegram) handleEntities(rmsg *config.Message, message *tgbotapi.Message) {
if message.Entities == nil {
return
}
// for now only do URL replacements
for _, e := range *message.Entities {
if e.Type == "text_link" {
url, err := e.ParseURL()
if err != nil {
b.Log.Errorf("entity text_link url parse failed: %s", err)
continue
}
link := rmsg.Text[e.Offset : e.Offset+e.Length]
rmsg.Text = strings.Replace(rmsg.Text, link, url.String(), 1)
}
}
} | [
"func",
"(",
"b",
"*",
"Btelegram",
")",
"handleEntities",
"(",
"rmsg",
"*",
"config",
".",
"Message",
",",
"message",
"*",
"tgbotapi",
".",
"Message",
")",
"{",
"if",
"message",
".",
"Entities",
"==",
"nil",
"{",
"return",
"\n",
"}",
"\n",
"// for now only do URL replacements",
"for",
"_",
",",
"e",
":=",
"range",
"*",
"message",
".",
"Entities",
"{",
"if",
"e",
".",
"Type",
"==",
"\"",
"\"",
"{",
"url",
",",
"err",
":=",
"e",
".",
"ParseURL",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"b",
".",
"Log",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"continue",
"\n",
"}",
"\n",
"link",
":=",
"rmsg",
".",
"Text",
"[",
"e",
".",
"Offset",
":",
"e",
".",
"Offset",
"+",
"e",
".",
"Length",
"]",
"\n",
"rmsg",
".",
"Text",
"=",
"strings",
".",
"Replace",
"(",
"rmsg",
".",
"Text",
",",
"link",
",",
"url",
".",
"String",
"(",
")",
",",
"1",
")",
"\n",
"}",
"\n",
"}",
"\n",
"}"
] | // handleEntities handles messageEntities | [
"handleEntities",
"handles",
"messageEntities"
] | 1b2feb19e506bc24580d5d61422d0de68349c24e | https://github.com/42wim/matterbridge/blob/1b2feb19e506bc24580d5d61422d0de68349c24e/bridge/telegram/handlers.go#L366-L382 | train |
42wim/matterbridge | bridge/whatsapp/whatsapp.go | Login | func (b *Bwhatsapp) Login() error {
b.Log.Debugln("Logging in..")
invert := b.GetBool(qrOnWhiteTerminal) // false is the default
qrChan := qrFromTerminal(invert)
session, err := b.conn.Login(qrChan)
if err != nil {
b.Log.Warnln("Failed to log in:", err)
return err
}
b.session = &session
b.Log.Infof("Logged into session: %#v", session)
b.Log.Infof("Connection: %#v", b.conn)
err = b.writeSession(session)
if err != nil {
fmt.Fprintf(os.Stderr, "error saving session: %v\n", err)
}
// TODO change connection strings to configured ones longClientName:"github.com/rhymen/go-whatsapp", shortClientName:"go-whatsapp"}" prefix=whatsapp
// TODO get also a nice logo
// TODO notification about unplugged and dead battery
// conn.Info: Wid, Pushname, Connected, Battery, Plugged
return nil
} | go | func (b *Bwhatsapp) Login() error {
b.Log.Debugln("Logging in..")
invert := b.GetBool(qrOnWhiteTerminal) // false is the default
qrChan := qrFromTerminal(invert)
session, err := b.conn.Login(qrChan)
if err != nil {
b.Log.Warnln("Failed to log in:", err)
return err
}
b.session = &session
b.Log.Infof("Logged into session: %#v", session)
b.Log.Infof("Connection: %#v", b.conn)
err = b.writeSession(session)
if err != nil {
fmt.Fprintf(os.Stderr, "error saving session: %v\n", err)
}
// TODO change connection strings to configured ones longClientName:"github.com/rhymen/go-whatsapp", shortClientName:"go-whatsapp"}" prefix=whatsapp
// TODO get also a nice logo
// TODO notification about unplugged and dead battery
// conn.Info: Wid, Pushname, Connected, Battery, Plugged
return nil
} | [
"func",
"(",
"b",
"*",
"Bwhatsapp",
")",
"Login",
"(",
")",
"error",
"{",
"b",
".",
"Log",
".",
"Debugln",
"(",
"\"",
"\"",
")",
"\n\n",
"invert",
":=",
"b",
".",
"GetBool",
"(",
"qrOnWhiteTerminal",
")",
"// false is the default",
"\n",
"qrChan",
":=",
"qrFromTerminal",
"(",
"invert",
")",
"\n\n",
"session",
",",
"err",
":=",
"b",
".",
"conn",
".",
"Login",
"(",
"qrChan",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"b",
".",
"Log",
".",
"Warnln",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"return",
"err",
"\n",
"}",
"\n",
"b",
".",
"session",
"=",
"&",
"session",
"\n\n",
"b",
".",
"Log",
".",
"Infof",
"(",
"\"",
"\"",
",",
"session",
")",
"\n",
"b",
".",
"Log",
".",
"Infof",
"(",
"\"",
"\"",
",",
"b",
".",
"conn",
")",
"\n\n",
"err",
"=",
"b",
".",
"writeSession",
"(",
"session",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"fmt",
".",
"Fprintf",
"(",
"os",
".",
"Stderr",
",",
"\"",
"\\n",
"\"",
",",
"err",
")",
"\n",
"}",
"\n\n",
"// TODO change connection strings to configured ones longClientName:\"github.com/rhymen/go-whatsapp\", shortClientName:\"go-whatsapp\"}\" prefix=whatsapp",
"// TODO get also a nice logo",
"// TODO notification about unplugged and dead battery",
"// conn.Info: Wid, Pushname, Connected, Battery, Plugged",
"return",
"nil",
"\n",
"}"
] | // Login to WhatsApp creating a new session. This will require to scan a QR code on your mobile device | [
"Login",
"to",
"WhatsApp",
"creating",
"a",
"new",
"session",
".",
"This",
"will",
"require",
"to",
"scan",
"a",
"QR",
"code",
"on",
"your",
"mobile",
"device"
] | 1b2feb19e506bc24580d5d61422d0de68349c24e | https://github.com/42wim/matterbridge/blob/1b2feb19e506bc24580d5d61422d0de68349c24e/bridge/whatsapp/whatsapp.go#L149-L177 | train |
42wim/matterbridge | bridge/whatsapp/whatsapp.go | JoinChannel | func (b *Bwhatsapp) JoinChannel(channel config.ChannelInfo) error {
byJid := isGroupJid(channel.Name)
// verify if we are member of the given group
if byJid {
// channel.Name specifies static group jID, not the name
if _, exists := b.conn.Store.Contacts[channel.Name]; !exists {
return fmt.Errorf("account doesn't belong to group with jid %s", channel.Name)
}
} else {
// channel.Name specifies group name that might change, warn about it
var jids []string
for id, contact := range b.conn.Store.Contacts {
if isGroupJid(id) && contact.Name == channel.Name {
jids = append(jids, id)
}
}
switch len(jids) {
case 0:
// didn't match any group - print out possibilites
// TODO sort
// copy b;
//sort.Slice(people, func(i, j int) bool {
// return people[i].Age > people[j].Age
//})
for id, contact := range b.conn.Store.Contacts {
if isGroupJid(id) {
b.Log.Infof("%s %s", contact.Jid, contact.Name)
}
}
return fmt.Errorf("please specify group's JID from the list above instead of the name '%s'", channel.Name)
case 1:
return fmt.Errorf("group name might change. Please configure gateway with channel=\"%v\" instead of channel=\"%v\"", jids[0], channel.Name)
default:
return fmt.Errorf("there is more than one group with name '%s'. Please specify one of JIDs as channel name: %v", channel.Name, jids)
}
}
return nil
} | go | func (b *Bwhatsapp) JoinChannel(channel config.ChannelInfo) error {
byJid := isGroupJid(channel.Name)
// verify if we are member of the given group
if byJid {
// channel.Name specifies static group jID, not the name
if _, exists := b.conn.Store.Contacts[channel.Name]; !exists {
return fmt.Errorf("account doesn't belong to group with jid %s", channel.Name)
}
} else {
// channel.Name specifies group name that might change, warn about it
var jids []string
for id, contact := range b.conn.Store.Contacts {
if isGroupJid(id) && contact.Name == channel.Name {
jids = append(jids, id)
}
}
switch len(jids) {
case 0:
// didn't match any group - print out possibilites
// TODO sort
// copy b;
//sort.Slice(people, func(i, j int) bool {
// return people[i].Age > people[j].Age
//})
for id, contact := range b.conn.Store.Contacts {
if isGroupJid(id) {
b.Log.Infof("%s %s", contact.Jid, contact.Name)
}
}
return fmt.Errorf("please specify group's JID from the list above instead of the name '%s'", channel.Name)
case 1:
return fmt.Errorf("group name might change. Please configure gateway with channel=\"%v\" instead of channel=\"%v\"", jids[0], channel.Name)
default:
return fmt.Errorf("there is more than one group with name '%s'. Please specify one of JIDs as channel name: %v", channel.Name, jids)
}
}
return nil
} | [
"func",
"(",
"b",
"*",
"Bwhatsapp",
")",
"JoinChannel",
"(",
"channel",
"config",
".",
"ChannelInfo",
")",
"error",
"{",
"byJid",
":=",
"isGroupJid",
"(",
"channel",
".",
"Name",
")",
"\n\n",
"// verify if we are member of the given group",
"if",
"byJid",
"{",
"// channel.Name specifies static group jID, not the name",
"if",
"_",
",",
"exists",
":=",
"b",
".",
"conn",
".",
"Store",
".",
"Contacts",
"[",
"channel",
".",
"Name",
"]",
";",
"!",
"exists",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"channel",
".",
"Name",
")",
"\n",
"}",
"\n",
"}",
"else",
"{",
"// channel.Name specifies group name that might change, warn about it",
"var",
"jids",
"[",
"]",
"string",
"\n",
"for",
"id",
",",
"contact",
":=",
"range",
"b",
".",
"conn",
".",
"Store",
".",
"Contacts",
"{",
"if",
"isGroupJid",
"(",
"id",
")",
"&&",
"contact",
".",
"Name",
"==",
"channel",
".",
"Name",
"{",
"jids",
"=",
"append",
"(",
"jids",
",",
"id",
")",
"\n",
"}",
"\n",
"}",
"\n\n",
"switch",
"len",
"(",
"jids",
")",
"{",
"case",
"0",
":",
"// didn't match any group - print out possibilites",
"// TODO sort",
"// copy b;",
"//sort.Slice(people, func(i, j int) bool {",
"//\treturn people[i].Age > people[j].Age",
"//})",
"for",
"id",
",",
"contact",
":=",
"range",
"b",
".",
"conn",
".",
"Store",
".",
"Contacts",
"{",
"if",
"isGroupJid",
"(",
"id",
")",
"{",
"b",
".",
"Log",
".",
"Infof",
"(",
"\"",
"\"",
",",
"contact",
".",
"Jid",
",",
"contact",
".",
"Name",
")",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"channel",
".",
"Name",
")",
"\n\n",
"case",
"1",
":",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\\\"",
"\\\"",
"\\\"",
"\\\"",
"\"",
",",
"jids",
"[",
"0",
"]",
",",
"channel",
".",
"Name",
")",
"\n\n",
"default",
":",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"channel",
".",
"Name",
",",
"jids",
")",
"\n",
"}",
"\n",
"}",
"\n\n",
"return",
"nil",
"\n",
"}"
] | // JoinChannel Join a WhatsApp group specified in gateway config as channel='[email protected]' or channel='Channel name'
// Required implementation of the Bridger interface
// https://github.com/42wim/matterbridge/blob/2cfd880cdb0df29771bf8f31df8d990ab897889d/bridge/bridge.go#L11-L16 | [
"JoinChannel",
"Join",
"a",
"WhatsApp",
"group",
"specified",
"in",
"gateway",
"config",
"as",
"channel",
"=",
"number",
"-",
"id"
] | 1b2feb19e506bc24580d5d61422d0de68349c24e | https://github.com/42wim/matterbridge/blob/1b2feb19e506bc24580d5d61422d0de68349c24e/bridge/whatsapp/whatsapp.go#L196-L238 | train |
42wim/matterbridge | bridge/discord/discord.go | useWebhook | func (b *Bdiscord) useWebhook() bool {
if b.GetString("WebhookURL") != "" {
return true
}
b.channelsMutex.RLock()
defer b.channelsMutex.RUnlock()
for _, channel := range b.channelInfoMap {
if channel.Options.WebhookURL != "" {
return true
}
}
return false
} | go | func (b *Bdiscord) useWebhook() bool {
if b.GetString("WebhookURL") != "" {
return true
}
b.channelsMutex.RLock()
defer b.channelsMutex.RUnlock()
for _, channel := range b.channelInfoMap {
if channel.Options.WebhookURL != "" {
return true
}
}
return false
} | [
"func",
"(",
"b",
"*",
"Bdiscord",
")",
"useWebhook",
"(",
")",
"bool",
"{",
"if",
"b",
".",
"GetString",
"(",
"\"",
"\"",
")",
"!=",
"\"",
"\"",
"{",
"return",
"true",
"\n",
"}",
"\n\n",
"b",
".",
"channelsMutex",
".",
"RLock",
"(",
")",
"\n",
"defer",
"b",
".",
"channelsMutex",
".",
"RUnlock",
"(",
")",
"\n\n",
"for",
"_",
",",
"channel",
":=",
"range",
"b",
".",
"channelInfoMap",
"{",
"if",
"channel",
".",
"Options",
".",
"WebhookURL",
"!=",
"\"",
"\"",
"{",
"return",
"true",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"false",
"\n",
"}"
] | // useWebhook returns true if we have a webhook defined somewhere | [
"useWebhook",
"returns",
"true",
"if",
"we",
"have",
"a",
"webhook",
"defined",
"somewhere"
] | 1b2feb19e506bc24580d5d61422d0de68349c24e | https://github.com/42wim/matterbridge/blob/1b2feb19e506bc24580d5d61422d0de68349c24e/bridge/discord/discord.go#L308-L322 | train |
42wim/matterbridge | bridge/discord/discord.go | isWebhookID | func (b *Bdiscord) isWebhookID(id string) bool {
if b.GetString("WebhookURL") != "" {
wID, _ := b.splitURL(b.GetString("WebhookURL"))
if wID == id {
return true
}
}
b.channelsMutex.RLock()
defer b.channelsMutex.RUnlock()
for _, channel := range b.channelInfoMap {
if channel.Options.WebhookURL != "" {
wID, _ := b.splitURL(channel.Options.WebhookURL)
if wID == id {
return true
}
}
}
return false
} | go | func (b *Bdiscord) isWebhookID(id string) bool {
if b.GetString("WebhookURL") != "" {
wID, _ := b.splitURL(b.GetString("WebhookURL"))
if wID == id {
return true
}
}
b.channelsMutex.RLock()
defer b.channelsMutex.RUnlock()
for _, channel := range b.channelInfoMap {
if channel.Options.WebhookURL != "" {
wID, _ := b.splitURL(channel.Options.WebhookURL)
if wID == id {
return true
}
}
}
return false
} | [
"func",
"(",
"b",
"*",
"Bdiscord",
")",
"isWebhookID",
"(",
"id",
"string",
")",
"bool",
"{",
"if",
"b",
".",
"GetString",
"(",
"\"",
"\"",
")",
"!=",
"\"",
"\"",
"{",
"wID",
",",
"_",
":=",
"b",
".",
"splitURL",
"(",
"b",
".",
"GetString",
"(",
"\"",
"\"",
")",
")",
"\n",
"if",
"wID",
"==",
"id",
"{",
"return",
"true",
"\n",
"}",
"\n",
"}",
"\n\n",
"b",
".",
"channelsMutex",
".",
"RLock",
"(",
")",
"\n",
"defer",
"b",
".",
"channelsMutex",
".",
"RUnlock",
"(",
")",
"\n\n",
"for",
"_",
",",
"channel",
":=",
"range",
"b",
".",
"channelInfoMap",
"{",
"if",
"channel",
".",
"Options",
".",
"WebhookURL",
"!=",
"\"",
"\"",
"{",
"wID",
",",
"_",
":=",
"b",
".",
"splitURL",
"(",
"channel",
".",
"Options",
".",
"WebhookURL",
")",
"\n",
"if",
"wID",
"==",
"id",
"{",
"return",
"true",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"false",
"\n",
"}"
] | // isWebhookID returns true if the specified id is used in a defined webhook | [
"isWebhookID",
"returns",
"true",
"if",
"the",
"specified",
"id",
"is",
"used",
"in",
"a",
"defined",
"webhook"
] | 1b2feb19e506bc24580d5d61422d0de68349c24e | https://github.com/42wim/matterbridge/blob/1b2feb19e506bc24580d5d61422d0de68349c24e/bridge/discord/discord.go#L325-L345 | train |
42wim/matterbridge | gateway/router.go | NewRouter | func NewRouter(rootLogger *logrus.Logger, cfg config.Config, bridgeMap map[string]bridge.Factory) (*Router, error) {
logger := rootLogger.WithFields(logrus.Fields{"prefix": "router"})
r := &Router{
Config: cfg,
BridgeMap: bridgeMap,
Message: make(chan config.Message),
MattermostPlugin: make(chan config.Message),
Gateways: make(map[string]*Gateway),
logger: logger,
}
sgw := samechannel.New(cfg)
gwconfigs := append(sgw.GetConfig(), cfg.BridgeValues().Gateway...)
for idx := range gwconfigs {
entry := &gwconfigs[idx]
if !entry.Enable {
continue
}
if entry.Name == "" {
return nil, fmt.Errorf("%s", "Gateway without name found")
}
if _, ok := r.Gateways[entry.Name]; ok {
return nil, fmt.Errorf("Gateway with name %s already exists", entry.Name)
}
r.Gateways[entry.Name] = New(rootLogger, entry, r)
}
return r, nil
} | go | func NewRouter(rootLogger *logrus.Logger, cfg config.Config, bridgeMap map[string]bridge.Factory) (*Router, error) {
logger := rootLogger.WithFields(logrus.Fields{"prefix": "router"})
r := &Router{
Config: cfg,
BridgeMap: bridgeMap,
Message: make(chan config.Message),
MattermostPlugin: make(chan config.Message),
Gateways: make(map[string]*Gateway),
logger: logger,
}
sgw := samechannel.New(cfg)
gwconfigs := append(sgw.GetConfig(), cfg.BridgeValues().Gateway...)
for idx := range gwconfigs {
entry := &gwconfigs[idx]
if !entry.Enable {
continue
}
if entry.Name == "" {
return nil, fmt.Errorf("%s", "Gateway without name found")
}
if _, ok := r.Gateways[entry.Name]; ok {
return nil, fmt.Errorf("Gateway with name %s already exists", entry.Name)
}
r.Gateways[entry.Name] = New(rootLogger, entry, r)
}
return r, nil
} | [
"func",
"NewRouter",
"(",
"rootLogger",
"*",
"logrus",
".",
"Logger",
",",
"cfg",
"config",
".",
"Config",
",",
"bridgeMap",
"map",
"[",
"string",
"]",
"bridge",
".",
"Factory",
")",
"(",
"*",
"Router",
",",
"error",
")",
"{",
"logger",
":=",
"rootLogger",
".",
"WithFields",
"(",
"logrus",
".",
"Fields",
"{",
"\"",
"\"",
":",
"\"",
"\"",
"}",
")",
"\n\n",
"r",
":=",
"&",
"Router",
"{",
"Config",
":",
"cfg",
",",
"BridgeMap",
":",
"bridgeMap",
",",
"Message",
":",
"make",
"(",
"chan",
"config",
".",
"Message",
")",
",",
"MattermostPlugin",
":",
"make",
"(",
"chan",
"config",
".",
"Message",
")",
",",
"Gateways",
":",
"make",
"(",
"map",
"[",
"string",
"]",
"*",
"Gateway",
")",
",",
"logger",
":",
"logger",
",",
"}",
"\n",
"sgw",
":=",
"samechannel",
".",
"New",
"(",
"cfg",
")",
"\n",
"gwconfigs",
":=",
"append",
"(",
"sgw",
".",
"GetConfig",
"(",
")",
",",
"cfg",
".",
"BridgeValues",
"(",
")",
".",
"Gateway",
"...",
")",
"\n\n",
"for",
"idx",
":=",
"range",
"gwconfigs",
"{",
"entry",
":=",
"&",
"gwconfigs",
"[",
"idx",
"]",
"\n",
"if",
"!",
"entry",
".",
"Enable",
"{",
"continue",
"\n",
"}",
"\n",
"if",
"entry",
".",
"Name",
"==",
"\"",
"\"",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"if",
"_",
",",
"ok",
":=",
"r",
".",
"Gateways",
"[",
"entry",
".",
"Name",
"]",
";",
"ok",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"entry",
".",
"Name",
")",
"\n",
"}",
"\n",
"r",
".",
"Gateways",
"[",
"entry",
".",
"Name",
"]",
"=",
"New",
"(",
"rootLogger",
",",
"entry",
",",
"r",
")",
"\n",
"}",
"\n",
"return",
"r",
",",
"nil",
"\n",
"}"
] | // NewRouter initializes a new Matterbridge router for the specified configuration and
// sets up all required gateways. | [
"NewRouter",
"initializes",
"a",
"new",
"Matterbridge",
"router",
"for",
"the",
"specified",
"configuration",
"and",
"sets",
"up",
"all",
"required",
"gateways",
"."
] | 1b2feb19e506bc24580d5d61422d0de68349c24e | https://github.com/42wim/matterbridge/blob/1b2feb19e506bc24580d5d61422d0de68349c24e/gateway/router.go#L28-L56 | train |
42wim/matterbridge | gateway/router.go | Start | func (r *Router) Start() error {
m := make(map[string]*bridge.Bridge)
for _, gw := range r.Gateways {
r.logger.Infof("Parsing gateway %s", gw.Name)
for _, br := range gw.Bridges {
m[br.Account] = br
}
}
for _, br := range m {
r.logger.Infof("Starting bridge: %s ", br.Account)
err := br.Connect()
if err != nil {
e := fmt.Errorf("Bridge %s failed to start: %v", br.Account, err)
if r.disableBridge(br, e) {
continue
}
return e
}
err = br.JoinChannels()
if err != nil {
e := fmt.Errorf("Bridge %s failed to join channel: %v", br.Account, err)
if r.disableBridge(br, e) {
continue
}
return e
}
}
// remove unused bridges
for _, gw := range r.Gateways {
for i, br := range gw.Bridges {
if br.Bridger == nil {
r.logger.Errorf("removing failed bridge %s", i)
delete(gw.Bridges, i)
}
}
}
go r.handleReceive()
//go r.updateChannelMembers()
return nil
} | go | func (r *Router) Start() error {
m := make(map[string]*bridge.Bridge)
for _, gw := range r.Gateways {
r.logger.Infof("Parsing gateway %s", gw.Name)
for _, br := range gw.Bridges {
m[br.Account] = br
}
}
for _, br := range m {
r.logger.Infof("Starting bridge: %s ", br.Account)
err := br.Connect()
if err != nil {
e := fmt.Errorf("Bridge %s failed to start: %v", br.Account, err)
if r.disableBridge(br, e) {
continue
}
return e
}
err = br.JoinChannels()
if err != nil {
e := fmt.Errorf("Bridge %s failed to join channel: %v", br.Account, err)
if r.disableBridge(br, e) {
continue
}
return e
}
}
// remove unused bridges
for _, gw := range r.Gateways {
for i, br := range gw.Bridges {
if br.Bridger == nil {
r.logger.Errorf("removing failed bridge %s", i)
delete(gw.Bridges, i)
}
}
}
go r.handleReceive()
//go r.updateChannelMembers()
return nil
} | [
"func",
"(",
"r",
"*",
"Router",
")",
"Start",
"(",
")",
"error",
"{",
"m",
":=",
"make",
"(",
"map",
"[",
"string",
"]",
"*",
"bridge",
".",
"Bridge",
")",
"\n",
"for",
"_",
",",
"gw",
":=",
"range",
"r",
".",
"Gateways",
"{",
"r",
".",
"logger",
".",
"Infof",
"(",
"\"",
"\"",
",",
"gw",
".",
"Name",
")",
"\n",
"for",
"_",
",",
"br",
":=",
"range",
"gw",
".",
"Bridges",
"{",
"m",
"[",
"br",
".",
"Account",
"]",
"=",
"br",
"\n",
"}",
"\n",
"}",
"\n",
"for",
"_",
",",
"br",
":=",
"range",
"m",
"{",
"r",
".",
"logger",
".",
"Infof",
"(",
"\"",
"\"",
",",
"br",
".",
"Account",
")",
"\n",
"err",
":=",
"br",
".",
"Connect",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"e",
":=",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"br",
".",
"Account",
",",
"err",
")",
"\n",
"if",
"r",
".",
"disableBridge",
"(",
"br",
",",
"e",
")",
"{",
"continue",
"\n",
"}",
"\n",
"return",
"e",
"\n",
"}",
"\n",
"err",
"=",
"br",
".",
"JoinChannels",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"e",
":=",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"br",
".",
"Account",
",",
"err",
")",
"\n",
"if",
"r",
".",
"disableBridge",
"(",
"br",
",",
"e",
")",
"{",
"continue",
"\n",
"}",
"\n",
"return",
"e",
"\n",
"}",
"\n",
"}",
"\n",
"// remove unused bridges",
"for",
"_",
",",
"gw",
":=",
"range",
"r",
".",
"Gateways",
"{",
"for",
"i",
",",
"br",
":=",
"range",
"gw",
".",
"Bridges",
"{",
"if",
"br",
".",
"Bridger",
"==",
"nil",
"{",
"r",
".",
"logger",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"i",
")",
"\n",
"delete",
"(",
"gw",
".",
"Bridges",
",",
"i",
")",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n",
"go",
"r",
".",
"handleReceive",
"(",
")",
"\n",
"//go r.updateChannelMembers()",
"return",
"nil",
"\n",
"}"
] | // Start will connect all gateways belonging to this router and subsequently route messages
// between them. | [
"Start",
"will",
"connect",
"all",
"gateways",
"belonging",
"to",
"this",
"router",
"and",
"subsequently",
"route",
"messages",
"between",
"them",
"."
] | 1b2feb19e506bc24580d5d61422d0de68349c24e | https://github.com/42wim/matterbridge/blob/1b2feb19e506bc24580d5d61422d0de68349c24e/gateway/router.go#L60-L99 | train |
42wim/matterbridge | gateway/router.go | disableBridge | func (r *Router) disableBridge(br *bridge.Bridge, err error) bool {
if r.BridgeValues().General.IgnoreFailureOnStart {
r.logger.Error(err)
// setting this bridge empty
*br = bridge.Bridge{}
return true
}
return false
} | go | func (r *Router) disableBridge(br *bridge.Bridge, err error) bool {
if r.BridgeValues().General.IgnoreFailureOnStart {
r.logger.Error(err)
// setting this bridge empty
*br = bridge.Bridge{}
return true
}
return false
} | [
"func",
"(",
"r",
"*",
"Router",
")",
"disableBridge",
"(",
"br",
"*",
"bridge",
".",
"Bridge",
",",
"err",
"error",
")",
"bool",
"{",
"if",
"r",
".",
"BridgeValues",
"(",
")",
".",
"General",
".",
"IgnoreFailureOnStart",
"{",
"r",
".",
"logger",
".",
"Error",
"(",
"err",
")",
"\n",
"// setting this bridge empty",
"*",
"br",
"=",
"bridge",
".",
"Bridge",
"{",
"}",
"\n",
"return",
"true",
"\n",
"}",
"\n",
"return",
"false",
"\n",
"}"
] | // disableBridge returns true and empties a bridge if we have IgnoreFailureOnStart configured
// otherwise returns false | [
"disableBridge",
"returns",
"true",
"and",
"empties",
"a",
"bridge",
"if",
"we",
"have",
"IgnoreFailureOnStart",
"configured",
"otherwise",
"returns",
"false"
] | 1b2feb19e506bc24580d5d61422d0de68349c24e | https://github.com/42wim/matterbridge/blob/1b2feb19e506bc24580d5d61422d0de68349c24e/gateway/router.go#L103-L111 | train |
42wim/matterbridge | gateway/router.go | updateChannelMembers | func (r *Router) updateChannelMembers() {
// TODO sleep a minute because slack can take a while
// fix this by having actually connectionDone events send to the router
time.Sleep(time.Minute)
for {
for _, gw := range r.Gateways {
for _, br := range gw.Bridges {
// only for slack now
if br.Protocol != "slack" {
continue
}
r.logger.Debugf("sending %s to %s", config.EventGetChannelMembers, br.Account)
if _, err := br.Send(config.Message{Event: config.EventGetChannelMembers}); err != nil {
r.logger.Errorf("updateChannelMembers: %s", err)
}
}
}
time.Sleep(time.Minute)
}
} | go | func (r *Router) updateChannelMembers() {
// TODO sleep a minute because slack can take a while
// fix this by having actually connectionDone events send to the router
time.Sleep(time.Minute)
for {
for _, gw := range r.Gateways {
for _, br := range gw.Bridges {
// only for slack now
if br.Protocol != "slack" {
continue
}
r.logger.Debugf("sending %s to %s", config.EventGetChannelMembers, br.Account)
if _, err := br.Send(config.Message{Event: config.EventGetChannelMembers}); err != nil {
r.logger.Errorf("updateChannelMembers: %s", err)
}
}
}
time.Sleep(time.Minute)
}
} | [
"func",
"(",
"r",
"*",
"Router",
")",
"updateChannelMembers",
"(",
")",
"{",
"// TODO sleep a minute because slack can take a while",
"// fix this by having actually connectionDone events send to the router",
"time",
".",
"Sleep",
"(",
"time",
".",
"Minute",
")",
"\n",
"for",
"{",
"for",
"_",
",",
"gw",
":=",
"range",
"r",
".",
"Gateways",
"{",
"for",
"_",
",",
"br",
":=",
"range",
"gw",
".",
"Bridges",
"{",
"// only for slack now",
"if",
"br",
".",
"Protocol",
"!=",
"\"",
"\"",
"{",
"continue",
"\n",
"}",
"\n",
"r",
".",
"logger",
".",
"Debugf",
"(",
"\"",
"\"",
",",
"config",
".",
"EventGetChannelMembers",
",",
"br",
".",
"Account",
")",
"\n",
"if",
"_",
",",
"err",
":=",
"br",
".",
"Send",
"(",
"config",
".",
"Message",
"{",
"Event",
":",
"config",
".",
"EventGetChannelMembers",
"}",
")",
";",
"err",
"!=",
"nil",
"{",
"r",
".",
"logger",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n",
"time",
".",
"Sleep",
"(",
"time",
".",
"Minute",
")",
"\n",
"}",
"\n",
"}"
] | // updateChannelMembers sends every minute an GetChannelMembers event to all bridges. | [
"updateChannelMembers",
"sends",
"every",
"minute",
"an",
"GetChannelMembers",
"event",
"to",
"all",
"bridges",
"."
] | 1b2feb19e506bc24580d5d61422d0de68349c24e | https://github.com/42wim/matterbridge/blob/1b2feb19e506bc24580d5d61422d0de68349c24e/gateway/router.go#L153-L172 | train |
42wim/matterbridge | bridge/discord/helpers.go | splitURL | func (b *Bdiscord) splitURL(url string) (string, string) {
const (
expectedWebhookSplitCount = 7
webhookIdxID = 5
webhookIdxToken = 6
)
webhookURLSplit := strings.Split(url, "/")
if len(webhookURLSplit) != expectedWebhookSplitCount {
b.Log.Fatalf("%s is no correct discord WebhookURL", url)
}
return webhookURLSplit[webhookIdxID], webhookURLSplit[webhookIdxToken]
} | go | func (b *Bdiscord) splitURL(url string) (string, string) {
const (
expectedWebhookSplitCount = 7
webhookIdxID = 5
webhookIdxToken = 6
)
webhookURLSplit := strings.Split(url, "/")
if len(webhookURLSplit) != expectedWebhookSplitCount {
b.Log.Fatalf("%s is no correct discord WebhookURL", url)
}
return webhookURLSplit[webhookIdxID], webhookURLSplit[webhookIdxToken]
} | [
"func",
"(",
"b",
"*",
"Bdiscord",
")",
"splitURL",
"(",
"url",
"string",
")",
"(",
"string",
",",
"string",
")",
"{",
"const",
"(",
"expectedWebhookSplitCount",
"=",
"7",
"\n",
"webhookIdxID",
"=",
"5",
"\n",
"webhookIdxToken",
"=",
"6",
"\n",
")",
"\n",
"webhookURLSplit",
":=",
"strings",
".",
"Split",
"(",
"url",
",",
"\"",
"\"",
")",
"\n",
"if",
"len",
"(",
"webhookURLSplit",
")",
"!=",
"expectedWebhookSplitCount",
"{",
"b",
".",
"Log",
".",
"Fatalf",
"(",
"\"",
"\"",
",",
"url",
")",
"\n",
"}",
"\n",
"return",
"webhookURLSplit",
"[",
"webhookIdxID",
"]",
",",
"webhookURLSplit",
"[",
"webhookIdxToken",
"]",
"\n",
"}"
] | // splitURL splits a webhookURL and returns the ID and token. | [
"splitURL",
"splits",
"a",
"webhookURL",
"and",
"returns",
"the",
"ID",
"and",
"token",
"."
] | 1b2feb19e506bc24580d5d61422d0de68349c24e | https://github.com/42wim/matterbridge/blob/1b2feb19e506bc24580d5d61422d0de68349c24e/bridge/discord/helpers.go#L143-L154 | train |
42wim/matterbridge | gateway/handlers.go | handleEventFailure | func (r *Router) handleEventFailure(msg *config.Message) {
if msg.Event != config.EventFailure {
return
}
for _, gw := range r.Gateways {
for _, br := range gw.Bridges {
if msg.Account == br.Account {
go gw.reconnectBridge(br)
return
}
}
}
} | go | func (r *Router) handleEventFailure(msg *config.Message) {
if msg.Event != config.EventFailure {
return
}
for _, gw := range r.Gateways {
for _, br := range gw.Bridges {
if msg.Account == br.Account {
go gw.reconnectBridge(br)
return
}
}
}
} | [
"func",
"(",
"r",
"*",
"Router",
")",
"handleEventFailure",
"(",
"msg",
"*",
"config",
".",
"Message",
")",
"{",
"if",
"msg",
".",
"Event",
"!=",
"config",
".",
"EventFailure",
"{",
"return",
"\n",
"}",
"\n",
"for",
"_",
",",
"gw",
":=",
"range",
"r",
".",
"Gateways",
"{",
"for",
"_",
",",
"br",
":=",
"range",
"gw",
".",
"Bridges",
"{",
"if",
"msg",
".",
"Account",
"==",
"br",
".",
"Account",
"{",
"go",
"gw",
".",
"reconnectBridge",
"(",
"br",
")",
"\n",
"return",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n",
"}"
] | // handleEventFailure handles failures and reconnects bridges. | [
"handleEventFailure",
"handles",
"failures",
"and",
"reconnects",
"bridges",
"."
] | 1b2feb19e506bc24580d5d61422d0de68349c24e | https://github.com/42wim/matterbridge/blob/1b2feb19e506bc24580d5d61422d0de68349c24e/gateway/handlers.go#L20-L32 | train |
42wim/matterbridge | gateway/handlers.go | handleEventGetChannelMembers | func (r *Router) handleEventGetChannelMembers(msg *config.Message) {
if msg.Event != config.EventGetChannelMembers {
return
}
for _, gw := range r.Gateways {
for _, br := range gw.Bridges {
if msg.Account == br.Account {
cMembers := msg.Extra[config.EventGetChannelMembers][0].(config.ChannelMembers)
r.logger.Debugf("Syncing channelmembers from %s", msg.Account)
br.SetChannelMembers(&cMembers)
return
}
}
}
} | go | func (r *Router) handleEventGetChannelMembers(msg *config.Message) {
if msg.Event != config.EventGetChannelMembers {
return
}
for _, gw := range r.Gateways {
for _, br := range gw.Bridges {
if msg.Account == br.Account {
cMembers := msg.Extra[config.EventGetChannelMembers][0].(config.ChannelMembers)
r.logger.Debugf("Syncing channelmembers from %s", msg.Account)
br.SetChannelMembers(&cMembers)
return
}
}
}
} | [
"func",
"(",
"r",
"*",
"Router",
")",
"handleEventGetChannelMembers",
"(",
"msg",
"*",
"config",
".",
"Message",
")",
"{",
"if",
"msg",
".",
"Event",
"!=",
"config",
".",
"EventGetChannelMembers",
"{",
"return",
"\n",
"}",
"\n",
"for",
"_",
",",
"gw",
":=",
"range",
"r",
".",
"Gateways",
"{",
"for",
"_",
",",
"br",
":=",
"range",
"gw",
".",
"Bridges",
"{",
"if",
"msg",
".",
"Account",
"==",
"br",
".",
"Account",
"{",
"cMembers",
":=",
"msg",
".",
"Extra",
"[",
"config",
".",
"EventGetChannelMembers",
"]",
"[",
"0",
"]",
".",
"(",
"config",
".",
"ChannelMembers",
")",
"\n",
"r",
".",
"logger",
".",
"Debugf",
"(",
"\"",
"\"",
",",
"msg",
".",
"Account",
")",
"\n",
"br",
".",
"SetChannelMembers",
"(",
"&",
"cMembers",
")",
"\n",
"return",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n",
"}"
] | // handleEventGetChannelMembers handles channel members | [
"handleEventGetChannelMembers",
"handles",
"channel",
"members"
] | 1b2feb19e506bc24580d5d61422d0de68349c24e | https://github.com/42wim/matterbridge/blob/1b2feb19e506bc24580d5d61422d0de68349c24e/gateway/handlers.go#L35-L49 | train |
42wim/matterbridge | gateway/handlers.go | handleEventRejoinChannels | func (r *Router) handleEventRejoinChannels(msg *config.Message) {
if msg.Event != config.EventRejoinChannels {
return
}
for _, gw := range r.Gateways {
for _, br := range gw.Bridges {
if msg.Account == br.Account {
br.Joined = make(map[string]bool)
if err := br.JoinChannels(); err != nil {
r.logger.Errorf("channel join failed for %s: %s", msg.Account, err)
}
}
}
}
} | go | func (r *Router) handleEventRejoinChannels(msg *config.Message) {
if msg.Event != config.EventRejoinChannels {
return
}
for _, gw := range r.Gateways {
for _, br := range gw.Bridges {
if msg.Account == br.Account {
br.Joined = make(map[string]bool)
if err := br.JoinChannels(); err != nil {
r.logger.Errorf("channel join failed for %s: %s", msg.Account, err)
}
}
}
}
} | [
"func",
"(",
"r",
"*",
"Router",
")",
"handleEventRejoinChannels",
"(",
"msg",
"*",
"config",
".",
"Message",
")",
"{",
"if",
"msg",
".",
"Event",
"!=",
"config",
".",
"EventRejoinChannels",
"{",
"return",
"\n",
"}",
"\n",
"for",
"_",
",",
"gw",
":=",
"range",
"r",
".",
"Gateways",
"{",
"for",
"_",
",",
"br",
":=",
"range",
"gw",
".",
"Bridges",
"{",
"if",
"msg",
".",
"Account",
"==",
"br",
".",
"Account",
"{",
"br",
".",
"Joined",
"=",
"make",
"(",
"map",
"[",
"string",
"]",
"bool",
")",
"\n",
"if",
"err",
":=",
"br",
".",
"JoinChannels",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"r",
".",
"logger",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"msg",
".",
"Account",
",",
"err",
")",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n",
"}"
] | // handleEventRejoinChannels handles rejoining of channels. | [
"handleEventRejoinChannels",
"handles",
"rejoining",
"of",
"channels",
"."
] | 1b2feb19e506bc24580d5d61422d0de68349c24e | https://github.com/42wim/matterbridge/blob/1b2feb19e506bc24580d5d61422d0de68349c24e/gateway/handlers.go#L52-L66 | train |
42wim/matterbridge | gateway/handlers.go | handleFiles | func (gw *Gateway) handleFiles(msg *config.Message) {
reg := regexp.MustCompile("[^a-zA-Z0-9]+")
// If we don't have a attachfield or we don't have a mediaserver configured return
if msg.Extra == nil ||
(gw.BridgeValues().General.MediaServerUpload == "" &&
gw.BridgeValues().General.MediaDownloadPath == "") {
return
}
// If we don't have files, nothing to upload.
if len(msg.Extra["file"]) == 0 {
return
}
for i, f := range msg.Extra["file"] {
fi := f.(config.FileInfo)
ext := filepath.Ext(fi.Name)
fi.Name = fi.Name[0 : len(fi.Name)-len(ext)]
fi.Name = reg.ReplaceAllString(fi.Name, "_")
fi.Name += ext
sha1sum := fmt.Sprintf("%x", sha1.Sum(*fi.Data))[:8] //nolint:gosec
if gw.BridgeValues().General.MediaServerUpload != "" {
// Use MediaServerUpload. Upload using a PUT HTTP request and basicauth.
if err := gw.handleFilesUpload(&fi); err != nil {
gw.logger.Error(err)
continue
}
} else {
// Use MediaServerPath. Place the file on the current filesystem.
if err := gw.handleFilesLocal(&fi); err != nil {
gw.logger.Error(err)
continue
}
}
// Download URL.
durl := gw.BridgeValues().General.MediaServerDownload + "/" + sha1sum + "/" + fi.Name
gw.logger.Debugf("mediaserver download URL = %s", durl)
// We uploaded/placed the file successfully. Add the SHA and URL.
extra := msg.Extra["file"][i].(config.FileInfo)
extra.URL = durl
extra.SHA = sha1sum
msg.Extra["file"][i] = extra
}
} | go | func (gw *Gateway) handleFiles(msg *config.Message) {
reg := regexp.MustCompile("[^a-zA-Z0-9]+")
// If we don't have a attachfield or we don't have a mediaserver configured return
if msg.Extra == nil ||
(gw.BridgeValues().General.MediaServerUpload == "" &&
gw.BridgeValues().General.MediaDownloadPath == "") {
return
}
// If we don't have files, nothing to upload.
if len(msg.Extra["file"]) == 0 {
return
}
for i, f := range msg.Extra["file"] {
fi := f.(config.FileInfo)
ext := filepath.Ext(fi.Name)
fi.Name = fi.Name[0 : len(fi.Name)-len(ext)]
fi.Name = reg.ReplaceAllString(fi.Name, "_")
fi.Name += ext
sha1sum := fmt.Sprintf("%x", sha1.Sum(*fi.Data))[:8] //nolint:gosec
if gw.BridgeValues().General.MediaServerUpload != "" {
// Use MediaServerUpload. Upload using a PUT HTTP request and basicauth.
if err := gw.handleFilesUpload(&fi); err != nil {
gw.logger.Error(err)
continue
}
} else {
// Use MediaServerPath. Place the file on the current filesystem.
if err := gw.handleFilesLocal(&fi); err != nil {
gw.logger.Error(err)
continue
}
}
// Download URL.
durl := gw.BridgeValues().General.MediaServerDownload + "/" + sha1sum + "/" + fi.Name
gw.logger.Debugf("mediaserver download URL = %s", durl)
// We uploaded/placed the file successfully. Add the SHA and URL.
extra := msg.Extra["file"][i].(config.FileInfo)
extra.URL = durl
extra.SHA = sha1sum
msg.Extra["file"][i] = extra
}
} | [
"func",
"(",
"gw",
"*",
"Gateway",
")",
"handleFiles",
"(",
"msg",
"*",
"config",
".",
"Message",
")",
"{",
"reg",
":=",
"regexp",
".",
"MustCompile",
"(",
"\"",
"\"",
")",
"\n\n",
"// If we don't have a attachfield or we don't have a mediaserver configured return",
"if",
"msg",
".",
"Extra",
"==",
"nil",
"||",
"(",
"gw",
".",
"BridgeValues",
"(",
")",
".",
"General",
".",
"MediaServerUpload",
"==",
"\"",
"\"",
"&&",
"gw",
".",
"BridgeValues",
"(",
")",
".",
"General",
".",
"MediaDownloadPath",
"==",
"\"",
"\"",
")",
"{",
"return",
"\n",
"}",
"\n\n",
"// If we don't have files, nothing to upload.",
"if",
"len",
"(",
"msg",
".",
"Extra",
"[",
"\"",
"\"",
"]",
")",
"==",
"0",
"{",
"return",
"\n",
"}",
"\n\n",
"for",
"i",
",",
"f",
":=",
"range",
"msg",
".",
"Extra",
"[",
"\"",
"\"",
"]",
"{",
"fi",
":=",
"f",
".",
"(",
"config",
".",
"FileInfo",
")",
"\n",
"ext",
":=",
"filepath",
".",
"Ext",
"(",
"fi",
".",
"Name",
")",
"\n",
"fi",
".",
"Name",
"=",
"fi",
".",
"Name",
"[",
"0",
":",
"len",
"(",
"fi",
".",
"Name",
")",
"-",
"len",
"(",
"ext",
")",
"]",
"\n",
"fi",
".",
"Name",
"=",
"reg",
".",
"ReplaceAllString",
"(",
"fi",
".",
"Name",
",",
"\"",
"\"",
")",
"\n",
"fi",
".",
"Name",
"+=",
"ext",
"\n\n",
"sha1sum",
":=",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"sha1",
".",
"Sum",
"(",
"*",
"fi",
".",
"Data",
")",
")",
"[",
":",
"8",
"]",
"//nolint:gosec",
"\n\n",
"if",
"gw",
".",
"BridgeValues",
"(",
")",
".",
"General",
".",
"MediaServerUpload",
"!=",
"\"",
"\"",
"{",
"// Use MediaServerUpload. Upload using a PUT HTTP request and basicauth.",
"if",
"err",
":=",
"gw",
".",
"handleFilesUpload",
"(",
"&",
"fi",
")",
";",
"err",
"!=",
"nil",
"{",
"gw",
".",
"logger",
".",
"Error",
"(",
"err",
")",
"\n",
"continue",
"\n",
"}",
"\n",
"}",
"else",
"{",
"// Use MediaServerPath. Place the file on the current filesystem.",
"if",
"err",
":=",
"gw",
".",
"handleFilesLocal",
"(",
"&",
"fi",
")",
";",
"err",
"!=",
"nil",
"{",
"gw",
".",
"logger",
".",
"Error",
"(",
"err",
")",
"\n",
"continue",
"\n",
"}",
"\n",
"}",
"\n\n",
"// Download URL.",
"durl",
":=",
"gw",
".",
"BridgeValues",
"(",
")",
".",
"General",
".",
"MediaServerDownload",
"+",
"\"",
"\"",
"+",
"sha1sum",
"+",
"\"",
"\"",
"+",
"fi",
".",
"Name",
"\n\n",
"gw",
".",
"logger",
".",
"Debugf",
"(",
"\"",
"\"",
",",
"durl",
")",
"\n\n",
"// We uploaded/placed the file successfully. Add the SHA and URL.",
"extra",
":=",
"msg",
".",
"Extra",
"[",
"\"",
"\"",
"]",
"[",
"i",
"]",
".",
"(",
"config",
".",
"FileInfo",
")",
"\n",
"extra",
".",
"URL",
"=",
"durl",
"\n",
"extra",
".",
"SHA",
"=",
"sha1sum",
"\n",
"msg",
".",
"Extra",
"[",
"\"",
"\"",
"]",
"[",
"i",
"]",
"=",
"extra",
"\n",
"}",
"\n",
"}"
] | // handleFiles uploads or places all files on the given msg to the MediaServer and
// adds the new URL of the file on the MediaServer onto the given msg. | [
"handleFiles",
"uploads",
"or",
"places",
"all",
"files",
"on",
"the",
"given",
"msg",
"to",
"the",
"MediaServer",
"and",
"adds",
"the",
"new",
"URL",
"of",
"the",
"file",
"on",
"the",
"MediaServer",
"onto",
"the",
"given",
"msg",
"."
] | 1b2feb19e506bc24580d5d61422d0de68349c24e | https://github.com/42wim/matterbridge/blob/1b2feb19e506bc24580d5d61422d0de68349c24e/gateway/handlers.go#L70-L119 | train |
42wim/matterbridge | gateway/handlers.go | handleFilesUpload | func (gw *Gateway) handleFilesUpload(fi *config.FileInfo) error {
client := &http.Client{
Timeout: time.Second * 5,
}
// Use MediaServerUpload. Upload using a PUT HTTP request and basicauth.
sha1sum := fmt.Sprintf("%x", sha1.Sum(*fi.Data))[:8] //nolint:gosec
url := gw.BridgeValues().General.MediaServerUpload + "/" + sha1sum + "/" + fi.Name
req, err := http.NewRequest("PUT", url, bytes.NewReader(*fi.Data))
if err != nil {
return fmt.Errorf("mediaserver upload failed, could not create request: %#v", err)
}
gw.logger.Debugf("mediaserver upload url: %s", url)
req.Header.Set("Content-Type", "binary/octet-stream")
_, err = client.Do(req)
if err != nil {
return fmt.Errorf("mediaserver upload failed, could not Do request: %#v", err)
}
return nil
} | go | func (gw *Gateway) handleFilesUpload(fi *config.FileInfo) error {
client := &http.Client{
Timeout: time.Second * 5,
}
// Use MediaServerUpload. Upload using a PUT HTTP request and basicauth.
sha1sum := fmt.Sprintf("%x", sha1.Sum(*fi.Data))[:8] //nolint:gosec
url := gw.BridgeValues().General.MediaServerUpload + "/" + sha1sum + "/" + fi.Name
req, err := http.NewRequest("PUT", url, bytes.NewReader(*fi.Data))
if err != nil {
return fmt.Errorf("mediaserver upload failed, could not create request: %#v", err)
}
gw.logger.Debugf("mediaserver upload url: %s", url)
req.Header.Set("Content-Type", "binary/octet-stream")
_, err = client.Do(req)
if err != nil {
return fmt.Errorf("mediaserver upload failed, could not Do request: %#v", err)
}
return nil
} | [
"func",
"(",
"gw",
"*",
"Gateway",
")",
"handleFilesUpload",
"(",
"fi",
"*",
"config",
".",
"FileInfo",
")",
"error",
"{",
"client",
":=",
"&",
"http",
".",
"Client",
"{",
"Timeout",
":",
"time",
".",
"Second",
"*",
"5",
",",
"}",
"\n",
"// Use MediaServerUpload. Upload using a PUT HTTP request and basicauth.",
"sha1sum",
":=",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"sha1",
".",
"Sum",
"(",
"*",
"fi",
".",
"Data",
")",
")",
"[",
":",
"8",
"]",
"//nolint:gosec",
"\n",
"url",
":=",
"gw",
".",
"BridgeValues",
"(",
")",
".",
"General",
".",
"MediaServerUpload",
"+",
"\"",
"\"",
"+",
"sha1sum",
"+",
"\"",
"\"",
"+",
"fi",
".",
"Name",
"\n\n",
"req",
",",
"err",
":=",
"http",
".",
"NewRequest",
"(",
"\"",
"\"",
",",
"url",
",",
"bytes",
".",
"NewReader",
"(",
"*",
"fi",
".",
"Data",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n\n",
"gw",
".",
"logger",
".",
"Debugf",
"(",
"\"",
"\"",
",",
"url",
")",
"\n\n",
"req",
".",
"Header",
".",
"Set",
"(",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\n",
"_",
",",
"err",
"=",
"client",
".",
"Do",
"(",
"req",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] | // handleFilesUpload uses MediaServerUpload configuration to upload the file.
// Returns error on failure. | [
"handleFilesUpload",
"uses",
"MediaServerUpload",
"configuration",
"to",
"upload",
"the",
"file",
".",
"Returns",
"error",
"on",
"failure",
"."
] | 1b2feb19e506bc24580d5d61422d0de68349c24e | https://github.com/42wim/matterbridge/blob/1b2feb19e506bc24580d5d61422d0de68349c24e/gateway/handlers.go#L123-L144 | train |
42wim/matterbridge | gateway/handlers.go | handleFilesLocal | func (gw *Gateway) handleFilesLocal(fi *config.FileInfo) error {
sha1sum := fmt.Sprintf("%x", sha1.Sum(*fi.Data))[:8] //nolint:gosec
dir := gw.BridgeValues().General.MediaDownloadPath + "/" + sha1sum
err := os.Mkdir(dir, os.ModePerm)
if err != nil && !os.IsExist(err) {
return fmt.Errorf("mediaserver path failed, could not mkdir: %s %#v", err, err)
}
path := dir + "/" + fi.Name
gw.logger.Debugf("mediaserver path placing file: %s", path)
err = ioutil.WriteFile(path, *fi.Data, os.ModePerm)
if err != nil {
return fmt.Errorf("mediaserver path failed, could not writefile: %s %#v", err, err)
}
return nil
} | go | func (gw *Gateway) handleFilesLocal(fi *config.FileInfo) error {
sha1sum := fmt.Sprintf("%x", sha1.Sum(*fi.Data))[:8] //nolint:gosec
dir := gw.BridgeValues().General.MediaDownloadPath + "/" + sha1sum
err := os.Mkdir(dir, os.ModePerm)
if err != nil && !os.IsExist(err) {
return fmt.Errorf("mediaserver path failed, could not mkdir: %s %#v", err, err)
}
path := dir + "/" + fi.Name
gw.logger.Debugf("mediaserver path placing file: %s", path)
err = ioutil.WriteFile(path, *fi.Data, os.ModePerm)
if err != nil {
return fmt.Errorf("mediaserver path failed, could not writefile: %s %#v", err, err)
}
return nil
} | [
"func",
"(",
"gw",
"*",
"Gateway",
")",
"handleFilesLocal",
"(",
"fi",
"*",
"config",
".",
"FileInfo",
")",
"error",
"{",
"sha1sum",
":=",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"sha1",
".",
"Sum",
"(",
"*",
"fi",
".",
"Data",
")",
")",
"[",
":",
"8",
"]",
"//nolint:gosec",
"\n",
"dir",
":=",
"gw",
".",
"BridgeValues",
"(",
")",
".",
"General",
".",
"MediaDownloadPath",
"+",
"\"",
"\"",
"+",
"sha1sum",
"\n",
"err",
":=",
"os",
".",
"Mkdir",
"(",
"dir",
",",
"os",
".",
"ModePerm",
")",
"\n",
"if",
"err",
"!=",
"nil",
"&&",
"!",
"os",
".",
"IsExist",
"(",
"err",
")",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
",",
"err",
")",
"\n",
"}",
"\n\n",
"path",
":=",
"dir",
"+",
"\"",
"\"",
"+",
"fi",
".",
"Name",
"\n",
"gw",
".",
"logger",
".",
"Debugf",
"(",
"\"",
"\"",
",",
"path",
")",
"\n\n",
"err",
"=",
"ioutil",
".",
"WriteFile",
"(",
"path",
",",
"*",
"fi",
".",
"Data",
",",
"os",
".",
"ModePerm",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
",",
"err",
")",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] | // handleFilesLocal use MediaServerPath configuration, places the file on the current filesystem.
// Returns error on failure. | [
"handleFilesLocal",
"use",
"MediaServerPath",
"configuration",
"places",
"the",
"file",
"on",
"the",
"current",
"filesystem",
".",
"Returns",
"error",
"on",
"failure",
"."
] | 1b2feb19e506bc24580d5d61422d0de68349c24e | https://github.com/42wim/matterbridge/blob/1b2feb19e506bc24580d5d61422d0de68349c24e/gateway/handlers.go#L148-L164 | train |
42wim/matterbridge | gateway/handlers.go | ignoreEvent | func (gw *Gateway) ignoreEvent(event string, dest *bridge.Bridge) bool {
switch event {
case config.EventAvatarDownload:
// Avatar downloads are only relevant for telegram and mattermost for now
if dest.Protocol != "mattermost" && dest.Protocol != "telegram" {
return true
}
case config.EventJoinLeave:
// only relay join/part when configured
if !dest.GetBool("ShowJoinPart") {
return true
}
case config.EventTopicChange:
// only relay topic change when used in some way on other side
if dest.GetBool("ShowTopicChange") && dest.GetBool("SyncTopic") {
return true
}
}
return false
} | go | func (gw *Gateway) ignoreEvent(event string, dest *bridge.Bridge) bool {
switch event {
case config.EventAvatarDownload:
// Avatar downloads are only relevant for telegram and mattermost for now
if dest.Protocol != "mattermost" && dest.Protocol != "telegram" {
return true
}
case config.EventJoinLeave:
// only relay join/part when configured
if !dest.GetBool("ShowJoinPart") {
return true
}
case config.EventTopicChange:
// only relay topic change when used in some way on other side
if dest.GetBool("ShowTopicChange") && dest.GetBool("SyncTopic") {
return true
}
}
return false
} | [
"func",
"(",
"gw",
"*",
"Gateway",
")",
"ignoreEvent",
"(",
"event",
"string",
",",
"dest",
"*",
"bridge",
".",
"Bridge",
")",
"bool",
"{",
"switch",
"event",
"{",
"case",
"config",
".",
"EventAvatarDownload",
":",
"// Avatar downloads are only relevant for telegram and mattermost for now",
"if",
"dest",
".",
"Protocol",
"!=",
"\"",
"\"",
"&&",
"dest",
".",
"Protocol",
"!=",
"\"",
"\"",
"{",
"return",
"true",
"\n",
"}",
"\n",
"case",
"config",
".",
"EventJoinLeave",
":",
"// only relay join/part when configured",
"if",
"!",
"dest",
".",
"GetBool",
"(",
"\"",
"\"",
")",
"{",
"return",
"true",
"\n",
"}",
"\n",
"case",
"config",
".",
"EventTopicChange",
":",
"// only relay topic change when used in some way on other side",
"if",
"dest",
".",
"GetBool",
"(",
"\"",
"\"",
")",
"&&",
"dest",
".",
"GetBool",
"(",
"\"",
"\"",
")",
"{",
"return",
"true",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"false",
"\n",
"}"
] | // ignoreEvent returns true if we need to ignore this event for the specified destination bridge. | [
"ignoreEvent",
"returns",
"true",
"if",
"we",
"need",
"to",
"ignore",
"this",
"event",
"for",
"the",
"specified",
"destination",
"bridge",
"."
] | 1b2feb19e506bc24580d5d61422d0de68349c24e | https://github.com/42wim/matterbridge/blob/1b2feb19e506bc24580d5d61422d0de68349c24e/gateway/handlers.go#L167-L186 | train |
42wim/matterbridge | matterhook/matterhook.go | Send | func (c *Client) Send(msg OMessage) error {
buf, err := json.Marshal(msg)
if err != nil {
return err
}
resp, err := c.httpclient.Post(c.Url, "application/json", bytes.NewReader(buf))
if err != nil {
return err
}
defer resp.Body.Close()
// Read entire body to completion to re-use keep-alive connections.
io.Copy(ioutil.Discard, resp.Body)
if resp.StatusCode != 200 {
return fmt.Errorf("unexpected status code: %d", resp.StatusCode)
}
return nil
} | go | func (c *Client) Send(msg OMessage) error {
buf, err := json.Marshal(msg)
if err != nil {
return err
}
resp, err := c.httpclient.Post(c.Url, "application/json", bytes.NewReader(buf))
if err != nil {
return err
}
defer resp.Body.Close()
// Read entire body to completion to re-use keep-alive connections.
io.Copy(ioutil.Discard, resp.Body)
if resp.StatusCode != 200 {
return fmt.Errorf("unexpected status code: %d", resp.StatusCode)
}
return nil
} | [
"func",
"(",
"c",
"*",
"Client",
")",
"Send",
"(",
"msg",
"OMessage",
")",
"error",
"{",
"buf",
",",
"err",
":=",
"json",
".",
"Marshal",
"(",
"msg",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"resp",
",",
"err",
":=",
"c",
".",
"httpclient",
".",
"Post",
"(",
"c",
".",
"Url",
",",
"\"",
"\"",
",",
"bytes",
".",
"NewReader",
"(",
"buf",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"defer",
"resp",
".",
"Body",
".",
"Close",
"(",
")",
"\n\n",
"// Read entire body to completion to re-use keep-alive connections.",
"io",
".",
"Copy",
"(",
"ioutil",
".",
"Discard",
",",
"resp",
".",
"Body",
")",
"\n\n",
"if",
"resp",
".",
"StatusCode",
"!=",
"200",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"resp",
".",
"StatusCode",
")",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] | // Send sends a msg to mattermost incoming webhooks URL. | [
"Send",
"sends",
"a",
"msg",
"to",
"mattermost",
"incoming",
"webhooks",
"URL",
"."
] | 1b2feb19e506bc24580d5d61422d0de68349c24e | https://github.com/42wim/matterbridge/blob/1b2feb19e506bc24580d5d61422d0de68349c24e/matterhook/matterhook.go#L150-L168 | train |
42wim/matterbridge | bridge/helper/helper.go | DownloadFileAuth | func DownloadFileAuth(url string, auth string) (*[]byte, error) {
var buf bytes.Buffer
client := &http.Client{
Timeout: time.Second * 5,
}
req, err := http.NewRequest("GET", url, nil)
if auth != "" {
req.Header.Add("Authorization", auth)
}
if err != nil {
return nil, err
}
resp, err := client.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
io.Copy(&buf, resp.Body)
data := buf.Bytes()
return &data, nil
} | go | func DownloadFileAuth(url string, auth string) (*[]byte, error) {
var buf bytes.Buffer
client := &http.Client{
Timeout: time.Second * 5,
}
req, err := http.NewRequest("GET", url, nil)
if auth != "" {
req.Header.Add("Authorization", auth)
}
if err != nil {
return nil, err
}
resp, err := client.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
io.Copy(&buf, resp.Body)
data := buf.Bytes()
return &data, nil
} | [
"func",
"DownloadFileAuth",
"(",
"url",
"string",
",",
"auth",
"string",
")",
"(",
"*",
"[",
"]",
"byte",
",",
"error",
")",
"{",
"var",
"buf",
"bytes",
".",
"Buffer",
"\n",
"client",
":=",
"&",
"http",
".",
"Client",
"{",
"Timeout",
":",
"time",
".",
"Second",
"*",
"5",
",",
"}",
"\n",
"req",
",",
"err",
":=",
"http",
".",
"NewRequest",
"(",
"\"",
"\"",
",",
"url",
",",
"nil",
")",
"\n",
"if",
"auth",
"!=",
"\"",
"\"",
"{",
"req",
".",
"Header",
".",
"Add",
"(",
"\"",
"\"",
",",
"auth",
")",
"\n",
"}",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"resp",
",",
"err",
":=",
"client",
".",
"Do",
"(",
"req",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"defer",
"resp",
".",
"Body",
".",
"Close",
"(",
")",
"\n",
"io",
".",
"Copy",
"(",
"&",
"buf",
",",
"resp",
".",
"Body",
")",
"\n",
"data",
":=",
"buf",
".",
"Bytes",
"(",
")",
"\n",
"return",
"&",
"data",
",",
"nil",
"\n",
"}"
] | // DownloadFileAuth downloads the given URL using the specified authentication token. | [
"DownloadFileAuth",
"downloads",
"the",
"given",
"URL",
"using",
"the",
"specified",
"authentication",
"token",
"."
] | 1b2feb19e506bc24580d5d61422d0de68349c24e | https://github.com/42wim/matterbridge/blob/1b2feb19e506bc24580d5d61422d0de68349c24e/bridge/helper/helper.go#L27-L47 | train |
42wim/matterbridge | bridge/helper/helper.go | HandleExtra | func HandleExtra(msg *config.Message, general *config.Protocol) []config.Message {
extra := msg.Extra
rmsg := []config.Message{}
for _, f := range extra[config.EventFileFailureSize] {
fi := f.(config.FileInfo)
text := fmt.Sprintf("file %s too big to download (%#v > allowed size: %#v)", fi.Name, fi.Size, general.MediaDownloadSize)
rmsg = append(rmsg, config.Message{
Text: text,
Username: "<system> ",
Channel: msg.Channel,
Account: msg.Account,
})
}
return rmsg
} | go | func HandleExtra(msg *config.Message, general *config.Protocol) []config.Message {
extra := msg.Extra
rmsg := []config.Message{}
for _, f := range extra[config.EventFileFailureSize] {
fi := f.(config.FileInfo)
text := fmt.Sprintf("file %s too big to download (%#v > allowed size: %#v)", fi.Name, fi.Size, general.MediaDownloadSize)
rmsg = append(rmsg, config.Message{
Text: text,
Username: "<system> ",
Channel: msg.Channel,
Account: msg.Account,
})
}
return rmsg
} | [
"func",
"HandleExtra",
"(",
"msg",
"*",
"config",
".",
"Message",
",",
"general",
"*",
"config",
".",
"Protocol",
")",
"[",
"]",
"config",
".",
"Message",
"{",
"extra",
":=",
"msg",
".",
"Extra",
"\n",
"rmsg",
":=",
"[",
"]",
"config",
".",
"Message",
"{",
"}",
"\n",
"for",
"_",
",",
"f",
":=",
"range",
"extra",
"[",
"config",
".",
"EventFileFailureSize",
"]",
"{",
"fi",
":=",
"f",
".",
"(",
"config",
".",
"FileInfo",
")",
"\n",
"text",
":=",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"fi",
".",
"Name",
",",
"fi",
".",
"Size",
",",
"general",
".",
"MediaDownloadSize",
")",
"\n",
"rmsg",
"=",
"append",
"(",
"rmsg",
",",
"config",
".",
"Message",
"{",
"Text",
":",
"text",
",",
"Username",
":",
"\"",
"\"",
",",
"Channel",
":",
"msg",
".",
"Channel",
",",
"Account",
":",
"msg",
".",
"Account",
",",
"}",
")",
"\n",
"}",
"\n",
"return",
"rmsg",
"\n",
"}"
] | // HandleExtra manages the supplementary details stored inside a message's 'Extra' field map. | [
"HandleExtra",
"manages",
"the",
"supplementary",
"details",
"stored",
"inside",
"a",
"message",
"s",
"Extra",
"field",
"map",
"."
] | 1b2feb19e506bc24580d5d61422d0de68349c24e | https://github.com/42wim/matterbridge/blob/1b2feb19e506bc24580d5d61422d0de68349c24e/bridge/helper/helper.go#L88-L102 | train |
42wim/matterbridge | bridge/helper/helper.go | GetAvatar | func GetAvatar(av map[string]string, userid string, general *config.Protocol) string {
if sha, ok := av[userid]; ok {
return general.MediaServerDownload + "/" + sha + "/" + userid + ".png"
}
return ""
} | go | func GetAvatar(av map[string]string, userid string, general *config.Protocol) string {
if sha, ok := av[userid]; ok {
return general.MediaServerDownload + "/" + sha + "/" + userid + ".png"
}
return ""
} | [
"func",
"GetAvatar",
"(",
"av",
"map",
"[",
"string",
"]",
"string",
",",
"userid",
"string",
",",
"general",
"*",
"config",
".",
"Protocol",
")",
"string",
"{",
"if",
"sha",
",",
"ok",
":=",
"av",
"[",
"userid",
"]",
";",
"ok",
"{",
"return",
"general",
".",
"MediaServerDownload",
"+",
"\"",
"\"",
"+",
"sha",
"+",
"\"",
"\"",
"+",
"userid",
"+",
"\"",
"\"",
"\n",
"}",
"\n",
"return",
"\"",
"\"",
"\n",
"}"
] | // GetAvatar constructs a URL for a given user-avatar if it is available in the cache. | [
"GetAvatar",
"constructs",
"a",
"URL",
"for",
"a",
"given",
"user",
"-",
"avatar",
"if",
"it",
"is",
"available",
"in",
"the",
"cache",
"."
] | 1b2feb19e506bc24580d5d61422d0de68349c24e | https://github.com/42wim/matterbridge/blob/1b2feb19e506bc24580d5d61422d0de68349c24e/bridge/helper/helper.go#L105-L110 | train |
42wim/matterbridge | bridge/helper/helper.go | HandleDownloadSize | func HandleDownloadSize(logger *logrus.Entry, msg *config.Message, name string, size int64, general *config.Protocol) error {
// check blacklist here
for _, entry := range general.MediaDownloadBlackList {
if entry != "" {
re, err := regexp.Compile(entry)
if err != nil {
logger.Errorf("incorrect regexp %s for %s", entry, msg.Account)
continue
}
if re.MatchString(name) {
return fmt.Errorf("Matching blacklist %s. Not downloading %s", entry, name)
}
}
}
logger.Debugf("Trying to download %#v with size %#v", name, size)
if int(size) > general.MediaDownloadSize {
msg.Event = config.EventFileFailureSize
msg.Extra[msg.Event] = append(msg.Extra[msg.Event], config.FileInfo{
Name: name,
Comment: msg.Text,
Size: size,
})
return fmt.Errorf("File %#v to large to download (%#v). MediaDownloadSize is %#v", name, size, general.MediaDownloadSize)
}
return nil
} | go | func HandleDownloadSize(logger *logrus.Entry, msg *config.Message, name string, size int64, general *config.Protocol) error {
// check blacklist here
for _, entry := range general.MediaDownloadBlackList {
if entry != "" {
re, err := regexp.Compile(entry)
if err != nil {
logger.Errorf("incorrect regexp %s for %s", entry, msg.Account)
continue
}
if re.MatchString(name) {
return fmt.Errorf("Matching blacklist %s. Not downloading %s", entry, name)
}
}
}
logger.Debugf("Trying to download %#v with size %#v", name, size)
if int(size) > general.MediaDownloadSize {
msg.Event = config.EventFileFailureSize
msg.Extra[msg.Event] = append(msg.Extra[msg.Event], config.FileInfo{
Name: name,
Comment: msg.Text,
Size: size,
})
return fmt.Errorf("File %#v to large to download (%#v). MediaDownloadSize is %#v", name, size, general.MediaDownloadSize)
}
return nil
} | [
"func",
"HandleDownloadSize",
"(",
"logger",
"*",
"logrus",
".",
"Entry",
",",
"msg",
"*",
"config",
".",
"Message",
",",
"name",
"string",
",",
"size",
"int64",
",",
"general",
"*",
"config",
".",
"Protocol",
")",
"error",
"{",
"// check blacklist here",
"for",
"_",
",",
"entry",
":=",
"range",
"general",
".",
"MediaDownloadBlackList",
"{",
"if",
"entry",
"!=",
"\"",
"\"",
"{",
"re",
",",
"err",
":=",
"regexp",
".",
"Compile",
"(",
"entry",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"logger",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"entry",
",",
"msg",
".",
"Account",
")",
"\n",
"continue",
"\n",
"}",
"\n",
"if",
"re",
".",
"MatchString",
"(",
"name",
")",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"entry",
",",
"name",
")",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n",
"logger",
".",
"Debugf",
"(",
"\"",
"\"",
",",
"name",
",",
"size",
")",
"\n",
"if",
"int",
"(",
"size",
")",
">",
"general",
".",
"MediaDownloadSize",
"{",
"msg",
".",
"Event",
"=",
"config",
".",
"EventFileFailureSize",
"\n",
"msg",
".",
"Extra",
"[",
"msg",
".",
"Event",
"]",
"=",
"append",
"(",
"msg",
".",
"Extra",
"[",
"msg",
".",
"Event",
"]",
",",
"config",
".",
"FileInfo",
"{",
"Name",
":",
"name",
",",
"Comment",
":",
"msg",
".",
"Text",
",",
"Size",
":",
"size",
",",
"}",
")",
"\n",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"name",
",",
"size",
",",
"general",
".",
"MediaDownloadSize",
")",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] | // HandleDownloadSize checks a specified filename against the configured download blacklist
// and checks a specified file-size against the configure limit. | [
"HandleDownloadSize",
"checks",
"a",
"specified",
"filename",
"against",
"the",
"configured",
"download",
"blacklist",
"and",
"checks",
"a",
"specified",
"file",
"-",
"size",
"against",
"the",
"configure",
"limit",
"."
] | 1b2feb19e506bc24580d5d61422d0de68349c24e | https://github.com/42wim/matterbridge/blob/1b2feb19e506bc24580d5d61422d0de68349c24e/bridge/helper/helper.go#L114-L139 | train |
42wim/matterbridge | bridge/helper/helper.go | HandleDownloadData | func HandleDownloadData(logger *logrus.Entry, msg *config.Message, name, comment, url string, data *[]byte, general *config.Protocol) {
var avatar bool
logger.Debugf("Download OK %#v %#v", name, len(*data))
if msg.Event == config.EventAvatarDownload {
avatar = true
}
msg.Extra["file"] = append(msg.Extra["file"], config.FileInfo{
Name: name,
Data: data,
URL: url,
Comment: comment,
Avatar: avatar,
})
} | go | func HandleDownloadData(logger *logrus.Entry, msg *config.Message, name, comment, url string, data *[]byte, general *config.Protocol) {
var avatar bool
logger.Debugf("Download OK %#v %#v", name, len(*data))
if msg.Event == config.EventAvatarDownload {
avatar = true
}
msg.Extra["file"] = append(msg.Extra["file"], config.FileInfo{
Name: name,
Data: data,
URL: url,
Comment: comment,
Avatar: avatar,
})
} | [
"func",
"HandleDownloadData",
"(",
"logger",
"*",
"logrus",
".",
"Entry",
",",
"msg",
"*",
"config",
".",
"Message",
",",
"name",
",",
"comment",
",",
"url",
"string",
",",
"data",
"*",
"[",
"]",
"byte",
",",
"general",
"*",
"config",
".",
"Protocol",
")",
"{",
"var",
"avatar",
"bool",
"\n",
"logger",
".",
"Debugf",
"(",
"\"",
"\"",
",",
"name",
",",
"len",
"(",
"*",
"data",
")",
")",
"\n",
"if",
"msg",
".",
"Event",
"==",
"config",
".",
"EventAvatarDownload",
"{",
"avatar",
"=",
"true",
"\n",
"}",
"\n",
"msg",
".",
"Extra",
"[",
"\"",
"\"",
"]",
"=",
"append",
"(",
"msg",
".",
"Extra",
"[",
"\"",
"\"",
"]",
",",
"config",
".",
"FileInfo",
"{",
"Name",
":",
"name",
",",
"Data",
":",
"data",
",",
"URL",
":",
"url",
",",
"Comment",
":",
"comment",
",",
"Avatar",
":",
"avatar",
",",
"}",
")",
"\n",
"}"
] | // HandleDownloadData adds the data for a remote file into a Matterbridge gateway message. | [
"HandleDownloadData",
"adds",
"the",
"data",
"for",
"a",
"remote",
"file",
"into",
"a",
"Matterbridge",
"gateway",
"message",
"."
] | 1b2feb19e506bc24580d5d61422d0de68349c24e | https://github.com/42wim/matterbridge/blob/1b2feb19e506bc24580d5d61422d0de68349c24e/bridge/helper/helper.go#L142-L155 | train |
42wim/matterbridge | bridge/helper/helper.go | ClipMessage | func ClipMessage(text string, length int) string {
const clippingMessage = " <clipped message>"
if len(text) > length {
text = text[:length-len(clippingMessage)]
if r, size := utf8.DecodeLastRuneInString(text); r == utf8.RuneError {
text = text[:len(text)-size]
}
text += clippingMessage
}
return text
} | go | func ClipMessage(text string, length int) string {
const clippingMessage = " <clipped message>"
if len(text) > length {
text = text[:length-len(clippingMessage)]
if r, size := utf8.DecodeLastRuneInString(text); r == utf8.RuneError {
text = text[:len(text)-size]
}
text += clippingMessage
}
return text
} | [
"func",
"ClipMessage",
"(",
"text",
"string",
",",
"length",
"int",
")",
"string",
"{",
"const",
"clippingMessage",
"=",
"\"",
"\"",
"\n",
"if",
"len",
"(",
"text",
")",
">",
"length",
"{",
"text",
"=",
"text",
"[",
":",
"length",
"-",
"len",
"(",
"clippingMessage",
")",
"]",
"\n",
"if",
"r",
",",
"size",
":=",
"utf8",
".",
"DecodeLastRuneInString",
"(",
"text",
")",
";",
"r",
"==",
"utf8",
".",
"RuneError",
"{",
"text",
"=",
"text",
"[",
":",
"len",
"(",
"text",
")",
"-",
"size",
"]",
"\n",
"}",
"\n",
"text",
"+=",
"clippingMessage",
"\n",
"}",
"\n",
"return",
"text",
"\n",
"}"
] | // ClipMessage trims a message to the specified length if it exceeds it and adds a warning
// to the message in case it does so. | [
"ClipMessage",
"trims",
"a",
"message",
"to",
"the",
"specified",
"length",
"if",
"it",
"exceeds",
"it",
"and",
"adds",
"a",
"warning",
"to",
"the",
"message",
"in",
"case",
"it",
"does",
"so",
"."
] | 1b2feb19e506bc24580d5d61422d0de68349c24e | https://github.com/42wim/matterbridge/blob/1b2feb19e506bc24580d5d61422d0de68349c24e/bridge/helper/helper.go#L167-L177 | train |
42wim/matterbridge | matterclient/matterclient.go | New | func New(login string, pass string, team string, server string) *MMClient {
rootLogger := logrus.New()
rootLogger.SetFormatter(&prefixed.TextFormatter{
PrefixPadding: 13,
DisableColors: true,
})
cred := &Credentials{
Login: login,
Pass: pass,
Team: team,
Server: server,
}
cache, _ := lru.New(500)
return &MMClient{
Credentials: cred,
MessageChan: make(chan *Message, 100),
Users: make(map[string]*model.User),
rootLogger: rootLogger,
lruCache: cache,
logger: rootLogger.WithFields(logrus.Fields{"prefix": "matterclient"}),
}
} | go | func New(login string, pass string, team string, server string) *MMClient {
rootLogger := logrus.New()
rootLogger.SetFormatter(&prefixed.TextFormatter{
PrefixPadding: 13,
DisableColors: true,
})
cred := &Credentials{
Login: login,
Pass: pass,
Team: team,
Server: server,
}
cache, _ := lru.New(500)
return &MMClient{
Credentials: cred,
MessageChan: make(chan *Message, 100),
Users: make(map[string]*model.User),
rootLogger: rootLogger,
lruCache: cache,
logger: rootLogger.WithFields(logrus.Fields{"prefix": "matterclient"}),
}
} | [
"func",
"New",
"(",
"login",
"string",
",",
"pass",
"string",
",",
"team",
"string",
",",
"server",
"string",
")",
"*",
"MMClient",
"{",
"rootLogger",
":=",
"logrus",
".",
"New",
"(",
")",
"\n",
"rootLogger",
".",
"SetFormatter",
"(",
"&",
"prefixed",
".",
"TextFormatter",
"{",
"PrefixPadding",
":",
"13",
",",
"DisableColors",
":",
"true",
",",
"}",
")",
"\n\n",
"cred",
":=",
"&",
"Credentials",
"{",
"Login",
":",
"login",
",",
"Pass",
":",
"pass",
",",
"Team",
":",
"team",
",",
"Server",
":",
"server",
",",
"}",
"\n\n",
"cache",
",",
"_",
":=",
"lru",
".",
"New",
"(",
"500",
")",
"\n",
"return",
"&",
"MMClient",
"{",
"Credentials",
":",
"cred",
",",
"MessageChan",
":",
"make",
"(",
"chan",
"*",
"Message",
",",
"100",
")",
",",
"Users",
":",
"make",
"(",
"map",
"[",
"string",
"]",
"*",
"model",
".",
"User",
")",
",",
"rootLogger",
":",
"rootLogger",
",",
"lruCache",
":",
"cache",
",",
"logger",
":",
"rootLogger",
".",
"WithFields",
"(",
"logrus",
".",
"Fields",
"{",
"\"",
"\"",
":",
"\"",
"\"",
"}",
")",
",",
"}",
"\n",
"}"
] | // New will instantiate a new Matterclient with the specified login details without connecting. | [
"New",
"will",
"instantiate",
"a",
"new",
"Matterclient",
"with",
"the",
"specified",
"login",
"details",
"without",
"connecting",
"."
] | 1b2feb19e506bc24580d5d61422d0de68349c24e | https://github.com/42wim/matterbridge/blob/1b2feb19e506bc24580d5d61422d0de68349c24e/matterclient/matterclient.go#L74-L97 | train |
42wim/matterbridge | matterclient/matterclient.go | SetDebugLog | func (m *MMClient) SetDebugLog() {
m.rootLogger.SetFormatter(&prefixed.TextFormatter{
PrefixPadding: 13,
DisableColors: true,
FullTimestamp: false,
ForceFormatting: true,
})
} | go | func (m *MMClient) SetDebugLog() {
m.rootLogger.SetFormatter(&prefixed.TextFormatter{
PrefixPadding: 13,
DisableColors: true,
FullTimestamp: false,
ForceFormatting: true,
})
} | [
"func",
"(",
"m",
"*",
"MMClient",
")",
"SetDebugLog",
"(",
")",
"{",
"m",
".",
"rootLogger",
".",
"SetFormatter",
"(",
"&",
"prefixed",
".",
"TextFormatter",
"{",
"PrefixPadding",
":",
"13",
",",
"DisableColors",
":",
"true",
",",
"FullTimestamp",
":",
"false",
",",
"ForceFormatting",
":",
"true",
",",
"}",
")",
"\n",
"}"
] | // SetDebugLog activates debugging logging on all Matterclient log output. | [
"SetDebugLog",
"activates",
"debugging",
"logging",
"on",
"all",
"Matterclient",
"log",
"output",
"."
] | 1b2feb19e506bc24580d5d61422d0de68349c24e | https://github.com/42wim/matterbridge/blob/1b2feb19e506bc24580d5d61422d0de68349c24e/matterclient/matterclient.go#L100-L107 | train |
42wim/matterbridge | matterclient/matterclient.go | Login | func (m *MMClient) Login() error {
// check if this is a first connect or a reconnection
firstConnection := true
if m.WsConnected {
firstConnection = false
}
m.WsConnected = false
if m.WsQuit {
return nil
}
b := &backoff.Backoff{
Min: time.Second,
Max: 5 * time.Minute,
Jitter: true,
}
// do initialization setup
if err := m.initClient(firstConnection, b); err != nil {
return err
}
if err := m.doLogin(firstConnection, b); err != nil {
return err
}
if err := m.initUser(); err != nil {
return err
}
if m.Team == nil {
validTeamNames := make([]string, len(m.OtherTeams))
for i, t := range m.OtherTeams {
validTeamNames[i] = t.Team.Name
}
return fmt.Errorf("Team '%s' not found in %v", m.Credentials.Team, validTeamNames)
}
m.wsConnect()
return nil
} | go | func (m *MMClient) Login() error {
// check if this is a first connect or a reconnection
firstConnection := true
if m.WsConnected {
firstConnection = false
}
m.WsConnected = false
if m.WsQuit {
return nil
}
b := &backoff.Backoff{
Min: time.Second,
Max: 5 * time.Minute,
Jitter: true,
}
// do initialization setup
if err := m.initClient(firstConnection, b); err != nil {
return err
}
if err := m.doLogin(firstConnection, b); err != nil {
return err
}
if err := m.initUser(); err != nil {
return err
}
if m.Team == nil {
validTeamNames := make([]string, len(m.OtherTeams))
for i, t := range m.OtherTeams {
validTeamNames[i] = t.Team.Name
}
return fmt.Errorf("Team '%s' not found in %v", m.Credentials.Team, validTeamNames)
}
m.wsConnect()
return nil
} | [
"func",
"(",
"m",
"*",
"MMClient",
")",
"Login",
"(",
")",
"error",
"{",
"// check if this is a first connect or a reconnection",
"firstConnection",
":=",
"true",
"\n",
"if",
"m",
".",
"WsConnected",
"{",
"firstConnection",
"=",
"false",
"\n",
"}",
"\n",
"m",
".",
"WsConnected",
"=",
"false",
"\n",
"if",
"m",
".",
"WsQuit",
"{",
"return",
"nil",
"\n",
"}",
"\n",
"b",
":=",
"&",
"backoff",
".",
"Backoff",
"{",
"Min",
":",
"time",
".",
"Second",
",",
"Max",
":",
"5",
"*",
"time",
".",
"Minute",
",",
"Jitter",
":",
"true",
",",
"}",
"\n\n",
"// do initialization setup",
"if",
"err",
":=",
"m",
".",
"initClient",
"(",
"firstConnection",
",",
"b",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"if",
"err",
":=",
"m",
".",
"doLogin",
"(",
"firstConnection",
",",
"b",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"if",
"err",
":=",
"m",
".",
"initUser",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"if",
"m",
".",
"Team",
"==",
"nil",
"{",
"validTeamNames",
":=",
"make",
"(",
"[",
"]",
"string",
",",
"len",
"(",
"m",
".",
"OtherTeams",
")",
")",
"\n",
"for",
"i",
",",
"t",
":=",
"range",
"m",
".",
"OtherTeams",
"{",
"validTeamNames",
"[",
"i",
"]",
"=",
"t",
".",
"Team",
".",
"Name",
"\n",
"}",
"\n",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"m",
".",
"Credentials",
".",
"Team",
",",
"validTeamNames",
")",
"\n",
"}",
"\n\n",
"m",
".",
"wsConnect",
"(",
")",
"\n\n",
"return",
"nil",
"\n",
"}"
] | // Login tries to connect the client with the loging details with which it was initialized. | [
"Login",
"tries",
"to",
"connect",
"the",
"client",
"with",
"the",
"loging",
"details",
"with",
"which",
"it",
"was",
"initialized",
"."
] | 1b2feb19e506bc24580d5d61422d0de68349c24e | https://github.com/42wim/matterbridge/blob/1b2feb19e506bc24580d5d61422d0de68349c24e/matterclient/matterclient.go#L122-L162 | train |
42wim/matterbridge | matterclient/matterclient.go | Logout | func (m *MMClient) Logout() error {
m.logger.Debugf("logout as %s (team: %s) on %s", m.Credentials.Login, m.Credentials.Team, m.Credentials.Server)
m.WsQuit = true
m.WsClient.Close()
m.WsClient.UnderlyingConn().Close()
if strings.Contains(m.Credentials.Pass, model.SESSION_COOKIE_TOKEN) {
m.logger.Debug("Not invalidating session in logout, credential is a token")
return nil
}
_, resp := m.Client.Logout()
if resp.Error != nil {
return resp.Error
}
return nil
} | go | func (m *MMClient) Logout() error {
m.logger.Debugf("logout as %s (team: %s) on %s", m.Credentials.Login, m.Credentials.Team, m.Credentials.Server)
m.WsQuit = true
m.WsClient.Close()
m.WsClient.UnderlyingConn().Close()
if strings.Contains(m.Credentials.Pass, model.SESSION_COOKIE_TOKEN) {
m.logger.Debug("Not invalidating session in logout, credential is a token")
return nil
}
_, resp := m.Client.Logout()
if resp.Error != nil {
return resp.Error
}
return nil
} | [
"func",
"(",
"m",
"*",
"MMClient",
")",
"Logout",
"(",
")",
"error",
"{",
"m",
".",
"logger",
".",
"Debugf",
"(",
"\"",
"\"",
",",
"m",
".",
"Credentials",
".",
"Login",
",",
"m",
".",
"Credentials",
".",
"Team",
",",
"m",
".",
"Credentials",
".",
"Server",
")",
"\n",
"m",
".",
"WsQuit",
"=",
"true",
"\n",
"m",
".",
"WsClient",
".",
"Close",
"(",
")",
"\n",
"m",
".",
"WsClient",
".",
"UnderlyingConn",
"(",
")",
".",
"Close",
"(",
")",
"\n",
"if",
"strings",
".",
"Contains",
"(",
"m",
".",
"Credentials",
".",
"Pass",
",",
"model",
".",
"SESSION_COOKIE_TOKEN",
")",
"{",
"m",
".",
"logger",
".",
"Debug",
"(",
"\"",
"\"",
")",
"\n",
"return",
"nil",
"\n",
"}",
"\n",
"_",
",",
"resp",
":=",
"m",
".",
"Client",
".",
"Logout",
"(",
")",
"\n",
"if",
"resp",
".",
"Error",
"!=",
"nil",
"{",
"return",
"resp",
".",
"Error",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] | // Logout disconnects the client from the chat server. | [
"Logout",
"disconnects",
"the",
"client",
"from",
"the",
"chat",
"server",
"."
] | 1b2feb19e506bc24580d5d61422d0de68349c24e | https://github.com/42wim/matterbridge/blob/1b2feb19e506bc24580d5d61422d0de68349c24e/matterclient/matterclient.go#L165-L179 | train |
42wim/matterbridge | matterclient/matterclient.go | WsReceiver | func (m *MMClient) WsReceiver() {
for {
var rawMsg json.RawMessage
var err error
if m.WsQuit {
m.logger.Debug("exiting WsReceiver")
return
}
if !m.WsConnected {
time.Sleep(time.Millisecond * 100)
continue
}
if _, rawMsg, err = m.WsClient.ReadMessage(); err != nil {
m.logger.Error("error:", err)
// reconnect
m.wsConnect()
}
var event model.WebSocketEvent
if err := json.Unmarshal(rawMsg, &event); err == nil && event.IsValid() {
m.logger.Debugf("WsReceiver event: %#v", event)
msg := &Message{Raw: &event, Team: m.Credentials.Team}
m.parseMessage(msg)
// check if we didn't empty the message
if msg.Text != "" {
m.MessageChan <- msg
continue
}
// if we have file attached but the message is empty, also send it
if msg.Post != nil {
if msg.Text != "" || len(msg.Post.FileIds) > 0 || msg.Post.Type == "slack_attachment" {
m.MessageChan <- msg
continue
}
}
switch msg.Raw.Event {
case model.WEBSOCKET_EVENT_USER_ADDED,
model.WEBSOCKET_EVENT_USER_REMOVED,
model.WEBSOCKET_EVENT_CHANNEL_CREATED,
model.WEBSOCKET_EVENT_CHANNEL_DELETED:
m.MessageChan <- msg
continue
}
}
var response model.WebSocketResponse
if err := json.Unmarshal(rawMsg, &response); err == nil && response.IsValid() {
m.logger.Debugf("WsReceiver response: %#v", response)
m.parseResponse(response)
}
}
} | go | func (m *MMClient) WsReceiver() {
for {
var rawMsg json.RawMessage
var err error
if m.WsQuit {
m.logger.Debug("exiting WsReceiver")
return
}
if !m.WsConnected {
time.Sleep(time.Millisecond * 100)
continue
}
if _, rawMsg, err = m.WsClient.ReadMessage(); err != nil {
m.logger.Error("error:", err)
// reconnect
m.wsConnect()
}
var event model.WebSocketEvent
if err := json.Unmarshal(rawMsg, &event); err == nil && event.IsValid() {
m.logger.Debugf("WsReceiver event: %#v", event)
msg := &Message{Raw: &event, Team: m.Credentials.Team}
m.parseMessage(msg)
// check if we didn't empty the message
if msg.Text != "" {
m.MessageChan <- msg
continue
}
// if we have file attached but the message is empty, also send it
if msg.Post != nil {
if msg.Text != "" || len(msg.Post.FileIds) > 0 || msg.Post.Type == "slack_attachment" {
m.MessageChan <- msg
continue
}
}
switch msg.Raw.Event {
case model.WEBSOCKET_EVENT_USER_ADDED,
model.WEBSOCKET_EVENT_USER_REMOVED,
model.WEBSOCKET_EVENT_CHANNEL_CREATED,
model.WEBSOCKET_EVENT_CHANNEL_DELETED:
m.MessageChan <- msg
continue
}
}
var response model.WebSocketResponse
if err := json.Unmarshal(rawMsg, &response); err == nil && response.IsValid() {
m.logger.Debugf("WsReceiver response: %#v", response)
m.parseResponse(response)
}
}
} | [
"func",
"(",
"m",
"*",
"MMClient",
")",
"WsReceiver",
"(",
")",
"{",
"for",
"{",
"var",
"rawMsg",
"json",
".",
"RawMessage",
"\n",
"var",
"err",
"error",
"\n\n",
"if",
"m",
".",
"WsQuit",
"{",
"m",
".",
"logger",
".",
"Debug",
"(",
"\"",
"\"",
")",
"\n",
"return",
"\n",
"}",
"\n\n",
"if",
"!",
"m",
".",
"WsConnected",
"{",
"time",
".",
"Sleep",
"(",
"time",
".",
"Millisecond",
"*",
"100",
")",
"\n",
"continue",
"\n",
"}",
"\n\n",
"if",
"_",
",",
"rawMsg",
",",
"err",
"=",
"m",
".",
"WsClient",
".",
"ReadMessage",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"m",
".",
"logger",
".",
"Error",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"// reconnect",
"m",
".",
"wsConnect",
"(",
")",
"\n",
"}",
"\n\n",
"var",
"event",
"model",
".",
"WebSocketEvent",
"\n",
"if",
"err",
":=",
"json",
".",
"Unmarshal",
"(",
"rawMsg",
",",
"&",
"event",
")",
";",
"err",
"==",
"nil",
"&&",
"event",
".",
"IsValid",
"(",
")",
"{",
"m",
".",
"logger",
".",
"Debugf",
"(",
"\"",
"\"",
",",
"event",
")",
"\n",
"msg",
":=",
"&",
"Message",
"{",
"Raw",
":",
"&",
"event",
",",
"Team",
":",
"m",
".",
"Credentials",
".",
"Team",
"}",
"\n",
"m",
".",
"parseMessage",
"(",
"msg",
")",
"\n",
"// check if we didn't empty the message",
"if",
"msg",
".",
"Text",
"!=",
"\"",
"\"",
"{",
"m",
".",
"MessageChan",
"<-",
"msg",
"\n",
"continue",
"\n",
"}",
"\n",
"// if we have file attached but the message is empty, also send it",
"if",
"msg",
".",
"Post",
"!=",
"nil",
"{",
"if",
"msg",
".",
"Text",
"!=",
"\"",
"\"",
"||",
"len",
"(",
"msg",
".",
"Post",
".",
"FileIds",
")",
">",
"0",
"||",
"msg",
".",
"Post",
".",
"Type",
"==",
"\"",
"\"",
"{",
"m",
".",
"MessageChan",
"<-",
"msg",
"\n",
"continue",
"\n",
"}",
"\n",
"}",
"\n",
"switch",
"msg",
".",
"Raw",
".",
"Event",
"{",
"case",
"model",
".",
"WEBSOCKET_EVENT_USER_ADDED",
",",
"model",
".",
"WEBSOCKET_EVENT_USER_REMOVED",
",",
"model",
".",
"WEBSOCKET_EVENT_CHANNEL_CREATED",
",",
"model",
".",
"WEBSOCKET_EVENT_CHANNEL_DELETED",
":",
"m",
".",
"MessageChan",
"<-",
"msg",
"\n",
"continue",
"\n",
"}",
"\n",
"}",
"\n\n",
"var",
"response",
"model",
".",
"WebSocketResponse",
"\n",
"if",
"err",
":=",
"json",
".",
"Unmarshal",
"(",
"rawMsg",
",",
"&",
"response",
")",
";",
"err",
"==",
"nil",
"&&",
"response",
".",
"IsValid",
"(",
")",
"{",
"m",
".",
"logger",
".",
"Debugf",
"(",
"\"",
"\"",
",",
"response",
")",
"\n",
"m",
".",
"parseResponse",
"(",
"response",
")",
"\n",
"}",
"\n",
"}",
"\n",
"}"
] | // WsReceiver implements the core loop that manages the connection to the chat server. In
// case of a disconnect it will try to reconnect. A call to this method is blocking until
// the 'WsQuite' field of the MMClient object is set to 'true'. | [
"WsReceiver",
"implements",
"the",
"core",
"loop",
"that",
"manages",
"the",
"connection",
"to",
"the",
"chat",
"server",
".",
"In",
"case",
"of",
"a",
"disconnect",
"it",
"will",
"try",
"to",
"reconnect",
".",
"A",
"call",
"to",
"this",
"method",
"is",
"blocking",
"until",
"the",
"WsQuite",
"field",
"of",
"the",
"MMClient",
"object",
"is",
"set",
"to",
"true",
"."
] | 1b2feb19e506bc24580d5d61422d0de68349c24e | https://github.com/42wim/matterbridge/blob/1b2feb19e506bc24580d5d61422d0de68349c24e/matterclient/matterclient.go#L184-L238 | train |
42wim/matterbridge | matterclient/matterclient.go | StatusLoop | func (m *MMClient) StatusLoop() {
retries := 0
backoff := time.Second * 60
if m.OnWsConnect != nil {
m.OnWsConnect()
}
m.logger.Debug("StatusLoop:", m.OnWsConnect != nil)
for {
if m.WsQuit {
return
}
if m.WsConnected {
if err := m.checkAlive(); err != nil {
m.logger.Errorf("Connection is not alive: %#v", err)
}
select {
case <-m.WsPingChan:
m.logger.Debug("WS PONG received")
backoff = time.Second * 60
case <-time.After(time.Second * 5):
if retries > 3 {
m.logger.Debug("StatusLoop() timeout")
m.Logout()
m.WsQuit = false
err := m.Login()
if err != nil {
m.logger.Errorf("Login failed: %#v", err)
break
}
if m.OnWsConnect != nil {
m.OnWsConnect()
}
go m.WsReceiver()
} else {
retries++
backoff = time.Second * 5
}
}
}
time.Sleep(backoff)
}
} | go | func (m *MMClient) StatusLoop() {
retries := 0
backoff := time.Second * 60
if m.OnWsConnect != nil {
m.OnWsConnect()
}
m.logger.Debug("StatusLoop:", m.OnWsConnect != nil)
for {
if m.WsQuit {
return
}
if m.WsConnected {
if err := m.checkAlive(); err != nil {
m.logger.Errorf("Connection is not alive: %#v", err)
}
select {
case <-m.WsPingChan:
m.logger.Debug("WS PONG received")
backoff = time.Second * 60
case <-time.After(time.Second * 5):
if retries > 3 {
m.logger.Debug("StatusLoop() timeout")
m.Logout()
m.WsQuit = false
err := m.Login()
if err != nil {
m.logger.Errorf("Login failed: %#v", err)
break
}
if m.OnWsConnect != nil {
m.OnWsConnect()
}
go m.WsReceiver()
} else {
retries++
backoff = time.Second * 5
}
}
}
time.Sleep(backoff)
}
} | [
"func",
"(",
"m",
"*",
"MMClient",
")",
"StatusLoop",
"(",
")",
"{",
"retries",
":=",
"0",
"\n",
"backoff",
":=",
"time",
".",
"Second",
"*",
"60",
"\n",
"if",
"m",
".",
"OnWsConnect",
"!=",
"nil",
"{",
"m",
".",
"OnWsConnect",
"(",
")",
"\n",
"}",
"\n",
"m",
".",
"logger",
".",
"Debug",
"(",
"\"",
"\"",
",",
"m",
".",
"OnWsConnect",
"!=",
"nil",
")",
"\n",
"for",
"{",
"if",
"m",
".",
"WsQuit",
"{",
"return",
"\n",
"}",
"\n",
"if",
"m",
".",
"WsConnected",
"{",
"if",
"err",
":=",
"m",
".",
"checkAlive",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"m",
".",
"logger",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n",
"select",
"{",
"case",
"<-",
"m",
".",
"WsPingChan",
":",
"m",
".",
"logger",
".",
"Debug",
"(",
"\"",
"\"",
")",
"\n",
"backoff",
"=",
"time",
".",
"Second",
"*",
"60",
"\n",
"case",
"<-",
"time",
".",
"After",
"(",
"time",
".",
"Second",
"*",
"5",
")",
":",
"if",
"retries",
">",
"3",
"{",
"m",
".",
"logger",
".",
"Debug",
"(",
"\"",
"\"",
")",
"\n",
"m",
".",
"Logout",
"(",
")",
"\n",
"m",
".",
"WsQuit",
"=",
"false",
"\n",
"err",
":=",
"m",
".",
"Login",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"m",
".",
"logger",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"break",
"\n",
"}",
"\n",
"if",
"m",
".",
"OnWsConnect",
"!=",
"nil",
"{",
"m",
".",
"OnWsConnect",
"(",
")",
"\n",
"}",
"\n",
"go",
"m",
".",
"WsReceiver",
"(",
")",
"\n",
"}",
"else",
"{",
"retries",
"++",
"\n",
"backoff",
"=",
"time",
".",
"Second",
"*",
"5",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n",
"time",
".",
"Sleep",
"(",
"backoff",
")",
"\n",
"}",
"\n",
"}"
] | // StatusLoop implements a ping-cycle that ensures that the connection to the chat servers
// remains alive. In case of a disconnect it will try to reconnect. A call to this method
// is blocking until the 'WsQuite' field of the MMClient object is set to 'true'. | [
"StatusLoop",
"implements",
"a",
"ping",
"-",
"cycle",
"that",
"ensures",
"that",
"the",
"connection",
"to",
"the",
"chat",
"servers",
"remains",
"alive",
".",
"In",
"case",
"of",
"a",
"disconnect",
"it",
"will",
"try",
"to",
"reconnect",
".",
"A",
"call",
"to",
"this",
"method",
"is",
"blocking",
"until",
"the",
"WsQuite",
"field",
"of",
"the",
"MMClient",
"object",
"is",
"set",
"to",
"true",
"."
] | 1b2feb19e506bc24580d5d61422d0de68349c24e | https://github.com/42wim/matterbridge/blob/1b2feb19e506bc24580d5d61422d0de68349c24e/matterclient/matterclient.go#L243-L284 | train |
42wim/matterbridge | bridge/slack/slack.go | JoinChannel | func (b *Bslack) JoinChannel(channel config.ChannelInfo) error {
// We can only join a channel through the Slack API.
if b.sc == nil {
return nil
}
b.channels.populateChannels(false)
channelInfo, err := b.channels.getChannel(channel.Name)
if err != nil {
return fmt.Errorf("could not join channel: %#v", err)
}
if strings.HasPrefix(channel.Name, "ID:") {
b.useChannelID = true
channel.Name = channelInfo.Name
}
if !channelInfo.IsMember {
return fmt.Errorf("slack integration that matterbridge is using is not member of channel '%s', please add it manually", channelInfo.Name)
}
return nil
} | go | func (b *Bslack) JoinChannel(channel config.ChannelInfo) error {
// We can only join a channel through the Slack API.
if b.sc == nil {
return nil
}
b.channels.populateChannels(false)
channelInfo, err := b.channels.getChannel(channel.Name)
if err != nil {
return fmt.Errorf("could not join channel: %#v", err)
}
if strings.HasPrefix(channel.Name, "ID:") {
b.useChannelID = true
channel.Name = channelInfo.Name
}
if !channelInfo.IsMember {
return fmt.Errorf("slack integration that matterbridge is using is not member of channel '%s', please add it manually", channelInfo.Name)
}
return nil
} | [
"func",
"(",
"b",
"*",
"Bslack",
")",
"JoinChannel",
"(",
"channel",
"config",
".",
"ChannelInfo",
")",
"error",
"{",
"// We can only join a channel through the Slack API.",
"if",
"b",
".",
"sc",
"==",
"nil",
"{",
"return",
"nil",
"\n",
"}",
"\n\n",
"b",
".",
"channels",
".",
"populateChannels",
"(",
"false",
")",
"\n\n",
"channelInfo",
",",
"err",
":=",
"b",
".",
"channels",
".",
"getChannel",
"(",
"channel",
".",
"Name",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n\n",
"if",
"strings",
".",
"HasPrefix",
"(",
"channel",
".",
"Name",
",",
"\"",
"\"",
")",
"{",
"b",
".",
"useChannelID",
"=",
"true",
"\n",
"channel",
".",
"Name",
"=",
"channelInfo",
".",
"Name",
"\n",
"}",
"\n\n",
"if",
"!",
"channelInfo",
".",
"IsMember",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"channelInfo",
".",
"Name",
")",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] | // JoinChannel only acts as a verification method that checks whether Matterbridge's
// Slack integration is already member of the channel. This is because Slack does not
// allow apps or bots to join channels themselves and they need to be invited
// manually by a user. | [
"JoinChannel",
"only",
"acts",
"as",
"a",
"verification",
"method",
"that",
"checks",
"whether",
"Matterbridge",
"s",
"Slack",
"integration",
"is",
"already",
"member",
"of",
"the",
"channel",
".",
"This",
"is",
"because",
"Slack",
"does",
"not",
"allow",
"apps",
"or",
"bots",
"to",
"join",
"channels",
"themselves",
"and",
"they",
"need",
"to",
"be",
"invited",
"manually",
"by",
"a",
"user",
"."
] | 1b2feb19e506bc24580d5d61422d0de68349c24e | https://github.com/42wim/matterbridge/blob/1b2feb19e506bc24580d5d61422d0de68349c24e/bridge/slack/slack.go#L148-L170 | train |
42wim/matterbridge | bridge/slack/slack.go | uploadFile | func (b *Bslack) uploadFile(msg *config.Message, channelID string) {
for _, f := range msg.Extra["file"] {
fi, ok := f.(config.FileInfo)
if !ok {
b.Log.Errorf("Received a file with unexpected content: %#v", f)
continue
}
if msg.Text == fi.Comment {
msg.Text = ""
}
// Because the result of the UploadFile is slower than the MessageEvent from slack
// we can't match on the file ID yet, so we have to match on the filename too.
ts := time.Now()
b.Log.Debugf("Adding file %s to cache at %s with timestamp", fi.Name, ts.String())
b.cache.Add("filename"+fi.Name, ts)
initialComment := fmt.Sprintf("File from %s", msg.Username)
if fi.Comment != "" {
initialComment += fmt.Sprintf("with comment: %s", fi.Comment)
}
res, err := b.sc.UploadFile(slack.FileUploadParameters{
Reader: bytes.NewReader(*fi.Data),
Filename: fi.Name,
Channels: []string{channelID},
InitialComment: initialComment,
ThreadTimestamp: msg.ParentID,
})
if err != nil {
b.Log.Errorf("uploadfile %#v", err)
return
}
if res.ID != "" {
b.Log.Debugf("Adding file ID %s to cache with timestamp %s", res.ID, ts.String())
b.cache.Add("file"+res.ID, ts)
}
}
} | go | func (b *Bslack) uploadFile(msg *config.Message, channelID string) {
for _, f := range msg.Extra["file"] {
fi, ok := f.(config.FileInfo)
if !ok {
b.Log.Errorf("Received a file with unexpected content: %#v", f)
continue
}
if msg.Text == fi.Comment {
msg.Text = ""
}
// Because the result of the UploadFile is slower than the MessageEvent from slack
// we can't match on the file ID yet, so we have to match on the filename too.
ts := time.Now()
b.Log.Debugf("Adding file %s to cache at %s with timestamp", fi.Name, ts.String())
b.cache.Add("filename"+fi.Name, ts)
initialComment := fmt.Sprintf("File from %s", msg.Username)
if fi.Comment != "" {
initialComment += fmt.Sprintf("with comment: %s", fi.Comment)
}
res, err := b.sc.UploadFile(slack.FileUploadParameters{
Reader: bytes.NewReader(*fi.Data),
Filename: fi.Name,
Channels: []string{channelID},
InitialComment: initialComment,
ThreadTimestamp: msg.ParentID,
})
if err != nil {
b.Log.Errorf("uploadfile %#v", err)
return
}
if res.ID != "" {
b.Log.Debugf("Adding file ID %s to cache with timestamp %s", res.ID, ts.String())
b.cache.Add("file"+res.ID, ts)
}
}
} | [
"func",
"(",
"b",
"*",
"Bslack",
")",
"uploadFile",
"(",
"msg",
"*",
"config",
".",
"Message",
",",
"channelID",
"string",
")",
"{",
"for",
"_",
",",
"f",
":=",
"range",
"msg",
".",
"Extra",
"[",
"\"",
"\"",
"]",
"{",
"fi",
",",
"ok",
":=",
"f",
".",
"(",
"config",
".",
"FileInfo",
")",
"\n",
"if",
"!",
"ok",
"{",
"b",
".",
"Log",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"f",
")",
"\n",
"continue",
"\n",
"}",
"\n",
"if",
"msg",
".",
"Text",
"==",
"fi",
".",
"Comment",
"{",
"msg",
".",
"Text",
"=",
"\"",
"\"",
"\n",
"}",
"\n",
"// Because the result of the UploadFile is slower than the MessageEvent from slack",
"// we can't match on the file ID yet, so we have to match on the filename too.",
"ts",
":=",
"time",
".",
"Now",
"(",
")",
"\n",
"b",
".",
"Log",
".",
"Debugf",
"(",
"\"",
"\"",
",",
"fi",
".",
"Name",
",",
"ts",
".",
"String",
"(",
")",
")",
"\n",
"b",
".",
"cache",
".",
"Add",
"(",
"\"",
"\"",
"+",
"fi",
".",
"Name",
",",
"ts",
")",
"\n",
"initialComment",
":=",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"msg",
".",
"Username",
")",
"\n",
"if",
"fi",
".",
"Comment",
"!=",
"\"",
"\"",
"{",
"initialComment",
"+=",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"fi",
".",
"Comment",
")",
"\n",
"}",
"\n",
"res",
",",
"err",
":=",
"b",
".",
"sc",
".",
"UploadFile",
"(",
"slack",
".",
"FileUploadParameters",
"{",
"Reader",
":",
"bytes",
".",
"NewReader",
"(",
"*",
"fi",
".",
"Data",
")",
",",
"Filename",
":",
"fi",
".",
"Name",
",",
"Channels",
":",
"[",
"]",
"string",
"{",
"channelID",
"}",
",",
"InitialComment",
":",
"initialComment",
",",
"ThreadTimestamp",
":",
"msg",
".",
"ParentID",
",",
"}",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"b",
".",
"Log",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"return",
"\n",
"}",
"\n",
"if",
"res",
".",
"ID",
"!=",
"\"",
"\"",
"{",
"b",
".",
"Log",
".",
"Debugf",
"(",
"\"",
"\"",
",",
"res",
".",
"ID",
",",
"ts",
".",
"String",
"(",
")",
")",
"\n",
"b",
".",
"cache",
".",
"Add",
"(",
"\"",
"\"",
"+",
"res",
".",
"ID",
",",
"ts",
")",
"\n",
"}",
"\n",
"}",
"\n",
"}"
] | // uploadFile handles native upload of files | [
"uploadFile",
"handles",
"native",
"upload",
"of",
"files"
] | 1b2feb19e506bc24580d5d61422d0de68349c24e | https://github.com/42wim/matterbridge/blob/1b2feb19e506bc24580d5d61422d0de68349c24e/bridge/slack/slack.go#L434-L469 | train |
42wim/matterbridge | bridge/irc/handlers.go | handleFiles | func (b *Birc) handleFiles(msg *config.Message) bool {
if msg.Extra == nil {
return false
}
for _, rmsg := range helper.HandleExtra(msg, b.General) {
b.Local <- rmsg
}
if len(msg.Extra["file"]) == 0 {
return false
}
for _, f := range msg.Extra["file"] {
fi := f.(config.FileInfo)
if fi.Comment != "" {
msg.Text += fi.Comment + ": "
}
if fi.URL != "" {
msg.Text = fi.URL
if fi.Comment != "" {
msg.Text = fi.Comment + ": " + fi.URL
}
}
b.Local <- config.Message{Text: msg.Text, Username: msg.Username, Channel: msg.Channel, Event: msg.Event}
}
return true
} | go | func (b *Birc) handleFiles(msg *config.Message) bool {
if msg.Extra == nil {
return false
}
for _, rmsg := range helper.HandleExtra(msg, b.General) {
b.Local <- rmsg
}
if len(msg.Extra["file"]) == 0 {
return false
}
for _, f := range msg.Extra["file"] {
fi := f.(config.FileInfo)
if fi.Comment != "" {
msg.Text += fi.Comment + ": "
}
if fi.URL != "" {
msg.Text = fi.URL
if fi.Comment != "" {
msg.Text = fi.Comment + ": " + fi.URL
}
}
b.Local <- config.Message{Text: msg.Text, Username: msg.Username, Channel: msg.Channel, Event: msg.Event}
}
return true
} | [
"func",
"(",
"b",
"*",
"Birc",
")",
"handleFiles",
"(",
"msg",
"*",
"config",
".",
"Message",
")",
"bool",
"{",
"if",
"msg",
".",
"Extra",
"==",
"nil",
"{",
"return",
"false",
"\n",
"}",
"\n",
"for",
"_",
",",
"rmsg",
":=",
"range",
"helper",
".",
"HandleExtra",
"(",
"msg",
",",
"b",
".",
"General",
")",
"{",
"b",
".",
"Local",
"<-",
"rmsg",
"\n",
"}",
"\n",
"if",
"len",
"(",
"msg",
".",
"Extra",
"[",
"\"",
"\"",
"]",
")",
"==",
"0",
"{",
"return",
"false",
"\n",
"}",
"\n",
"for",
"_",
",",
"f",
":=",
"range",
"msg",
".",
"Extra",
"[",
"\"",
"\"",
"]",
"{",
"fi",
":=",
"f",
".",
"(",
"config",
".",
"FileInfo",
")",
"\n",
"if",
"fi",
".",
"Comment",
"!=",
"\"",
"\"",
"{",
"msg",
".",
"Text",
"+=",
"fi",
".",
"Comment",
"+",
"\"",
"\"",
"\n",
"}",
"\n",
"if",
"fi",
".",
"URL",
"!=",
"\"",
"\"",
"{",
"msg",
".",
"Text",
"=",
"fi",
".",
"URL",
"\n",
"if",
"fi",
".",
"Comment",
"!=",
"\"",
"\"",
"{",
"msg",
".",
"Text",
"=",
"fi",
".",
"Comment",
"+",
"\"",
"\"",
"+",
"fi",
".",
"URL",
"\n",
"}",
"\n",
"}",
"\n",
"b",
".",
"Local",
"<-",
"config",
".",
"Message",
"{",
"Text",
":",
"msg",
".",
"Text",
",",
"Username",
":",
"msg",
".",
"Username",
",",
"Channel",
":",
"msg",
".",
"Channel",
",",
"Event",
":",
"msg",
".",
"Event",
"}",
"\n",
"}",
"\n",
"return",
"true",
"\n",
"}"
] | // handleFiles returns true if we have handled the files, otherwise return false | [
"handleFiles",
"returns",
"true",
"if",
"we",
"have",
"handled",
"the",
"files",
"otherwise",
"return",
"false"
] | 1b2feb19e506bc24580d5d61422d0de68349c24e | https://github.com/42wim/matterbridge/blob/1b2feb19e506bc24580d5d61422d0de68349c24e/bridge/irc/handlers.go#L44-L68 | train |
42wim/matterbridge | bridge/config/config.go | NewConfig | func NewConfig(rootLogger *logrus.Logger, cfgfile string) Config {
logger := rootLogger.WithFields(logrus.Fields{"prefix": "config"})
viper.SetConfigFile(cfgfile)
input, err := ioutil.ReadFile(cfgfile)
if err != nil {
logger.Fatalf("Failed to read configuration file: %#v", err)
}
mycfg := newConfigFromString(logger, input)
if mycfg.cv.General.MediaDownloadSize == 0 {
mycfg.cv.General.MediaDownloadSize = 1000000
}
viper.WatchConfig()
viper.OnConfigChange(func(e fsnotify.Event) {
logger.Println("Config file changed:", e.Name)
})
return mycfg
} | go | func NewConfig(rootLogger *logrus.Logger, cfgfile string) Config {
logger := rootLogger.WithFields(logrus.Fields{"prefix": "config"})
viper.SetConfigFile(cfgfile)
input, err := ioutil.ReadFile(cfgfile)
if err != nil {
logger.Fatalf("Failed to read configuration file: %#v", err)
}
mycfg := newConfigFromString(logger, input)
if mycfg.cv.General.MediaDownloadSize == 0 {
mycfg.cv.General.MediaDownloadSize = 1000000
}
viper.WatchConfig()
viper.OnConfigChange(func(e fsnotify.Event) {
logger.Println("Config file changed:", e.Name)
})
return mycfg
} | [
"func",
"NewConfig",
"(",
"rootLogger",
"*",
"logrus",
".",
"Logger",
",",
"cfgfile",
"string",
")",
"Config",
"{",
"logger",
":=",
"rootLogger",
".",
"WithFields",
"(",
"logrus",
".",
"Fields",
"{",
"\"",
"\"",
":",
"\"",
"\"",
"}",
")",
"\n\n",
"viper",
".",
"SetConfigFile",
"(",
"cfgfile",
")",
"\n",
"input",
",",
"err",
":=",
"ioutil",
".",
"ReadFile",
"(",
"cfgfile",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"logger",
".",
"Fatalf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n\n",
"mycfg",
":=",
"newConfigFromString",
"(",
"logger",
",",
"input",
")",
"\n",
"if",
"mycfg",
".",
"cv",
".",
"General",
".",
"MediaDownloadSize",
"==",
"0",
"{",
"mycfg",
".",
"cv",
".",
"General",
".",
"MediaDownloadSize",
"=",
"1000000",
"\n",
"}",
"\n",
"viper",
".",
"WatchConfig",
"(",
")",
"\n",
"viper",
".",
"OnConfigChange",
"(",
"func",
"(",
"e",
"fsnotify",
".",
"Event",
")",
"{",
"logger",
".",
"Println",
"(",
"\"",
"\"",
",",
"e",
".",
"Name",
")",
"\n",
"}",
")",
"\n",
"return",
"mycfg",
"\n",
"}"
] | // NewConfig instantiates a new configuration based on the specified configuration file path. | [
"NewConfig",
"instantiates",
"a",
"new",
"configuration",
"based",
"on",
"the",
"specified",
"configuration",
"file",
"path",
"."
] | 1b2feb19e506bc24580d5d61422d0de68349c24e | https://github.com/42wim/matterbridge/blob/1b2feb19e506bc24580d5d61422d0de68349c24e/bridge/config/config.go#L224-L242 | train |
42wim/matterbridge | bridge/config/config.go | NewConfigFromString | func NewConfigFromString(rootLogger *logrus.Logger, input []byte) Config {
logger := rootLogger.WithFields(logrus.Fields{"prefix": "config"})
return newConfigFromString(logger, input)
} | go | func NewConfigFromString(rootLogger *logrus.Logger, input []byte) Config {
logger := rootLogger.WithFields(logrus.Fields{"prefix": "config"})
return newConfigFromString(logger, input)
} | [
"func",
"NewConfigFromString",
"(",
"rootLogger",
"*",
"logrus",
".",
"Logger",
",",
"input",
"[",
"]",
"byte",
")",
"Config",
"{",
"logger",
":=",
"rootLogger",
".",
"WithFields",
"(",
"logrus",
".",
"Fields",
"{",
"\"",
"\"",
":",
"\"",
"\"",
"}",
")",
"\n",
"return",
"newConfigFromString",
"(",
"logger",
",",
"input",
")",
"\n",
"}"
] | // NewConfigFromString instantiates a new configuration based on the specified string. | [
"NewConfigFromString",
"instantiates",
"a",
"new",
"configuration",
"based",
"on",
"the",
"specified",
"string",
"."
] | 1b2feb19e506bc24580d5d61422d0de68349c24e | https://github.com/42wim/matterbridge/blob/1b2feb19e506bc24580d5d61422d0de68349c24e/bridge/config/config.go#L245-L248 | train |
42wim/matterbridge | bridge/steam/handlers.go | handleFileInfo | func (b *Bsteam) handleFileInfo(msg *config.Message, f interface{}) error {
if _, ok := f.(config.FileInfo); !ok {
return fmt.Errorf("handleFileInfo cast failed %#v", f)
}
fi := f.(config.FileInfo)
if fi.Comment != "" {
msg.Text += fi.Comment + ": "
}
if fi.URL != "" {
msg.Text = fi.URL
if fi.Comment != "" {
msg.Text = fi.Comment + ": " + fi.URL
}
}
return nil
} | go | func (b *Bsteam) handleFileInfo(msg *config.Message, f interface{}) error {
if _, ok := f.(config.FileInfo); !ok {
return fmt.Errorf("handleFileInfo cast failed %#v", f)
}
fi := f.(config.FileInfo)
if fi.Comment != "" {
msg.Text += fi.Comment + ": "
}
if fi.URL != "" {
msg.Text = fi.URL
if fi.Comment != "" {
msg.Text = fi.Comment + ": " + fi.URL
}
}
return nil
} | [
"func",
"(",
"b",
"*",
"Bsteam",
")",
"handleFileInfo",
"(",
"msg",
"*",
"config",
".",
"Message",
",",
"f",
"interface",
"{",
"}",
")",
"error",
"{",
"if",
"_",
",",
"ok",
":=",
"f",
".",
"(",
"config",
".",
"FileInfo",
")",
";",
"!",
"ok",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"f",
")",
"\n",
"}",
"\n",
"fi",
":=",
"f",
".",
"(",
"config",
".",
"FileInfo",
")",
"\n",
"if",
"fi",
".",
"Comment",
"!=",
"\"",
"\"",
"{",
"msg",
".",
"Text",
"+=",
"fi",
".",
"Comment",
"+",
"\"",
"\"",
"\n",
"}",
"\n",
"if",
"fi",
".",
"URL",
"!=",
"\"",
"\"",
"{",
"msg",
".",
"Text",
"=",
"fi",
".",
"URL",
"\n",
"if",
"fi",
".",
"Comment",
"!=",
"\"",
"\"",
"{",
"msg",
".",
"Text",
"=",
"fi",
".",
"Comment",
"+",
"\"",
"\"",
"+",
"fi",
".",
"URL",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] | // handleFileInfo handles config.FileInfo and adds correct file comment or URL to msg.Text.
// Returns error if cast fails. | [
"handleFileInfo",
"handles",
"config",
".",
"FileInfo",
"and",
"adds",
"correct",
"file",
"comment",
"or",
"URL",
"to",
"msg",
".",
"Text",
".",
"Returns",
"error",
"if",
"cast",
"fails",
"."
] | 1b2feb19e506bc24580d5d61422d0de68349c24e | https://github.com/42wim/matterbridge/blob/1b2feb19e506bc24580d5d61422d0de68349c24e/bridge/steam/handlers.go#L111-L126 | train |
42wim/matterbridge | bridge/whatsapp/handlers.go | HandleTextMessage | func (b *Bwhatsapp) HandleTextMessage(message whatsapp.TextMessage) {
if message.Info.FromMe { // || !strings.Contains(strings.ToLower(message.Text), "@echo") {
return
}
// whatsapp sends last messages to show context , cut them
if message.Info.Timestamp < b.startedAt {
return
}
messageTime := time.Unix(int64(message.Info.Timestamp), 0) // TODO check how behaves between timezones
groupJid := message.Info.RemoteJid
senderJid := message.Info.SenderJid
if len(senderJid) == 0 {
// TODO workaround till https://github.com/Rhymen/go-whatsapp/issues/86 resolved
senderJid = *message.Info.Source.Participant
}
// translate sender's Jid to the nicest username we can get
senderName := b.getSenderName(senderJid)
if senderName == "" {
senderName = "Someone" // don't expose telephone number
}
extText := message.Info.Source.Message.ExtendedTextMessage
if extText != nil && extText.ContextInfo != nil && extText.ContextInfo.MentionedJid != nil {
// handle user mentions
for _, mentionedJid := range extText.ContextInfo.MentionedJid {
numberAndSuffix := strings.SplitN(mentionedJid, "@", 2)
// mentions comes as telephone numbers and we don't want to expose it to other bridges
// replace it with something more meaninful to others
mention := b.getSenderNotify(numberAndSuffix[0] + whatsappExt.NewUserSuffix)
if mention == "" {
mention = "someone"
}
message.Text = strings.Replace(message.Text, "@"+numberAndSuffix[0], "@"+mention, 1)
}
}
b.Log.Debugf("<= Sending message from %s on %s to gateway", senderJid, b.Account)
rmsg := config.Message{
UserID: senderJid,
Username: senderName,
Text: message.Text,
Timestamp: messageTime,
Channel: groupJid,
Account: b.Account,
Protocol: b.Protocol,
Extra: make(map[string][]interface{}),
// ParentID: TODO, // TODO handle thread replies // map from Info.QuotedMessageID string
// Event string `json:"event"`
// Gateway string // will be added during message processing
ID: message.Info.Id}
if avatarURL, exists := b.userAvatars[senderJid]; exists {
rmsg.Avatar = avatarURL
}
b.Log.Debugf("<= Message is %#v", rmsg)
b.Remote <- rmsg
} | go | func (b *Bwhatsapp) HandleTextMessage(message whatsapp.TextMessage) {
if message.Info.FromMe { // || !strings.Contains(strings.ToLower(message.Text), "@echo") {
return
}
// whatsapp sends last messages to show context , cut them
if message.Info.Timestamp < b.startedAt {
return
}
messageTime := time.Unix(int64(message.Info.Timestamp), 0) // TODO check how behaves between timezones
groupJid := message.Info.RemoteJid
senderJid := message.Info.SenderJid
if len(senderJid) == 0 {
// TODO workaround till https://github.com/Rhymen/go-whatsapp/issues/86 resolved
senderJid = *message.Info.Source.Participant
}
// translate sender's Jid to the nicest username we can get
senderName := b.getSenderName(senderJid)
if senderName == "" {
senderName = "Someone" // don't expose telephone number
}
extText := message.Info.Source.Message.ExtendedTextMessage
if extText != nil && extText.ContextInfo != nil && extText.ContextInfo.MentionedJid != nil {
// handle user mentions
for _, mentionedJid := range extText.ContextInfo.MentionedJid {
numberAndSuffix := strings.SplitN(mentionedJid, "@", 2)
// mentions comes as telephone numbers and we don't want to expose it to other bridges
// replace it with something more meaninful to others
mention := b.getSenderNotify(numberAndSuffix[0] + whatsappExt.NewUserSuffix)
if mention == "" {
mention = "someone"
}
message.Text = strings.Replace(message.Text, "@"+numberAndSuffix[0], "@"+mention, 1)
}
}
b.Log.Debugf("<= Sending message from %s on %s to gateway", senderJid, b.Account)
rmsg := config.Message{
UserID: senderJid,
Username: senderName,
Text: message.Text,
Timestamp: messageTime,
Channel: groupJid,
Account: b.Account,
Protocol: b.Protocol,
Extra: make(map[string][]interface{}),
// ParentID: TODO, // TODO handle thread replies // map from Info.QuotedMessageID string
// Event string `json:"event"`
// Gateway string // will be added during message processing
ID: message.Info.Id}
if avatarURL, exists := b.userAvatars[senderJid]; exists {
rmsg.Avatar = avatarURL
}
b.Log.Debugf("<= Message is %#v", rmsg)
b.Remote <- rmsg
} | [
"func",
"(",
"b",
"*",
"Bwhatsapp",
")",
"HandleTextMessage",
"(",
"message",
"whatsapp",
".",
"TextMessage",
")",
"{",
"if",
"message",
".",
"Info",
".",
"FromMe",
"{",
"// || !strings.Contains(strings.ToLower(message.Text), \"@echo\") {",
"return",
"\n",
"}",
"\n",
"// whatsapp sends last messages to show context , cut them",
"if",
"message",
".",
"Info",
".",
"Timestamp",
"<",
"b",
".",
"startedAt",
"{",
"return",
"\n",
"}",
"\n\n",
"messageTime",
":=",
"time",
".",
"Unix",
"(",
"int64",
"(",
"message",
".",
"Info",
".",
"Timestamp",
")",
",",
"0",
")",
"// TODO check how behaves between timezones",
"\n",
"groupJid",
":=",
"message",
".",
"Info",
".",
"RemoteJid",
"\n\n",
"senderJid",
":=",
"message",
".",
"Info",
".",
"SenderJid",
"\n",
"if",
"len",
"(",
"senderJid",
")",
"==",
"0",
"{",
"// TODO workaround till https://github.com/Rhymen/go-whatsapp/issues/86 resolved",
"senderJid",
"=",
"*",
"message",
".",
"Info",
".",
"Source",
".",
"Participant",
"\n",
"}",
"\n\n",
"// translate sender's Jid to the nicest username we can get",
"senderName",
":=",
"b",
".",
"getSenderName",
"(",
"senderJid",
")",
"\n",
"if",
"senderName",
"==",
"\"",
"\"",
"{",
"senderName",
"=",
"\"",
"\"",
"// don't expose telephone number",
"\n",
"}",
"\n\n",
"extText",
":=",
"message",
".",
"Info",
".",
"Source",
".",
"Message",
".",
"ExtendedTextMessage",
"\n",
"if",
"extText",
"!=",
"nil",
"&&",
"extText",
".",
"ContextInfo",
"!=",
"nil",
"&&",
"extText",
".",
"ContextInfo",
".",
"MentionedJid",
"!=",
"nil",
"{",
"// handle user mentions",
"for",
"_",
",",
"mentionedJid",
":=",
"range",
"extText",
".",
"ContextInfo",
".",
"MentionedJid",
"{",
"numberAndSuffix",
":=",
"strings",
".",
"SplitN",
"(",
"mentionedJid",
",",
"\"",
"\"",
",",
"2",
")",
"\n\n",
"// mentions comes as telephone numbers and we don't want to expose it to other bridges",
"// replace it with something more meaninful to others",
"mention",
":=",
"b",
".",
"getSenderNotify",
"(",
"numberAndSuffix",
"[",
"0",
"]",
"+",
"whatsappExt",
".",
"NewUserSuffix",
")",
"\n",
"if",
"mention",
"==",
"\"",
"\"",
"{",
"mention",
"=",
"\"",
"\"",
"\n",
"}",
"\n",
"message",
".",
"Text",
"=",
"strings",
".",
"Replace",
"(",
"message",
".",
"Text",
",",
"\"",
"\"",
"+",
"numberAndSuffix",
"[",
"0",
"]",
",",
"\"",
"\"",
"+",
"mention",
",",
"1",
")",
"\n",
"}",
"\n",
"}",
"\n\n",
"b",
".",
"Log",
".",
"Debugf",
"(",
"\"",
"\"",
",",
"senderJid",
",",
"b",
".",
"Account",
")",
"\n",
"rmsg",
":=",
"config",
".",
"Message",
"{",
"UserID",
":",
"senderJid",
",",
"Username",
":",
"senderName",
",",
"Text",
":",
"message",
".",
"Text",
",",
"Timestamp",
":",
"messageTime",
",",
"Channel",
":",
"groupJid",
",",
"Account",
":",
"b",
".",
"Account",
",",
"Protocol",
":",
"b",
".",
"Protocol",
",",
"Extra",
":",
"make",
"(",
"map",
"[",
"string",
"]",
"[",
"]",
"interface",
"{",
"}",
")",
",",
"//\t\tParentID: TODO, // TODO handle thread replies // map from Info.QuotedMessageID string",
"//\tEvent string `json:\"event\"`",
"//\tGateway string // will be added during message processing",
"ID",
":",
"message",
".",
"Info",
".",
"Id",
"}",
"\n\n",
"if",
"avatarURL",
",",
"exists",
":=",
"b",
".",
"userAvatars",
"[",
"senderJid",
"]",
";",
"exists",
"{",
"rmsg",
".",
"Avatar",
"=",
"avatarURL",
"\n",
"}",
"\n\n",
"b",
".",
"Log",
".",
"Debugf",
"(",
"\"",
"\"",
",",
"rmsg",
")",
"\n",
"b",
".",
"Remote",
"<-",
"rmsg",
"\n",
"}"
] | // HandleTextMessage sent from WhatsApp, relay it to the brige | [
"HandleTextMessage",
"sent",
"from",
"WhatsApp",
"relay",
"it",
"to",
"the",
"brige"
] | 1b2feb19e506bc24580d5d61422d0de68349c24e | https://github.com/42wim/matterbridge/blob/1b2feb19e506bc24580d5d61422d0de68349c24e/bridge/whatsapp/handlers.go#L28-L89 | train |
42wim/matterbridge | bridge/slack/helpers.go | populateReceivedMessage | func (b *Bslack) populateReceivedMessage(ev *slack.MessageEvent) (*config.Message, error) {
// Use our own func because rtm.GetChannelInfo doesn't work for private channels.
channel, err := b.channels.getChannelByID(ev.Channel)
if err != nil {
return nil, err
}
rmsg := &config.Message{
Text: ev.Text,
Channel: channel.Name,
Account: b.Account,
ID: ev.Timestamp,
Extra: make(map[string][]interface{}),
ParentID: ev.ThreadTimestamp,
Protocol: b.Protocol,
}
if b.useChannelID {
rmsg.Channel = "ID:" + channel.ID
}
// Handle 'edit' messages.
if ev.SubMessage != nil && !b.GetBool(editDisableConfig) {
rmsg.ID = ev.SubMessage.Timestamp
if ev.SubMessage.ThreadTimestamp != ev.SubMessage.Timestamp {
b.Log.Debugf("SubMessage %#v", ev.SubMessage)
rmsg.Text = ev.SubMessage.Text + b.GetString(editSuffixConfig)
}
}
// For edits, only submessage has thread ts.
// Ensures edits to threaded messages maintain their prefix hint on the
// unthreaded end.
if ev.SubMessage != nil {
rmsg.ParentID = ev.SubMessage.ThreadTimestamp
}
if err = b.populateMessageWithUserInfo(ev, rmsg); err != nil {
return nil, err
}
return rmsg, err
} | go | func (b *Bslack) populateReceivedMessage(ev *slack.MessageEvent) (*config.Message, error) {
// Use our own func because rtm.GetChannelInfo doesn't work for private channels.
channel, err := b.channels.getChannelByID(ev.Channel)
if err != nil {
return nil, err
}
rmsg := &config.Message{
Text: ev.Text,
Channel: channel.Name,
Account: b.Account,
ID: ev.Timestamp,
Extra: make(map[string][]interface{}),
ParentID: ev.ThreadTimestamp,
Protocol: b.Protocol,
}
if b.useChannelID {
rmsg.Channel = "ID:" + channel.ID
}
// Handle 'edit' messages.
if ev.SubMessage != nil && !b.GetBool(editDisableConfig) {
rmsg.ID = ev.SubMessage.Timestamp
if ev.SubMessage.ThreadTimestamp != ev.SubMessage.Timestamp {
b.Log.Debugf("SubMessage %#v", ev.SubMessage)
rmsg.Text = ev.SubMessage.Text + b.GetString(editSuffixConfig)
}
}
// For edits, only submessage has thread ts.
// Ensures edits to threaded messages maintain their prefix hint on the
// unthreaded end.
if ev.SubMessage != nil {
rmsg.ParentID = ev.SubMessage.ThreadTimestamp
}
if err = b.populateMessageWithUserInfo(ev, rmsg); err != nil {
return nil, err
}
return rmsg, err
} | [
"func",
"(",
"b",
"*",
"Bslack",
")",
"populateReceivedMessage",
"(",
"ev",
"*",
"slack",
".",
"MessageEvent",
")",
"(",
"*",
"config",
".",
"Message",
",",
"error",
")",
"{",
"// Use our own func because rtm.GetChannelInfo doesn't work for private channels.",
"channel",
",",
"err",
":=",
"b",
".",
"channels",
".",
"getChannelByID",
"(",
"ev",
".",
"Channel",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"rmsg",
":=",
"&",
"config",
".",
"Message",
"{",
"Text",
":",
"ev",
".",
"Text",
",",
"Channel",
":",
"channel",
".",
"Name",
",",
"Account",
":",
"b",
".",
"Account",
",",
"ID",
":",
"ev",
".",
"Timestamp",
",",
"Extra",
":",
"make",
"(",
"map",
"[",
"string",
"]",
"[",
"]",
"interface",
"{",
"}",
")",
",",
"ParentID",
":",
"ev",
".",
"ThreadTimestamp",
",",
"Protocol",
":",
"b",
".",
"Protocol",
",",
"}",
"\n",
"if",
"b",
".",
"useChannelID",
"{",
"rmsg",
".",
"Channel",
"=",
"\"",
"\"",
"+",
"channel",
".",
"ID",
"\n",
"}",
"\n\n",
"// Handle 'edit' messages.",
"if",
"ev",
".",
"SubMessage",
"!=",
"nil",
"&&",
"!",
"b",
".",
"GetBool",
"(",
"editDisableConfig",
")",
"{",
"rmsg",
".",
"ID",
"=",
"ev",
".",
"SubMessage",
".",
"Timestamp",
"\n",
"if",
"ev",
".",
"SubMessage",
".",
"ThreadTimestamp",
"!=",
"ev",
".",
"SubMessage",
".",
"Timestamp",
"{",
"b",
".",
"Log",
".",
"Debugf",
"(",
"\"",
"\"",
",",
"ev",
".",
"SubMessage",
")",
"\n",
"rmsg",
".",
"Text",
"=",
"ev",
".",
"SubMessage",
".",
"Text",
"+",
"b",
".",
"GetString",
"(",
"editSuffixConfig",
")",
"\n",
"}",
"\n",
"}",
"\n\n",
"// For edits, only submessage has thread ts.",
"// Ensures edits to threaded messages maintain their prefix hint on the",
"// unthreaded end.",
"if",
"ev",
".",
"SubMessage",
"!=",
"nil",
"{",
"rmsg",
".",
"ParentID",
"=",
"ev",
".",
"SubMessage",
".",
"ThreadTimestamp",
"\n",
"}",
"\n\n",
"if",
"err",
"=",
"b",
".",
"populateMessageWithUserInfo",
"(",
"ev",
",",
"rmsg",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"return",
"rmsg",
",",
"err",
"\n",
"}"
] | // populateReceivedMessage shapes the initial Matterbridge message that we will forward to the
// router before we apply message-dependent modifications. | [
"populateReceivedMessage",
"shapes",
"the",
"initial",
"Matterbridge",
"message",
"that",
"we",
"will",
"forward",
"to",
"the",
"router",
"before",
"we",
"apply",
"message",
"-",
"dependent",
"modifications",
"."
] | 1b2feb19e506bc24580d5d61422d0de68349c24e | https://github.com/42wim/matterbridge/blob/1b2feb19e506bc24580d5d61422d0de68349c24e/bridge/slack/helpers.go#L16-L56 | train |
42wim/matterbridge | bridge/slack/helpers.go | getUsersInConversation | func (b *Bslack) getUsersInConversation(channelID string) ([]string, error) {
channelMembers := []string{}
for {
queryParams := &slack.GetUsersInConversationParameters{
ChannelID: channelID,
}
members, nextCursor, err := b.sc.GetUsersInConversation(queryParams)
if err != nil {
if err = handleRateLimit(b.Log, err); err != nil {
return channelMembers, fmt.Errorf("Could not retrieve users in channels: %#v", err)
}
continue
}
channelMembers = append(channelMembers, members...)
if nextCursor == "" {
break
}
queryParams.Cursor = nextCursor
}
return channelMembers, nil
} | go | func (b *Bslack) getUsersInConversation(channelID string) ([]string, error) {
channelMembers := []string{}
for {
queryParams := &slack.GetUsersInConversationParameters{
ChannelID: channelID,
}
members, nextCursor, err := b.sc.GetUsersInConversation(queryParams)
if err != nil {
if err = handleRateLimit(b.Log, err); err != nil {
return channelMembers, fmt.Errorf("Could not retrieve users in channels: %#v", err)
}
continue
}
channelMembers = append(channelMembers, members...)
if nextCursor == "" {
break
}
queryParams.Cursor = nextCursor
}
return channelMembers, nil
} | [
"func",
"(",
"b",
"*",
"Bslack",
")",
"getUsersInConversation",
"(",
"channelID",
"string",
")",
"(",
"[",
"]",
"string",
",",
"error",
")",
"{",
"channelMembers",
":=",
"[",
"]",
"string",
"{",
"}",
"\n",
"for",
"{",
"queryParams",
":=",
"&",
"slack",
".",
"GetUsersInConversationParameters",
"{",
"ChannelID",
":",
"channelID",
",",
"}",
"\n\n",
"members",
",",
"nextCursor",
",",
"err",
":=",
"b",
".",
"sc",
".",
"GetUsersInConversation",
"(",
"queryParams",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"if",
"err",
"=",
"handleRateLimit",
"(",
"b",
".",
"Log",
",",
"err",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"channelMembers",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n",
"continue",
"\n",
"}",
"\n\n",
"channelMembers",
"=",
"append",
"(",
"channelMembers",
",",
"members",
"...",
")",
"\n\n",
"if",
"nextCursor",
"==",
"\"",
"\"",
"{",
"break",
"\n",
"}",
"\n",
"queryParams",
".",
"Cursor",
"=",
"nextCursor",
"\n",
"}",
"\n",
"return",
"channelMembers",
",",
"nil",
"\n",
"}"
] | // getUsersInConversation returns an array of userIDs that are members of channelID | [
"getUsersInConversation",
"returns",
"an",
"array",
"of",
"userIDs",
"that",
"are",
"members",
"of",
"channelID"
] | 1b2feb19e506bc24580d5d61422d0de68349c24e | https://github.com/42wim/matterbridge/blob/1b2feb19e506bc24580d5d61422d0de68349c24e/bridge/slack/helpers.go#L196-L219 | train |
42wim/matterbridge | gateway/gateway.go | New | func New(rootLogger *logrus.Logger, cfg *config.Gateway, r *Router) *Gateway {
logger := rootLogger.WithFields(logrus.Fields{"prefix": "gateway"})
cache, _ := lru.New(5000)
gw := &Gateway{
Channels: make(map[string]*config.ChannelInfo),
Message: r.Message,
Router: r,
Bridges: make(map[string]*bridge.Bridge),
Config: r.Config,
Messages: cache,
logger: logger,
}
if err := gw.AddConfig(cfg); err != nil {
logger.Errorf("Failed to add configuration to gateway: %#v", err)
}
return gw
} | go | func New(rootLogger *logrus.Logger, cfg *config.Gateway, r *Router) *Gateway {
logger := rootLogger.WithFields(logrus.Fields{"prefix": "gateway"})
cache, _ := lru.New(5000)
gw := &Gateway{
Channels: make(map[string]*config.ChannelInfo),
Message: r.Message,
Router: r,
Bridges: make(map[string]*bridge.Bridge),
Config: r.Config,
Messages: cache,
logger: logger,
}
if err := gw.AddConfig(cfg); err != nil {
logger.Errorf("Failed to add configuration to gateway: %#v", err)
}
return gw
} | [
"func",
"New",
"(",
"rootLogger",
"*",
"logrus",
".",
"Logger",
",",
"cfg",
"*",
"config",
".",
"Gateway",
",",
"r",
"*",
"Router",
")",
"*",
"Gateway",
"{",
"logger",
":=",
"rootLogger",
".",
"WithFields",
"(",
"logrus",
".",
"Fields",
"{",
"\"",
"\"",
":",
"\"",
"\"",
"}",
")",
"\n\n",
"cache",
",",
"_",
":=",
"lru",
".",
"New",
"(",
"5000",
")",
"\n",
"gw",
":=",
"&",
"Gateway",
"{",
"Channels",
":",
"make",
"(",
"map",
"[",
"string",
"]",
"*",
"config",
".",
"ChannelInfo",
")",
",",
"Message",
":",
"r",
".",
"Message",
",",
"Router",
":",
"r",
",",
"Bridges",
":",
"make",
"(",
"map",
"[",
"string",
"]",
"*",
"bridge",
".",
"Bridge",
")",
",",
"Config",
":",
"r",
".",
"Config",
",",
"Messages",
":",
"cache",
",",
"logger",
":",
"logger",
",",
"}",
"\n",
"if",
"err",
":=",
"gw",
".",
"AddConfig",
"(",
"cfg",
")",
";",
"err",
"!=",
"nil",
"{",
"logger",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n",
"return",
"gw",
"\n",
"}"
] | // New creates a new Gateway object associated with the specified router and
// following the given configuration. | [
"New",
"creates",
"a",
"new",
"Gateway",
"object",
"associated",
"with",
"the",
"specified",
"router",
"and",
"following",
"the",
"given",
"configuration",
"."
] | 1b2feb19e506bc24580d5d61422d0de68349c24e | https://github.com/42wim/matterbridge/blob/1b2feb19e506bc24580d5d61422d0de68349c24e/gateway/gateway.go#L45-L62 | train |
42wim/matterbridge | gateway/gateway.go | FindCanonicalMsgID | func (gw *Gateway) FindCanonicalMsgID(protocol string, mID string) string {
ID := protocol + " " + mID
if gw.Messages.Contains(ID) {
return mID
}
// If not keyed, iterate through cache for downstream, and infer upstream.
for _, mid := range gw.Messages.Keys() {
v, _ := gw.Messages.Peek(mid)
ids := v.([]*BrMsgID)
for _, downstreamMsgObj := range ids {
if ID == downstreamMsgObj.ID {
return strings.Replace(mid.(string), protocol+" ", "", 1)
}
}
}
return ""
} | go | func (gw *Gateway) FindCanonicalMsgID(protocol string, mID string) string {
ID := protocol + " " + mID
if gw.Messages.Contains(ID) {
return mID
}
// If not keyed, iterate through cache for downstream, and infer upstream.
for _, mid := range gw.Messages.Keys() {
v, _ := gw.Messages.Peek(mid)
ids := v.([]*BrMsgID)
for _, downstreamMsgObj := range ids {
if ID == downstreamMsgObj.ID {
return strings.Replace(mid.(string), protocol+" ", "", 1)
}
}
}
return ""
} | [
"func",
"(",
"gw",
"*",
"Gateway",
")",
"FindCanonicalMsgID",
"(",
"protocol",
"string",
",",
"mID",
"string",
")",
"string",
"{",
"ID",
":=",
"protocol",
"+",
"\"",
"\"",
"+",
"mID",
"\n",
"if",
"gw",
".",
"Messages",
".",
"Contains",
"(",
"ID",
")",
"{",
"return",
"mID",
"\n",
"}",
"\n\n",
"// If not keyed, iterate through cache for downstream, and infer upstream.",
"for",
"_",
",",
"mid",
":=",
"range",
"gw",
".",
"Messages",
".",
"Keys",
"(",
")",
"{",
"v",
",",
"_",
":=",
"gw",
".",
"Messages",
".",
"Peek",
"(",
"mid",
")",
"\n",
"ids",
":=",
"v",
".",
"(",
"[",
"]",
"*",
"BrMsgID",
")",
"\n",
"for",
"_",
",",
"downstreamMsgObj",
":=",
"range",
"ids",
"{",
"if",
"ID",
"==",
"downstreamMsgObj",
".",
"ID",
"{",
"return",
"strings",
".",
"Replace",
"(",
"mid",
".",
"(",
"string",
")",
",",
"protocol",
"+",
"\"",
"\"",
",",
"\"",
"\"",
",",
"1",
")",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"\"",
"\"",
"\n",
"}"
] | // FindCanonicalMsgID returns the ID under which a message was stored in the cache. | [
"FindCanonicalMsgID",
"returns",
"the",
"ID",
"under",
"which",
"a",
"message",
"was",
"stored",
"in",
"the",
"cache",
"."
] | 1b2feb19e506bc24580d5d61422d0de68349c24e | https://github.com/42wim/matterbridge/blob/1b2feb19e506bc24580d5d61422d0de68349c24e/gateway/gateway.go#L65-L82 | train |
42wim/matterbridge | gateway/gateway.go | AddBridge | func (gw *Gateway) AddBridge(cfg *config.Bridge) error {
br := gw.Router.getBridge(cfg.Account)
if br == nil {
br = bridge.New(cfg)
br.Config = gw.Router.Config
br.General = &gw.BridgeValues().General
br.Log = gw.logger.WithFields(logrus.Fields{"prefix": br.Protocol})
brconfig := &bridge.Config{
Remote: gw.Message,
Bridge: br,
}
// add the actual bridger for this protocol to this bridge using the bridgeMap
if _, ok := gw.Router.BridgeMap[br.Protocol]; !ok {
gw.logger.Fatalf("Incorrect protocol %s specified in gateway configuration %s, exiting.", br.Protocol, cfg.Account)
}
br.Bridger = gw.Router.BridgeMap[br.Protocol](brconfig)
}
gw.mapChannelsToBridge(br)
gw.Bridges[cfg.Account] = br
return nil
} | go | func (gw *Gateway) AddBridge(cfg *config.Bridge) error {
br := gw.Router.getBridge(cfg.Account)
if br == nil {
br = bridge.New(cfg)
br.Config = gw.Router.Config
br.General = &gw.BridgeValues().General
br.Log = gw.logger.WithFields(logrus.Fields{"prefix": br.Protocol})
brconfig := &bridge.Config{
Remote: gw.Message,
Bridge: br,
}
// add the actual bridger for this protocol to this bridge using the bridgeMap
if _, ok := gw.Router.BridgeMap[br.Protocol]; !ok {
gw.logger.Fatalf("Incorrect protocol %s specified in gateway configuration %s, exiting.", br.Protocol, cfg.Account)
}
br.Bridger = gw.Router.BridgeMap[br.Protocol](brconfig)
}
gw.mapChannelsToBridge(br)
gw.Bridges[cfg.Account] = br
return nil
} | [
"func",
"(",
"gw",
"*",
"Gateway",
")",
"AddBridge",
"(",
"cfg",
"*",
"config",
".",
"Bridge",
")",
"error",
"{",
"br",
":=",
"gw",
".",
"Router",
".",
"getBridge",
"(",
"cfg",
".",
"Account",
")",
"\n",
"if",
"br",
"==",
"nil",
"{",
"br",
"=",
"bridge",
".",
"New",
"(",
"cfg",
")",
"\n",
"br",
".",
"Config",
"=",
"gw",
".",
"Router",
".",
"Config",
"\n",
"br",
".",
"General",
"=",
"&",
"gw",
".",
"BridgeValues",
"(",
")",
".",
"General",
"\n",
"br",
".",
"Log",
"=",
"gw",
".",
"logger",
".",
"WithFields",
"(",
"logrus",
".",
"Fields",
"{",
"\"",
"\"",
":",
"br",
".",
"Protocol",
"}",
")",
"\n",
"brconfig",
":=",
"&",
"bridge",
".",
"Config",
"{",
"Remote",
":",
"gw",
".",
"Message",
",",
"Bridge",
":",
"br",
",",
"}",
"\n",
"// add the actual bridger for this protocol to this bridge using the bridgeMap",
"if",
"_",
",",
"ok",
":=",
"gw",
".",
"Router",
".",
"BridgeMap",
"[",
"br",
".",
"Protocol",
"]",
";",
"!",
"ok",
"{",
"gw",
".",
"logger",
".",
"Fatalf",
"(",
"\"",
"\"",
",",
"br",
".",
"Protocol",
",",
"cfg",
".",
"Account",
")",
"\n",
"}",
"\n",
"br",
".",
"Bridger",
"=",
"gw",
".",
"Router",
".",
"BridgeMap",
"[",
"br",
".",
"Protocol",
"]",
"(",
"brconfig",
")",
"\n",
"}",
"\n",
"gw",
".",
"mapChannelsToBridge",
"(",
"br",
")",
"\n",
"gw",
".",
"Bridges",
"[",
"cfg",
".",
"Account",
"]",
"=",
"br",
"\n",
"return",
"nil",
"\n",
"}"
] | // AddBridge sets up a new bridge in the gateway object with the specified configuration. | [
"AddBridge",
"sets",
"up",
"a",
"new",
"bridge",
"in",
"the",
"gateway",
"object",
"with",
"the",
"specified",
"configuration",
"."
] | 1b2feb19e506bc24580d5d61422d0de68349c24e | https://github.com/42wim/matterbridge/blob/1b2feb19e506bc24580d5d61422d0de68349c24e/gateway/gateway.go#L85-L105 | train |
42wim/matterbridge | gateway/gateway.go | AddConfig | func (gw *Gateway) AddConfig(cfg *config.Gateway) error {
gw.Name = cfg.Name
gw.MyConfig = cfg
if err := gw.mapChannels(); err != nil {
gw.logger.Errorf("mapChannels() failed: %s", err)
}
for _, br := range append(gw.MyConfig.In, append(gw.MyConfig.InOut, gw.MyConfig.Out...)...) {
br := br //scopelint
err := gw.AddBridge(&br)
if err != nil {
return err
}
}
return nil
} | go | func (gw *Gateway) AddConfig(cfg *config.Gateway) error {
gw.Name = cfg.Name
gw.MyConfig = cfg
if err := gw.mapChannels(); err != nil {
gw.logger.Errorf("mapChannels() failed: %s", err)
}
for _, br := range append(gw.MyConfig.In, append(gw.MyConfig.InOut, gw.MyConfig.Out...)...) {
br := br //scopelint
err := gw.AddBridge(&br)
if err != nil {
return err
}
}
return nil
} | [
"func",
"(",
"gw",
"*",
"Gateway",
")",
"AddConfig",
"(",
"cfg",
"*",
"config",
".",
"Gateway",
")",
"error",
"{",
"gw",
".",
"Name",
"=",
"cfg",
".",
"Name",
"\n",
"gw",
".",
"MyConfig",
"=",
"cfg",
"\n",
"if",
"err",
":=",
"gw",
".",
"mapChannels",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"gw",
".",
"logger",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n",
"for",
"_",
",",
"br",
":=",
"range",
"append",
"(",
"gw",
".",
"MyConfig",
".",
"In",
",",
"append",
"(",
"gw",
".",
"MyConfig",
".",
"InOut",
",",
"gw",
".",
"MyConfig",
".",
"Out",
"...",
")",
"...",
")",
"{",
"br",
":=",
"br",
"//scopelint",
"\n",
"err",
":=",
"gw",
".",
"AddBridge",
"(",
"&",
"br",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] | // AddConfig associates a new configuration with the gateway object. | [
"AddConfig",
"associates",
"a",
"new",
"configuration",
"with",
"the",
"gateway",
"object",
"."
] | 1b2feb19e506bc24580d5d61422d0de68349c24e | https://github.com/42wim/matterbridge/blob/1b2feb19e506bc24580d5d61422d0de68349c24e/gateway/gateway.go#L108-L122 | train |
42wim/matterbridge | gateway/gateway.go | ignoreTextEmpty | func (gw *Gateway) ignoreTextEmpty(msg *config.Message) bool {
if msg.Text != "" {
return false
}
if msg.Event == config.EventUserTyping {
return false
}
// we have an attachment or actual bytes, do not ignore
if msg.Extra != nil &&
(msg.Extra["attachments"] != nil ||
len(msg.Extra["file"]) > 0 ||
len(msg.Extra[config.EventFileFailureSize]) > 0) {
return false
}
gw.logger.Debugf("ignoring empty message %#v from %s", msg, msg.Account)
return true
} | go | func (gw *Gateway) ignoreTextEmpty(msg *config.Message) bool {
if msg.Text != "" {
return false
}
if msg.Event == config.EventUserTyping {
return false
}
// we have an attachment or actual bytes, do not ignore
if msg.Extra != nil &&
(msg.Extra["attachments"] != nil ||
len(msg.Extra["file"]) > 0 ||
len(msg.Extra[config.EventFileFailureSize]) > 0) {
return false
}
gw.logger.Debugf("ignoring empty message %#v from %s", msg, msg.Account)
return true
} | [
"func",
"(",
"gw",
"*",
"Gateway",
")",
"ignoreTextEmpty",
"(",
"msg",
"*",
"config",
".",
"Message",
")",
"bool",
"{",
"if",
"msg",
".",
"Text",
"!=",
"\"",
"\"",
"{",
"return",
"false",
"\n",
"}",
"\n",
"if",
"msg",
".",
"Event",
"==",
"config",
".",
"EventUserTyping",
"{",
"return",
"false",
"\n",
"}",
"\n",
"// we have an attachment or actual bytes, do not ignore",
"if",
"msg",
".",
"Extra",
"!=",
"nil",
"&&",
"(",
"msg",
".",
"Extra",
"[",
"\"",
"\"",
"]",
"!=",
"nil",
"||",
"len",
"(",
"msg",
".",
"Extra",
"[",
"\"",
"\"",
"]",
")",
">",
"0",
"||",
"len",
"(",
"msg",
".",
"Extra",
"[",
"config",
".",
"EventFileFailureSize",
"]",
")",
">",
"0",
")",
"{",
"return",
"false",
"\n",
"}",
"\n",
"gw",
".",
"logger",
".",
"Debugf",
"(",
"\"",
"\"",
",",
"msg",
",",
"msg",
".",
"Account",
")",
"\n",
"return",
"true",
"\n",
"}"
] | // ignoreTextEmpty returns true if we need to ignore a message with an empty text. | [
"ignoreTextEmpty",
"returns",
"true",
"if",
"we",
"need",
"to",
"ignore",
"a",
"message",
"with",
"an",
"empty",
"text",
"."
] | 1b2feb19e506bc24580d5d61422d0de68349c24e | https://github.com/42wim/matterbridge/blob/1b2feb19e506bc24580d5d61422d0de68349c24e/gateway/gateway.go#L261-L277 | train |
42wim/matterbridge | gateway/gateway.go | ignoreText | func (gw *Gateway) ignoreText(text string, input []string) bool {
for _, entry := range input {
if entry == "" {
continue
}
// TODO do not compile regexps everytime
re, err := regexp.Compile(entry)
if err != nil {
gw.logger.Errorf("incorrect regexp %s", entry)
continue
}
if re.MatchString(text) {
gw.logger.Debugf("matching %s. ignoring %s", entry, text)
return true
}
}
return false
} | go | func (gw *Gateway) ignoreText(text string, input []string) bool {
for _, entry := range input {
if entry == "" {
continue
}
// TODO do not compile regexps everytime
re, err := regexp.Compile(entry)
if err != nil {
gw.logger.Errorf("incorrect regexp %s", entry)
continue
}
if re.MatchString(text) {
gw.logger.Debugf("matching %s. ignoring %s", entry, text)
return true
}
}
return false
} | [
"func",
"(",
"gw",
"*",
"Gateway",
")",
"ignoreText",
"(",
"text",
"string",
",",
"input",
"[",
"]",
"string",
")",
"bool",
"{",
"for",
"_",
",",
"entry",
":=",
"range",
"input",
"{",
"if",
"entry",
"==",
"\"",
"\"",
"{",
"continue",
"\n",
"}",
"\n",
"// TODO do not compile regexps everytime",
"re",
",",
"err",
":=",
"regexp",
".",
"Compile",
"(",
"entry",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"gw",
".",
"logger",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"entry",
")",
"\n",
"continue",
"\n",
"}",
"\n",
"if",
"re",
".",
"MatchString",
"(",
"text",
")",
"{",
"gw",
".",
"logger",
".",
"Debugf",
"(",
"\"",
"\"",
",",
"entry",
",",
"text",
")",
"\n",
"return",
"true",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"false",
"\n",
"}"
] | // ignoreText returns true if text matches any of the input regexes. | [
"ignoreText",
"returns",
"true",
"if",
"text",
"matches",
"any",
"of",
"the",
"input",
"regexes",
"."
] | 1b2feb19e506bc24580d5d61422d0de68349c24e | https://github.com/42wim/matterbridge/blob/1b2feb19e506bc24580d5d61422d0de68349c24e/gateway/gateway.go#L471-L488 | train |
42wim/matterbridge | bridge/matrix/matrix.go | handleUploadFiles | func (b *Bmatrix) handleUploadFiles(msg *config.Message, channel string) (string, error) {
for _, f := range msg.Extra["file"] {
if fi, ok := f.(config.FileInfo); ok {
b.handleUploadFile(msg, channel, &fi)
}
}
return "", nil
} | go | func (b *Bmatrix) handleUploadFiles(msg *config.Message, channel string) (string, error) {
for _, f := range msg.Extra["file"] {
if fi, ok := f.(config.FileInfo); ok {
b.handleUploadFile(msg, channel, &fi)
}
}
return "", nil
} | [
"func",
"(",
"b",
"*",
"Bmatrix",
")",
"handleUploadFiles",
"(",
"msg",
"*",
"config",
".",
"Message",
",",
"channel",
"string",
")",
"(",
"string",
",",
"error",
")",
"{",
"for",
"_",
",",
"f",
":=",
"range",
"msg",
".",
"Extra",
"[",
"\"",
"\"",
"]",
"{",
"if",
"fi",
",",
"ok",
":=",
"f",
".",
"(",
"config",
".",
"FileInfo",
")",
";",
"ok",
"{",
"b",
".",
"handleUploadFile",
"(",
"msg",
",",
"channel",
",",
"&",
"fi",
")",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"\"",
"\"",
",",
"nil",
"\n",
"}"
] | // handleUploadFiles handles native upload of files. | [
"handleUploadFiles",
"handles",
"native",
"upload",
"of",
"files",
"."
] | 1b2feb19e506bc24580d5d61422d0de68349c24e | https://github.com/42wim/matterbridge/blob/1b2feb19e506bc24580d5d61422d0de68349c24e/bridge/matrix/matrix.go#L280-L287 | train |
42wim/matterbridge | bridge/matrix/matrix.go | handleUploadFile | func (b *Bmatrix) handleUploadFile(msg *config.Message, channel string, fi *config.FileInfo) {
content := bytes.NewReader(*fi.Data)
sp := strings.Split(fi.Name, ".")
mtype := mime.TypeByExtension("." + sp[len(sp)-1])
if !strings.Contains(mtype, "image") && !strings.Contains(mtype, "video") {
return
}
if fi.Comment != "" {
_, err := b.mc.SendText(channel, msg.Username+fi.Comment)
if err != nil {
b.Log.Errorf("file comment failed: %#v", err)
}
} else {
// image and video uploads send no username, we have to do this ourself here #715
_, err := b.mc.SendText(channel, msg.Username)
if err != nil {
b.Log.Errorf("file comment failed: %#v", err)
}
}
b.Log.Debugf("uploading file: %s %s", fi.Name, mtype)
res, err := b.mc.UploadToContentRepo(content, mtype, int64(len(*fi.Data)))
if err != nil {
b.Log.Errorf("file upload failed: %#v", err)
return
}
switch {
case strings.Contains(mtype, "video"):
b.Log.Debugf("sendVideo %s", res.ContentURI)
_, err = b.mc.SendVideo(channel, fi.Name, res.ContentURI)
if err != nil {
b.Log.Errorf("sendVideo failed: %#v", err)
}
case strings.Contains(mtype, "image"):
b.Log.Debugf("sendImage %s", res.ContentURI)
_, err = b.mc.SendImage(channel, fi.Name, res.ContentURI)
if err != nil {
b.Log.Errorf("sendImage failed: %#v", err)
}
}
b.Log.Debugf("result: %#v", res)
} | go | func (b *Bmatrix) handleUploadFile(msg *config.Message, channel string, fi *config.FileInfo) {
content := bytes.NewReader(*fi.Data)
sp := strings.Split(fi.Name, ".")
mtype := mime.TypeByExtension("." + sp[len(sp)-1])
if !strings.Contains(mtype, "image") && !strings.Contains(mtype, "video") {
return
}
if fi.Comment != "" {
_, err := b.mc.SendText(channel, msg.Username+fi.Comment)
if err != nil {
b.Log.Errorf("file comment failed: %#v", err)
}
} else {
// image and video uploads send no username, we have to do this ourself here #715
_, err := b.mc.SendText(channel, msg.Username)
if err != nil {
b.Log.Errorf("file comment failed: %#v", err)
}
}
b.Log.Debugf("uploading file: %s %s", fi.Name, mtype)
res, err := b.mc.UploadToContentRepo(content, mtype, int64(len(*fi.Data)))
if err != nil {
b.Log.Errorf("file upload failed: %#v", err)
return
}
switch {
case strings.Contains(mtype, "video"):
b.Log.Debugf("sendVideo %s", res.ContentURI)
_, err = b.mc.SendVideo(channel, fi.Name, res.ContentURI)
if err != nil {
b.Log.Errorf("sendVideo failed: %#v", err)
}
case strings.Contains(mtype, "image"):
b.Log.Debugf("sendImage %s", res.ContentURI)
_, err = b.mc.SendImage(channel, fi.Name, res.ContentURI)
if err != nil {
b.Log.Errorf("sendImage failed: %#v", err)
}
}
b.Log.Debugf("result: %#v", res)
} | [
"func",
"(",
"b",
"*",
"Bmatrix",
")",
"handleUploadFile",
"(",
"msg",
"*",
"config",
".",
"Message",
",",
"channel",
"string",
",",
"fi",
"*",
"config",
".",
"FileInfo",
")",
"{",
"content",
":=",
"bytes",
".",
"NewReader",
"(",
"*",
"fi",
".",
"Data",
")",
"\n",
"sp",
":=",
"strings",
".",
"Split",
"(",
"fi",
".",
"Name",
",",
"\"",
"\"",
")",
"\n",
"mtype",
":=",
"mime",
".",
"TypeByExtension",
"(",
"\"",
"\"",
"+",
"sp",
"[",
"len",
"(",
"sp",
")",
"-",
"1",
"]",
")",
"\n",
"if",
"!",
"strings",
".",
"Contains",
"(",
"mtype",
",",
"\"",
"\"",
")",
"&&",
"!",
"strings",
".",
"Contains",
"(",
"mtype",
",",
"\"",
"\"",
")",
"{",
"return",
"\n",
"}",
"\n",
"if",
"fi",
".",
"Comment",
"!=",
"\"",
"\"",
"{",
"_",
",",
"err",
":=",
"b",
".",
"mc",
".",
"SendText",
"(",
"channel",
",",
"msg",
".",
"Username",
"+",
"fi",
".",
"Comment",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"b",
".",
"Log",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n",
"}",
"else",
"{",
"// image and video uploads send no username, we have to do this ourself here #715",
"_",
",",
"err",
":=",
"b",
".",
"mc",
".",
"SendText",
"(",
"channel",
",",
"msg",
".",
"Username",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"b",
".",
"Log",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n",
"}",
"\n",
"b",
".",
"Log",
".",
"Debugf",
"(",
"\"",
"\"",
",",
"fi",
".",
"Name",
",",
"mtype",
")",
"\n",
"res",
",",
"err",
":=",
"b",
".",
"mc",
".",
"UploadToContentRepo",
"(",
"content",
",",
"mtype",
",",
"int64",
"(",
"len",
"(",
"*",
"fi",
".",
"Data",
")",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"b",
".",
"Log",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"return",
"\n",
"}",
"\n\n",
"switch",
"{",
"case",
"strings",
".",
"Contains",
"(",
"mtype",
",",
"\"",
"\"",
")",
":",
"b",
".",
"Log",
".",
"Debugf",
"(",
"\"",
"\"",
",",
"res",
".",
"ContentURI",
")",
"\n",
"_",
",",
"err",
"=",
"b",
".",
"mc",
".",
"SendVideo",
"(",
"channel",
",",
"fi",
".",
"Name",
",",
"res",
".",
"ContentURI",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"b",
".",
"Log",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n",
"case",
"strings",
".",
"Contains",
"(",
"mtype",
",",
"\"",
"\"",
")",
":",
"b",
".",
"Log",
".",
"Debugf",
"(",
"\"",
"\"",
",",
"res",
".",
"ContentURI",
")",
"\n",
"_",
",",
"err",
"=",
"b",
".",
"mc",
".",
"SendImage",
"(",
"channel",
",",
"fi",
".",
"Name",
",",
"res",
".",
"ContentURI",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"b",
".",
"Log",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n",
"}",
"\n",
"b",
".",
"Log",
".",
"Debugf",
"(",
"\"",
"\"",
",",
"res",
")",
"\n",
"}"
] | // handleUploadFile handles native upload of a file. | [
"handleUploadFile",
"handles",
"native",
"upload",
"of",
"a",
"file",
"."
] | 1b2feb19e506bc24580d5d61422d0de68349c24e | https://github.com/42wim/matterbridge/blob/1b2feb19e506bc24580d5d61422d0de68349c24e/bridge/matrix/matrix.go#L290-L331 | train |
42wim/matterbridge | bridge/xmpp/xmpp.go | skipMessage | func (b *Bxmpp) skipMessage(message xmpp.Chat) bool {
// skip messages from ourselves
if b.parseNick(message.Remote) == b.GetString("Nick") {
return true
}
// skip empty messages
if message.Text == "" {
return true
}
// skip subject messages
if strings.Contains(message.Text, "</subject>") {
return true
}
// do not show subjects on connect #732
if strings.Contains(message.Text, "has set the subject to:") && time.Since(b.startTime) < time.Second*5 {
return true
}
// skip delayed messages
t := time.Time{}
return message.Stamp != t
} | go | func (b *Bxmpp) skipMessage(message xmpp.Chat) bool {
// skip messages from ourselves
if b.parseNick(message.Remote) == b.GetString("Nick") {
return true
}
// skip empty messages
if message.Text == "" {
return true
}
// skip subject messages
if strings.Contains(message.Text, "</subject>") {
return true
}
// do not show subjects on connect #732
if strings.Contains(message.Text, "has set the subject to:") && time.Since(b.startTime) < time.Second*5 {
return true
}
// skip delayed messages
t := time.Time{}
return message.Stamp != t
} | [
"func",
"(",
"b",
"*",
"Bxmpp",
")",
"skipMessage",
"(",
"message",
"xmpp",
".",
"Chat",
")",
"bool",
"{",
"// skip messages from ourselves",
"if",
"b",
".",
"parseNick",
"(",
"message",
".",
"Remote",
")",
"==",
"b",
".",
"GetString",
"(",
"\"",
"\"",
")",
"{",
"return",
"true",
"\n",
"}",
"\n\n",
"// skip empty messages",
"if",
"message",
".",
"Text",
"==",
"\"",
"\"",
"{",
"return",
"true",
"\n",
"}",
"\n\n",
"// skip subject messages",
"if",
"strings",
".",
"Contains",
"(",
"message",
".",
"Text",
",",
"\"",
"\"",
")",
"{",
"return",
"true",
"\n",
"}",
"\n\n",
"// do not show subjects on connect #732",
"if",
"strings",
".",
"Contains",
"(",
"message",
".",
"Text",
",",
"\"",
"\"",
")",
"&&",
"time",
".",
"Since",
"(",
"b",
".",
"startTime",
")",
"<",
"time",
".",
"Second",
"*",
"5",
"{",
"return",
"true",
"\n",
"}",
"\n\n",
"// skip delayed messages",
"t",
":=",
"time",
".",
"Time",
"{",
"}",
"\n",
"return",
"message",
".",
"Stamp",
"!=",
"t",
"\n",
"}"
] | // skipMessage skips messages that need to be skipped | [
"skipMessage",
"skips",
"messages",
"that",
"need",
"to",
"be",
"skipped"
] | 1b2feb19e506bc24580d5d61422d0de68349c24e | https://github.com/42wim/matterbridge/blob/1b2feb19e506bc24580d5d61422d0de68349c24e/bridge/xmpp/xmpp.go#L260-L284 | train |
go-acme/lego | challenge/dns01/dns_challenge.go | CondOption | func CondOption(condition bool, opt ChallengeOption) ChallengeOption {
if !condition {
// NoOp options
return func(*Challenge) error {
return nil
}
}
return opt
} | go | func CondOption(condition bool, opt ChallengeOption) ChallengeOption {
if !condition {
// NoOp options
return func(*Challenge) error {
return nil
}
}
return opt
} | [
"func",
"CondOption",
"(",
"condition",
"bool",
",",
"opt",
"ChallengeOption",
")",
"ChallengeOption",
"{",
"if",
"!",
"condition",
"{",
"// NoOp options",
"return",
"func",
"(",
"*",
"Challenge",
")",
"error",
"{",
"return",
"nil",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"opt",
"\n",
"}"
] | // CondOption Conditional challenge option. | [
"CondOption",
"Conditional",
"challenge",
"option",
"."
] | 29c63545ce6fffd8289c55c39d81c4fde993533d | https://github.com/go-acme/lego/blob/29c63545ce6fffd8289c55c39d81c4fde993533d/challenge/dns01/dns_challenge.go#L35-L43 | train |
go-acme/lego | challenge/dns01/dns_challenge.go | PreSolve | func (c *Challenge) PreSolve(authz acme.Authorization) error {
domain := challenge.GetTargetedDomain(authz)
log.Infof("[%s] acme: Preparing to solve DNS-01", domain)
chlng, err := challenge.FindChallenge(challenge.DNS01, authz)
if err != nil {
return err
}
if c.provider == nil {
return fmt.Errorf("[%s] acme: no DNS Provider configured", domain)
}
// Generate the Key Authorization for the challenge
keyAuth, err := c.core.GetKeyAuthorization(chlng.Token)
if err != nil {
return err
}
err = c.provider.Present(authz.Identifier.Value, chlng.Token, keyAuth)
if err != nil {
return fmt.Errorf("[%s] acme: error presenting token: %s", domain, err)
}
return nil
} | go | func (c *Challenge) PreSolve(authz acme.Authorization) error {
domain := challenge.GetTargetedDomain(authz)
log.Infof("[%s] acme: Preparing to solve DNS-01", domain)
chlng, err := challenge.FindChallenge(challenge.DNS01, authz)
if err != nil {
return err
}
if c.provider == nil {
return fmt.Errorf("[%s] acme: no DNS Provider configured", domain)
}
// Generate the Key Authorization for the challenge
keyAuth, err := c.core.GetKeyAuthorization(chlng.Token)
if err != nil {
return err
}
err = c.provider.Present(authz.Identifier.Value, chlng.Token, keyAuth)
if err != nil {
return fmt.Errorf("[%s] acme: error presenting token: %s", domain, err)
}
return nil
} | [
"func",
"(",
"c",
"*",
"Challenge",
")",
"PreSolve",
"(",
"authz",
"acme",
".",
"Authorization",
")",
"error",
"{",
"domain",
":=",
"challenge",
".",
"GetTargetedDomain",
"(",
"authz",
")",
"\n",
"log",
".",
"Infof",
"(",
"\"",
"\"",
",",
"domain",
")",
"\n\n",
"chlng",
",",
"err",
":=",
"challenge",
".",
"FindChallenge",
"(",
"challenge",
".",
"DNS01",
",",
"authz",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"if",
"c",
".",
"provider",
"==",
"nil",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"domain",
")",
"\n",
"}",
"\n\n",
"// Generate the Key Authorization for the challenge",
"keyAuth",
",",
"err",
":=",
"c",
".",
"core",
".",
"GetKeyAuthorization",
"(",
"chlng",
".",
"Token",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"err",
"=",
"c",
".",
"provider",
".",
"Present",
"(",
"authz",
".",
"Identifier",
".",
"Value",
",",
"chlng",
".",
"Token",
",",
"keyAuth",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"domain",
",",
"err",
")",
"\n",
"}",
"\n\n",
"return",
"nil",
"\n",
"}"
] | // PreSolve just submits the txt record to the dns provider.
// It does not validate record propagation, or do anything at all with the acme server. | [
"PreSolve",
"just",
"submits",
"the",
"txt",
"record",
"to",
"the",
"dns",
"provider",
".",
"It",
"does",
"not",
"validate",
"record",
"propagation",
"or",
"do",
"anything",
"at",
"all",
"with",
"the",
"acme",
"server",
"."
] | 29c63545ce6fffd8289c55c39d81c4fde993533d | https://github.com/go-acme/lego/blob/29c63545ce6fffd8289c55c39d81c4fde993533d/challenge/dns01/dns_challenge.go#L75-L100 | train |
go-acme/lego | challenge/dns01/dns_challenge.go | CleanUp | func (c *Challenge) CleanUp(authz acme.Authorization) error {
log.Infof("[%s] acme: Cleaning DNS-01 challenge", challenge.GetTargetedDomain(authz))
chlng, err := challenge.FindChallenge(challenge.DNS01, authz)
if err != nil {
return err
}
keyAuth, err := c.core.GetKeyAuthorization(chlng.Token)
if err != nil {
return err
}
return c.provider.CleanUp(authz.Identifier.Value, chlng.Token, keyAuth)
} | go | func (c *Challenge) CleanUp(authz acme.Authorization) error {
log.Infof("[%s] acme: Cleaning DNS-01 challenge", challenge.GetTargetedDomain(authz))
chlng, err := challenge.FindChallenge(challenge.DNS01, authz)
if err != nil {
return err
}
keyAuth, err := c.core.GetKeyAuthorization(chlng.Token)
if err != nil {
return err
}
return c.provider.CleanUp(authz.Identifier.Value, chlng.Token, keyAuth)
} | [
"func",
"(",
"c",
"*",
"Challenge",
")",
"CleanUp",
"(",
"authz",
"acme",
".",
"Authorization",
")",
"error",
"{",
"log",
".",
"Infof",
"(",
"\"",
"\"",
",",
"challenge",
".",
"GetTargetedDomain",
"(",
"authz",
")",
")",
"\n\n",
"chlng",
",",
"err",
":=",
"challenge",
".",
"FindChallenge",
"(",
"challenge",
".",
"DNS01",
",",
"authz",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"keyAuth",
",",
"err",
":=",
"c",
".",
"core",
".",
"GetKeyAuthorization",
"(",
"chlng",
".",
"Token",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"return",
"c",
".",
"provider",
".",
"CleanUp",
"(",
"authz",
".",
"Identifier",
".",
"Value",
",",
"chlng",
".",
"Token",
",",
"keyAuth",
")",
"\n",
"}"
] | // CleanUp cleans the challenge. | [
"CleanUp",
"cleans",
"the",
"challenge",
"."
] | 29c63545ce6fffd8289c55c39d81c4fde993533d | https://github.com/go-acme/lego/blob/29c63545ce6fffd8289c55c39d81c4fde993533d/challenge/dns01/dns_challenge.go#L145-L159 | train |
go-acme/lego | challenge/dns01/dns_challenge.go | GetRecord | func GetRecord(domain, keyAuth string) (fqdn string, value string) {
keyAuthShaBytes := sha256.Sum256([]byte(keyAuth))
// base64URL encoding without padding
value = base64.RawURLEncoding.EncodeToString(keyAuthShaBytes[:sha256.Size])
fqdn = fmt.Sprintf("_acme-challenge.%s.", domain)
if ok, _ := strconv.ParseBool(os.Getenv("LEGO_EXPERIMENTAL_CNAME_SUPPORT")); ok {
r, err := dnsQuery(fqdn, dns.TypeCNAME, recursiveNameservers, true)
// Check if the domain has CNAME then return that
if err == nil && r.Rcode == dns.RcodeSuccess {
fqdn = updateDomainWithCName(r, fqdn)
}
}
return
} | go | func GetRecord(domain, keyAuth string) (fqdn string, value string) {
keyAuthShaBytes := sha256.Sum256([]byte(keyAuth))
// base64URL encoding without padding
value = base64.RawURLEncoding.EncodeToString(keyAuthShaBytes[:sha256.Size])
fqdn = fmt.Sprintf("_acme-challenge.%s.", domain)
if ok, _ := strconv.ParseBool(os.Getenv("LEGO_EXPERIMENTAL_CNAME_SUPPORT")); ok {
r, err := dnsQuery(fqdn, dns.TypeCNAME, recursiveNameservers, true)
// Check if the domain has CNAME then return that
if err == nil && r.Rcode == dns.RcodeSuccess {
fqdn = updateDomainWithCName(r, fqdn)
}
}
return
} | [
"func",
"GetRecord",
"(",
"domain",
",",
"keyAuth",
"string",
")",
"(",
"fqdn",
"string",
",",
"value",
"string",
")",
"{",
"keyAuthShaBytes",
":=",
"sha256",
".",
"Sum256",
"(",
"[",
"]",
"byte",
"(",
"keyAuth",
")",
")",
"\n",
"// base64URL encoding without padding",
"value",
"=",
"base64",
".",
"RawURLEncoding",
".",
"EncodeToString",
"(",
"keyAuthShaBytes",
"[",
":",
"sha256",
".",
"Size",
"]",
")",
"\n",
"fqdn",
"=",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"domain",
")",
"\n\n",
"if",
"ok",
",",
"_",
":=",
"strconv",
".",
"ParseBool",
"(",
"os",
".",
"Getenv",
"(",
"\"",
"\"",
")",
")",
";",
"ok",
"{",
"r",
",",
"err",
":=",
"dnsQuery",
"(",
"fqdn",
",",
"dns",
".",
"TypeCNAME",
",",
"recursiveNameservers",
",",
"true",
")",
"\n",
"// Check if the domain has CNAME then return that",
"if",
"err",
"==",
"nil",
"&&",
"r",
".",
"Rcode",
"==",
"dns",
".",
"RcodeSuccess",
"{",
"fqdn",
"=",
"updateDomainWithCName",
"(",
"r",
",",
"fqdn",
")",
"\n",
"}",
"\n",
"}",
"\n\n",
"return",
"\n",
"}"
] | // GetRecord returns a DNS record which will fulfill the `dns-01` challenge | [
"GetRecord",
"returns",
"a",
"DNS",
"record",
"which",
"will",
"fulfill",
"the",
"dns",
"-",
"01",
"challenge"
] | 29c63545ce6fffd8289c55c39d81c4fde993533d | https://github.com/go-acme/lego/blob/29c63545ce6fffd8289c55c39d81c4fde993533d/challenge/dns01/dns_challenge.go#L173-L188 | train |
go-acme/lego | providers/dns/dnsmadeeasy/dnsmadeeasy.go | NewDNSProviderConfig | func NewDNSProviderConfig(config *Config) (*DNSProvider, error) {
if config == nil {
return nil, errors.New("dnsmadeeasy: the configuration of the DNS provider is nil")
}
var baseURL string
if config.Sandbox {
baseURL = "https://api.sandbox.dnsmadeeasy.com/V2.0"
} else {
if len(config.BaseURL) > 0 {
baseURL = config.BaseURL
} else {
baseURL = "https://api.dnsmadeeasy.com/V2.0"
}
}
client, err := internal.NewClient(config.APIKey, config.APISecret)
if err != nil {
return nil, fmt.Errorf("dnsmadeeasy: %v", err)
}
client.HTTPClient = config.HTTPClient
client.BaseURL = baseURL
return &DNSProvider{
client: client,
config: config,
}, nil
} | go | func NewDNSProviderConfig(config *Config) (*DNSProvider, error) {
if config == nil {
return nil, errors.New("dnsmadeeasy: the configuration of the DNS provider is nil")
}
var baseURL string
if config.Sandbox {
baseURL = "https://api.sandbox.dnsmadeeasy.com/V2.0"
} else {
if len(config.BaseURL) > 0 {
baseURL = config.BaseURL
} else {
baseURL = "https://api.dnsmadeeasy.com/V2.0"
}
}
client, err := internal.NewClient(config.APIKey, config.APISecret)
if err != nil {
return nil, fmt.Errorf("dnsmadeeasy: %v", err)
}
client.HTTPClient = config.HTTPClient
client.BaseURL = baseURL
return &DNSProvider{
client: client,
config: config,
}, nil
} | [
"func",
"NewDNSProviderConfig",
"(",
"config",
"*",
"Config",
")",
"(",
"*",
"DNSProvider",
",",
"error",
")",
"{",
"if",
"config",
"==",
"nil",
"{",
"return",
"nil",
",",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"var",
"baseURL",
"string",
"\n",
"if",
"config",
".",
"Sandbox",
"{",
"baseURL",
"=",
"\"",
"\"",
"\n",
"}",
"else",
"{",
"if",
"len",
"(",
"config",
".",
"BaseURL",
")",
">",
"0",
"{",
"baseURL",
"=",
"config",
".",
"BaseURL",
"\n",
"}",
"else",
"{",
"baseURL",
"=",
"\"",
"\"",
"\n",
"}",
"\n",
"}",
"\n\n",
"client",
",",
"err",
":=",
"internal",
".",
"NewClient",
"(",
"config",
".",
"APIKey",
",",
"config",
".",
"APISecret",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n\n",
"client",
".",
"HTTPClient",
"=",
"config",
".",
"HTTPClient",
"\n",
"client",
".",
"BaseURL",
"=",
"baseURL",
"\n\n",
"return",
"&",
"DNSProvider",
"{",
"client",
":",
"client",
",",
"config",
":",
"config",
",",
"}",
",",
"nil",
"\n",
"}"
] | // NewDNSProviderConfig return a DNSProvider instance configured for DNS Made Easy. | [
"NewDNSProviderConfig",
"return",
"a",
"DNSProvider",
"instance",
"configured",
"for",
"DNS",
"Made",
"Easy",
"."
] | 29c63545ce6fffd8289c55c39d81c4fde993533d | https://github.com/go-acme/lego/blob/29c63545ce6fffd8289c55c39d81c4fde993533d/providers/dns/dnsmadeeasy/dnsmadeeasy.go#L69-L97 | train |
go-acme/lego | providers/dns/dnsmadeeasy/dnsmadeeasy.go | CleanUp | func (d *DNSProvider) CleanUp(domainName, token, keyAuth string) error {
fqdn, _ := dns01.GetRecord(domainName, keyAuth)
authZone, err := dns01.FindZoneByFqdn(fqdn)
if err != nil {
return fmt.Errorf("dnsmadeeasy: unable to find zone for %s: %v", fqdn, err)
}
// fetch the domain details
domain, err := d.client.GetDomain(authZone)
if err != nil {
return fmt.Errorf("dnsmadeeasy: unable to get domain for zone %s: %v", authZone, err)
}
// find matching records
name := strings.Replace(fqdn, "."+authZone, "", 1)
records, err := d.client.GetRecords(domain, name, "TXT")
if err != nil {
return fmt.Errorf("dnsmadeeasy: unable to get records for domain %s: %v", domain.Name, err)
}
// delete records
var lastError error
for _, record := range *records {
err = d.client.DeleteRecord(record)
if err != nil {
lastError = fmt.Errorf("dnsmadeeasy: unable to delete record [id=%d, name=%s]: %v", record.ID, record.Name, err)
}
}
return lastError
} | go | func (d *DNSProvider) CleanUp(domainName, token, keyAuth string) error {
fqdn, _ := dns01.GetRecord(domainName, keyAuth)
authZone, err := dns01.FindZoneByFqdn(fqdn)
if err != nil {
return fmt.Errorf("dnsmadeeasy: unable to find zone for %s: %v", fqdn, err)
}
// fetch the domain details
domain, err := d.client.GetDomain(authZone)
if err != nil {
return fmt.Errorf("dnsmadeeasy: unable to get domain for zone %s: %v", authZone, err)
}
// find matching records
name := strings.Replace(fqdn, "."+authZone, "", 1)
records, err := d.client.GetRecords(domain, name, "TXT")
if err != nil {
return fmt.Errorf("dnsmadeeasy: unable to get records for domain %s: %v", domain.Name, err)
}
// delete records
var lastError error
for _, record := range *records {
err = d.client.DeleteRecord(record)
if err != nil {
lastError = fmt.Errorf("dnsmadeeasy: unable to delete record [id=%d, name=%s]: %v", record.ID, record.Name, err)
}
}
return lastError
} | [
"func",
"(",
"d",
"*",
"DNSProvider",
")",
"CleanUp",
"(",
"domainName",
",",
"token",
",",
"keyAuth",
"string",
")",
"error",
"{",
"fqdn",
",",
"_",
":=",
"dns01",
".",
"GetRecord",
"(",
"domainName",
",",
"keyAuth",
")",
"\n\n",
"authZone",
",",
"err",
":=",
"dns01",
".",
"FindZoneByFqdn",
"(",
"fqdn",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"fqdn",
",",
"err",
")",
"\n",
"}",
"\n\n",
"// fetch the domain details",
"domain",
",",
"err",
":=",
"d",
".",
"client",
".",
"GetDomain",
"(",
"authZone",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"authZone",
",",
"err",
")",
"\n",
"}",
"\n\n",
"// find matching records",
"name",
":=",
"strings",
".",
"Replace",
"(",
"fqdn",
",",
"\"",
"\"",
"+",
"authZone",
",",
"\"",
"\"",
",",
"1",
")",
"\n",
"records",
",",
"err",
":=",
"d",
".",
"client",
".",
"GetRecords",
"(",
"domain",
",",
"name",
",",
"\"",
"\"",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"domain",
".",
"Name",
",",
"err",
")",
"\n",
"}",
"\n\n",
"// delete records",
"var",
"lastError",
"error",
"\n",
"for",
"_",
",",
"record",
":=",
"range",
"*",
"records",
"{",
"err",
"=",
"d",
".",
"client",
".",
"DeleteRecord",
"(",
"record",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"lastError",
"=",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"record",
".",
"ID",
",",
"record",
".",
"Name",
",",
"err",
")",
"\n",
"}",
"\n",
"}",
"\n\n",
"return",
"lastError",
"\n",
"}"
] | // CleanUp removes the TXT records matching the specified parameters | [
"CleanUp",
"removes",
"the",
"TXT",
"records",
"matching",
"the",
"specified",
"parameters"
] | 29c63545ce6fffd8289c55c39d81c4fde993533d | https://github.com/go-acme/lego/blob/29c63545ce6fffd8289c55c39d81c4fde993533d/providers/dns/dnsmadeeasy/dnsmadeeasy.go#L126-L157 | train |
go-acme/lego | providers/dns/zoneee/zoneee.go | CleanUp | func (d *DNSProvider) CleanUp(domain, token, keyAuth string) error {
_, value := dns01.GetRecord(domain, keyAuth)
records, err := d.getTxtRecords(domain)
if err != nil {
return fmt.Errorf("zoneee: %v", err)
}
var id string
for _, record := range records {
if record.Destination == value {
id = record.ID
}
}
if id == "" {
return fmt.Errorf("zoneee: txt record does not exist for %v", value)
}
if err = d.removeTxtRecord(domain, id); err != nil {
return fmt.Errorf("zoneee: %v", err)
}
return nil
} | go | func (d *DNSProvider) CleanUp(domain, token, keyAuth string) error {
_, value := dns01.GetRecord(domain, keyAuth)
records, err := d.getTxtRecords(domain)
if err != nil {
return fmt.Errorf("zoneee: %v", err)
}
var id string
for _, record := range records {
if record.Destination == value {
id = record.ID
}
}
if id == "" {
return fmt.Errorf("zoneee: txt record does not exist for %v", value)
}
if err = d.removeTxtRecord(domain, id); err != nil {
return fmt.Errorf("zoneee: %v", err)
}
return nil
} | [
"func",
"(",
"d",
"*",
"DNSProvider",
")",
"CleanUp",
"(",
"domain",
",",
"token",
",",
"keyAuth",
"string",
")",
"error",
"{",
"_",
",",
"value",
":=",
"dns01",
".",
"GetRecord",
"(",
"domain",
",",
"keyAuth",
")",
"\n\n",
"records",
",",
"err",
":=",
"d",
".",
"getTxtRecords",
"(",
"domain",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n\n",
"var",
"id",
"string",
"\n",
"for",
"_",
",",
"record",
":=",
"range",
"records",
"{",
"if",
"record",
".",
"Destination",
"==",
"value",
"{",
"id",
"=",
"record",
".",
"ID",
"\n",
"}",
"\n",
"}",
"\n\n",
"if",
"id",
"==",
"\"",
"\"",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"value",
")",
"\n",
"}",
"\n\n",
"if",
"err",
"=",
"d",
".",
"removeTxtRecord",
"(",
"domain",
",",
"id",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n\n",
"return",
"nil",
"\n",
"}"
] | // CleanUp removes the TXT record previously created | [
"CleanUp",
"removes",
"the",
"TXT",
"record",
"previously",
"created"
] | 29c63545ce6fffd8289c55c39d81c4fde993533d | https://github.com/go-acme/lego/blob/29c63545ce6fffd8289c55c39d81c4fde993533d/providers/dns/zoneee/zoneee.go#L110-L134 | train |
go-acme/lego | providers/dns/iij/iij.go | NewDNSProviderConfig | func NewDNSProviderConfig(config *Config) (*DNSProvider, error) {
if config.SecretKey == "" || config.AccessKey == "" || config.DoServiceCode == "" {
return nil, fmt.Errorf("iij: credentials missing")
}
return &DNSProvider{
api: doapi.NewAPI(config.AccessKey, config.SecretKey),
config: config,
}, nil
} | go | func NewDNSProviderConfig(config *Config) (*DNSProvider, error) {
if config.SecretKey == "" || config.AccessKey == "" || config.DoServiceCode == "" {
return nil, fmt.Errorf("iij: credentials missing")
}
return &DNSProvider{
api: doapi.NewAPI(config.AccessKey, config.SecretKey),
config: config,
}, nil
} | [
"func",
"NewDNSProviderConfig",
"(",
"config",
"*",
"Config",
")",
"(",
"*",
"DNSProvider",
",",
"error",
")",
"{",
"if",
"config",
".",
"SecretKey",
"==",
"\"",
"\"",
"||",
"config",
".",
"AccessKey",
"==",
"\"",
"\"",
"||",
"config",
".",
"DoServiceCode",
"==",
"\"",
"\"",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"return",
"&",
"DNSProvider",
"{",
"api",
":",
"doapi",
".",
"NewAPI",
"(",
"config",
".",
"AccessKey",
",",
"config",
".",
"SecretKey",
")",
",",
"config",
":",
"config",
",",
"}",
",",
"nil",
"\n",
"}"
] | // NewDNSProviderConfig takes a given config
// and returns a custom configured DNSProvider instance | [
"NewDNSProviderConfig",
"takes",
"a",
"given",
"config",
"and",
"returns",
"a",
"custom",
"configured",
"DNSProvider",
"instance"
] | 29c63545ce6fffd8289c55c39d81c4fde993533d | https://github.com/go-acme/lego/blob/29c63545ce6fffd8289c55c39d81c4fde993533d/providers/dns/iij/iij.go#L58-L67 | train |
go-acme/lego | providers/dns/rackspace/client.go | getHostedZoneID | func (d *DNSProvider) getHostedZoneID(fqdn string) (int, error) {
authZone, err := dns01.FindZoneByFqdn(fqdn)
if err != nil {
return 0, err
}
result, err := d.makeRequest(http.MethodGet, fmt.Sprintf("/domains?name=%s", dns01.UnFqdn(authZone)), nil)
if err != nil {
return 0, err
}
var zoneSearchResponse ZoneSearchResponse
err = json.Unmarshal(result, &zoneSearchResponse)
if err != nil {
return 0, err
}
// If nothing was returned, or for whatever reason more than 1 was returned (the search uses exact match, so should not occur)
if zoneSearchResponse.TotalEntries != 1 {
return 0, fmt.Errorf("found %d zones for %s in Rackspace for domain %s", zoneSearchResponse.TotalEntries, authZone, fqdn)
}
return zoneSearchResponse.HostedZones[0].ID, nil
} | go | func (d *DNSProvider) getHostedZoneID(fqdn string) (int, error) {
authZone, err := dns01.FindZoneByFqdn(fqdn)
if err != nil {
return 0, err
}
result, err := d.makeRequest(http.MethodGet, fmt.Sprintf("/domains?name=%s", dns01.UnFqdn(authZone)), nil)
if err != nil {
return 0, err
}
var zoneSearchResponse ZoneSearchResponse
err = json.Unmarshal(result, &zoneSearchResponse)
if err != nil {
return 0, err
}
// If nothing was returned, or for whatever reason more than 1 was returned (the search uses exact match, so should not occur)
if zoneSearchResponse.TotalEntries != 1 {
return 0, fmt.Errorf("found %d zones for %s in Rackspace for domain %s", zoneSearchResponse.TotalEntries, authZone, fqdn)
}
return zoneSearchResponse.HostedZones[0].ID, nil
} | [
"func",
"(",
"d",
"*",
"DNSProvider",
")",
"getHostedZoneID",
"(",
"fqdn",
"string",
")",
"(",
"int",
",",
"error",
")",
"{",
"authZone",
",",
"err",
":=",
"dns01",
".",
"FindZoneByFqdn",
"(",
"fqdn",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"0",
",",
"err",
"\n",
"}",
"\n\n",
"result",
",",
"err",
":=",
"d",
".",
"makeRequest",
"(",
"http",
".",
"MethodGet",
",",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"dns01",
".",
"UnFqdn",
"(",
"authZone",
")",
")",
",",
"nil",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"0",
",",
"err",
"\n",
"}",
"\n\n",
"var",
"zoneSearchResponse",
"ZoneSearchResponse",
"\n",
"err",
"=",
"json",
".",
"Unmarshal",
"(",
"result",
",",
"&",
"zoneSearchResponse",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"0",
",",
"err",
"\n",
"}",
"\n\n",
"// If nothing was returned, or for whatever reason more than 1 was returned (the search uses exact match, so should not occur)",
"if",
"zoneSearchResponse",
".",
"TotalEntries",
"!=",
"1",
"{",
"return",
"0",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"zoneSearchResponse",
".",
"TotalEntries",
",",
"authZone",
",",
"fqdn",
")",
"\n",
"}",
"\n\n",
"return",
"zoneSearchResponse",
".",
"HostedZones",
"[",
"0",
"]",
".",
"ID",
",",
"nil",
"\n",
"}"
] | // getHostedZoneID performs a lookup to get the DNS zone which needs
// modifying for a given FQDN | [
"getHostedZoneID",
"performs",
"a",
"lookup",
"to",
"get",
"the",
"DNS",
"zone",
"which",
"needs",
"modifying",
"for",
"a",
"given",
"FQDN"
] | 29c63545ce6fffd8289c55c39d81c4fde993533d | https://github.com/go-acme/lego/blob/29c63545ce6fffd8289c55c39d81c4fde993533d/providers/dns/rackspace/client.go#L85-L108 | train |
go-acme/lego | providers/dns/rackspace/client.go | findTxtRecord | func (d *DNSProvider) findTxtRecord(fqdn string, zoneID int) (*Record, error) {
result, err := d.makeRequest(http.MethodGet, fmt.Sprintf("/domains/%d/records?type=TXT&name=%s", zoneID, dns01.UnFqdn(fqdn)), nil)
if err != nil {
return nil, err
}
var records Records
err = json.Unmarshal(result, &records)
if err != nil {
return nil, err
}
switch len(records.Record) {
case 1:
case 0:
return nil, fmt.Errorf("no TXT record found for %s", fqdn)
default:
return nil, fmt.Errorf("more than 1 TXT record found for %s", fqdn)
}
return &records.Record[0], nil
} | go | func (d *DNSProvider) findTxtRecord(fqdn string, zoneID int) (*Record, error) {
result, err := d.makeRequest(http.MethodGet, fmt.Sprintf("/domains/%d/records?type=TXT&name=%s", zoneID, dns01.UnFqdn(fqdn)), nil)
if err != nil {
return nil, err
}
var records Records
err = json.Unmarshal(result, &records)
if err != nil {
return nil, err
}
switch len(records.Record) {
case 1:
case 0:
return nil, fmt.Errorf("no TXT record found for %s", fqdn)
default:
return nil, fmt.Errorf("more than 1 TXT record found for %s", fqdn)
}
return &records.Record[0], nil
} | [
"func",
"(",
"d",
"*",
"DNSProvider",
")",
"findTxtRecord",
"(",
"fqdn",
"string",
",",
"zoneID",
"int",
")",
"(",
"*",
"Record",
",",
"error",
")",
"{",
"result",
",",
"err",
":=",
"d",
".",
"makeRequest",
"(",
"http",
".",
"MethodGet",
",",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"zoneID",
",",
"dns01",
".",
"UnFqdn",
"(",
"fqdn",
")",
")",
",",
"nil",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"var",
"records",
"Records",
"\n",
"err",
"=",
"json",
".",
"Unmarshal",
"(",
"result",
",",
"&",
"records",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"switch",
"len",
"(",
"records",
".",
"Record",
")",
"{",
"case",
"1",
":",
"case",
"0",
":",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"fqdn",
")",
"\n",
"default",
":",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"fqdn",
")",
"\n",
"}",
"\n\n",
"return",
"&",
"records",
".",
"Record",
"[",
"0",
"]",
",",
"nil",
"\n",
"}"
] | // findTxtRecord searches a DNS zone for a TXT record with a specific name | [
"findTxtRecord",
"searches",
"a",
"DNS",
"zone",
"for",
"a",
"TXT",
"record",
"with",
"a",
"specific",
"name"
] | 29c63545ce6fffd8289c55c39d81c4fde993533d | https://github.com/go-acme/lego/blob/29c63545ce6fffd8289c55c39d81c4fde993533d/providers/dns/rackspace/client.go#L111-L132 | train |
go-acme/lego | providers/dns/rackspace/client.go | makeRequest | func (d *DNSProvider) makeRequest(method, uri string, body io.Reader) (json.RawMessage, error) {
url := d.cloudDNSEndpoint + uri
req, err := http.NewRequest(method, url, body)
if err != nil {
return nil, err
}
req.Header.Set("X-Auth-Token", d.token)
req.Header.Set("Content-Type", "application/json")
resp, err := d.config.HTTPClient.Do(req)
if err != nil {
return nil, fmt.Errorf("error querying DNS API: %v", err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK && resp.StatusCode != http.StatusAccepted {
return nil, fmt.Errorf("request failed for %s %s. Response code: %d", method, url, resp.StatusCode)
}
var r json.RawMessage
err = json.NewDecoder(resp.Body).Decode(&r)
if err != nil {
return nil, fmt.Errorf("JSON decode failed for %s %s. Response code: %d", method, url, resp.StatusCode)
}
return r, nil
} | go | func (d *DNSProvider) makeRequest(method, uri string, body io.Reader) (json.RawMessage, error) {
url := d.cloudDNSEndpoint + uri
req, err := http.NewRequest(method, url, body)
if err != nil {
return nil, err
}
req.Header.Set("X-Auth-Token", d.token)
req.Header.Set("Content-Type", "application/json")
resp, err := d.config.HTTPClient.Do(req)
if err != nil {
return nil, fmt.Errorf("error querying DNS API: %v", err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK && resp.StatusCode != http.StatusAccepted {
return nil, fmt.Errorf("request failed for %s %s. Response code: %d", method, url, resp.StatusCode)
}
var r json.RawMessage
err = json.NewDecoder(resp.Body).Decode(&r)
if err != nil {
return nil, fmt.Errorf("JSON decode failed for %s %s. Response code: %d", method, url, resp.StatusCode)
}
return r, nil
} | [
"func",
"(",
"d",
"*",
"DNSProvider",
")",
"makeRequest",
"(",
"method",
",",
"uri",
"string",
",",
"body",
"io",
".",
"Reader",
")",
"(",
"json",
".",
"RawMessage",
",",
"error",
")",
"{",
"url",
":=",
"d",
".",
"cloudDNSEndpoint",
"+",
"uri",
"\n\n",
"req",
",",
"err",
":=",
"http",
".",
"NewRequest",
"(",
"method",
",",
"url",
",",
"body",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"req",
".",
"Header",
".",
"Set",
"(",
"\"",
"\"",
",",
"d",
".",
"token",
")",
"\n",
"req",
".",
"Header",
".",
"Set",
"(",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\n\n",
"resp",
",",
"err",
":=",
"d",
".",
"config",
".",
"HTTPClient",
".",
"Do",
"(",
"req",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n\n",
"defer",
"resp",
".",
"Body",
".",
"Close",
"(",
")",
"\n\n",
"if",
"resp",
".",
"StatusCode",
"!=",
"http",
".",
"StatusOK",
"&&",
"resp",
".",
"StatusCode",
"!=",
"http",
".",
"StatusAccepted",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"method",
",",
"url",
",",
"resp",
".",
"StatusCode",
")",
"\n",
"}",
"\n\n",
"var",
"r",
"json",
".",
"RawMessage",
"\n",
"err",
"=",
"json",
".",
"NewDecoder",
"(",
"resp",
".",
"Body",
")",
".",
"Decode",
"(",
"&",
"r",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"method",
",",
"url",
",",
"resp",
".",
"StatusCode",
")",
"\n",
"}",
"\n\n",
"return",
"r",
",",
"nil",
"\n",
"}"
] | // makeRequest is a wrapper function used for making DNS API requests | [
"makeRequest",
"is",
"a",
"wrapper",
"function",
"used",
"for",
"making",
"DNS",
"API",
"requests"
] | 29c63545ce6fffd8289c55c39d81c4fde993533d | https://github.com/go-acme/lego/blob/29c63545ce6fffd8289c55c39d81c4fde993533d/providers/dns/rackspace/client.go#L135-L164 | train |
go-acme/lego | providers/dns/rackspace/rackspace.go | NewDNSProviderConfig | func NewDNSProviderConfig(config *Config) (*DNSProvider, error) {
if config == nil {
return nil, errors.New("rackspace: the configuration of the DNS provider is nil")
}
if config.APIUser == "" || config.APIKey == "" {
return nil, fmt.Errorf("rackspace: credentials missing")
}
identity, err := login(config)
if err != nil {
return nil, fmt.Errorf("rackspace: %v", err)
}
// Iterate through the Service Catalog to get the DNS Endpoint
var dnsEndpoint string
for _, service := range identity.Access.ServiceCatalog {
if service.Name == "cloudDNS" {
dnsEndpoint = service.Endpoints[0].PublicURL
break
}
}
if dnsEndpoint == "" {
return nil, fmt.Errorf("rackspace: failed to populate DNS endpoint, check Rackspace API for changes")
}
return &DNSProvider{
config: config,
token: identity.Access.Token.ID,
cloudDNSEndpoint: dnsEndpoint,
}, nil
} | go | func NewDNSProviderConfig(config *Config) (*DNSProvider, error) {
if config == nil {
return nil, errors.New("rackspace: the configuration of the DNS provider is nil")
}
if config.APIUser == "" || config.APIKey == "" {
return nil, fmt.Errorf("rackspace: credentials missing")
}
identity, err := login(config)
if err != nil {
return nil, fmt.Errorf("rackspace: %v", err)
}
// Iterate through the Service Catalog to get the DNS Endpoint
var dnsEndpoint string
for _, service := range identity.Access.ServiceCatalog {
if service.Name == "cloudDNS" {
dnsEndpoint = service.Endpoints[0].PublicURL
break
}
}
if dnsEndpoint == "" {
return nil, fmt.Errorf("rackspace: failed to populate DNS endpoint, check Rackspace API for changes")
}
return &DNSProvider{
config: config,
token: identity.Access.Token.ID,
cloudDNSEndpoint: dnsEndpoint,
}, nil
} | [
"func",
"NewDNSProviderConfig",
"(",
"config",
"*",
"Config",
")",
"(",
"*",
"DNSProvider",
",",
"error",
")",
"{",
"if",
"config",
"==",
"nil",
"{",
"return",
"nil",
",",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"if",
"config",
".",
"APIUser",
"==",
"\"",
"\"",
"||",
"config",
".",
"APIKey",
"==",
"\"",
"\"",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"identity",
",",
"err",
":=",
"login",
"(",
"config",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n\n",
"// Iterate through the Service Catalog to get the DNS Endpoint",
"var",
"dnsEndpoint",
"string",
"\n",
"for",
"_",
",",
"service",
":=",
"range",
"identity",
".",
"Access",
".",
"ServiceCatalog",
"{",
"if",
"service",
".",
"Name",
"==",
"\"",
"\"",
"{",
"dnsEndpoint",
"=",
"service",
".",
"Endpoints",
"[",
"0",
"]",
".",
"PublicURL",
"\n",
"break",
"\n",
"}",
"\n",
"}",
"\n\n",
"if",
"dnsEndpoint",
"==",
"\"",
"\"",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"return",
"&",
"DNSProvider",
"{",
"config",
":",
"config",
",",
"token",
":",
"identity",
".",
"Access",
".",
"Token",
".",
"ID",
",",
"cloudDNSEndpoint",
":",
"dnsEndpoint",
",",
"}",
",",
"nil",
"\n\n",
"}"
] | // NewDNSProviderConfig return a DNSProvider instance configured for Rackspace.
// It authenticates against the API, also grabbing the DNS Endpoint. | [
"NewDNSProviderConfig",
"return",
"a",
"DNSProvider",
"instance",
"configured",
"for",
"Rackspace",
".",
"It",
"authenticates",
"against",
"the",
"API",
"also",
"grabbing",
"the",
"DNS",
"Endpoint",
"."
] | 29c63545ce6fffd8289c55c39d81c4fde993533d | https://github.com/go-acme/lego/blob/29c63545ce6fffd8289c55c39d81c4fde993533d/providers/dns/rackspace/rackspace.go#L69-L102 | train |
Subsets and Splits