repo
stringlengths
5
67
path
stringlengths
4
218
func_name
stringlengths
0
151
original_string
stringlengths
52
373k
language
stringclasses
6 values
code
stringlengths
52
373k
code_tokens
listlengths
10
512
docstring
stringlengths
3
47.2k
docstring_tokens
listlengths
3
234
sha
stringlengths
40
40
url
stringlengths
85
339
partition
stringclasses
3 values
asaskevich/govalidator
utils.go
SafeFileName
func SafeFileName(str string) string { name := strings.ToLower(str) name = path.Clean(path.Base(name)) name = strings.Trim(name, " ") separators, err := regexp.Compile(`[ &_=+:]`) if err == nil { name = separators.ReplaceAllString(name, "-") } legal, err := regexp.Compile(`[^[:alnum:]-.]`) if err == nil { name = legal.ReplaceAllString(name, "") } for strings.Contains(name, "--") { name = strings.Replace(name, "--", "-", -1) } return name }
go
func SafeFileName(str string) string { name := strings.ToLower(str) name = path.Clean(path.Base(name)) name = strings.Trim(name, " ") separators, err := regexp.Compile(`[ &_=+:]`) if err == nil { name = separators.ReplaceAllString(name, "-") } legal, err := regexp.Compile(`[^[:alnum:]-.]`) if err == nil { name = legal.ReplaceAllString(name, "") } for strings.Contains(name, "--") { name = strings.Replace(name, "--", "-", -1) } return name }
[ "func", "SafeFileName", "(", "str", "string", ")", "string", "{", "name", ":=", "strings", ".", "ToLower", "(", "str", ")", "\n", "name", "=", "path", ".", "Clean", "(", "path", ".", "Base", "(", "name", ")", ")", "\n", "name", "=", "strings", ".", "Trim", "(", "name", ",", "\" \"", ")", "\n", "separators", ",", "err", ":=", "regexp", ".", "Compile", "(", "`[ &_=+:]`", ")", "\n", "if", "err", "==", "nil", "{", "name", "=", "separators", ".", "ReplaceAllString", "(", "name", ",", "\"-\"", ")", "\n", "}", "\n", "legal", ",", "err", ":=", "regexp", ".", "Compile", "(", "`[^[:alnum:]-.]`", ")", "\n", "if", "err", "==", "nil", "{", "name", "=", "legal", ".", "ReplaceAllString", "(", "name", ",", "\"\"", ")", "\n", "}", "\n", "for", "strings", ".", "Contains", "(", "name", ",", "\"--\"", ")", "{", "name", "=", "strings", ".", "Replace", "(", "name", ",", "\"--\"", ",", "\"-\"", ",", "-", "1", ")", "\n", "}", "\n", "return", "name", "\n", "}" ]
// SafeFileName return safe string that can be used in file names
[ "SafeFileName", "return", "safe", "string", "that", "can", "be", "used", "in", "file", "names" ]
f61b66f89f4a311bef65f13e575bcf1a2ffadda6
https://github.com/asaskevich/govalidator/blob/f61b66f89f4a311bef65f13e575bcf1a2ffadda6/utils.go#L152-L168
train
asaskevich/govalidator
utils.go
Truncate
func Truncate(str string, length int, ending string) string { var aftstr, befstr string if len(str) > length { words := strings.Fields(str) before, present := 0, 0 for i := range words { befstr = aftstr before = present aftstr = aftstr + words[i] + " " present = len(aftstr) if present > length && i != 0 { if (length - before) < (present - length) { return Trim(befstr, " /\\.,\"'#!?&@+-") + ending } return Trim(aftstr, " /\\.,\"'#!?&@+-") + ending } } } return str }
go
func Truncate(str string, length int, ending string) string { var aftstr, befstr string if len(str) > length { words := strings.Fields(str) before, present := 0, 0 for i := range words { befstr = aftstr before = present aftstr = aftstr + words[i] + " " present = len(aftstr) if present > length && i != 0 { if (length - before) < (present - length) { return Trim(befstr, " /\\.,\"'#!?&@+-") + ending } return Trim(aftstr, " /\\.,\"'#!?&@+-") + ending } } } return str }
[ "func", "Truncate", "(", "str", "string", ",", "length", "int", ",", "ending", "string", ")", "string", "{", "var", "aftstr", ",", "befstr", "string", "\n", "if", "len", "(", "str", ")", ">", "length", "{", "words", ":=", "strings", ".", "Fields", "(", "str", ")", "\n", "before", ",", "present", ":=", "0", ",", "0", "\n", "for", "i", ":=", "range", "words", "{", "befstr", "=", "aftstr", "\n", "before", "=", "present", "\n", "aftstr", "=", "aftstr", "+", "words", "[", "i", "]", "+", "\" \"", "\n", "present", "=", "len", "(", "aftstr", ")", "\n", "if", "present", ">", "length", "&&", "i", "!=", "0", "{", "if", "(", "length", "-", "before", ")", "<", "(", "present", "-", "length", ")", "{", "return", "Trim", "(", "befstr", ",", "\" /\\\\.,\\\"'#!?&@+-\"", ")", "+", "\\\\", "\n", "}", "\n", "\\\"", "\n", "}", "\n", "}", "\n", "}", "\n", "ending", "\n", "}" ]
// Truncate a string to the closest length without breaking words.
[ "Truncate", "a", "string", "to", "the", "closest", "length", "without", "breaking", "words", "." ]
f61b66f89f4a311bef65f13e575bcf1a2ffadda6
https://github.com/asaskevich/govalidator/blob/f61b66f89f4a311bef65f13e575bcf1a2ffadda6/utils.go#L191-L211
train
asaskevich/govalidator
utils.go
PadLeft
func PadLeft(str string, padStr string, padLen int) string { return buildPadStr(str, padStr, padLen, true, false) }
go
func PadLeft(str string, padStr string, padLen int) string { return buildPadStr(str, padStr, padLen, true, false) }
[ "func", "PadLeft", "(", "str", "string", ",", "padStr", "string", ",", "padLen", "int", ")", "string", "{", "return", "buildPadStr", "(", "str", ",", "padStr", ",", "padLen", ",", "true", ",", "false", ")", "\n", "}" ]
// PadLeft pad left side of string if size of string is less then indicated pad length
[ "PadLeft", "pad", "left", "side", "of", "string", "if", "size", "of", "string", "is", "less", "then", "indicated", "pad", "length" ]
f61b66f89f4a311bef65f13e575bcf1a2ffadda6
https://github.com/asaskevich/govalidator/blob/f61b66f89f4a311bef65f13e575bcf1a2ffadda6/utils.go#L214-L216
train
asaskevich/govalidator
utils.go
PadBoth
func PadBoth(str string, padStr string, padLen int) string { return buildPadStr(str, padStr, padLen, true, true) }
go
func PadBoth(str string, padStr string, padLen int) string { return buildPadStr(str, padStr, padLen, true, true) }
[ "func", "PadBoth", "(", "str", "string", ",", "padStr", "string", ",", "padLen", "int", ")", "string", "{", "return", "buildPadStr", "(", "str", ",", "padStr", ",", "padLen", ",", "true", ",", "true", ")", "\n", "}" ]
// PadBoth pad sides of string if size of string is less then indicated pad length
[ "PadBoth", "pad", "sides", "of", "string", "if", "size", "of", "string", "is", "less", "then", "indicated", "pad", "length" ]
f61b66f89f4a311bef65f13e575bcf1a2ffadda6
https://github.com/asaskevich/govalidator/blob/f61b66f89f4a311bef65f13e575bcf1a2ffadda6/utils.go#L224-L226
train
asaskevich/govalidator
utils.go
buildPadStr
func buildPadStr(str string, padStr string, padLen int, padLeft bool, padRight bool) string { // When padded length is less then the current string size if padLen < utf8.RuneCountInString(str) { return str } padLen -= utf8.RuneCountInString(str) targetLen := padLen targetLenLeft := targetLen targetLenRight := targetLen if padLeft && padRight { targetLenLeft = padLen / 2 targetLenRight = padLen - targetLenLeft } strToRepeatLen := utf8.RuneCountInString(padStr) repeatTimes := int(math.Ceil(float64(targetLen) / float64(strToRepeatLen))) repeatedString := strings.Repeat(padStr, repeatTimes) leftSide := "" if padLeft { leftSide = repeatedString[0:targetLenLeft] } rightSide := "" if padRight { rightSide = repeatedString[0:targetLenRight] } return leftSide + str + rightSide }
go
func buildPadStr(str string, padStr string, padLen int, padLeft bool, padRight bool) string { // When padded length is less then the current string size if padLen < utf8.RuneCountInString(str) { return str } padLen -= utf8.RuneCountInString(str) targetLen := padLen targetLenLeft := targetLen targetLenRight := targetLen if padLeft && padRight { targetLenLeft = padLen / 2 targetLenRight = padLen - targetLenLeft } strToRepeatLen := utf8.RuneCountInString(padStr) repeatTimes := int(math.Ceil(float64(targetLen) / float64(strToRepeatLen))) repeatedString := strings.Repeat(padStr, repeatTimes) leftSide := "" if padLeft { leftSide = repeatedString[0:targetLenLeft] } rightSide := "" if padRight { rightSide = repeatedString[0:targetLenRight] } return leftSide + str + rightSide }
[ "func", "buildPadStr", "(", "str", "string", ",", "padStr", "string", ",", "padLen", "int", ",", "padLeft", "bool", ",", "padRight", "bool", ")", "string", "{", "if", "padLen", "<", "utf8", ".", "RuneCountInString", "(", "str", ")", "{", "return", "str", "\n", "}", "\n", "padLen", "-=", "utf8", ".", "RuneCountInString", "(", "str", ")", "\n", "targetLen", ":=", "padLen", "\n", "targetLenLeft", ":=", "targetLen", "\n", "targetLenRight", ":=", "targetLen", "\n", "if", "padLeft", "&&", "padRight", "{", "targetLenLeft", "=", "padLen", "/", "2", "\n", "targetLenRight", "=", "padLen", "-", "targetLenLeft", "\n", "}", "\n", "strToRepeatLen", ":=", "utf8", ".", "RuneCountInString", "(", "padStr", ")", "\n", "repeatTimes", ":=", "int", "(", "math", ".", "Ceil", "(", "float64", "(", "targetLen", ")", "/", "float64", "(", "strToRepeatLen", ")", ")", ")", "\n", "repeatedString", ":=", "strings", ".", "Repeat", "(", "padStr", ",", "repeatTimes", ")", "\n", "leftSide", ":=", "\"\"", "\n", "if", "padLeft", "{", "leftSide", "=", "repeatedString", "[", "0", ":", "targetLenLeft", "]", "\n", "}", "\n", "rightSide", ":=", "\"\"", "\n", "if", "padRight", "{", "rightSide", "=", "repeatedString", "[", "0", ":", "targetLenRight", "]", "\n", "}", "\n", "return", "leftSide", "+", "str", "+", "rightSide", "\n", "}" ]
// PadString either left, right or both sides, not the padding string can be unicode and more then one // character
[ "PadString", "either", "left", "right", "or", "both", "sides", "not", "the", "padding", "string", "can", "be", "unicode", "and", "more", "then", "one", "character" ]
f61b66f89f4a311bef65f13e575bcf1a2ffadda6
https://github.com/asaskevich/govalidator/blob/f61b66f89f4a311bef65f13e575bcf1a2ffadda6/utils.go#L230-L264
train
asaskevich/govalidator
utils.go
TruncatingErrorf
func TruncatingErrorf(str string, args ...interface{}) error { n := strings.Count(str, "%s") return fmt.Errorf(str, args[:n]...) }
go
func TruncatingErrorf(str string, args ...interface{}) error { n := strings.Count(str, "%s") return fmt.Errorf(str, args[:n]...) }
[ "func", "TruncatingErrorf", "(", "str", "string", ",", "args", "...", "interface", "{", "}", ")", "error", "{", "n", ":=", "strings", ".", "Count", "(", "str", ",", "\"%s\"", ")", "\n", "return", "fmt", ".", "Errorf", "(", "str", ",", "args", "[", ":", "n", "]", "...", ")", "\n", "}" ]
// TruncatingErrorf removes extra args from fmt.Errorf if not formatted in the str object
[ "TruncatingErrorf", "removes", "extra", "args", "from", "fmt", ".", "Errorf", "if", "not", "formatted", "in", "the", "str", "object" ]
f61b66f89f4a311bef65f13e575bcf1a2ffadda6
https://github.com/asaskevich/govalidator/blob/f61b66f89f4a311bef65f13e575bcf1a2ffadda6/utils.go#L267-L270
train
asaskevich/govalidator
converter.go
ToJSON
func ToJSON(obj interface{}) (string, error) { res, err := json.Marshal(obj) if err != nil { res = []byte("") } return string(res), err }
go
func ToJSON(obj interface{}) (string, error) { res, err := json.Marshal(obj) if err != nil { res = []byte("") } return string(res), err }
[ "func", "ToJSON", "(", "obj", "interface", "{", "}", ")", "(", "string", ",", "error", ")", "{", "res", ",", "err", ":=", "json", ".", "Marshal", "(", "obj", ")", "\n", "if", "err", "!=", "nil", "{", "res", "=", "[", "]", "byte", "(", "\"\"", ")", "\n", "}", "\n", "return", "string", "(", "res", ")", ",", "err", "\n", "}" ]
// ToJSON convert the input to a valid JSON string
[ "ToJSON", "convert", "the", "input", "to", "a", "valid", "JSON", "string" ]
f61b66f89f4a311bef65f13e575bcf1a2ffadda6
https://github.com/asaskevich/govalidator/blob/f61b66f89f4a311bef65f13e575bcf1a2ffadda6/converter.go#L17-L23
train
asaskevich/govalidator
converter.go
ToFloat
func ToFloat(str string) (float64, error) { res, err := strconv.ParseFloat(str, 64) if err != nil { res = 0.0 } return res, err }
go
func ToFloat(str string) (float64, error) { res, err := strconv.ParseFloat(str, 64) if err != nil { res = 0.0 } return res, err }
[ "func", "ToFloat", "(", "str", "string", ")", "(", "float64", ",", "error", ")", "{", "res", ",", "err", ":=", "strconv", ".", "ParseFloat", "(", "str", ",", "64", ")", "\n", "if", "err", "!=", "nil", "{", "res", "=", "0.0", "\n", "}", "\n", "return", "res", ",", "err", "\n", "}" ]
// ToFloat convert the input string to a float, or 0.0 if the input is not a float.
[ "ToFloat", "convert", "the", "input", "string", "to", "a", "float", "or", "0", ".", "0", "if", "the", "input", "is", "not", "a", "float", "." ]
f61b66f89f4a311bef65f13e575bcf1a2ffadda6
https://github.com/asaskevich/govalidator/blob/f61b66f89f4a311bef65f13e575bcf1a2ffadda6/converter.go#L26-L32
train
asaskevich/govalidator
converter.go
ToInt
func ToInt(value interface{}) (res int64, err error) { val := reflect.ValueOf(value) switch value.(type) { case int, int8, int16, int32, int64: res = val.Int() case uint, uint8, uint16, uint32, uint64: res = int64(val.Uint()) case string: if IsInt(val.String()) { res, err = strconv.ParseInt(val.String(), 0, 64) if err != nil { res = 0 } } else { err = fmt.Errorf("math: square root of negative number %g", value) res = 0 } default: err = fmt.Errorf("math: square root of negative number %g", value) res = 0 } return }
go
func ToInt(value interface{}) (res int64, err error) { val := reflect.ValueOf(value) switch value.(type) { case int, int8, int16, int32, int64: res = val.Int() case uint, uint8, uint16, uint32, uint64: res = int64(val.Uint()) case string: if IsInt(val.String()) { res, err = strconv.ParseInt(val.String(), 0, 64) if err != nil { res = 0 } } else { err = fmt.Errorf("math: square root of negative number %g", value) res = 0 } default: err = fmt.Errorf("math: square root of negative number %g", value) res = 0 } return }
[ "func", "ToInt", "(", "value", "interface", "{", "}", ")", "(", "res", "int64", ",", "err", "error", ")", "{", "val", ":=", "reflect", ".", "ValueOf", "(", "value", ")", "\n", "switch", "value", ".", "(", "type", ")", "{", "case", "int", ",", "int8", ",", "int16", ",", "int32", ",", "int64", ":", "res", "=", "val", ".", "Int", "(", ")", "\n", "case", "uint", ",", "uint8", ",", "uint16", ",", "uint32", ",", "uint64", ":", "res", "=", "int64", "(", "val", ".", "Uint", "(", ")", ")", "\n", "case", "string", ":", "if", "IsInt", "(", "val", ".", "String", "(", ")", ")", "{", "res", ",", "err", "=", "strconv", ".", "ParseInt", "(", "val", ".", "String", "(", ")", ",", "0", ",", "64", ")", "\n", "if", "err", "!=", "nil", "{", "res", "=", "0", "\n", "}", "\n", "}", "else", "{", "err", "=", "fmt", ".", "Errorf", "(", "\"math: square root of negative number %g\"", ",", "value", ")", "\n", "res", "=", "0", "\n", "}", "\n", "default", ":", "err", "=", "fmt", ".", "Errorf", "(", "\"math: square root of negative number %g\"", ",", "value", ")", "\n", "res", "=", "0", "\n", "}", "\n", "return", "\n", "}" ]
// ToInt convert the input string or any int type to an integer type 64, or 0 if the input is not an integer.
[ "ToInt", "convert", "the", "input", "string", "or", "any", "int", "type", "to", "an", "integer", "type", "64", "or", "0", "if", "the", "input", "is", "not", "an", "integer", "." ]
f61b66f89f4a311bef65f13e575bcf1a2ffadda6
https://github.com/asaskevich/govalidator/blob/f61b66f89f4a311bef65f13e575bcf1a2ffadda6/converter.go#L35-L59
train
asaskevich/govalidator
numerics.go
InRange
func InRange(value interface{}, left interface{}, right interface{}) bool { reflectValue := reflect.TypeOf(value).Kind() reflectLeft := reflect.TypeOf(left).Kind() reflectRight := reflect.TypeOf(right).Kind() if reflectValue == reflect.Int && reflectLeft == reflect.Int && reflectRight == reflect.Int { return InRangeInt(value.(int), left.(int), right.(int)) } else if reflectValue == reflect.Float32 && reflectLeft == reflect.Float32 && reflectRight == reflect.Float32 { return InRangeFloat32(value.(float32), left.(float32), right.(float32)) } else if reflectValue == reflect.Float64 && reflectLeft == reflect.Float64 && reflectRight == reflect.Float64 { return InRangeFloat64(value.(float64), left.(float64), right.(float64)) } else { return false } }
go
func InRange(value interface{}, left interface{}, right interface{}) bool { reflectValue := reflect.TypeOf(value).Kind() reflectLeft := reflect.TypeOf(left).Kind() reflectRight := reflect.TypeOf(right).Kind() if reflectValue == reflect.Int && reflectLeft == reflect.Int && reflectRight == reflect.Int { return InRangeInt(value.(int), left.(int), right.(int)) } else if reflectValue == reflect.Float32 && reflectLeft == reflect.Float32 && reflectRight == reflect.Float32 { return InRangeFloat32(value.(float32), left.(float32), right.(float32)) } else if reflectValue == reflect.Float64 && reflectLeft == reflect.Float64 && reflectRight == reflect.Float64 { return InRangeFloat64(value.(float64), left.(float64), right.(float64)) } else { return false } }
[ "func", "InRange", "(", "value", "interface", "{", "}", ",", "left", "interface", "{", "}", ",", "right", "interface", "{", "}", ")", "bool", "{", "reflectValue", ":=", "reflect", ".", "TypeOf", "(", "value", ")", ".", "Kind", "(", ")", "\n", "reflectLeft", ":=", "reflect", ".", "TypeOf", "(", "left", ")", ".", "Kind", "(", ")", "\n", "reflectRight", ":=", "reflect", ".", "TypeOf", "(", "right", ")", ".", "Kind", "(", ")", "\n", "if", "reflectValue", "==", "reflect", ".", "Int", "&&", "reflectLeft", "==", "reflect", ".", "Int", "&&", "reflectRight", "==", "reflect", ".", "Int", "{", "return", "InRangeInt", "(", "value", ".", "(", "int", ")", ",", "left", ".", "(", "int", ")", ",", "right", ".", "(", "int", ")", ")", "\n", "}", "else", "if", "reflectValue", "==", "reflect", ".", "Float32", "&&", "reflectLeft", "==", "reflect", ".", "Float32", "&&", "reflectRight", "==", "reflect", ".", "Float32", "{", "return", "InRangeFloat32", "(", "value", ".", "(", "float32", ")", ",", "left", ".", "(", "float32", ")", ",", "right", ".", "(", "float32", ")", ")", "\n", "}", "else", "if", "reflectValue", "==", "reflect", ".", "Float64", "&&", "reflectLeft", "==", "reflect", ".", "Float64", "&&", "reflectRight", "==", "reflect", ".", "Float64", "{", "return", "InRangeFloat64", "(", "value", ".", "(", "float64", ")", ",", "left", ".", "(", "float64", ")", ",", "right", ".", "(", "float64", ")", ")", "\n", "}", "else", "{", "return", "false", "\n", "}", "\n", "}" ]
// InRange returns true if value lies between left and right border, generic type to handle int, float32 or float64, all types must the same type
[ "InRange", "returns", "true", "if", "value", "lies", "between", "left", "and", "right", "border", "generic", "type", "to", "handle", "int", "float32", "or", "float64", "all", "types", "must", "the", "same", "type" ]
f61b66f89f4a311bef65f13e575bcf1a2ffadda6
https://github.com/asaskevich/govalidator/blob/f61b66f89f4a311bef65f13e575bcf1a2ffadda6/numerics.go#L72-L87
train
asaskevich/govalidator
validator.go
IsExistingEmail
func IsExistingEmail(email string) bool { if len(email) < 6 || len(email) > 254 { return false } at := strings.LastIndex(email, "@") if at <= 0 || at > len(email)-3 { return false } user := email[:at] host := email[at+1:] if len(user) > 64 { return false } if userDotRegexp.MatchString(user) || !userRegexp.MatchString(user) || !hostRegexp.MatchString(host) { return false } switch host { case "localhost", "example.com": return true } if _, err := net.LookupMX(host); err != nil { if _, err := net.LookupIP(host); err != nil { return false } } return true }
go
func IsExistingEmail(email string) bool { if len(email) < 6 || len(email) > 254 { return false } at := strings.LastIndex(email, "@") if at <= 0 || at > len(email)-3 { return false } user := email[:at] host := email[at+1:] if len(user) > 64 { return false } if userDotRegexp.MatchString(user) || !userRegexp.MatchString(user) || !hostRegexp.MatchString(host) { return false } switch host { case "localhost", "example.com": return true } if _, err := net.LookupMX(host); err != nil { if _, err := net.LookupIP(host); err != nil { return false } } return true }
[ "func", "IsExistingEmail", "(", "email", "string", ")", "bool", "{", "if", "len", "(", "email", ")", "<", "6", "||", "len", "(", "email", ")", ">", "254", "{", "return", "false", "\n", "}", "\n", "at", ":=", "strings", ".", "LastIndex", "(", "email", ",", "\"@\"", ")", "\n", "if", "at", "<=", "0", "||", "at", ">", "len", "(", "email", ")", "-", "3", "{", "return", "false", "\n", "}", "\n", "user", ":=", "email", "[", ":", "at", "]", "\n", "host", ":=", "email", "[", "at", "+", "1", ":", "]", "\n", "if", "len", "(", "user", ")", ">", "64", "{", "return", "false", "\n", "}", "\n", "if", "userDotRegexp", ".", "MatchString", "(", "user", ")", "||", "!", "userRegexp", ".", "MatchString", "(", "user", ")", "||", "!", "hostRegexp", ".", "MatchString", "(", "host", ")", "{", "return", "false", "\n", "}", "\n", "switch", "host", "{", "case", "\"localhost\"", ",", "\"example.com\"", ":", "return", "true", "\n", "}", "\n", "if", "_", ",", "err", ":=", "net", ".", "LookupMX", "(", "host", ")", ";", "err", "!=", "nil", "{", "if", "_", ",", "err", ":=", "net", ".", "LookupIP", "(", "host", ")", ";", "err", "!=", "nil", "{", "return", "false", "\n", "}", "\n", "}", "\n", "return", "true", "\n", "}" ]
// IsExistingEmail check if the string is an email of existing domain
[ "IsExistingEmail", "check", "if", "the", "string", "is", "an", "email", "of", "existing", "domain" ]
f61b66f89f4a311bef65f13e575bcf1a2ffadda6
https://github.com/asaskevich/govalidator/blob/f61b66f89f4a311bef65f13e575bcf1a2ffadda6/validator.go#L73-L101
train
asaskevich/govalidator
validator.go
IsRequestURL
func IsRequestURL(rawurl string) bool { url, err := url.ParseRequestURI(rawurl) if err != nil { return false //Couldn't even parse the rawurl } if len(url.Scheme) == 0 { return false //No Scheme found } return true }
go
func IsRequestURL(rawurl string) bool { url, err := url.ParseRequestURI(rawurl) if err != nil { return false //Couldn't even parse the rawurl } if len(url.Scheme) == 0 { return false //No Scheme found } return true }
[ "func", "IsRequestURL", "(", "rawurl", "string", ")", "bool", "{", "url", ",", "err", ":=", "url", ".", "ParseRequestURI", "(", "rawurl", ")", "\n", "if", "err", "!=", "nil", "{", "return", "false", "\n", "}", "\n", "if", "len", "(", "url", ".", "Scheme", ")", "==", "0", "{", "return", "false", "\n", "}", "\n", "return", "true", "\n", "}" ]
// IsRequestURL check if the string rawurl, assuming // it was received in an HTTP request, is a valid // URL confirm to RFC 3986
[ "IsRequestURL", "check", "if", "the", "string", "rawurl", "assuming", "it", "was", "received", "in", "an", "HTTP", "request", "is", "a", "valid", "URL", "confirm", "to", "RFC", "3986" ]
f61b66f89f4a311bef65f13e575bcf1a2ffadda6
https://github.com/asaskevich/govalidator/blob/f61b66f89f4a311bef65f13e575bcf1a2ffadda6/validator.go#L130-L139
train
asaskevich/govalidator
validator.go
IsRequestURI
func IsRequestURI(rawurl string) bool { _, err := url.ParseRequestURI(rawurl) return err == nil }
go
func IsRequestURI(rawurl string) bool { _, err := url.ParseRequestURI(rawurl) return err == nil }
[ "func", "IsRequestURI", "(", "rawurl", "string", ")", "bool", "{", "_", ",", "err", ":=", "url", ".", "ParseRequestURI", "(", "rawurl", ")", "\n", "return", "err", "==", "nil", "\n", "}" ]
// IsRequestURI check if the string rawurl, assuming // it was received in an HTTP request, is an // absolute URI or an absolute path.
[ "IsRequestURI", "check", "if", "the", "string", "rawurl", "assuming", "it", "was", "received", "in", "an", "HTTP", "request", "is", "an", "absolute", "URI", "or", "an", "absolute", "path", "." ]
f61b66f89f4a311bef65f13e575bcf1a2ffadda6
https://github.com/asaskevich/govalidator/blob/f61b66f89f4a311bef65f13e575bcf1a2ffadda6/validator.go#L144-L147
train
asaskevich/govalidator
validator.go
IsLowerCase
func IsLowerCase(str string) bool { if IsNull(str) { return true } return str == strings.ToLower(str) }
go
func IsLowerCase(str string) bool { if IsNull(str) { return true } return str == strings.ToLower(str) }
[ "func", "IsLowerCase", "(", "str", "string", ")", "bool", "{", "if", "IsNull", "(", "str", ")", "{", "return", "true", "\n", "}", "\n", "return", "str", "==", "strings", ".", "ToLower", "(", "str", ")", "\n", "}" ]
// IsLowerCase check if the string is lowercase. Empty string is valid.
[ "IsLowerCase", "check", "if", "the", "string", "is", "lowercase", ".", "Empty", "string", "is", "valid", "." ]
f61b66f89f4a311bef65f13e575bcf1a2ffadda6
https://github.com/asaskevich/govalidator/blob/f61b66f89f4a311bef65f13e575bcf1a2ffadda6/validator.go#L262-L267
train
asaskevich/govalidator
validator.go
IsUpperCase
func IsUpperCase(str string) bool { if IsNull(str) { return true } return str == strings.ToUpper(str) }
go
func IsUpperCase(str string) bool { if IsNull(str) { return true } return str == strings.ToUpper(str) }
[ "func", "IsUpperCase", "(", "str", "string", ")", "bool", "{", "if", "IsNull", "(", "str", ")", "{", "return", "true", "\n", "}", "\n", "return", "str", "==", "strings", ".", "ToUpper", "(", "str", ")", "\n", "}" ]
// IsUpperCase check if the string is uppercase. Empty string is valid.
[ "IsUpperCase", "check", "if", "the", "string", "is", "uppercase", ".", "Empty", "string", "is", "valid", "." ]
f61b66f89f4a311bef65f13e575bcf1a2ffadda6
https://github.com/asaskevich/govalidator/blob/f61b66f89f4a311bef65f13e575bcf1a2ffadda6/validator.go#L270-L275
train
asaskevich/govalidator
validator.go
HasLowerCase
func HasLowerCase(str string) bool { if IsNull(str) { return true } return rxHasLowerCase.MatchString(str) }
go
func HasLowerCase(str string) bool { if IsNull(str) { return true } return rxHasLowerCase.MatchString(str) }
[ "func", "HasLowerCase", "(", "str", "string", ")", "bool", "{", "if", "IsNull", "(", "str", ")", "{", "return", "true", "\n", "}", "\n", "return", "rxHasLowerCase", ".", "MatchString", "(", "str", ")", "\n", "}" ]
// HasLowerCase check if the string contains at least 1 lowercase. Empty string is valid.
[ "HasLowerCase", "check", "if", "the", "string", "contains", "at", "least", "1", "lowercase", ".", "Empty", "string", "is", "valid", "." ]
f61b66f89f4a311bef65f13e575bcf1a2ffadda6
https://github.com/asaskevich/govalidator/blob/f61b66f89f4a311bef65f13e575bcf1a2ffadda6/validator.go#L278-L283
train
asaskevich/govalidator
validator.go
HasUpperCase
func HasUpperCase(str string) bool { if IsNull(str) { return true } return rxHasUpperCase.MatchString(str) }
go
func HasUpperCase(str string) bool { if IsNull(str) { return true } return rxHasUpperCase.MatchString(str) }
[ "func", "HasUpperCase", "(", "str", "string", ")", "bool", "{", "if", "IsNull", "(", "str", ")", "{", "return", "true", "\n", "}", "\n", "return", "rxHasUpperCase", ".", "MatchString", "(", "str", ")", "\n", "}" ]
// HasUpperCase check if the string contians as least 1 uppercase. Empty string is valid.
[ "HasUpperCase", "check", "if", "the", "string", "contians", "as", "least", "1", "uppercase", ".", "Empty", "string", "is", "valid", "." ]
f61b66f89f4a311bef65f13e575bcf1a2ffadda6
https://github.com/asaskevich/govalidator/blob/f61b66f89f4a311bef65f13e575bcf1a2ffadda6/validator.go#L286-L291
train
asaskevich/govalidator
validator.go
IsInt
func IsInt(str string) bool { if IsNull(str) { return true } return rxInt.MatchString(str) }
go
func IsInt(str string) bool { if IsNull(str) { return true } return rxInt.MatchString(str) }
[ "func", "IsInt", "(", "str", "string", ")", "bool", "{", "if", "IsNull", "(", "str", ")", "{", "return", "true", "\n", "}", "\n", "return", "rxInt", ".", "MatchString", "(", "str", ")", "\n", "}" ]
// IsInt check if the string is an integer. Empty string is valid.
[ "IsInt", "check", "if", "the", "string", "is", "an", "integer", ".", "Empty", "string", "is", "valid", "." ]
f61b66f89f4a311bef65f13e575bcf1a2ffadda6
https://github.com/asaskevich/govalidator/blob/f61b66f89f4a311bef65f13e575bcf1a2ffadda6/validator.go#L294-L299
train
asaskevich/govalidator
validator.go
IsFullWidth
func IsFullWidth(str string) bool { if IsNull(str) { return true } return rxFullWidth.MatchString(str) }
go
func IsFullWidth(str string) bool { if IsNull(str) { return true } return rxFullWidth.MatchString(str) }
[ "func", "IsFullWidth", "(", "str", "string", ")", "bool", "{", "if", "IsNull", "(", "str", ")", "{", "return", "true", "\n", "}", "\n", "return", "rxFullWidth", ".", "MatchString", "(", "str", ")", "\n", "}" ]
// IsFullWidth check if the string contains any full-width chars. Empty string is valid.
[ "IsFullWidth", "check", "if", "the", "string", "contains", "any", "full", "-", "width", "chars", ".", "Empty", "string", "is", "valid", "." ]
f61b66f89f4a311bef65f13e575bcf1a2ffadda6
https://github.com/asaskevich/govalidator/blob/f61b66f89f4a311bef65f13e575bcf1a2ffadda6/validator.go#L464-L469
train
asaskevich/govalidator
validator.go
IsHalfWidth
func IsHalfWidth(str string) bool { if IsNull(str) { return true } return rxHalfWidth.MatchString(str) }
go
func IsHalfWidth(str string) bool { if IsNull(str) { return true } return rxHalfWidth.MatchString(str) }
[ "func", "IsHalfWidth", "(", "str", "string", ")", "bool", "{", "if", "IsNull", "(", "str", ")", "{", "return", "true", "\n", "}", "\n", "return", "rxHalfWidth", ".", "MatchString", "(", "str", ")", "\n", "}" ]
// IsHalfWidth check if the string contains any half-width chars. Empty string is valid.
[ "IsHalfWidth", "check", "if", "the", "string", "contains", "any", "half", "-", "width", "chars", ".", "Empty", "string", "is", "valid", "." ]
f61b66f89f4a311bef65f13e575bcf1a2ffadda6
https://github.com/asaskevich/govalidator/blob/f61b66f89f4a311bef65f13e575bcf1a2ffadda6/validator.go#L472-L477
train
asaskevich/govalidator
validator.go
IsVariableWidth
func IsVariableWidth(str string) bool { if IsNull(str) { return true } return rxHalfWidth.MatchString(str) && rxFullWidth.MatchString(str) }
go
func IsVariableWidth(str string) bool { if IsNull(str) { return true } return rxHalfWidth.MatchString(str) && rxFullWidth.MatchString(str) }
[ "func", "IsVariableWidth", "(", "str", "string", ")", "bool", "{", "if", "IsNull", "(", "str", ")", "{", "return", "true", "\n", "}", "\n", "return", "rxHalfWidth", ".", "MatchString", "(", "str", ")", "&&", "rxFullWidth", ".", "MatchString", "(", "str", ")", "\n", "}" ]
// IsVariableWidth check if the string contains a mixture of full and half-width chars. Empty string is valid.
[ "IsVariableWidth", "check", "if", "the", "string", "contains", "a", "mixture", "of", "full", "and", "half", "-", "width", "chars", ".", "Empty", "string", "is", "valid", "." ]
f61b66f89f4a311bef65f13e575bcf1a2ffadda6
https://github.com/asaskevich/govalidator/blob/f61b66f89f4a311bef65f13e575bcf1a2ffadda6/validator.go#L480-L485
train
asaskevich/govalidator
validator.go
IsFilePath
func IsFilePath(str string) (bool, int) { if rxWinPath.MatchString(str) { //check windows path limit see: // http://msdn.microsoft.com/en-us/library/aa365247(VS.85).aspx#maxpath if len(str[3:]) > 32767 { return false, Win } return true, Win } else if rxUnixPath.MatchString(str) { return true, Unix } return false, Unknown }
go
func IsFilePath(str string) (bool, int) { if rxWinPath.MatchString(str) { //check windows path limit see: // http://msdn.microsoft.com/en-us/library/aa365247(VS.85).aspx#maxpath if len(str[3:]) > 32767 { return false, Win } return true, Win } else if rxUnixPath.MatchString(str) { return true, Unix } return false, Unknown }
[ "func", "IsFilePath", "(", "str", "string", ")", "(", "bool", ",", "int", ")", "{", "if", "rxWinPath", ".", "MatchString", "(", "str", ")", "{", "if", "len", "(", "str", "[", "3", ":", "]", ")", ">", "32767", "{", "return", "false", ",", "Win", "\n", "}", "\n", "return", "true", ",", "Win", "\n", "}", "else", "if", "rxUnixPath", ".", "MatchString", "(", "str", ")", "{", "return", "true", ",", "Unix", "\n", "}", "\n", "return", "false", ",", "Unknown", "\n", "}" ]
// IsFilePath check is a string is Win or Unix file path and returns it's type.
[ "IsFilePath", "check", "is", "a", "string", "is", "Win", "or", "Unix", "file", "path", "and", "returns", "it", "s", "type", "." ]
f61b66f89f4a311bef65f13e575bcf1a2ffadda6
https://github.com/asaskevich/govalidator/blob/f61b66f89f4a311bef65f13e575bcf1a2ffadda6/validator.go#L493-L505
train
asaskevich/govalidator
validator.go
IsDataURI
func IsDataURI(str string) bool { dataURI := strings.Split(str, ",") if !rxDataURI.MatchString(dataURI[0]) { return false } return IsBase64(dataURI[1]) }
go
func IsDataURI(str string) bool { dataURI := strings.Split(str, ",") if !rxDataURI.MatchString(dataURI[0]) { return false } return IsBase64(dataURI[1]) }
[ "func", "IsDataURI", "(", "str", "string", ")", "bool", "{", "dataURI", ":=", "strings", ".", "Split", "(", "str", ",", "\",\"", ")", "\n", "if", "!", "rxDataURI", ".", "MatchString", "(", "dataURI", "[", "0", "]", ")", "{", "return", "false", "\n", "}", "\n", "return", "IsBase64", "(", "dataURI", "[", "1", "]", ")", "\n", "}" ]
// IsDataURI checks if a string is base64 encoded data URI such as an image
[ "IsDataURI", "checks", "if", "a", "string", "is", "base64", "encoded", "data", "URI", "such", "as", "an", "image" ]
f61b66f89f4a311bef65f13e575bcf1a2ffadda6
https://github.com/asaskevich/govalidator/blob/f61b66f89f4a311bef65f13e575bcf1a2ffadda6/validator.go#L508-L514
train
asaskevich/govalidator
validator.go
IsISO3166Alpha2
func IsISO3166Alpha2(str string) bool { for _, entry := range ISO3166List { if str == entry.Alpha2Code { return true } } return false }
go
func IsISO3166Alpha2(str string) bool { for _, entry := range ISO3166List { if str == entry.Alpha2Code { return true } } return false }
[ "func", "IsISO3166Alpha2", "(", "str", "string", ")", "bool", "{", "for", "_", ",", "entry", ":=", "range", "ISO3166List", "{", "if", "str", "==", "entry", ".", "Alpha2Code", "{", "return", "true", "\n", "}", "\n", "}", "\n", "return", "false", "\n", "}" ]
// IsISO3166Alpha2 checks if a string is valid two-letter country code
[ "IsISO3166Alpha2", "checks", "if", "a", "string", "is", "valid", "two", "-", "letter", "country", "code" ]
f61b66f89f4a311bef65f13e575bcf1a2ffadda6
https://github.com/asaskevich/govalidator/blob/f61b66f89f4a311bef65f13e575bcf1a2ffadda6/validator.go#L517-L524
train
asaskevich/govalidator
validator.go
IsISO3166Alpha3
func IsISO3166Alpha3(str string) bool { for _, entry := range ISO3166List { if str == entry.Alpha3Code { return true } } return false }
go
func IsISO3166Alpha3(str string) bool { for _, entry := range ISO3166List { if str == entry.Alpha3Code { return true } } return false }
[ "func", "IsISO3166Alpha3", "(", "str", "string", ")", "bool", "{", "for", "_", ",", "entry", ":=", "range", "ISO3166List", "{", "if", "str", "==", "entry", ".", "Alpha3Code", "{", "return", "true", "\n", "}", "\n", "}", "\n", "return", "false", "\n", "}" ]
// IsISO3166Alpha3 checks if a string is valid three-letter country code
[ "IsISO3166Alpha3", "checks", "if", "a", "string", "is", "valid", "three", "-", "letter", "country", "code" ]
f61b66f89f4a311bef65f13e575bcf1a2ffadda6
https://github.com/asaskevich/govalidator/blob/f61b66f89f4a311bef65f13e575bcf1a2ffadda6/validator.go#L527-L534
train
asaskevich/govalidator
validator.go
IsISO693Alpha2
func IsISO693Alpha2(str string) bool { for _, entry := range ISO693List { if str == entry.Alpha2Code { return true } } return false }
go
func IsISO693Alpha2(str string) bool { for _, entry := range ISO693List { if str == entry.Alpha2Code { return true } } return false }
[ "func", "IsISO693Alpha2", "(", "str", "string", ")", "bool", "{", "for", "_", ",", "entry", ":=", "range", "ISO693List", "{", "if", "str", "==", "entry", ".", "Alpha2Code", "{", "return", "true", "\n", "}", "\n", "}", "\n", "return", "false", "\n", "}" ]
// IsISO693Alpha2 checks if a string is valid two-letter language code
[ "IsISO693Alpha2", "checks", "if", "a", "string", "is", "valid", "two", "-", "letter", "language", "code" ]
f61b66f89f4a311bef65f13e575bcf1a2ffadda6
https://github.com/asaskevich/govalidator/blob/f61b66f89f4a311bef65f13e575bcf1a2ffadda6/validator.go#L537-L544
train
asaskevich/govalidator
validator.go
IsISO693Alpha3b
func IsISO693Alpha3b(str string) bool { for _, entry := range ISO693List { if str == entry.Alpha3bCode { return true } } return false }
go
func IsISO693Alpha3b(str string) bool { for _, entry := range ISO693List { if str == entry.Alpha3bCode { return true } } return false }
[ "func", "IsISO693Alpha3b", "(", "str", "string", ")", "bool", "{", "for", "_", ",", "entry", ":=", "range", "ISO693List", "{", "if", "str", "==", "entry", ".", "Alpha3bCode", "{", "return", "true", "\n", "}", "\n", "}", "\n", "return", "false", "\n", "}" ]
// IsISO693Alpha3b checks if a string is valid three-letter language code
[ "IsISO693Alpha3b", "checks", "if", "a", "string", "is", "valid", "three", "-", "letter", "language", "code" ]
f61b66f89f4a311bef65f13e575bcf1a2ffadda6
https://github.com/asaskevich/govalidator/blob/f61b66f89f4a311bef65f13e575bcf1a2ffadda6/validator.go#L547-L554
train
asaskevich/govalidator
validator.go
IsPort
func IsPort(str string) bool { if i, err := strconv.Atoi(str); err == nil && i > 0 && i < 65536 { return true } return false }
go
func IsPort(str string) bool { if i, err := strconv.Atoi(str); err == nil && i > 0 && i < 65536 { return true } return false }
[ "func", "IsPort", "(", "str", "string", ")", "bool", "{", "if", "i", ",", "err", ":=", "strconv", ".", "Atoi", "(", "str", ")", ";", "err", "==", "nil", "&&", "i", ">", "0", "&&", "i", "<", "65536", "{", "return", "true", "\n", "}", "\n", "return", "false", "\n", "}" ]
// IsPort checks if a string represents a valid port
[ "IsPort", "checks", "if", "a", "string", "represents", "a", "valid", "port" ]
f61b66f89f4a311bef65f13e575bcf1a2ffadda6
https://github.com/asaskevich/govalidator/blob/f61b66f89f4a311bef65f13e575bcf1a2ffadda6/validator.go#L608-L613
train
asaskevich/govalidator
validator.go
IsIPv4
func IsIPv4(str string) bool { ip := net.ParseIP(str) return ip != nil && strings.Contains(str, ".") }
go
func IsIPv4(str string) bool { ip := net.ParseIP(str) return ip != nil && strings.Contains(str, ".") }
[ "func", "IsIPv4", "(", "str", "string", ")", "bool", "{", "ip", ":=", "net", ".", "ParseIP", "(", "str", ")", "\n", "return", "ip", "!=", "nil", "&&", "strings", ".", "Contains", "(", "str", ",", "\".\"", ")", "\n", "}" ]
// IsIPv4 check if the string is an IP version 4.
[ "IsIPv4", "check", "if", "the", "string", "is", "an", "IP", "version", "4", "." ]
f61b66f89f4a311bef65f13e575bcf1a2ffadda6
https://github.com/asaskevich/govalidator/blob/f61b66f89f4a311bef65f13e575bcf1a2ffadda6/validator.go#L616-L619
train
asaskevich/govalidator
validator.go
IsRsaPublicKey
func IsRsaPublicKey(str string, keylen int) bool { bb := bytes.NewBufferString(str) pemBytes, err := ioutil.ReadAll(bb) if err != nil { return false } block, _ := pem.Decode(pemBytes) if block != nil && block.Type != "PUBLIC KEY" { return false } var der []byte if block != nil { der = block.Bytes } else { der, err = base64.StdEncoding.DecodeString(str) if err != nil { return false } } key, err := x509.ParsePKIXPublicKey(der) if err != nil { return false } pubkey, ok := key.(*rsa.PublicKey) if !ok { return false } bitlen := len(pubkey.N.Bytes()) * 8 return bitlen == int(keylen) }
go
func IsRsaPublicKey(str string, keylen int) bool { bb := bytes.NewBufferString(str) pemBytes, err := ioutil.ReadAll(bb) if err != nil { return false } block, _ := pem.Decode(pemBytes) if block != nil && block.Type != "PUBLIC KEY" { return false } var der []byte if block != nil { der = block.Bytes } else { der, err = base64.StdEncoding.DecodeString(str) if err != nil { return false } } key, err := x509.ParsePKIXPublicKey(der) if err != nil { return false } pubkey, ok := key.(*rsa.PublicKey) if !ok { return false } bitlen := len(pubkey.N.Bytes()) * 8 return bitlen == int(keylen) }
[ "func", "IsRsaPublicKey", "(", "str", "string", ",", "keylen", "int", ")", "bool", "{", "bb", ":=", "bytes", ".", "NewBufferString", "(", "str", ")", "\n", "pemBytes", ",", "err", ":=", "ioutil", ".", "ReadAll", "(", "bb", ")", "\n", "if", "err", "!=", "nil", "{", "return", "false", "\n", "}", "\n", "block", ",", "_", ":=", "pem", ".", "Decode", "(", "pemBytes", ")", "\n", "if", "block", "!=", "nil", "&&", "block", ".", "Type", "!=", "\"PUBLIC KEY\"", "{", "return", "false", "\n", "}", "\n", "var", "der", "[", "]", "byte", "\n", "if", "block", "!=", "nil", "{", "der", "=", "block", ".", "Bytes", "\n", "}", "else", "{", "der", ",", "err", "=", "base64", ".", "StdEncoding", ".", "DecodeString", "(", "str", ")", "\n", "if", "err", "!=", "nil", "{", "return", "false", "\n", "}", "\n", "}", "\n", "key", ",", "err", ":=", "x509", ".", "ParsePKIXPublicKey", "(", "der", ")", "\n", "if", "err", "!=", "nil", "{", "return", "false", "\n", "}", "\n", "pubkey", ",", "ok", ":=", "key", ".", "(", "*", "rsa", ".", "PublicKey", ")", "\n", "if", "!", "ok", "{", "return", "false", "\n", "}", "\n", "bitlen", ":=", "len", "(", "pubkey", ".", "N", ".", "Bytes", "(", ")", ")", "*", "8", "\n", "return", "bitlen", "==", "int", "(", "keylen", ")", "\n", "}" ]
// IsRsaPublicKey check if a string is valid public key with provided length
[ "IsRsaPublicKey", "check", "if", "a", "string", "is", "valid", "public", "key", "with", "provided", "length" ]
f61b66f89f4a311bef65f13e575bcf1a2ffadda6
https://github.com/asaskevich/govalidator/blob/f61b66f89f4a311bef65f13e575bcf1a2ffadda6/validator.go#L667-L698
train
asaskevich/govalidator
validator.go
ValidateStruct
func ValidateStruct(s interface{}) (bool, error) { if s == nil { return true, nil } result := true var err error val := reflect.ValueOf(s) if val.Kind() == reflect.Interface || val.Kind() == reflect.Ptr { val = val.Elem() } // we only accept structs if val.Kind() != reflect.Struct { return false, fmt.Errorf("function only accepts structs; got %s", val.Kind()) } var errs Errors for i := 0; i < val.NumField(); i++ { valueField := val.Field(i) typeField := val.Type().Field(i) if typeField.PkgPath != "" { continue // Private field } structResult := true if valueField.Kind() == reflect.Interface { valueField = valueField.Elem() } if (valueField.Kind() == reflect.Struct || (valueField.Kind() == reflect.Ptr && valueField.Elem().Kind() == reflect.Struct)) && typeField.Tag.Get(tagName) != "-" { var err error structResult, err = ValidateStruct(valueField.Interface()) if err != nil { err = PrependPathToErrors(err, typeField.Name) errs = append(errs, err) } } resultField, err2 := typeCheck(valueField, typeField, val, nil) if err2 != nil { // Replace structure name with JSON name if there is a tag on the variable jsonTag := toJSONName(typeField.Tag.Get("json")) if jsonTag != "" { switch jsonError := err2.(type) { case Error: jsonError.Name = jsonTag err2 = jsonError case Errors: for i2, err3 := range jsonError { switch customErr := err3.(type) { case Error: customErr.Name = jsonTag jsonError[i2] = customErr } } err2 = jsonError } } errs = append(errs, err2) } result = result && resultField && structResult } if len(errs) > 0 { err = errs } return result, err }
go
func ValidateStruct(s interface{}) (bool, error) { if s == nil { return true, nil } result := true var err error val := reflect.ValueOf(s) if val.Kind() == reflect.Interface || val.Kind() == reflect.Ptr { val = val.Elem() } // we only accept structs if val.Kind() != reflect.Struct { return false, fmt.Errorf("function only accepts structs; got %s", val.Kind()) } var errs Errors for i := 0; i < val.NumField(); i++ { valueField := val.Field(i) typeField := val.Type().Field(i) if typeField.PkgPath != "" { continue // Private field } structResult := true if valueField.Kind() == reflect.Interface { valueField = valueField.Elem() } if (valueField.Kind() == reflect.Struct || (valueField.Kind() == reflect.Ptr && valueField.Elem().Kind() == reflect.Struct)) && typeField.Tag.Get(tagName) != "-" { var err error structResult, err = ValidateStruct(valueField.Interface()) if err != nil { err = PrependPathToErrors(err, typeField.Name) errs = append(errs, err) } } resultField, err2 := typeCheck(valueField, typeField, val, nil) if err2 != nil { // Replace structure name with JSON name if there is a tag on the variable jsonTag := toJSONName(typeField.Tag.Get("json")) if jsonTag != "" { switch jsonError := err2.(type) { case Error: jsonError.Name = jsonTag err2 = jsonError case Errors: for i2, err3 := range jsonError { switch customErr := err3.(type) { case Error: customErr.Name = jsonTag jsonError[i2] = customErr } } err2 = jsonError } } errs = append(errs, err2) } result = result && resultField && structResult } if len(errs) > 0 { err = errs } return result, err }
[ "func", "ValidateStruct", "(", "s", "interface", "{", "}", ")", "(", "bool", ",", "error", ")", "{", "if", "s", "==", "nil", "{", "return", "true", ",", "nil", "\n", "}", "\n", "result", ":=", "true", "\n", "var", "err", "error", "\n", "val", ":=", "reflect", ".", "ValueOf", "(", "s", ")", "\n", "if", "val", ".", "Kind", "(", ")", "==", "reflect", ".", "Interface", "||", "val", ".", "Kind", "(", ")", "==", "reflect", ".", "Ptr", "{", "val", "=", "val", ".", "Elem", "(", ")", "\n", "}", "\n", "if", "val", ".", "Kind", "(", ")", "!=", "reflect", ".", "Struct", "{", "return", "false", ",", "fmt", ".", "Errorf", "(", "\"function only accepts structs; got %s\"", ",", "val", ".", "Kind", "(", ")", ")", "\n", "}", "\n", "var", "errs", "Errors", "\n", "for", "i", ":=", "0", ";", "i", "<", "val", ".", "NumField", "(", ")", ";", "i", "++", "{", "valueField", ":=", "val", ".", "Field", "(", "i", ")", "\n", "typeField", ":=", "val", ".", "Type", "(", ")", ".", "Field", "(", "i", ")", "\n", "if", "typeField", ".", "PkgPath", "!=", "\"\"", "{", "continue", "\n", "}", "\n", "structResult", ":=", "true", "\n", "if", "valueField", ".", "Kind", "(", ")", "==", "reflect", ".", "Interface", "{", "valueField", "=", "valueField", ".", "Elem", "(", ")", "\n", "}", "\n", "if", "(", "valueField", ".", "Kind", "(", ")", "==", "reflect", ".", "Struct", "||", "(", "valueField", ".", "Kind", "(", ")", "==", "reflect", ".", "Ptr", "&&", "valueField", ".", "Elem", "(", ")", ".", "Kind", "(", ")", "==", "reflect", ".", "Struct", ")", ")", "&&", "typeField", ".", "Tag", ".", "Get", "(", "tagName", ")", "!=", "\"-\"", "{", "var", "err", "error", "\n", "structResult", ",", "err", "=", "ValidateStruct", "(", "valueField", ".", "Interface", "(", ")", ")", "\n", "if", "err", "!=", "nil", "{", "err", "=", "PrependPathToErrors", "(", "err", ",", "typeField", ".", "Name", ")", "\n", "errs", "=", "append", "(", "errs", ",", "err", ")", "\n", "}", "\n", "}", "\n", "resultField", ",", "err2", ":=", "typeCheck", "(", "valueField", ",", "typeField", ",", "val", ",", "nil", ")", "\n", "if", "err2", "!=", "nil", "{", "jsonTag", ":=", "toJSONName", "(", "typeField", ".", "Tag", ".", "Get", "(", "\"json\"", ")", ")", "\n", "if", "jsonTag", "!=", "\"\"", "{", "switch", "jsonError", ":=", "err2", ".", "(", "type", ")", "{", "case", "Error", ":", "jsonError", ".", "Name", "=", "jsonTag", "\n", "err2", "=", "jsonError", "\n", "case", "Errors", ":", "for", "i2", ",", "err3", ":=", "range", "jsonError", "{", "switch", "customErr", ":=", "err3", ".", "(", "type", ")", "{", "case", "Error", ":", "customErr", ".", "Name", "=", "jsonTag", "\n", "jsonError", "[", "i2", "]", "=", "customErr", "\n", "}", "\n", "}", "\n", "err2", "=", "jsonError", "\n", "}", "\n", "}", "\n", "errs", "=", "append", "(", "errs", ",", "err2", ")", "\n", "}", "\n", "result", "=", "result", "&&", "resultField", "&&", "structResult", "\n", "}", "\n", "if", "len", "(", "errs", ")", ">", "0", "{", "err", "=", "errs", "\n", "}", "\n", "return", "result", ",", "err", "\n", "}" ]
// ValidateStruct use tags for fields. // result will be equal to `false` if there are any errors.
[ "ValidateStruct", "use", "tags", "for", "fields", ".", "result", "will", "be", "equal", "to", "false", "if", "there", "are", "any", "errors", "." ]
f61b66f89f4a311bef65f13e575bcf1a2ffadda6
https://github.com/asaskevich/govalidator/blob/f61b66f89f4a311bef65f13e575bcf1a2ffadda6/validator.go#L738-L804
train
asaskevich/govalidator
validator.go
IsSSN
func IsSSN(str string) bool { if str == "" || len(str) != 11 { return false } return rxSSN.MatchString(str) }
go
func IsSSN(str string) bool { if str == "" || len(str) != 11 { return false } return rxSSN.MatchString(str) }
[ "func", "IsSSN", "(", "str", "string", ")", "bool", "{", "if", "str", "==", "\"\"", "||", "len", "(", "str", ")", "!=", "11", "{", "return", "false", "\n", "}", "\n", "return", "rxSSN", ".", "MatchString", "(", "str", ")", "\n", "}" ]
// IsSSN will validate the given string as a U.S. Social Security Number
[ "IsSSN", "will", "validate", "the", "given", "string", "as", "a", "U", ".", "S", ".", "Social", "Security", "Number" ]
f61b66f89f4a311bef65f13e575bcf1a2ffadda6
https://github.com/asaskevich/govalidator/blob/f61b66f89f4a311bef65f13e575bcf1a2ffadda6/validator.go#L847-L852
train
asaskevich/govalidator
validator.go
IsTime
func IsTime(str string, format string) bool { _, err := time.Parse(format, str) return err == nil }
go
func IsTime(str string, format string) bool { _, err := time.Parse(format, str) return err == nil }
[ "func", "IsTime", "(", "str", "string", ",", "format", "string", ")", "bool", "{", "_", ",", "err", ":=", "time", ".", "Parse", "(", "format", ",", "str", ")", "\n", "return", "err", "==", "nil", "\n", "}" ]
// IsTime check if string is valid according to given format
[ "IsTime", "check", "if", "string", "is", "valid", "according", "to", "given", "format" ]
f61b66f89f4a311bef65f13e575bcf1a2ffadda6
https://github.com/asaskevich/govalidator/blob/f61b66f89f4a311bef65f13e575bcf1a2ffadda6/validator.go#L860-L863
train
asaskevich/govalidator
validator.go
IsISO4217
func IsISO4217(str string) bool { for _, currency := range ISO4217List { if str == currency { return true } } return false }
go
func IsISO4217(str string) bool { for _, currency := range ISO4217List { if str == currency { return true } } return false }
[ "func", "IsISO4217", "(", "str", "string", ")", "bool", "{", "for", "_", ",", "currency", ":=", "range", "ISO4217List", "{", "if", "str", "==", "currency", "{", "return", "true", "\n", "}", "\n", "}", "\n", "return", "false", "\n", "}" ]
// IsISO4217 check if string is valid ISO currency code
[ "IsISO4217", "check", "if", "string", "is", "valid", "ISO", "currency", "code" ]
f61b66f89f4a311bef65f13e575bcf1a2ffadda6
https://github.com/asaskevich/govalidator/blob/f61b66f89f4a311bef65f13e575bcf1a2ffadda6/validator.go#L876-L884
train
asaskevich/govalidator
validator.go
ByteLength
func ByteLength(str string, params ...string) bool { if len(params) == 2 { min, _ := ToInt(params[0]) max, _ := ToInt(params[1]) return len(str) >= int(min) && len(str) <= int(max) } return false }
go
func ByteLength(str string, params ...string) bool { if len(params) == 2 { min, _ := ToInt(params[0]) max, _ := ToInt(params[1]) return len(str) >= int(min) && len(str) <= int(max) } return false }
[ "func", "ByteLength", "(", "str", "string", ",", "params", "...", "string", ")", "bool", "{", "if", "len", "(", "params", ")", "==", "2", "{", "min", ",", "_", ":=", "ToInt", "(", "params", "[", "0", "]", ")", "\n", "max", ",", "_", ":=", "ToInt", "(", "params", "[", "1", "]", ")", "\n", "return", "len", "(", "str", ")", ">=", "int", "(", "min", ")", "&&", "len", "(", "str", ")", "<=", "int", "(", "max", ")", "\n", "}", "\n", "return", "false", "\n", "}" ]
// ByteLength check string's length
[ "ByteLength", "check", "string", "s", "length" ]
f61b66f89f4a311bef65f13e575bcf1a2ffadda6
https://github.com/asaskevich/govalidator/blob/f61b66f89f4a311bef65f13e575bcf1a2ffadda6/validator.go#L887-L895
train
asaskevich/govalidator
validator.go
IsRsaPub
func IsRsaPub(str string, params ...string) bool { if len(params) == 1 { len, _ := ToInt(params[0]) return IsRsaPublicKey(str, int(len)) } return false }
go
func IsRsaPub(str string, params ...string) bool { if len(params) == 1 { len, _ := ToInt(params[0]) return IsRsaPublicKey(str, int(len)) } return false }
[ "func", "IsRsaPub", "(", "str", "string", ",", "params", "...", "string", ")", "bool", "{", "if", "len", "(", "params", ")", "==", "1", "{", "len", ",", "_", ":=", "ToInt", "(", "params", "[", "0", "]", ")", "\n", "return", "IsRsaPublicKey", "(", "str", ",", "int", "(", "len", ")", ")", "\n", "}", "\n", "return", "false", "\n", "}" ]
// IsRsaPub check whether string is valid RSA key // Alias for IsRsaPublicKey
[ "IsRsaPub", "check", "whether", "string", "is", "valid", "RSA", "key", "Alias", "for", "IsRsaPublicKey" ]
f61b66f89f4a311bef65f13e575bcf1a2ffadda6
https://github.com/asaskevich/govalidator/blob/f61b66f89f4a311bef65f13e575bcf1a2ffadda6/validator.go#L905-L912
train
asaskevich/govalidator
validator.go
StringMatches
func StringMatches(s string, params ...string) bool { if len(params) == 1 { pattern := params[0] return Matches(s, pattern) } return false }
go
func StringMatches(s string, params ...string) bool { if len(params) == 1 { pattern := params[0] return Matches(s, pattern) } return false }
[ "func", "StringMatches", "(", "s", "string", ",", "params", "...", "string", ")", "bool", "{", "if", "len", "(", "params", ")", "==", "1", "{", "pattern", ":=", "params", "[", "0", "]", "\n", "return", "Matches", "(", "s", ",", "pattern", ")", "\n", "}", "\n", "return", "false", "\n", "}" ]
// StringMatches checks if a string matches a given pattern.
[ "StringMatches", "checks", "if", "a", "string", "matches", "a", "given", "pattern", "." ]
f61b66f89f4a311bef65f13e575bcf1a2ffadda6
https://github.com/asaskevich/govalidator/blob/f61b66f89f4a311bef65f13e575bcf1a2ffadda6/validator.go#L915-L921
train
asaskevich/govalidator
validator.go
Range
func Range(str string, params ...string) bool { if len(params) == 2 { value, _ := ToFloat(str) min, _ := ToFloat(params[0]) max, _ := ToFloat(params[1]) return InRange(value, min, max) } return false }
go
func Range(str string, params ...string) bool { if len(params) == 2 { value, _ := ToFloat(str) min, _ := ToFloat(params[0]) max, _ := ToFloat(params[1]) return InRange(value, min, max) } return false }
[ "func", "Range", "(", "str", "string", ",", "params", "...", "string", ")", "bool", "{", "if", "len", "(", "params", ")", "==", "2", "{", "value", ",", "_", ":=", "ToFloat", "(", "str", ")", "\n", "min", ",", "_", ":=", "ToFloat", "(", "params", "[", "0", "]", ")", "\n", "max", ",", "_", ":=", "ToFloat", "(", "params", "[", "1", "]", ")", "\n", "return", "InRange", "(", "value", ",", "min", ",", "max", ")", "\n", "}", "\n", "return", "false", "\n", "}" ]
// Range check string's length
[ "Range", "check", "string", "s", "length" ]
f61b66f89f4a311bef65f13e575bcf1a2ffadda6
https://github.com/asaskevich/govalidator/blob/f61b66f89f4a311bef65f13e575bcf1a2ffadda6/validator.go#L937-L946
train
asaskevich/govalidator
validator.go
IsIn
func IsIn(str string, params ...string) bool { for _, param := range params { if str == param { return true } } return false }
go
func IsIn(str string, params ...string) bool { for _, param := range params { if str == param { return true } } return false }
[ "func", "IsIn", "(", "str", "string", ",", "params", "...", "string", ")", "bool", "{", "for", "_", ",", "param", ":=", "range", "params", "{", "if", "str", "==", "param", "{", "return", "true", "\n", "}", "\n", "}", "\n", "return", "false", "\n", "}" ]
// IsIn check if string str is a member of the set of strings params
[ "IsIn", "check", "if", "string", "str", "is", "a", "member", "of", "the", "set", "of", "strings", "params" ]
f61b66f89f4a311bef65f13e575bcf1a2ffadda6
https://github.com/asaskevich/govalidator/blob/f61b66f89f4a311bef65f13e575bcf1a2ffadda6/validator.go#L961-L969
train
asaskevich/govalidator
validator.go
ErrorByField
func ErrorByField(e error, field string) string { if e == nil { return "" } return ErrorsByField(e)[field] }
go
func ErrorByField(e error, field string) string { if e == nil { return "" } return ErrorsByField(e)[field] }
[ "func", "ErrorByField", "(", "e", "error", ",", "field", "string", ")", "string", "{", "if", "e", "==", "nil", "{", "return", "\"\"", "\n", "}", "\n", "return", "ErrorsByField", "(", "e", ")", "[", "field", "]", "\n", "}" ]
// ErrorByField returns error for specified field of the struct // validated by ValidateStruct or empty string if there are no errors // or this field doesn't exists or doesn't have any errors.
[ "ErrorByField", "returns", "error", "for", "specified", "field", "of", "the", "struct", "validated", "by", "ValidateStruct", "or", "empty", "string", "if", "there", "are", "no", "errors", "or", "this", "field", "doesn", "t", "exists", "or", "doesn", "t", "have", "any", "errors", "." ]
f61b66f89f4a311bef65f13e575bcf1a2ffadda6
https://github.com/asaskevich/govalidator/blob/f61b66f89f4a311bef65f13e575bcf1a2ffadda6/validator.go#L1239-L1244
train
asaskevich/govalidator
validator.go
ErrorsByField
func ErrorsByField(e error) map[string]string { m := make(map[string]string) if e == nil { return m } // prototype for ValidateStruct switch e.(type) { case Error: m[e.(Error).Name] = e.(Error).Err.Error() case Errors: for _, item := range e.(Errors).Errors() { n := ErrorsByField(item) for k, v := range n { m[k] = v } } } return m }
go
func ErrorsByField(e error) map[string]string { m := make(map[string]string) if e == nil { return m } // prototype for ValidateStruct switch e.(type) { case Error: m[e.(Error).Name] = e.(Error).Err.Error() case Errors: for _, item := range e.(Errors).Errors() { n := ErrorsByField(item) for k, v := range n { m[k] = v } } } return m }
[ "func", "ErrorsByField", "(", "e", "error", ")", "map", "[", "string", "]", "string", "{", "m", ":=", "make", "(", "map", "[", "string", "]", "string", ")", "\n", "if", "e", "==", "nil", "{", "return", "m", "\n", "}", "\n", "switch", "e", ".", "(", "type", ")", "{", "case", "Error", ":", "m", "[", "e", ".", "(", "Error", ")", ".", "Name", "]", "=", "e", ".", "(", "Error", ")", ".", "Err", ".", "Error", "(", ")", "\n", "case", "Errors", ":", "for", "_", ",", "item", ":=", "range", "e", ".", "(", "Errors", ")", ".", "Errors", "(", ")", "{", "n", ":=", "ErrorsByField", "(", "item", ")", "\n", "for", "k", ",", "v", ":=", "range", "n", "{", "m", "[", "k", "]", "=", "v", "\n", "}", "\n", "}", "\n", "}", "\n", "return", "m", "\n", "}" ]
// ErrorsByField returns map of errors of the struct validated // by ValidateStruct or empty map if there are no errors.
[ "ErrorsByField", "returns", "map", "of", "errors", "of", "the", "struct", "validated", "by", "ValidateStruct", "or", "empty", "map", "if", "there", "are", "no", "errors", "." ]
f61b66f89f4a311bef65f13e575bcf1a2ffadda6
https://github.com/asaskevich/govalidator/blob/f61b66f89f4a311bef65f13e575bcf1a2ffadda6/validator.go#L1248-L1268
train
beego/bee
cmd/commands/dlv/dlv_amd64.go
buildDebug
func buildDebug() (string, error) { args := []string{"-gcflags", "-N -l", "-o", "debug"} args = append(args, utils.SplitQuotedFields("-ldflags='-linkmode internal'")...) args = append(args, packageName) if err := utils.GoCommand("build", args...); err != nil { return "", err } fp, err := filepath.Abs("./debug") if err != nil { return "", err } return fp, nil }
go
func buildDebug() (string, error) { args := []string{"-gcflags", "-N -l", "-o", "debug"} args = append(args, utils.SplitQuotedFields("-ldflags='-linkmode internal'")...) args = append(args, packageName) if err := utils.GoCommand("build", args...); err != nil { return "", err } fp, err := filepath.Abs("./debug") if err != nil { return "", err } return fp, nil }
[ "func", "buildDebug", "(", ")", "(", "string", ",", "error", ")", "{", "args", ":=", "[", "]", "string", "{", "\"-gcflags\"", ",", "\"-N -l\"", ",", "\"-o\"", ",", "\"debug\"", "}", "\n", "args", "=", "append", "(", "args", ",", "utils", ".", "SplitQuotedFields", "(", "\"-ldflags='-linkmode internal'\"", ")", "...", ")", "\n", "args", "=", "append", "(", "args", ",", "packageName", ")", "\n", "if", "err", ":=", "utils", ".", "GoCommand", "(", "\"build\"", ",", "args", "...", ")", ";", "err", "!=", "nil", "{", "return", "\"\"", ",", "err", "\n", "}", "\n", "fp", ",", "err", ":=", "filepath", ".", "Abs", "(", "\"./debug\"", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\"\"", ",", "err", "\n", "}", "\n", "return", "fp", ",", "nil", "\n", "}" ]
// buildDebug builds a debug binary in the current working directory
[ "buildDebug", "builds", "a", "debug", "binary", "in", "the", "current", "working", "directory" ]
6a86284cec9a17f9aae6fe82ecf3c436aafed68d
https://github.com/beego/bee/blob/6a86284cec9a17f9aae6fe82ecf3c436aafed68d/cmd/commands/dlv/dlv_amd64.go#L86-L99
train
beego/bee
cmd/commands/dlv/dlv_amd64.go
loadPathsToWatch
func loadPathsToWatch(paths *[]string) error { directory, err := os.Getwd() if err != nil { return err } filepath.Walk(directory, func(path string, info os.FileInfo, _ error) error { if strings.HasSuffix(info.Name(), "docs") { return filepath.SkipDir } if strings.HasSuffix(info.Name(), "swagger") { return filepath.SkipDir } if strings.HasSuffix(info.Name(), "vendor") { return filepath.SkipDir } if filepath.Ext(info.Name()) == ".go" { *paths = append(*paths, path) } return nil }) return nil }
go
func loadPathsToWatch(paths *[]string) error { directory, err := os.Getwd() if err != nil { return err } filepath.Walk(directory, func(path string, info os.FileInfo, _ error) error { if strings.HasSuffix(info.Name(), "docs") { return filepath.SkipDir } if strings.HasSuffix(info.Name(), "swagger") { return filepath.SkipDir } if strings.HasSuffix(info.Name(), "vendor") { return filepath.SkipDir } if filepath.Ext(info.Name()) == ".go" { *paths = append(*paths, path) } return nil }) return nil }
[ "func", "loadPathsToWatch", "(", "paths", "*", "[", "]", "string", ")", "error", "{", "directory", ",", "err", ":=", "os", ".", "Getwd", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "filepath", ".", "Walk", "(", "directory", ",", "func", "(", "path", "string", ",", "info", "os", ".", "FileInfo", ",", "_", "error", ")", "error", "{", "if", "strings", ".", "HasSuffix", "(", "info", ".", "Name", "(", ")", ",", "\"docs\"", ")", "{", "return", "filepath", ".", "SkipDir", "\n", "}", "\n", "if", "strings", ".", "HasSuffix", "(", "info", ".", "Name", "(", ")", ",", "\"swagger\"", ")", "{", "return", "filepath", ".", "SkipDir", "\n", "}", "\n", "if", "strings", ".", "HasSuffix", "(", "info", ".", "Name", "(", ")", ",", "\"vendor\"", ")", "{", "return", "filepath", ".", "SkipDir", "\n", "}", "\n", "if", "filepath", ".", "Ext", "(", "info", ".", "Name", "(", ")", ")", "==", "\".go\"", "{", "*", "paths", "=", "append", "(", "*", "paths", ",", "path", ")", "\n", "}", "\n", "return", "nil", "\n", "}", ")", "\n", "return", "nil", "\n", "}" ]
// loadPathsToWatch loads the paths that needs to be watched for changes
[ "loadPathsToWatch", "loads", "the", "paths", "that", "needs", "to", "be", "watched", "for", "changes" ]
6a86284cec9a17f9aae6fe82ecf3c436aafed68d
https://github.com/beego/bee/blob/6a86284cec9a17f9aae6fe82ecf3c436aafed68d/cmd/commands/dlv/dlv_amd64.go#L102-L124
train
beego/bee
cmd/commands/dlv/dlv_amd64.go
startDelveDebugger
func startDelveDebugger(addr string, ch chan int) int { beeLogger.Log.Info("Starting Delve Debugger...") fp, err := buildDebug() if err != nil { beeLogger.Log.Fatalf("Error while building debug binary: %v", err) } defer os.Remove(fp) abs, err := filepath.Abs("./debug") if err != nil { beeLogger.Log.Fatalf("%v", err) } // Create and start the debugger server listener, err := net.Listen("tcp", addr) if err != nil { beeLogger.Log.Fatalf("Could not start listener: %s", err) } defer listener.Close() server := rpccommon.NewServer(&service.Config{ Listener: listener, AcceptMulti: true, AttachPid: 0, APIVersion: 2, WorkingDir: ".", ProcessArgs: []string{abs}, }, false) if err := server.Run(); err != nil { beeLogger.Log.Fatalf("Could not start debugger server: %v", err) } // Start the Delve client REPL client := rpc2.NewClient(addr) // Make sure the client is restarted when new changes are introduced go func() { for { if val := <-ch; val == 0 { if _, err := client.Restart(); err != nil { utils.Notify("Error while restarting the client: "+err.Error(), "bee") } else { if verbose { utils.Notify("Delve Debugger Restarted", "bee") } } } } }() // Create the terminal and connect it to the client debugger term := terminal.New(client, nil) status, err := term.Run() if err != nil { beeLogger.Log.Fatalf("Could not start Delve REPL: %v", err) } // Stop and kill the debugger server once user quits the REPL if err := server.Stop(true); err != nil { beeLogger.Log.Fatalf("Could not stop Delve server: %v", err) } return status }
go
func startDelveDebugger(addr string, ch chan int) int { beeLogger.Log.Info("Starting Delve Debugger...") fp, err := buildDebug() if err != nil { beeLogger.Log.Fatalf("Error while building debug binary: %v", err) } defer os.Remove(fp) abs, err := filepath.Abs("./debug") if err != nil { beeLogger.Log.Fatalf("%v", err) } // Create and start the debugger server listener, err := net.Listen("tcp", addr) if err != nil { beeLogger.Log.Fatalf("Could not start listener: %s", err) } defer listener.Close() server := rpccommon.NewServer(&service.Config{ Listener: listener, AcceptMulti: true, AttachPid: 0, APIVersion: 2, WorkingDir: ".", ProcessArgs: []string{abs}, }, false) if err := server.Run(); err != nil { beeLogger.Log.Fatalf("Could not start debugger server: %v", err) } // Start the Delve client REPL client := rpc2.NewClient(addr) // Make sure the client is restarted when new changes are introduced go func() { for { if val := <-ch; val == 0 { if _, err := client.Restart(); err != nil { utils.Notify("Error while restarting the client: "+err.Error(), "bee") } else { if verbose { utils.Notify("Delve Debugger Restarted", "bee") } } } } }() // Create the terminal and connect it to the client debugger term := terminal.New(client, nil) status, err := term.Run() if err != nil { beeLogger.Log.Fatalf("Could not start Delve REPL: %v", err) } // Stop and kill the debugger server once user quits the REPL if err := server.Stop(true); err != nil { beeLogger.Log.Fatalf("Could not stop Delve server: %v", err) } return status }
[ "func", "startDelveDebugger", "(", "addr", "string", ",", "ch", "chan", "int", ")", "int", "{", "beeLogger", ".", "Log", ".", "Info", "(", "\"Starting Delve Debugger...\"", ")", "\n", "fp", ",", "err", ":=", "buildDebug", "(", ")", "\n", "if", "err", "!=", "nil", "{", "beeLogger", ".", "Log", ".", "Fatalf", "(", "\"Error while building debug binary: %v\"", ",", "err", ")", "\n", "}", "\n", "defer", "os", ".", "Remove", "(", "fp", ")", "\n", "abs", ",", "err", ":=", "filepath", ".", "Abs", "(", "\"./debug\"", ")", "\n", "if", "err", "!=", "nil", "{", "beeLogger", ".", "Log", ".", "Fatalf", "(", "\"%v\"", ",", "err", ")", "\n", "}", "\n", "listener", ",", "err", ":=", "net", ".", "Listen", "(", "\"tcp\"", ",", "addr", ")", "\n", "if", "err", "!=", "nil", "{", "beeLogger", ".", "Log", ".", "Fatalf", "(", "\"Could not start listener: %s\"", ",", "err", ")", "\n", "}", "\n", "defer", "listener", ".", "Close", "(", ")", "\n", "server", ":=", "rpccommon", ".", "NewServer", "(", "&", "service", ".", "Config", "{", "Listener", ":", "listener", ",", "AcceptMulti", ":", "true", ",", "AttachPid", ":", "0", ",", "APIVersion", ":", "2", ",", "WorkingDir", ":", "\".\"", ",", "ProcessArgs", ":", "[", "]", "string", "{", "abs", "}", ",", "}", ",", "false", ")", "\n", "if", "err", ":=", "server", ".", "Run", "(", ")", ";", "err", "!=", "nil", "{", "beeLogger", ".", "Log", ".", "Fatalf", "(", "\"Could not start debugger server: %v\"", ",", "err", ")", "\n", "}", "\n", "client", ":=", "rpc2", ".", "NewClient", "(", "addr", ")", "\n", "go", "func", "(", ")", "{", "for", "{", "if", "val", ":=", "<-", "ch", ";", "val", "==", "0", "{", "if", "_", ",", "err", ":=", "client", ".", "Restart", "(", ")", ";", "err", "!=", "nil", "{", "utils", ".", "Notify", "(", "\"Error while restarting the client: \"", "+", "err", ".", "Error", "(", ")", ",", "\"bee\"", ")", "\n", "}", "else", "{", "if", "verbose", "{", "utils", ".", "Notify", "(", "\"Delve Debugger Restarted\"", ",", "\"bee\"", ")", "\n", "}", "\n", "}", "\n", "}", "\n", "}", "\n", "}", "(", ")", "\n", "term", ":=", "terminal", ".", "New", "(", "client", ",", "nil", ")", "\n", "status", ",", "err", ":=", "term", ".", "Run", "(", ")", "\n", "if", "err", "!=", "nil", "{", "beeLogger", ".", "Log", ".", "Fatalf", "(", "\"Could not start Delve REPL: %v\"", ",", "err", ")", "\n", "}", "\n", "if", "err", ":=", "server", ".", "Stop", "(", "true", ")", ";", "err", "!=", "nil", "{", "beeLogger", ".", "Log", ".", "Fatalf", "(", "\"Could not stop Delve server: %v\"", ",", "err", ")", "\n", "}", "\n", "return", "status", "\n", "}" ]
// startDelveDebugger starts the Delve debugger server
[ "startDelveDebugger", "starts", "the", "Delve", "debugger", "server" ]
6a86284cec9a17f9aae6fe82ecf3c436aafed68d
https://github.com/beego/bee/blob/6a86284cec9a17f9aae6fe82ecf3c436aafed68d/cmd/commands/dlv/dlv_amd64.go#L127-L189
train
beego/bee
cmd/commands/dlv/dlv_amd64.go
startWatcher
func startWatcher(paths []string, ch chan int) { watcher, err := fsnotify.NewWatcher() if err != nil { beeLogger.Log.Fatalf("Could not start the watcher: %v", err) } defer watcher.Close() // Feed the paths to the watcher for _, path := range paths { if err := watcher.Add(path); err != nil { beeLogger.Log.Fatalf("Could not set a watch on path: %v", err) } } for { select { case evt := <-watcher.Events: build := true if filepath.Ext(evt.Name) != ".go" { continue } mt := utils.GetFileModTime(evt.Name) if t := eventsModTime[evt.Name]; mt == t { build = false } eventsModTime[evt.Name] = mt if build { go func() { if verbose { utils.Notify("Rebuilding application with the new changes", "bee") } // Wait 1s before re-build until there is no file change scheduleTime := time.Now().Add(1 * time.Second) time.Sleep(time.Until(scheduleTime)) _, err := buildDebug() if err != nil { utils.Notify("Build Failed: "+err.Error(), "bee") } else { ch <- 0 // Notify listeners } }() } case err := <-watcher.Errors: if err != nil { ch <- -1 } } } }
go
func startWatcher(paths []string, ch chan int) { watcher, err := fsnotify.NewWatcher() if err != nil { beeLogger.Log.Fatalf("Could not start the watcher: %v", err) } defer watcher.Close() // Feed the paths to the watcher for _, path := range paths { if err := watcher.Add(path); err != nil { beeLogger.Log.Fatalf("Could not set a watch on path: %v", err) } } for { select { case evt := <-watcher.Events: build := true if filepath.Ext(evt.Name) != ".go" { continue } mt := utils.GetFileModTime(evt.Name) if t := eventsModTime[evt.Name]; mt == t { build = false } eventsModTime[evt.Name] = mt if build { go func() { if verbose { utils.Notify("Rebuilding application with the new changes", "bee") } // Wait 1s before re-build until there is no file change scheduleTime := time.Now().Add(1 * time.Second) time.Sleep(time.Until(scheduleTime)) _, err := buildDebug() if err != nil { utils.Notify("Build Failed: "+err.Error(), "bee") } else { ch <- 0 // Notify listeners } }() } case err := <-watcher.Errors: if err != nil { ch <- -1 } } } }
[ "func", "startWatcher", "(", "paths", "[", "]", "string", ",", "ch", "chan", "int", ")", "{", "watcher", ",", "err", ":=", "fsnotify", ".", "NewWatcher", "(", ")", "\n", "if", "err", "!=", "nil", "{", "beeLogger", ".", "Log", ".", "Fatalf", "(", "\"Could not start the watcher: %v\"", ",", "err", ")", "\n", "}", "\n", "defer", "watcher", ".", "Close", "(", ")", "\n", "for", "_", ",", "path", ":=", "range", "paths", "{", "if", "err", ":=", "watcher", ".", "Add", "(", "path", ")", ";", "err", "!=", "nil", "{", "beeLogger", ".", "Log", ".", "Fatalf", "(", "\"Could not set a watch on path: %v\"", ",", "err", ")", "\n", "}", "\n", "}", "\n", "for", "{", "select", "{", "case", "evt", ":=", "<-", "watcher", ".", "Events", ":", "build", ":=", "true", "\n", "if", "filepath", ".", "Ext", "(", "evt", ".", "Name", ")", "!=", "\".go\"", "{", "continue", "\n", "}", "\n", "mt", ":=", "utils", ".", "GetFileModTime", "(", "evt", ".", "Name", ")", "\n", "if", "t", ":=", "eventsModTime", "[", "evt", ".", "Name", "]", ";", "mt", "==", "t", "{", "build", "=", "false", "\n", "}", "\n", "eventsModTime", "[", "evt", ".", "Name", "]", "=", "mt", "\n", "if", "build", "{", "go", "func", "(", ")", "{", "if", "verbose", "{", "utils", ".", "Notify", "(", "\"Rebuilding application with the new changes\"", ",", "\"bee\"", ")", "\n", "}", "\n", "scheduleTime", ":=", "time", ".", "Now", "(", ")", ".", "Add", "(", "1", "*", "time", ".", "Second", ")", "\n", "time", ".", "Sleep", "(", "time", ".", "Until", "(", "scheduleTime", ")", ")", "\n", "_", ",", "err", ":=", "buildDebug", "(", ")", "\n", "if", "err", "!=", "nil", "{", "utils", ".", "Notify", "(", "\"Build Failed: \"", "+", "err", ".", "Error", "(", ")", ",", "\"bee\"", ")", "\n", "}", "else", "{", "ch", "<-", "0", "\n", "}", "\n", "}", "(", ")", "\n", "}", "\n", "case", "err", ":=", "<-", "watcher", ".", "Errors", ":", "if", "err", "!=", "nil", "{", "ch", "<-", "-", "1", "\n", "}", "\n", "}", "\n", "}", "\n", "}" ]
// startWatcher starts the fsnotify watcher on the passed paths
[ "startWatcher", "starts", "the", "fsnotify", "watcher", "on", "the", "passed", "paths" ]
6a86284cec9a17f9aae6fe82ecf3c436aafed68d
https://github.com/beego/bee/blob/6a86284cec9a17f9aae6fe82ecf3c436aafed68d/cmd/commands/dlv/dlv_amd64.go#L194-L245
train
beego/bee
generate/swaggergen/g_docs.go
ParsePackagesFromDir
func ParsePackagesFromDir(dirpath string) { c := make(chan error) go func() { filepath.Walk(dirpath, func(fpath string, fileInfo os.FileInfo, err error) error { if err != nil { return nil } if !fileInfo.IsDir() { return nil } // skip folder if it's a 'vendor' folder within dirpath or its child, // all 'tests' folders and dot folders wihin dirpath d, _ := filepath.Rel(dirpath, fpath) if !(d == "vendor" || strings.HasPrefix(d, "vendor"+string(os.PathSeparator))) && !strings.Contains(d, "tests") && !(d[0] == '.') { err = parsePackageFromDir(fpath) if err != nil { // Send the error to through the channel and continue walking c <- fmt.Errorf("error while parsing directory: %s", err.Error()) return nil } } return nil }) close(c) }() for err := range c { beeLogger.Log.Warnf("%s", err) } }
go
func ParsePackagesFromDir(dirpath string) { c := make(chan error) go func() { filepath.Walk(dirpath, func(fpath string, fileInfo os.FileInfo, err error) error { if err != nil { return nil } if !fileInfo.IsDir() { return nil } // skip folder if it's a 'vendor' folder within dirpath or its child, // all 'tests' folders and dot folders wihin dirpath d, _ := filepath.Rel(dirpath, fpath) if !(d == "vendor" || strings.HasPrefix(d, "vendor"+string(os.PathSeparator))) && !strings.Contains(d, "tests") && !(d[0] == '.') { err = parsePackageFromDir(fpath) if err != nil { // Send the error to through the channel and continue walking c <- fmt.Errorf("error while parsing directory: %s", err.Error()) return nil } } return nil }) close(c) }() for err := range c { beeLogger.Log.Warnf("%s", err) } }
[ "func", "ParsePackagesFromDir", "(", "dirpath", "string", ")", "{", "c", ":=", "make", "(", "chan", "error", ")", "\n", "go", "func", "(", ")", "{", "filepath", ".", "Walk", "(", "dirpath", ",", "func", "(", "fpath", "string", ",", "fileInfo", "os", ".", "FileInfo", ",", "err", "error", ")", "error", "{", "if", "err", "!=", "nil", "{", "return", "nil", "\n", "}", "\n", "if", "!", "fileInfo", ".", "IsDir", "(", ")", "{", "return", "nil", "\n", "}", "\n", "d", ",", "_", ":=", "filepath", ".", "Rel", "(", "dirpath", ",", "fpath", ")", "\n", "if", "!", "(", "d", "==", "\"vendor\"", "||", "strings", ".", "HasPrefix", "(", "d", ",", "\"vendor\"", "+", "string", "(", "os", ".", "PathSeparator", ")", ")", ")", "&&", "!", "strings", ".", "Contains", "(", "d", ",", "\"tests\"", ")", "&&", "!", "(", "d", "[", "0", "]", "==", "'.'", ")", "{", "err", "=", "parsePackageFromDir", "(", "fpath", ")", "\n", "if", "err", "!=", "nil", "{", "c", "<-", "fmt", ".", "Errorf", "(", "\"error while parsing directory: %s\"", ",", "err", ".", "Error", "(", ")", ")", "\n", "return", "nil", "\n", "}", "\n", "}", "\n", "return", "nil", "\n", "}", ")", "\n", "close", "(", "c", ")", "\n", "}", "(", ")", "\n", "for", "err", ":=", "range", "c", "{", "beeLogger", ".", "Log", ".", "Warnf", "(", "\"%s\"", ",", "err", ")", "\n", "}", "\n", "}" ]
// ParsePackagesFromDir parses packages from a given directory
[ "ParsePackagesFromDir", "parses", "packages", "from", "a", "given", "directory" ]
6a86284cec9a17f9aae6fe82ecf3c436aafed68d
https://github.com/beego/bee/blob/6a86284cec9a17f9aae6fe82ecf3c436aafed68d/generate/swaggergen/g_docs.go#L106-L139
train
beego/bee
generate/swaggergen/g_docs.go
analyseNewNamespace
func analyseNewNamespace(ce *ast.CallExpr) (first string, others []ast.Expr) { for i, p := range ce.Args { if i == 0 { switch pp := p.(type) { case *ast.BasicLit: first = strings.Trim(pp.Value, `"`) } continue } others = append(others, p) } return }
go
func analyseNewNamespace(ce *ast.CallExpr) (first string, others []ast.Expr) { for i, p := range ce.Args { if i == 0 { switch pp := p.(type) { case *ast.BasicLit: first = strings.Trim(pp.Value, `"`) } continue } others = append(others, p) } return }
[ "func", "analyseNewNamespace", "(", "ce", "*", "ast", ".", "CallExpr", ")", "(", "first", "string", ",", "others", "[", "]", "ast", ".", "Expr", ")", "{", "for", "i", ",", "p", ":=", "range", "ce", ".", "Args", "{", "if", "i", "==", "0", "{", "switch", "pp", ":=", "p", ".", "(", "type", ")", "{", "case", "*", "ast", ".", "BasicLit", ":", "first", "=", "strings", ".", "Trim", "(", "pp", ".", "Value", ",", "`\"`", ")", "\n", "}", "\n", "continue", "\n", "}", "\n", "others", "=", "append", "(", "others", ",", "p", ")", "\n", "}", "\n", "return", "\n", "}" ]
// analyseNewNamespace returns version and the others params
[ "analyseNewNamespace", "returns", "version", "and", "the", "others", "params" ]
6a86284cec9a17f9aae6fe82ecf3c436aafed68d
https://github.com/beego/bee/blob/6a86284cec9a17f9aae6fe82ecf3c436aafed68d/generate/swaggergen/g_docs.go#L347-L359
train
beego/bee
generate/g_appcode.go
String
func (tb *Table) String() string { rv := fmt.Sprintf("type %s struct {\n", utils.CamelCase(tb.Name)) for _, v := range tb.Columns { rv += v.String() + "\n" } rv += "}\n" return rv }
go
func (tb *Table) String() string { rv := fmt.Sprintf("type %s struct {\n", utils.CamelCase(tb.Name)) for _, v := range tb.Columns { rv += v.String() + "\n" } rv += "}\n" return rv }
[ "func", "(", "tb", "*", "Table", ")", "String", "(", ")", "string", "{", "rv", ":=", "fmt", ".", "Sprintf", "(", "\"type %s struct {\\n\"", ",", "\\n", ")", "\n", "utils", ".", "CamelCase", "(", "tb", ".", "Name", ")", "\n", "for", "_", ",", "v", ":=", "range", "tb", ".", "Columns", "{", "rv", "+=", "v", ".", "String", "(", ")", "+", "\"\\n\"", "\n", "}", "\n", "\\n", "\n", "}" ]
// String returns the source code string for the Table struct
[ "String", "returns", "the", "source", "code", "string", "for", "the", "Table", "struct" ]
6a86284cec9a17f9aae6fe82ecf3c436aafed68d
https://github.com/beego/bee/blob/6a86284cec9a17f9aae6fe82ecf3c436aafed68d/generate/g_appcode.go#L190-L197
train
beego/bee
generate/g_appcode.go
String
func (tag *OrmTag) String() string { var ormOptions []string if tag.Column != "" { ormOptions = append(ormOptions, fmt.Sprintf("column(%s)", tag.Column)) } if tag.Auto { ormOptions = append(ormOptions, "auto") } if tag.Size != "" { ormOptions = append(ormOptions, fmt.Sprintf("size(%s)", tag.Size)) } if tag.Type != "" { ormOptions = append(ormOptions, fmt.Sprintf("type(%s)", tag.Type)) } if tag.Null { ormOptions = append(ormOptions, "null") } if tag.AutoNow { ormOptions = append(ormOptions, "auto_now") } if tag.AutoNowAdd { ormOptions = append(ormOptions, "auto_now_add") } if tag.Decimals != "" { ormOptions = append(ormOptions, fmt.Sprintf("digits(%s);decimals(%s)", tag.Digits, tag.Decimals)) } if tag.RelFk { ormOptions = append(ormOptions, "rel(fk)") } if tag.RelOne { ormOptions = append(ormOptions, "rel(one)") } if tag.ReverseOne { ormOptions = append(ormOptions, "reverse(one)") } if tag.ReverseMany { ormOptions = append(ormOptions, "reverse(many)") } if tag.RelM2M { ormOptions = append(ormOptions, "rel(m2m)") } if tag.Pk { ormOptions = append(ormOptions, "pk") } if tag.Unique { ormOptions = append(ormOptions, "unique") } if tag.Default != "" { ormOptions = append(ormOptions, fmt.Sprintf("default(%s)", tag.Default)) } if len(ormOptions) == 0 { return "" } if tag.Comment != "" { return fmt.Sprintf("`orm:\"%s\" description:\"%s\"`", strings.Join(ormOptions, ";"), tag.Comment) } return fmt.Sprintf("`orm:\"%s\"`", strings.Join(ormOptions, ";")) }
go
func (tag *OrmTag) String() string { var ormOptions []string if tag.Column != "" { ormOptions = append(ormOptions, fmt.Sprintf("column(%s)", tag.Column)) } if tag.Auto { ormOptions = append(ormOptions, "auto") } if tag.Size != "" { ormOptions = append(ormOptions, fmt.Sprintf("size(%s)", tag.Size)) } if tag.Type != "" { ormOptions = append(ormOptions, fmt.Sprintf("type(%s)", tag.Type)) } if tag.Null { ormOptions = append(ormOptions, "null") } if tag.AutoNow { ormOptions = append(ormOptions, "auto_now") } if tag.AutoNowAdd { ormOptions = append(ormOptions, "auto_now_add") } if tag.Decimals != "" { ormOptions = append(ormOptions, fmt.Sprintf("digits(%s);decimals(%s)", tag.Digits, tag.Decimals)) } if tag.RelFk { ormOptions = append(ormOptions, "rel(fk)") } if tag.RelOne { ormOptions = append(ormOptions, "rel(one)") } if tag.ReverseOne { ormOptions = append(ormOptions, "reverse(one)") } if tag.ReverseMany { ormOptions = append(ormOptions, "reverse(many)") } if tag.RelM2M { ormOptions = append(ormOptions, "rel(m2m)") } if tag.Pk { ormOptions = append(ormOptions, "pk") } if tag.Unique { ormOptions = append(ormOptions, "unique") } if tag.Default != "" { ormOptions = append(ormOptions, fmt.Sprintf("default(%s)", tag.Default)) } if len(ormOptions) == 0 { return "" } if tag.Comment != "" { return fmt.Sprintf("`orm:\"%s\" description:\"%s\"`", strings.Join(ormOptions, ";"), tag.Comment) } return fmt.Sprintf("`orm:\"%s\"`", strings.Join(ormOptions, ";")) }
[ "func", "(", "tag", "*", "OrmTag", ")", "String", "(", ")", "string", "{", "var", "ormOptions", "[", "]", "string", "\n", "if", "tag", ".", "Column", "!=", "\"\"", "{", "ormOptions", "=", "append", "(", "ormOptions", ",", "fmt", ".", "Sprintf", "(", "\"column(%s)\"", ",", "tag", ".", "Column", ")", ")", "\n", "}", "\n", "if", "tag", ".", "Auto", "{", "ormOptions", "=", "append", "(", "ormOptions", ",", "\"auto\"", ")", "\n", "}", "\n", "if", "tag", ".", "Size", "!=", "\"\"", "{", "ormOptions", "=", "append", "(", "ormOptions", ",", "fmt", ".", "Sprintf", "(", "\"size(%s)\"", ",", "tag", ".", "Size", ")", ")", "\n", "}", "\n", "if", "tag", ".", "Type", "!=", "\"\"", "{", "ormOptions", "=", "append", "(", "ormOptions", ",", "fmt", ".", "Sprintf", "(", "\"type(%s)\"", ",", "tag", ".", "Type", ")", ")", "\n", "}", "\n", "if", "tag", ".", "Null", "{", "ormOptions", "=", "append", "(", "ormOptions", ",", "\"null\"", ")", "\n", "}", "\n", "if", "tag", ".", "AutoNow", "{", "ormOptions", "=", "append", "(", "ormOptions", ",", "\"auto_now\"", ")", "\n", "}", "\n", "if", "tag", ".", "AutoNowAdd", "{", "ormOptions", "=", "append", "(", "ormOptions", ",", "\"auto_now_add\"", ")", "\n", "}", "\n", "if", "tag", ".", "Decimals", "!=", "\"\"", "{", "ormOptions", "=", "append", "(", "ormOptions", ",", "fmt", ".", "Sprintf", "(", "\"digits(%s);decimals(%s)\"", ",", "tag", ".", "Digits", ",", "tag", ".", "Decimals", ")", ")", "\n", "}", "\n", "if", "tag", ".", "RelFk", "{", "ormOptions", "=", "append", "(", "ormOptions", ",", "\"rel(fk)\"", ")", "\n", "}", "\n", "if", "tag", ".", "RelOne", "{", "ormOptions", "=", "append", "(", "ormOptions", ",", "\"rel(one)\"", ")", "\n", "}", "\n", "if", "tag", ".", "ReverseOne", "{", "ormOptions", "=", "append", "(", "ormOptions", ",", "\"reverse(one)\"", ")", "\n", "}", "\n", "if", "tag", ".", "ReverseMany", "{", "ormOptions", "=", "append", "(", "ormOptions", ",", "\"reverse(many)\"", ")", "\n", "}", "\n", "if", "tag", ".", "RelM2M", "{", "ormOptions", "=", "append", "(", "ormOptions", ",", "\"rel(m2m)\"", ")", "\n", "}", "\n", "if", "tag", ".", "Pk", "{", "ormOptions", "=", "append", "(", "ormOptions", ",", "\"pk\"", ")", "\n", "}", "\n", "if", "tag", ".", "Unique", "{", "ormOptions", "=", "append", "(", "ormOptions", ",", "\"unique\"", ")", "\n", "}", "\n", "if", "tag", ".", "Default", "!=", "\"\"", "{", "ormOptions", "=", "append", "(", "ormOptions", ",", "fmt", ".", "Sprintf", "(", "\"default(%s)\"", ",", "tag", ".", "Default", ")", ")", "\n", "}", "\n", "if", "len", "(", "ormOptions", ")", "==", "0", "{", "return", "\"\"", "\n", "}", "\n", "if", "tag", ".", "Comment", "!=", "\"\"", "{", "return", "fmt", ".", "Sprintf", "(", "\"`orm:\\\"%s\\\" description:\\\"%s\\\"`\"", ",", "\\\"", ",", "\\\"", ")", "\n", "}", "\n", "\\\"", "\n", "}" ]
// String returns the ORM tag string for a column
[ "String", "returns", "the", "ORM", "tag", "string", "for", "a", "column" ]
6a86284cec9a17f9aae6fe82ecf3c436aafed68d
https://github.com/beego/bee/blob/6a86284cec9a17f9aae6fe82ecf3c436aafed68d/generate/g_appcode.go#L206-L264
train
beego/bee
generate/g_appcode.go
getTableObjects
func getTableObjects(tableNames []string, db *sql.DB, dbTransformer DbTransformer) (tables []*Table) { // if a table has a composite pk or doesn't have pk, we can't use it yet // these tables will be put into blacklist so that other struct will not // reference it. blackList := make(map[string]bool) // process constraints information for each table, also gather blacklisted table names for _, tableName := range tableNames { // create a table struct tb := new(Table) tb.Name = tableName tb.Fk = make(map[string]*ForeignKey) dbTransformer.GetConstraints(db, tb, blackList) tables = append(tables, tb) } // process columns, ignoring blacklisted tables for _, tb := range tables { dbTransformer.GetColumns(db, tb, blackList) } return }
go
func getTableObjects(tableNames []string, db *sql.DB, dbTransformer DbTransformer) (tables []*Table) { // if a table has a composite pk or doesn't have pk, we can't use it yet // these tables will be put into blacklist so that other struct will not // reference it. blackList := make(map[string]bool) // process constraints information for each table, also gather blacklisted table names for _, tableName := range tableNames { // create a table struct tb := new(Table) tb.Name = tableName tb.Fk = make(map[string]*ForeignKey) dbTransformer.GetConstraints(db, tb, blackList) tables = append(tables, tb) } // process columns, ignoring blacklisted tables for _, tb := range tables { dbTransformer.GetColumns(db, tb, blackList) } return }
[ "func", "getTableObjects", "(", "tableNames", "[", "]", "string", ",", "db", "*", "sql", ".", "DB", ",", "dbTransformer", "DbTransformer", ")", "(", "tables", "[", "]", "*", "Table", ")", "{", "blackList", ":=", "make", "(", "map", "[", "string", "]", "bool", ")", "\n", "for", "_", ",", "tableName", ":=", "range", "tableNames", "{", "tb", ":=", "new", "(", "Table", ")", "\n", "tb", ".", "Name", "=", "tableName", "\n", "tb", ".", "Fk", "=", "make", "(", "map", "[", "string", "]", "*", "ForeignKey", ")", "\n", "dbTransformer", ".", "GetConstraints", "(", "db", ",", "tb", ",", "blackList", ")", "\n", "tables", "=", "append", "(", "tables", ",", "tb", ")", "\n", "}", "\n", "for", "_", ",", "tb", ":=", "range", "tables", "{", "dbTransformer", ".", "GetColumns", "(", "db", ",", "tb", ",", "blackList", ")", "\n", "}", "\n", "return", "\n", "}" ]
// getTableObjects process each table name
[ "getTableObjects", "process", "each", "table", "name" ]
6a86284cec9a17f9aae6fe82ecf3c436aafed68d
https://github.com/beego/bee/blob/6a86284cec9a17f9aae6fe82ecf3c436aafed68d/generate/g_appcode.go#L345-L364
train
beego/bee
generate/g_appcode.go
GetGoDataType
func (*MysqlDB) GetGoDataType(sqlType string) (string, error) { if v, ok := typeMappingMysql[sqlType]; ok { return v, nil } return "", fmt.Errorf("data type '%s' not found", sqlType) }
go
func (*MysqlDB) GetGoDataType(sqlType string) (string, error) { if v, ok := typeMappingMysql[sqlType]; ok { return v, nil } return "", fmt.Errorf("data type '%s' not found", sqlType) }
[ "func", "(", "*", "MysqlDB", ")", "GetGoDataType", "(", "sqlType", "string", ")", "(", "string", ",", "error", ")", "{", "if", "v", ",", "ok", ":=", "typeMappingMysql", "[", "sqlType", "]", ";", "ok", "{", "return", "v", ",", "nil", "\n", "}", "\n", "return", "\"\"", ",", "fmt", ".", "Errorf", "(", "\"data type '%s' not found\"", ",", "sqlType", ")", "\n", "}" ]
// GetGoDataType maps an SQL data type to Golang data type
[ "GetGoDataType", "maps", "an", "SQL", "data", "type", "to", "Golang", "data", "type" ]
6a86284cec9a17f9aae6fe82ecf3c436aafed68d
https://github.com/beego/bee/blob/6a86284cec9a17f9aae6fe82ecf3c436aafed68d/generate/g_appcode.go#L518-L523
train
beego/bee
generate/g_appcode.go
GetTableNames
func (*PostgresDB) GetTableNames(db *sql.DB) (tables []string) { rows, err := db.Query(` SELECT table_name FROM information_schema.tables WHERE table_catalog = current_database() AND table_type = 'BASE TABLE' AND table_schema NOT IN ('pg_catalog', 'information_schema')`) if err != nil { beeLogger.Log.Fatalf("Could not show tables: %s", err) } defer rows.Close() for rows.Next() { var name string if err := rows.Scan(&name); err != nil { beeLogger.Log.Fatalf("Could not show tables: %s", err) } tables = append(tables, name) } return }
go
func (*PostgresDB) GetTableNames(db *sql.DB) (tables []string) { rows, err := db.Query(` SELECT table_name FROM information_schema.tables WHERE table_catalog = current_database() AND table_type = 'BASE TABLE' AND table_schema NOT IN ('pg_catalog', 'information_schema')`) if err != nil { beeLogger.Log.Fatalf("Could not show tables: %s", err) } defer rows.Close() for rows.Next() { var name string if err := rows.Scan(&name); err != nil { beeLogger.Log.Fatalf("Could not show tables: %s", err) } tables = append(tables, name) } return }
[ "func", "(", "*", "PostgresDB", ")", "GetTableNames", "(", "db", "*", "sql", ".", "DB", ")", "(", "tables", "[", "]", "string", ")", "{", "rows", ",", "err", ":=", "db", ".", "Query", "(", "`\t\tSELECT table_name FROM information_schema.tables\t\tWHERE table_catalog = current_database() AND\t\ttable_type = 'BASE TABLE' AND\t\ttable_schema NOT IN ('pg_catalog', 'information_schema')`", ")", "\n", "if", "err", "!=", "nil", "{", "beeLogger", ".", "Log", ".", "Fatalf", "(", "\"Could not show tables: %s\"", ",", "err", ")", "\n", "}", "\n", "defer", "rows", ".", "Close", "(", ")", "\n", "for", "rows", ".", "Next", "(", ")", "{", "var", "name", "string", "\n", "if", "err", ":=", "rows", ".", "Scan", "(", "&", "name", ")", ";", "err", "!=", "nil", "{", "beeLogger", ".", "Log", ".", "Fatalf", "(", "\"Could not show tables: %s\"", ",", "err", ")", "\n", "}", "\n", "tables", "=", "append", "(", "tables", ",", "name", ")", "\n", "}", "\n", "return", "\n", "}" ]
// GetTableNames for PostgreSQL
[ "GetTableNames", "for", "PostgreSQL" ]
6a86284cec9a17f9aae6fe82ecf3c436aafed68d
https://github.com/beego/bee/blob/6a86284cec9a17f9aae6fe82ecf3c436aafed68d/generate/g_appcode.go#L526-L545
train
beego/bee
generate/g_appcode.go
GetConstraints
func (*PostgresDB) GetConstraints(db *sql.DB, table *Table, blackList map[string]bool) { rows, err := db.Query( `SELECT c.constraint_type, u.column_name, cu.table_catalog AS referenced_table_catalog, cu.table_name AS referenced_table_name, cu.column_name AS referenced_column_name, u.ordinal_position FROM information_schema.table_constraints c INNER JOIN information_schema.key_column_usage u ON c.constraint_name = u.constraint_name INNER JOIN information_schema.constraint_column_usage cu ON cu.constraint_name = c.constraint_name WHERE c.table_catalog = current_database() AND c.table_schema NOT IN ('pg_catalog', 'information_schema') AND c.table_name = $1 AND u.table_catalog = current_database() AND u.table_schema NOT IN ('pg_catalog', 'information_schema') AND u.table_name = $2`, table.Name, table.Name) // u.position_in_unique_constraint, if err != nil { beeLogger.Log.Fatalf("Could not query INFORMATION_SCHEMA for PK/UK/FK information: %s", err) } for rows.Next() { var constraintTypeBytes, columnNameBytes, refTableSchemaBytes, refTableNameBytes, refColumnNameBytes, refOrdinalPosBytes []byte if err := rows.Scan(&constraintTypeBytes, &columnNameBytes, &refTableSchemaBytes, &refTableNameBytes, &refColumnNameBytes, &refOrdinalPosBytes); err != nil { beeLogger.Log.Fatalf("Could not read INFORMATION_SCHEMA for PK/UK/FK information: %s", err) } constraintType, columnName, refTableSchema, refTableName, refColumnName, refOrdinalPos := string(constraintTypeBytes), string(columnNameBytes), string(refTableSchemaBytes), string(refTableNameBytes), string(refColumnNameBytes), string(refOrdinalPosBytes) if constraintType == "PRIMARY KEY" { if refOrdinalPos == "1" { table.Pk = columnName } else { table.Pk = "" // add table to blacklist so that other struct will not reference it, because we are not // registering blacklisted tables blackList[table.Name] = true } } else if constraintType == "UNIQUE" { table.Uk = append(table.Uk, columnName) } else if constraintType == "FOREIGN KEY" { fk := new(ForeignKey) fk.Name = columnName fk.RefSchema = refTableSchema fk.RefTable = refTableName fk.RefColumn = refColumnName table.Fk[columnName] = fk } } }
go
func (*PostgresDB) GetConstraints(db *sql.DB, table *Table, blackList map[string]bool) { rows, err := db.Query( `SELECT c.constraint_type, u.column_name, cu.table_catalog AS referenced_table_catalog, cu.table_name AS referenced_table_name, cu.column_name AS referenced_column_name, u.ordinal_position FROM information_schema.table_constraints c INNER JOIN information_schema.key_column_usage u ON c.constraint_name = u.constraint_name INNER JOIN information_schema.constraint_column_usage cu ON cu.constraint_name = c.constraint_name WHERE c.table_catalog = current_database() AND c.table_schema NOT IN ('pg_catalog', 'information_schema') AND c.table_name = $1 AND u.table_catalog = current_database() AND u.table_schema NOT IN ('pg_catalog', 'information_schema') AND u.table_name = $2`, table.Name, table.Name) // u.position_in_unique_constraint, if err != nil { beeLogger.Log.Fatalf("Could not query INFORMATION_SCHEMA for PK/UK/FK information: %s", err) } for rows.Next() { var constraintTypeBytes, columnNameBytes, refTableSchemaBytes, refTableNameBytes, refColumnNameBytes, refOrdinalPosBytes []byte if err := rows.Scan(&constraintTypeBytes, &columnNameBytes, &refTableSchemaBytes, &refTableNameBytes, &refColumnNameBytes, &refOrdinalPosBytes); err != nil { beeLogger.Log.Fatalf("Could not read INFORMATION_SCHEMA for PK/UK/FK information: %s", err) } constraintType, columnName, refTableSchema, refTableName, refColumnName, refOrdinalPos := string(constraintTypeBytes), string(columnNameBytes), string(refTableSchemaBytes), string(refTableNameBytes), string(refColumnNameBytes), string(refOrdinalPosBytes) if constraintType == "PRIMARY KEY" { if refOrdinalPos == "1" { table.Pk = columnName } else { table.Pk = "" // add table to blacklist so that other struct will not reference it, because we are not // registering blacklisted tables blackList[table.Name] = true } } else if constraintType == "UNIQUE" { table.Uk = append(table.Uk, columnName) } else if constraintType == "FOREIGN KEY" { fk := new(ForeignKey) fk.Name = columnName fk.RefSchema = refTableSchema fk.RefTable = refTableName fk.RefColumn = refColumnName table.Fk[columnName] = fk } } }
[ "func", "(", "*", "PostgresDB", ")", "GetConstraints", "(", "db", "*", "sql", ".", "DB", ",", "table", "*", "Table", ",", "blackList", "map", "[", "string", "]", "bool", ")", "{", "rows", ",", "err", ":=", "db", ".", "Query", "(", "`SELECT\t\t\tc.constraint_type,\t\t\tu.column_name,\t\t\tcu.table_catalog AS referenced_table_catalog,\t\t\tcu.table_name AS referenced_table_name,\t\t\tcu.column_name AS referenced_column_name,\t\t\tu.ordinal_position\t\tFROM\t\t\tinformation_schema.table_constraints c\t\tINNER JOIN\t\t\tinformation_schema.key_column_usage u ON c.constraint_name = u.constraint_name\t\tINNER JOIN\t\t\tinformation_schema.constraint_column_usage cu ON cu.constraint_name = c.constraint_name\t\tWHERE\t\t\tc.table_catalog = current_database() AND c.table_schema NOT IN ('pg_catalog', 'information_schema')\t\t\t AND c.table_name = $1\t\t\tAND u.table_catalog = current_database() AND u.table_schema NOT IN ('pg_catalog', 'information_schema')\t\t\t AND u.table_name = $2`", ",", "table", ".", "Name", ",", "table", ".", "Name", ")", "\n", "if", "err", "!=", "nil", "{", "beeLogger", ".", "Log", ".", "Fatalf", "(", "\"Could not query INFORMATION_SCHEMA for PK/UK/FK information: %s\"", ",", "err", ")", "\n", "}", "\n", "for", "rows", ".", "Next", "(", ")", "{", "var", "constraintTypeBytes", ",", "columnNameBytes", ",", "refTableSchemaBytes", ",", "refTableNameBytes", ",", "refColumnNameBytes", ",", "refOrdinalPosBytes", "[", "]", "byte", "\n", "if", "err", ":=", "rows", ".", "Scan", "(", "&", "constraintTypeBytes", ",", "&", "columnNameBytes", ",", "&", "refTableSchemaBytes", ",", "&", "refTableNameBytes", ",", "&", "refColumnNameBytes", ",", "&", "refOrdinalPosBytes", ")", ";", "err", "!=", "nil", "{", "beeLogger", ".", "Log", ".", "Fatalf", "(", "\"Could not read INFORMATION_SCHEMA for PK/UK/FK information: %s\"", ",", "err", ")", "\n", "}", "\n", "constraintType", ",", "columnName", ",", "refTableSchema", ",", "refTableName", ",", "refColumnName", ",", "refOrdinalPos", ":=", "string", "(", "constraintTypeBytes", ")", ",", "string", "(", "columnNameBytes", ")", ",", "string", "(", "refTableSchemaBytes", ")", ",", "string", "(", "refTableNameBytes", ")", ",", "string", "(", "refColumnNameBytes", ")", ",", "string", "(", "refOrdinalPosBytes", ")", "\n", "if", "constraintType", "==", "\"PRIMARY KEY\"", "{", "if", "refOrdinalPos", "==", "\"1\"", "{", "table", ".", "Pk", "=", "columnName", "\n", "}", "else", "{", "table", ".", "Pk", "=", "\"\"", "\n", "blackList", "[", "table", ".", "Name", "]", "=", "true", "\n", "}", "\n", "}", "else", "if", "constraintType", "==", "\"UNIQUE\"", "{", "table", ".", "Uk", "=", "append", "(", "table", ".", "Uk", ",", "columnName", ")", "\n", "}", "else", "if", "constraintType", "==", "\"FOREIGN KEY\"", "{", "fk", ":=", "new", "(", "ForeignKey", ")", "\n", "fk", ".", "Name", "=", "columnName", "\n", "fk", ".", "RefSchema", "=", "refTableSchema", "\n", "fk", ".", "RefTable", "=", "refTableName", "\n", "fk", ".", "RefColumn", "=", "refColumnName", "\n", "table", ".", "Fk", "[", "columnName", "]", "=", "fk", "\n", "}", "\n", "}", "\n", "}" ]
// GetConstraints for PostgreSQL
[ "GetConstraints", "for", "PostgreSQL" ]
6a86284cec9a17f9aae6fe82ecf3c436aafed68d
https://github.com/beego/bee/blob/6a86284cec9a17f9aae6fe82ecf3c436aafed68d/generate/g_appcode.go#L548-L601
train
beego/bee
generate/g_appcode.go
GetGoDataType
func (*PostgresDB) GetGoDataType(sqlType string) (string, error) { if v, ok := typeMappingPostgres[sqlType]; ok { return v, nil } return "", fmt.Errorf("data type '%s' not found", sqlType) }
go
func (*PostgresDB) GetGoDataType(sqlType string) (string, error) { if v, ok := typeMappingPostgres[sqlType]; ok { return v, nil } return "", fmt.Errorf("data type '%s' not found", sqlType) }
[ "func", "(", "*", "PostgresDB", ")", "GetGoDataType", "(", "sqlType", "string", ")", "(", "string", ",", "error", ")", "{", "if", "v", ",", "ok", ":=", "typeMappingPostgres", "[", "sqlType", "]", ";", "ok", "{", "return", "v", ",", "nil", "\n", "}", "\n", "return", "\"\"", ",", "fmt", ".", "Errorf", "(", "\"data type '%s' not found\"", ",", "sqlType", ")", "\n", "}" ]
// GetGoDataType returns the Go type from the mapped Postgres type
[ "GetGoDataType", "returns", "the", "Go", "type", "from", "the", "mapped", "Postgres", "type" ]
6a86284cec9a17f9aae6fe82ecf3c436aafed68d
https://github.com/beego/bee/blob/6a86284cec9a17f9aae6fe82ecf3c436aafed68d/generate/g_appcode.go#L708-L713
train
beego/bee
generate/g_appcode.go
createPaths
func createPaths(mode byte, paths *MvcPath) { if (mode & OModel) == OModel { os.Mkdir(paths.ModelPath, 0777) } if (mode & OController) == OController { os.Mkdir(paths.ControllerPath, 0777) } if (mode & ORouter) == ORouter { os.Mkdir(paths.RouterPath, 0777) } }
go
func createPaths(mode byte, paths *MvcPath) { if (mode & OModel) == OModel { os.Mkdir(paths.ModelPath, 0777) } if (mode & OController) == OController { os.Mkdir(paths.ControllerPath, 0777) } if (mode & ORouter) == ORouter { os.Mkdir(paths.RouterPath, 0777) } }
[ "func", "createPaths", "(", "mode", "byte", ",", "paths", "*", "MvcPath", ")", "{", "if", "(", "mode", "&", "OModel", ")", "==", "OModel", "{", "os", ".", "Mkdir", "(", "paths", ".", "ModelPath", ",", "0777", ")", "\n", "}", "\n", "if", "(", "mode", "&", "OController", ")", "==", "OController", "{", "os", ".", "Mkdir", "(", "paths", ".", "ControllerPath", ",", "0777", ")", "\n", "}", "\n", "if", "(", "mode", "&", "ORouter", ")", "==", "ORouter", "{", "os", ".", "Mkdir", "(", "paths", ".", "RouterPath", ",", "0777", ")", "\n", "}", "\n", "}" ]
// deleteAndRecreatePaths removes several directories completely
[ "deleteAndRecreatePaths", "removes", "several", "directories", "completely" ]
6a86284cec9a17f9aae6fe82ecf3c436aafed68d
https://github.com/beego/bee/blob/6a86284cec9a17f9aae6fe82ecf3c436aafed68d/generate/g_appcode.go#L716-L726
train
beego/bee
generate/g_appcode.go
writeModelFiles
func writeModelFiles(tables []*Table, mPath string) { w := colors.NewColorWriter(os.Stdout) for _, tb := range tables { filename := getFileName(tb.Name) fpath := path.Join(mPath, filename+".go") var f *os.File var err error if utils.IsExist(fpath) { beeLogger.Log.Warnf("'%s' already exists. Do you want to overwrite it? [Yes|No] ", fpath) if utils.AskForConfirmation() { f, err = os.OpenFile(fpath, os.O_RDWR|os.O_TRUNC, 0666) if err != nil { beeLogger.Log.Warnf("%s", err) continue } } else { beeLogger.Log.Warnf("Skipped create file '%s'", fpath) continue } } else { f, err = os.OpenFile(fpath, os.O_CREATE|os.O_RDWR, 0666) if err != nil { beeLogger.Log.Warnf("%s", err) continue } } var template string if tb.Pk == "" { template = StructModelTPL } else { template = ModelTPL } fileStr := strings.Replace(template, "{{modelStruct}}", tb.String(), 1) fileStr = strings.Replace(fileStr, "{{modelName}}", utils.CamelCase(tb.Name), -1) fileStr = strings.Replace(fileStr, "{{tableName}}", tb.Name, -1) // If table contains time field, import time.Time package timePkg := "" importTimePkg := "" if tb.ImportTimePkg { timePkg = "\"time\"\n" importTimePkg = "import \"time\"\n" } fileStr = strings.Replace(fileStr, "{{timePkg}}", timePkg, -1) fileStr = strings.Replace(fileStr, "{{importTimePkg}}", importTimePkg, -1) if _, err := f.WriteString(fileStr); err != nil { beeLogger.Log.Fatalf("Could not write model file to '%s': %s", fpath, err) } utils.CloseFile(f) fmt.Fprintf(w, "\t%s%screate%s\t %s%s\n", "\x1b[32m", "\x1b[1m", "\x1b[21m", fpath, "\x1b[0m") utils.FormatSourceCode(fpath) } }
go
func writeModelFiles(tables []*Table, mPath string) { w := colors.NewColorWriter(os.Stdout) for _, tb := range tables { filename := getFileName(tb.Name) fpath := path.Join(mPath, filename+".go") var f *os.File var err error if utils.IsExist(fpath) { beeLogger.Log.Warnf("'%s' already exists. Do you want to overwrite it? [Yes|No] ", fpath) if utils.AskForConfirmation() { f, err = os.OpenFile(fpath, os.O_RDWR|os.O_TRUNC, 0666) if err != nil { beeLogger.Log.Warnf("%s", err) continue } } else { beeLogger.Log.Warnf("Skipped create file '%s'", fpath) continue } } else { f, err = os.OpenFile(fpath, os.O_CREATE|os.O_RDWR, 0666) if err != nil { beeLogger.Log.Warnf("%s", err) continue } } var template string if tb.Pk == "" { template = StructModelTPL } else { template = ModelTPL } fileStr := strings.Replace(template, "{{modelStruct}}", tb.String(), 1) fileStr = strings.Replace(fileStr, "{{modelName}}", utils.CamelCase(tb.Name), -1) fileStr = strings.Replace(fileStr, "{{tableName}}", tb.Name, -1) // If table contains time field, import time.Time package timePkg := "" importTimePkg := "" if tb.ImportTimePkg { timePkg = "\"time\"\n" importTimePkg = "import \"time\"\n" } fileStr = strings.Replace(fileStr, "{{timePkg}}", timePkg, -1) fileStr = strings.Replace(fileStr, "{{importTimePkg}}", importTimePkg, -1) if _, err := f.WriteString(fileStr); err != nil { beeLogger.Log.Fatalf("Could not write model file to '%s': %s", fpath, err) } utils.CloseFile(f) fmt.Fprintf(w, "\t%s%screate%s\t %s%s\n", "\x1b[32m", "\x1b[1m", "\x1b[21m", fpath, "\x1b[0m") utils.FormatSourceCode(fpath) } }
[ "func", "writeModelFiles", "(", "tables", "[", "]", "*", "Table", ",", "mPath", "string", ")", "{", "w", ":=", "colors", ".", "NewColorWriter", "(", "os", ".", "Stdout", ")", "\n", "for", "_", ",", "tb", ":=", "range", "tables", "{", "filename", ":=", "getFileName", "(", "tb", ".", "Name", ")", "\n", "fpath", ":=", "path", ".", "Join", "(", "mPath", ",", "filename", "+", "\".go\"", ")", "\n", "var", "f", "*", "os", ".", "File", "\n", "var", "err", "error", "\n", "if", "utils", ".", "IsExist", "(", "fpath", ")", "{", "beeLogger", ".", "Log", ".", "Warnf", "(", "\"'%s' already exists. Do you want to overwrite it? [Yes|No] \"", ",", "fpath", ")", "\n", "if", "utils", ".", "AskForConfirmation", "(", ")", "{", "f", ",", "err", "=", "os", ".", "OpenFile", "(", "fpath", ",", "os", ".", "O_RDWR", "|", "os", ".", "O_TRUNC", ",", "0666", ")", "\n", "if", "err", "!=", "nil", "{", "beeLogger", ".", "Log", ".", "Warnf", "(", "\"%s\"", ",", "err", ")", "\n", "continue", "\n", "}", "\n", "}", "else", "{", "beeLogger", ".", "Log", ".", "Warnf", "(", "\"Skipped create file '%s'\"", ",", "fpath", ")", "\n", "continue", "\n", "}", "\n", "}", "else", "{", "f", ",", "err", "=", "os", ".", "OpenFile", "(", "fpath", ",", "os", ".", "O_CREATE", "|", "os", ".", "O_RDWR", ",", "0666", ")", "\n", "if", "err", "!=", "nil", "{", "beeLogger", ".", "Log", ".", "Warnf", "(", "\"%s\"", ",", "err", ")", "\n", "continue", "\n", "}", "\n", "}", "\n", "var", "template", "string", "\n", "if", "tb", ".", "Pk", "==", "\"\"", "{", "template", "=", "StructModelTPL", "\n", "}", "else", "{", "template", "=", "ModelTPL", "\n", "}", "\n", "fileStr", ":=", "strings", ".", "Replace", "(", "template", ",", "\"{{modelStruct}}\"", ",", "tb", ".", "String", "(", ")", ",", "1", ")", "\n", "fileStr", "=", "strings", ".", "Replace", "(", "fileStr", ",", "\"{{modelName}}\"", ",", "utils", ".", "CamelCase", "(", "tb", ".", "Name", ")", ",", "-", "1", ")", "\n", "fileStr", "=", "strings", ".", "Replace", "(", "fileStr", ",", "\"{{tableName}}\"", ",", "tb", ".", "Name", ",", "-", "1", ")", "\n", "timePkg", ":=", "\"\"", "\n", "importTimePkg", ":=", "\"\"", "\n", "if", "tb", ".", "ImportTimePkg", "{", "timePkg", "=", "\"\\\"time\\\"\\n\"", "\n", "\\\"", "\n", "}", "\n", "\\\"", "\n", "\\n", "\n", "importTimePkg", "=", "\"import \\\"time\\\"\\n\"", "\n", "\\\"", "\n", "\\\"", "\n", "\\n", "\n", "}", "\n", "}" ]
// writeModelFiles generates model files
[ "writeModelFiles", "generates", "model", "files" ]
6a86284cec9a17f9aae6fe82ecf3c436aafed68d
https://github.com/beego/bee/blob/6a86284cec9a17f9aae6fe82ecf3c436aafed68d/generate/g_appcode.go#L747-L800
train
beego/bee
generate/g_appcode.go
writeControllerFiles
func writeControllerFiles(tables []*Table, cPath string, pkgPath string) { w := colors.NewColorWriter(os.Stdout) for _, tb := range tables { if tb.Pk == "" { continue } filename := getFileName(tb.Name) fpath := path.Join(cPath, filename+".go") var f *os.File var err error if utils.IsExist(fpath) { beeLogger.Log.Warnf("'%s' already exists. Do you want to overwrite it? [Yes|No] ", fpath) if utils.AskForConfirmation() { f, err = os.OpenFile(fpath, os.O_RDWR|os.O_TRUNC, 0666) if err != nil { beeLogger.Log.Warnf("%s", err) continue } } else { beeLogger.Log.Warnf("Skipped create file '%s'", fpath) continue } } else { f, err = os.OpenFile(fpath, os.O_CREATE|os.O_RDWR, 0666) if err != nil { beeLogger.Log.Warnf("%s", err) continue } } fileStr := strings.Replace(CtrlTPL, "{{ctrlName}}", utils.CamelCase(tb.Name), -1) fileStr = strings.Replace(fileStr, "{{pkgPath}}", pkgPath, -1) if _, err := f.WriteString(fileStr); err != nil { beeLogger.Log.Fatalf("Could not write controller file to '%s': %s", fpath, err) } utils.CloseFile(f) fmt.Fprintf(w, "\t%s%screate%s\t %s%s\n", "\x1b[32m", "\x1b[1m", "\x1b[21m", fpath, "\x1b[0m") utils.FormatSourceCode(fpath) } }
go
func writeControllerFiles(tables []*Table, cPath string, pkgPath string) { w := colors.NewColorWriter(os.Stdout) for _, tb := range tables { if tb.Pk == "" { continue } filename := getFileName(tb.Name) fpath := path.Join(cPath, filename+".go") var f *os.File var err error if utils.IsExist(fpath) { beeLogger.Log.Warnf("'%s' already exists. Do you want to overwrite it? [Yes|No] ", fpath) if utils.AskForConfirmation() { f, err = os.OpenFile(fpath, os.O_RDWR|os.O_TRUNC, 0666) if err != nil { beeLogger.Log.Warnf("%s", err) continue } } else { beeLogger.Log.Warnf("Skipped create file '%s'", fpath) continue } } else { f, err = os.OpenFile(fpath, os.O_CREATE|os.O_RDWR, 0666) if err != nil { beeLogger.Log.Warnf("%s", err) continue } } fileStr := strings.Replace(CtrlTPL, "{{ctrlName}}", utils.CamelCase(tb.Name), -1) fileStr = strings.Replace(fileStr, "{{pkgPath}}", pkgPath, -1) if _, err := f.WriteString(fileStr); err != nil { beeLogger.Log.Fatalf("Could not write controller file to '%s': %s", fpath, err) } utils.CloseFile(f) fmt.Fprintf(w, "\t%s%screate%s\t %s%s\n", "\x1b[32m", "\x1b[1m", "\x1b[21m", fpath, "\x1b[0m") utils.FormatSourceCode(fpath) } }
[ "func", "writeControllerFiles", "(", "tables", "[", "]", "*", "Table", ",", "cPath", "string", ",", "pkgPath", "string", ")", "{", "w", ":=", "colors", ".", "NewColorWriter", "(", "os", ".", "Stdout", ")", "\n", "for", "_", ",", "tb", ":=", "range", "tables", "{", "if", "tb", ".", "Pk", "==", "\"\"", "{", "continue", "\n", "}", "\n", "filename", ":=", "getFileName", "(", "tb", ".", "Name", ")", "\n", "fpath", ":=", "path", ".", "Join", "(", "cPath", ",", "filename", "+", "\".go\"", ")", "\n", "var", "f", "*", "os", ".", "File", "\n", "var", "err", "error", "\n", "if", "utils", ".", "IsExist", "(", "fpath", ")", "{", "beeLogger", ".", "Log", ".", "Warnf", "(", "\"'%s' already exists. Do you want to overwrite it? [Yes|No] \"", ",", "fpath", ")", "\n", "if", "utils", ".", "AskForConfirmation", "(", ")", "{", "f", ",", "err", "=", "os", ".", "OpenFile", "(", "fpath", ",", "os", ".", "O_RDWR", "|", "os", ".", "O_TRUNC", ",", "0666", ")", "\n", "if", "err", "!=", "nil", "{", "beeLogger", ".", "Log", ".", "Warnf", "(", "\"%s\"", ",", "err", ")", "\n", "continue", "\n", "}", "\n", "}", "else", "{", "beeLogger", ".", "Log", ".", "Warnf", "(", "\"Skipped create file '%s'\"", ",", "fpath", ")", "\n", "continue", "\n", "}", "\n", "}", "else", "{", "f", ",", "err", "=", "os", ".", "OpenFile", "(", "fpath", ",", "os", ".", "O_CREATE", "|", "os", ".", "O_RDWR", ",", "0666", ")", "\n", "if", "err", "!=", "nil", "{", "beeLogger", ".", "Log", ".", "Warnf", "(", "\"%s\"", ",", "err", ")", "\n", "continue", "\n", "}", "\n", "}", "\n", "fileStr", ":=", "strings", ".", "Replace", "(", "CtrlTPL", ",", "\"{{ctrlName}}\"", ",", "utils", ".", "CamelCase", "(", "tb", ".", "Name", ")", ",", "-", "1", ")", "\n", "fileStr", "=", "strings", ".", "Replace", "(", "fileStr", ",", "\"{{pkgPath}}\"", ",", "pkgPath", ",", "-", "1", ")", "\n", "if", "_", ",", "err", ":=", "f", ".", "WriteString", "(", "fileStr", ")", ";", "err", "!=", "nil", "{", "beeLogger", ".", "Log", ".", "Fatalf", "(", "\"Could not write controller file to '%s': %s\"", ",", "fpath", ",", "err", ")", "\n", "}", "\n", "utils", ".", "CloseFile", "(", "f", ")", "\n", "fmt", ".", "Fprintf", "(", "w", ",", "\"\\t%s%screate%s\\t %s%s\\n\"", ",", "\\t", ",", "\\t", ",", "\\n", ",", "\"\\x1b[32m\"", ",", "\\x1b", ")", "\n", "\"\\x1b[1m\"", "\n", "}", "\n", "}" ]
// writeControllerFiles generates controller files
[ "writeControllerFiles", "generates", "controller", "files" ]
6a86284cec9a17f9aae6fe82ecf3c436aafed68d
https://github.com/beego/bee/blob/6a86284cec9a17f9aae6fe82ecf3c436aafed68d/generate/g_appcode.go#L803-L842
train
beego/bee
generate/g_appcode.go
writeRouterFile
func writeRouterFile(tables []*Table, rPath string, pkgPath string) { w := colors.NewColorWriter(os.Stdout) var nameSpaces []string for _, tb := range tables { if tb.Pk == "" { continue } // Add namespaces nameSpace := strings.Replace(NamespaceTPL, "{{nameSpace}}", tb.Name, -1) nameSpace = strings.Replace(nameSpace, "{{ctrlName}}", utils.CamelCase(tb.Name), -1) nameSpaces = append(nameSpaces, nameSpace) } // Add export controller fpath := filepath.Join(rPath, "router.go") routerStr := strings.Replace(RouterTPL, "{{nameSpaces}}", strings.Join(nameSpaces, ""), 1) routerStr = strings.Replace(routerStr, "{{pkgPath}}", pkgPath, 1) var f *os.File var err error if utils.IsExist(fpath) { beeLogger.Log.Warnf("'%s' already exists. Do you want to overwrite it? [Yes|No] ", fpath) if utils.AskForConfirmation() { f, err = os.OpenFile(fpath, os.O_RDWR|os.O_TRUNC, 0666) if err != nil { beeLogger.Log.Warnf("%s", err) return } } else { beeLogger.Log.Warnf("Skipped create file '%s'", fpath) return } } else { f, err = os.OpenFile(fpath, os.O_CREATE|os.O_RDWR, 0666) if err != nil { beeLogger.Log.Warnf("%s", err) return } } if _, err := f.WriteString(routerStr); err != nil { beeLogger.Log.Fatalf("Could not write router file to '%s': %s", fpath, err) } utils.CloseFile(f) fmt.Fprintf(w, "\t%s%screate%s\t %s%s\n", "\x1b[32m", "\x1b[1m", "\x1b[21m", fpath, "\x1b[0m") utils.FormatSourceCode(fpath) }
go
func writeRouterFile(tables []*Table, rPath string, pkgPath string) { w := colors.NewColorWriter(os.Stdout) var nameSpaces []string for _, tb := range tables { if tb.Pk == "" { continue } // Add namespaces nameSpace := strings.Replace(NamespaceTPL, "{{nameSpace}}", tb.Name, -1) nameSpace = strings.Replace(nameSpace, "{{ctrlName}}", utils.CamelCase(tb.Name), -1) nameSpaces = append(nameSpaces, nameSpace) } // Add export controller fpath := filepath.Join(rPath, "router.go") routerStr := strings.Replace(RouterTPL, "{{nameSpaces}}", strings.Join(nameSpaces, ""), 1) routerStr = strings.Replace(routerStr, "{{pkgPath}}", pkgPath, 1) var f *os.File var err error if utils.IsExist(fpath) { beeLogger.Log.Warnf("'%s' already exists. Do you want to overwrite it? [Yes|No] ", fpath) if utils.AskForConfirmation() { f, err = os.OpenFile(fpath, os.O_RDWR|os.O_TRUNC, 0666) if err != nil { beeLogger.Log.Warnf("%s", err) return } } else { beeLogger.Log.Warnf("Skipped create file '%s'", fpath) return } } else { f, err = os.OpenFile(fpath, os.O_CREATE|os.O_RDWR, 0666) if err != nil { beeLogger.Log.Warnf("%s", err) return } } if _, err := f.WriteString(routerStr); err != nil { beeLogger.Log.Fatalf("Could not write router file to '%s': %s", fpath, err) } utils.CloseFile(f) fmt.Fprintf(w, "\t%s%screate%s\t %s%s\n", "\x1b[32m", "\x1b[1m", "\x1b[21m", fpath, "\x1b[0m") utils.FormatSourceCode(fpath) }
[ "func", "writeRouterFile", "(", "tables", "[", "]", "*", "Table", ",", "rPath", "string", ",", "pkgPath", "string", ")", "{", "w", ":=", "colors", ".", "NewColorWriter", "(", "os", ".", "Stdout", ")", "\n", "var", "nameSpaces", "[", "]", "string", "\n", "for", "_", ",", "tb", ":=", "range", "tables", "{", "if", "tb", ".", "Pk", "==", "\"\"", "{", "continue", "\n", "}", "\n", "nameSpace", ":=", "strings", ".", "Replace", "(", "NamespaceTPL", ",", "\"{{nameSpace}}\"", ",", "tb", ".", "Name", ",", "-", "1", ")", "\n", "nameSpace", "=", "strings", ".", "Replace", "(", "nameSpace", ",", "\"{{ctrlName}}\"", ",", "utils", ".", "CamelCase", "(", "tb", ".", "Name", ")", ",", "-", "1", ")", "\n", "nameSpaces", "=", "append", "(", "nameSpaces", ",", "nameSpace", ")", "\n", "}", "\n", "fpath", ":=", "filepath", ".", "Join", "(", "rPath", ",", "\"router.go\"", ")", "\n", "routerStr", ":=", "strings", ".", "Replace", "(", "RouterTPL", ",", "\"{{nameSpaces}}\"", ",", "strings", ".", "Join", "(", "nameSpaces", ",", "\"\"", ")", ",", "1", ")", "\n", "routerStr", "=", "strings", ".", "Replace", "(", "routerStr", ",", "\"{{pkgPath}}\"", ",", "pkgPath", ",", "1", ")", "\n", "var", "f", "*", "os", ".", "File", "\n", "var", "err", "error", "\n", "if", "utils", ".", "IsExist", "(", "fpath", ")", "{", "beeLogger", ".", "Log", ".", "Warnf", "(", "\"'%s' already exists. Do you want to overwrite it? [Yes|No] \"", ",", "fpath", ")", "\n", "if", "utils", ".", "AskForConfirmation", "(", ")", "{", "f", ",", "err", "=", "os", ".", "OpenFile", "(", "fpath", ",", "os", ".", "O_RDWR", "|", "os", ".", "O_TRUNC", ",", "0666", ")", "\n", "if", "err", "!=", "nil", "{", "beeLogger", ".", "Log", ".", "Warnf", "(", "\"%s\"", ",", "err", ")", "\n", "return", "\n", "}", "\n", "}", "else", "{", "beeLogger", ".", "Log", ".", "Warnf", "(", "\"Skipped create file '%s'\"", ",", "fpath", ")", "\n", "return", "\n", "}", "\n", "}", "else", "{", "f", ",", "err", "=", "os", ".", "OpenFile", "(", "fpath", ",", "os", ".", "O_CREATE", "|", "os", ".", "O_RDWR", ",", "0666", ")", "\n", "if", "err", "!=", "nil", "{", "beeLogger", ".", "Log", ".", "Warnf", "(", "\"%s\"", ",", "err", ")", "\n", "return", "\n", "}", "\n", "}", "\n", "if", "_", ",", "err", ":=", "f", ".", "WriteString", "(", "routerStr", ")", ";", "err", "!=", "nil", "{", "beeLogger", ".", "Log", ".", "Fatalf", "(", "\"Could not write router file to '%s': %s\"", ",", "fpath", ",", "err", ")", "\n", "}", "\n", "utils", ".", "CloseFile", "(", "f", ")", "\n", "fmt", ".", "Fprintf", "(", "w", ",", "\"\\t%s%screate%s\\t %s%s\\n\"", ",", "\\t", ",", "\\t", ",", "\\n", ",", "\"\\x1b[32m\"", ",", "\\x1b", ")", "\n", "\"\\x1b[1m\"", "\n", "}" ]
// writeRouterFile generates router file
[ "writeRouterFile", "generates", "router", "file" ]
6a86284cec9a17f9aae6fe82ecf3c436aafed68d
https://github.com/beego/bee/blob/6a86284cec9a17f9aae6fe82ecf3c436aafed68d/generate/g_appcode.go#L845-L889
train
beego/bee
cmd/commands/version/banner.go
InitBanner
func InitBanner(out io.Writer, in io.Reader) { if in == nil { beeLogger.Log.Fatal("The input is nil") } banner, err := ioutil.ReadAll(in) if err != nil { beeLogger.Log.Fatalf("Error while trying to read the banner: %s", err) } show(out, string(banner)) }
go
func InitBanner(out io.Writer, in io.Reader) { if in == nil { beeLogger.Log.Fatal("The input is nil") } banner, err := ioutil.ReadAll(in) if err != nil { beeLogger.Log.Fatalf("Error while trying to read the banner: %s", err) } show(out, string(banner)) }
[ "func", "InitBanner", "(", "out", "io", ".", "Writer", ",", "in", "io", ".", "Reader", ")", "{", "if", "in", "==", "nil", "{", "beeLogger", ".", "Log", ".", "Fatal", "(", "\"The input is nil\"", ")", "\n", "}", "\n", "banner", ",", "err", ":=", "ioutil", ".", "ReadAll", "(", "in", ")", "\n", "if", "err", "!=", "nil", "{", "beeLogger", ".", "Log", ".", "Fatalf", "(", "\"Error while trying to read the banner: %s\"", ",", "err", ")", "\n", "}", "\n", "show", "(", "out", ",", "string", "(", "banner", ")", ")", "\n", "}" ]
// InitBanner loads the banner and prints it to output // All errors are ignored, the application will not // print the banner in case of error.
[ "InitBanner", "loads", "the", "banner", "and", "prints", "it", "to", "output", "All", "errors", "are", "ignored", "the", "application", "will", "not", "print", "the", "banner", "in", "case", "of", "error", "." ]
6a86284cec9a17f9aae6fe82ecf3c436aafed68d
https://github.com/beego/bee/blob/6a86284cec9a17f9aae6fe82ecf3c436aafed68d/cmd/commands/version/banner.go#L31-L42
train
beego/bee
cmd/commands/command.go
Out
func (c *Command) Out() io.Writer { if c.output != nil { return *c.output } return colors.NewColorWriter(os.Stderr) }
go
func (c *Command) Out() io.Writer { if c.output != nil { return *c.output } return colors.NewColorWriter(os.Stderr) }
[ "func", "(", "c", "*", "Command", ")", "Out", "(", ")", "io", ".", "Writer", "{", "if", "c", ".", "output", "!=", "nil", "{", "return", "*", "c", ".", "output", "\n", "}", "\n", "return", "colors", ".", "NewColorWriter", "(", "os", ".", "Stderr", ")", "\n", "}" ]
// Out returns the out writer of the current command. // If cmd.output is nil, os.Stderr is used.
[ "Out", "returns", "the", "out", "writer", "of", "the", "current", "command", ".", "If", "cmd", ".", "output", "is", "nil", "os", ".", "Stderr", "is", "used", "." ]
6a86284cec9a17f9aae6fe82ecf3c436aafed68d
https://github.com/beego/bee/blob/6a86284cec9a17f9aae6fe82ecf3c436aafed68d/cmd/commands/command.go#L64-L69
train
beego/bee
cmd/commands/run/reload.go
readPump
func (c *wsClient) readPump() { defer func() { c.broker.unregister <- c c.conn.Close() }() for { _, _, err := c.conn.ReadMessage() if err != nil { if websocket.IsUnexpectedCloseError(err, websocket.CloseGoingAway) { beeLogger.Log.Errorf("An error happened when reading from the Websocket client: %v", err) } break } } }
go
func (c *wsClient) readPump() { defer func() { c.broker.unregister <- c c.conn.Close() }() for { _, _, err := c.conn.ReadMessage() if err != nil { if websocket.IsUnexpectedCloseError(err, websocket.CloseGoingAway) { beeLogger.Log.Errorf("An error happened when reading from the Websocket client: %v", err) } break } } }
[ "func", "(", "c", "*", "wsClient", ")", "readPump", "(", ")", "{", "defer", "func", "(", ")", "{", "c", ".", "broker", ".", "unregister", "<-", "c", "\n", "c", ".", "conn", ".", "Close", "(", ")", "\n", "}", "(", ")", "\n", "for", "{", "_", ",", "_", ",", "err", ":=", "c", ".", "conn", ".", "ReadMessage", "(", ")", "\n", "if", "err", "!=", "nil", "{", "if", "websocket", ".", "IsUnexpectedCloseError", "(", "err", ",", "websocket", ".", "CloseGoingAway", ")", "{", "beeLogger", ".", "Log", ".", "Errorf", "(", "\"An error happened when reading from the Websocket client: %v\"", ",", "err", ")", "\n", "}", "\n", "break", "\n", "}", "\n", "}", "\n", "}" ]
// readPump pumps messages from the websocket connection to the broker.
[ "readPump", "pumps", "messages", "from", "the", "websocket", "connection", "to", "the", "broker", "." ]
6a86284cec9a17f9aae6fe82ecf3c436aafed68d
https://github.com/beego/bee/blob/6a86284cec9a17f9aae6fe82ecf3c436aafed68d/cmd/commands/run/reload.go#L64-L79
train
beego/bee
cmd/commands/run/reload.go
handleWsRequest
func handleWsRequest(broker *wsBroker, w http.ResponseWriter, r *http.Request) { conn, err := upgrader.Upgrade(w, r, nil) if err != nil { beeLogger.Log.Errorf("error while upgrading server connection: %v", err) return } client := &wsClient{ broker: broker, conn: conn, send: make(chan []byte, 256), } client.broker.register <- client go client.writePump() client.readPump() }
go
func handleWsRequest(broker *wsBroker, w http.ResponseWriter, r *http.Request) { conn, err := upgrader.Upgrade(w, r, nil) if err != nil { beeLogger.Log.Errorf("error while upgrading server connection: %v", err) return } client := &wsClient{ broker: broker, conn: conn, send: make(chan []byte, 256), } client.broker.register <- client go client.writePump() client.readPump() }
[ "func", "handleWsRequest", "(", "broker", "*", "wsBroker", ",", "w", "http", ".", "ResponseWriter", ",", "r", "*", "http", ".", "Request", ")", "{", "conn", ",", "err", ":=", "upgrader", ".", "Upgrade", "(", "w", ",", "r", ",", "nil", ")", "\n", "if", "err", "!=", "nil", "{", "beeLogger", ".", "Log", ".", "Errorf", "(", "\"error while upgrading server connection: %v\"", ",", "err", ")", "\n", "return", "\n", "}", "\n", "client", ":=", "&", "wsClient", "{", "broker", ":", "broker", ",", "conn", ":", "conn", ",", "send", ":", "make", "(", "chan", "[", "]", "byte", ",", "256", ")", ",", "}", "\n", "client", ".", "broker", ".", "register", "<-", "client", "\n", "go", "client", ".", "writePump", "(", ")", "\n", "client", ".", "readPump", "(", ")", "\n", "}" ]
// handleWsRequest handles websocket requests from the peer.
[ "handleWsRequest", "handles", "websocket", "requests", "from", "the", "peer", "." ]
6a86284cec9a17f9aae6fe82ecf3c436aafed68d
https://github.com/beego/bee/blob/6a86284cec9a17f9aae6fe82ecf3c436aafed68d/cmd/commands/run/reload.go#L176-L192
train
beego/bee
config/conf.go
LoadConfig
func LoadConfig() { currentPath, err := os.Getwd() if err != nil { beeLogger.Log.Error(err.Error()) } dir, err := os.Open(currentPath) if err != nil { beeLogger.Log.Error(err.Error()) } defer dir.Close() files, err := dir.Readdir(-1) if err != nil { beeLogger.Log.Error(err.Error()) } for _, file := range files { switch file.Name() { case "bee.json": { err = parseJSON(filepath.Join(currentPath, file.Name()), &Conf) if err != nil { beeLogger.Log.Errorf("Failed to parse JSON file: %s", err) } break } case "Beefile": { err = parseYAML(filepath.Join(currentPath, file.Name()), &Conf) if err != nil { beeLogger.Log.Errorf("Failed to parse YAML file: %s", err) } break } } } // Check format version if Conf.Version != confVer { beeLogger.Log.Warn("Your configuration file is outdated. Please do consider updating it.") beeLogger.Log.Hint("Check the latest version of bee's configuration file.") } // Set variables if len(Conf.DirStruct.Controllers) == 0 { Conf.DirStruct.Controllers = "controllers" } if len(Conf.DirStruct.Models) == 0 { Conf.DirStruct.Models = "models" } }
go
func LoadConfig() { currentPath, err := os.Getwd() if err != nil { beeLogger.Log.Error(err.Error()) } dir, err := os.Open(currentPath) if err != nil { beeLogger.Log.Error(err.Error()) } defer dir.Close() files, err := dir.Readdir(-1) if err != nil { beeLogger.Log.Error(err.Error()) } for _, file := range files { switch file.Name() { case "bee.json": { err = parseJSON(filepath.Join(currentPath, file.Name()), &Conf) if err != nil { beeLogger.Log.Errorf("Failed to parse JSON file: %s", err) } break } case "Beefile": { err = parseYAML(filepath.Join(currentPath, file.Name()), &Conf) if err != nil { beeLogger.Log.Errorf("Failed to parse YAML file: %s", err) } break } } } // Check format version if Conf.Version != confVer { beeLogger.Log.Warn("Your configuration file is outdated. Please do consider updating it.") beeLogger.Log.Hint("Check the latest version of bee's configuration file.") } // Set variables if len(Conf.DirStruct.Controllers) == 0 { Conf.DirStruct.Controllers = "controllers" } if len(Conf.DirStruct.Models) == 0 { Conf.DirStruct.Models = "models" } }
[ "func", "LoadConfig", "(", ")", "{", "currentPath", ",", "err", ":=", "os", ".", "Getwd", "(", ")", "\n", "if", "err", "!=", "nil", "{", "beeLogger", ".", "Log", ".", "Error", "(", "err", ".", "Error", "(", ")", ")", "\n", "}", "\n", "dir", ",", "err", ":=", "os", ".", "Open", "(", "currentPath", ")", "\n", "if", "err", "!=", "nil", "{", "beeLogger", ".", "Log", ".", "Error", "(", "err", ".", "Error", "(", ")", ")", "\n", "}", "\n", "defer", "dir", ".", "Close", "(", ")", "\n", "files", ",", "err", ":=", "dir", ".", "Readdir", "(", "-", "1", ")", "\n", "if", "err", "!=", "nil", "{", "beeLogger", ".", "Log", ".", "Error", "(", "err", ".", "Error", "(", ")", ")", "\n", "}", "\n", "for", "_", ",", "file", ":=", "range", "files", "{", "switch", "file", ".", "Name", "(", ")", "{", "case", "\"bee.json\"", ":", "{", "err", "=", "parseJSON", "(", "filepath", ".", "Join", "(", "currentPath", ",", "file", ".", "Name", "(", ")", ")", ",", "&", "Conf", ")", "\n", "if", "err", "!=", "nil", "{", "beeLogger", ".", "Log", ".", "Errorf", "(", "\"Failed to parse JSON file: %s\"", ",", "err", ")", "\n", "}", "\n", "break", "\n", "}", "\n", "case", "\"Beefile\"", ":", "{", "err", "=", "parseYAML", "(", "filepath", ".", "Join", "(", "currentPath", ",", "file", ".", "Name", "(", ")", ")", ",", "&", "Conf", ")", "\n", "if", "err", "!=", "nil", "{", "beeLogger", ".", "Log", ".", "Errorf", "(", "\"Failed to parse YAML file: %s\"", ",", "err", ")", "\n", "}", "\n", "break", "\n", "}", "\n", "}", "\n", "}", "\n", "if", "Conf", ".", "Version", "!=", "confVer", "{", "beeLogger", ".", "Log", ".", "Warn", "(", "\"Your configuration file is outdated. Please do consider updating it.\"", ")", "\n", "beeLogger", ".", "Log", ".", "Hint", "(", "\"Check the latest version of bee's configuration file.\"", ")", "\n", "}", "\n", "if", "len", "(", "Conf", ".", "DirStruct", ".", "Controllers", ")", "==", "0", "{", "Conf", ".", "DirStruct", ".", "Controllers", "=", "\"controllers\"", "\n", "}", "\n", "if", "len", "(", "Conf", ".", "DirStruct", ".", "Models", ")", "==", "0", "{", "Conf", ".", "DirStruct", ".", "Models", "=", "\"models\"", "\n", "}", "\n", "}" ]
// LoadConfig loads the bee tool configuration. // It looks for Beefile or bee.json in the current path, // and falls back to default configuration in case not found.
[ "LoadConfig", "loads", "the", "bee", "tool", "configuration", ".", "It", "looks", "for", "Beefile", "or", "bee", ".", "json", "in", "the", "current", "path", "and", "falls", "back", "to", "default", "configuration", "in", "case", "not", "found", "." ]
6a86284cec9a17f9aae6fe82ecf3c436aafed68d
https://github.com/beego/bee/blob/6a86284cec9a17f9aae6fe82ecf3c436aafed68d/config/conf.go#L86-L138
train
beego/bee
utils/utils.go
IsInGOPATH
func IsInGOPATH(thePath string) bool { for _, gopath := range GetGOPATHs() { if strings.Contains(thePath, filepath.Join(gopath, "src")) { return true } } return false }
go
func IsInGOPATH(thePath string) bool { for _, gopath := range GetGOPATHs() { if strings.Contains(thePath, filepath.Join(gopath, "src")) { return true } } return false }
[ "func", "IsInGOPATH", "(", "thePath", "string", ")", "bool", "{", "for", "_", ",", "gopath", ":=", "range", "GetGOPATHs", "(", ")", "{", "if", "strings", ".", "Contains", "(", "thePath", ",", "filepath", ".", "Join", "(", "gopath", ",", "\"src\"", ")", ")", "{", "return", "true", "\n", "}", "\n", "}", "\n", "return", "false", "\n", "}" ]
// IsInGOPATH checks whether the path is inside of any GOPATH or not
[ "IsInGOPATH", "checks", "whether", "the", "path", "is", "inside", "of", "any", "GOPATH", "or", "not" ]
6a86284cec9a17f9aae6fe82ecf3c436aafed68d
https://github.com/beego/bee/blob/6a86284cec9a17f9aae6fe82ecf3c436aafed68d/utils/utils.go#L62-L69
train
beego/bee
utils/utils.go
IsBeegoProject
func IsBeegoProject(thePath string) bool { mainFiles := []string{} hasBeegoRegex := regexp.MustCompile(`(?s)package main.*?import.*?\(.*?github.com/astaxie/beego".*?\).*func main()`) c := make(chan error) // Walk the application path tree to look for main files. // Main files must satisfy the 'hasBeegoRegex' regular expression. go func() { filepath.Walk(thePath, func(fpath string, f os.FileInfo, err error) error { if err != nil { return nil } // Skip sub-directories if !f.IsDir() { var data []byte data, err = ioutil.ReadFile(fpath) if err != nil { c <- err return nil } if len(hasBeegoRegex.Find(data)) > 0 { mainFiles = append(mainFiles, fpath) } } return nil }) close(c) }() if err := <-c; err != nil { beeLogger.Log.Fatalf("Unable to walk '%s' tree: %s", thePath, err) } if len(mainFiles) > 0 { return true } return false }
go
func IsBeegoProject(thePath string) bool { mainFiles := []string{} hasBeegoRegex := regexp.MustCompile(`(?s)package main.*?import.*?\(.*?github.com/astaxie/beego".*?\).*func main()`) c := make(chan error) // Walk the application path tree to look for main files. // Main files must satisfy the 'hasBeegoRegex' regular expression. go func() { filepath.Walk(thePath, func(fpath string, f os.FileInfo, err error) error { if err != nil { return nil } // Skip sub-directories if !f.IsDir() { var data []byte data, err = ioutil.ReadFile(fpath) if err != nil { c <- err return nil } if len(hasBeegoRegex.Find(data)) > 0 { mainFiles = append(mainFiles, fpath) } } return nil }) close(c) }() if err := <-c; err != nil { beeLogger.Log.Fatalf("Unable to walk '%s' tree: %s", thePath, err) } if len(mainFiles) > 0 { return true } return false }
[ "func", "IsBeegoProject", "(", "thePath", "string", ")", "bool", "{", "mainFiles", ":=", "[", "]", "string", "{", "}", "\n", "hasBeegoRegex", ":=", "regexp", ".", "MustCompile", "(", "`(?s)package main.*?import.*?\\(.*?github.com/astaxie/beego\".*?\\).*func main()`", ")", "\n", "c", ":=", "make", "(", "chan", "error", ")", "\n", "go", "func", "(", ")", "{", "filepath", ".", "Walk", "(", "thePath", ",", "func", "(", "fpath", "string", ",", "f", "os", ".", "FileInfo", ",", "err", "error", ")", "error", "{", "if", "err", "!=", "nil", "{", "return", "nil", "\n", "}", "\n", "if", "!", "f", ".", "IsDir", "(", ")", "{", "var", "data", "[", "]", "byte", "\n", "data", ",", "err", "=", "ioutil", ".", "ReadFile", "(", "fpath", ")", "\n", "if", "err", "!=", "nil", "{", "c", "<-", "err", "\n", "return", "nil", "\n", "}", "\n", "if", "len", "(", "hasBeegoRegex", ".", "Find", "(", "data", ")", ")", ">", "0", "{", "mainFiles", "=", "append", "(", "mainFiles", ",", "fpath", ")", "\n", "}", "\n", "}", "\n", "return", "nil", "\n", "}", ")", "\n", "close", "(", "c", ")", "\n", "}", "(", ")", "\n", "if", "err", ":=", "<-", "c", ";", "err", "!=", "nil", "{", "beeLogger", ".", "Log", ".", "Fatalf", "(", "\"Unable to walk '%s' tree: %s\"", ",", "thePath", ",", "err", ")", "\n", "}", "\n", "if", "len", "(", "mainFiles", ")", ">", "0", "{", "return", "true", "\n", "}", "\n", "return", "false", "\n", "}" ]
// IsBeegoProject checks whether the current path is a Beego application or not
[ "IsBeegoProject", "checks", "whether", "the", "current", "path", "is", "a", "Beego", "application", "or", "not" ]
6a86284cec9a17f9aae6fe82ecf3c436aafed68d
https://github.com/beego/bee/blob/6a86284cec9a17f9aae6fe82ecf3c436aafed68d/utils/utils.go#L72-L109
train
beego/bee
utils/utils.go
SnakeString
func SnakeString(s string) string { data := make([]byte, 0, len(s)*2) j := false num := len(s) for i := 0; i < num; i++ { d := s[i] if i > 0 && d >= 'A' && d <= 'Z' && j { data = append(data, '_') } if d != '_' { j = true } data = append(data, d) } return strings.ToLower(string(data[:])) }
go
func SnakeString(s string) string { data := make([]byte, 0, len(s)*2) j := false num := len(s) for i := 0; i < num; i++ { d := s[i] if i > 0 && d >= 'A' && d <= 'Z' && j { data = append(data, '_') } if d != '_' { j = true } data = append(data, d) } return strings.ToLower(string(data[:])) }
[ "func", "SnakeString", "(", "s", "string", ")", "string", "{", "data", ":=", "make", "(", "[", "]", "byte", ",", "0", ",", "len", "(", "s", ")", "*", "2", ")", "\n", "j", ":=", "false", "\n", "num", ":=", "len", "(", "s", ")", "\n", "for", "i", ":=", "0", ";", "i", "<", "num", ";", "i", "++", "{", "d", ":=", "s", "[", "i", "]", "\n", "if", "i", ">", "0", "&&", "d", ">=", "'A'", "&&", "d", "<=", "'Z'", "&&", "j", "{", "data", "=", "append", "(", "data", ",", "'_'", ")", "\n", "}", "\n", "if", "d", "!=", "'_'", "{", "j", "=", "true", "\n", "}", "\n", "data", "=", "append", "(", "data", ",", "d", ")", "\n", "}", "\n", "return", "strings", ".", "ToLower", "(", "string", "(", "data", "[", ":", "]", ")", ")", "\n", "}" ]
// snake string, XxYy to xx_yy
[ "snake", "string", "XxYy", "to", "xx_yy" ]
6a86284cec9a17f9aae6fe82ecf3c436aafed68d
https://github.com/beego/bee/blob/6a86284cec9a17f9aae6fe82ecf3c436aafed68d/utils/utils.go#L170-L185
train
beego/bee
utils/utils.go
FormatSourceCode
func FormatSourceCode(filename string) { cmd := exec.Command("gofmt", "-w", filename) if err := cmd.Run(); err != nil { beeLogger.Log.Warnf("Error while running gofmt: %s", err) } }
go
func FormatSourceCode(filename string) { cmd := exec.Command("gofmt", "-w", filename) if err := cmd.Run(); err != nil { beeLogger.Log.Warnf("Error while running gofmt: %s", err) } }
[ "func", "FormatSourceCode", "(", "filename", "string", ")", "{", "cmd", ":=", "exec", ".", "Command", "(", "\"gofmt\"", ",", "\"-w\"", ",", "filename", ")", "\n", "if", "err", ":=", "cmd", ".", "Run", "(", ")", ";", "err", "!=", "nil", "{", "beeLogger", ".", "Log", ".", "Warnf", "(", "\"Error while running gofmt: %s\"", ",", "err", ")", "\n", "}", "\n", "}" ]
// formatSourceCode formats source files
[ "formatSourceCode", "formats", "source", "files" ]
6a86284cec9a17f9aae6fe82ecf3c436aafed68d
https://github.com/beego/bee/blob/6a86284cec9a17f9aae6fe82ecf3c436aafed68d/utils/utils.go#L222-L227
train
beego/bee
utils/utils.go
WriteToFile
func WriteToFile(filename, content string) { f, err := os.Create(filename) MustCheck(err) defer CloseFile(f) _, err = f.WriteString(content) MustCheck(err) }
go
func WriteToFile(filename, content string) { f, err := os.Create(filename) MustCheck(err) defer CloseFile(f) _, err = f.WriteString(content) MustCheck(err) }
[ "func", "WriteToFile", "(", "filename", ",", "content", "string", ")", "{", "f", ",", "err", ":=", "os", ".", "Create", "(", "filename", ")", "\n", "MustCheck", "(", "err", ")", "\n", "defer", "CloseFile", "(", "f", ")", "\n", "_", ",", "err", "=", "f", ".", "WriteString", "(", "content", ")", "\n", "MustCheck", "(", "err", ")", "\n", "}" ]
// WriteToFile creates a file and writes content to it
[ "WriteToFile", "creates", "a", "file", "and", "writes", "content", "to", "it" ]
6a86284cec9a17f9aae6fe82ecf3c436aafed68d
https://github.com/beego/bee/blob/6a86284cec9a17f9aae6fe82ecf3c436aafed68d/utils/utils.go#L244-L250
train
beego/bee
utils/utils.go
BeeFuncMap
func BeeFuncMap() template.FuncMap { return template.FuncMap{ "trim": strings.TrimSpace, "bold": colors.Bold, "headline": colors.MagentaBold, "foldername": colors.RedBold, "endline": EndLine, "tmpltostr": TmplToString, } }
go
func BeeFuncMap() template.FuncMap { return template.FuncMap{ "trim": strings.TrimSpace, "bold": colors.Bold, "headline": colors.MagentaBold, "foldername": colors.RedBold, "endline": EndLine, "tmpltostr": TmplToString, } }
[ "func", "BeeFuncMap", "(", ")", "template", ".", "FuncMap", "{", "return", "template", ".", "FuncMap", "{", "\"trim\"", ":", "strings", ".", "TrimSpace", ",", "\"bold\"", ":", "colors", ".", "Bold", ",", "\"headline\"", ":", "colors", ".", "MagentaBold", ",", "\"foldername\"", ":", "colors", ".", "RedBold", ",", "\"endline\"", ":", "EndLine", ",", "\"tmpltostr\"", ":", "TmplToString", ",", "}", "\n", "}" ]
// BeeFuncMap returns a FuncMap of functions used in different templates.
[ "BeeFuncMap", "returns", "a", "FuncMap", "of", "functions", "used", "in", "different", "templates", "." ]
6a86284cec9a17f9aae6fe82ecf3c436aafed68d
https://github.com/beego/bee/blob/6a86284cec9a17f9aae6fe82ecf3c436aafed68d/utils/utils.go#L265-L274
train
beego/bee
utils/utils.go
TmplToString
func TmplToString(tmpl string, data interface{}) string { t := template.New("tmpl").Funcs(BeeFuncMap()) template.Must(t.Parse(tmpl)) var doc bytes.Buffer err := t.Execute(&doc, data) MustCheck(err) return doc.String() }
go
func TmplToString(tmpl string, data interface{}) string { t := template.New("tmpl").Funcs(BeeFuncMap()) template.Must(t.Parse(tmpl)) var doc bytes.Buffer err := t.Execute(&doc, data) MustCheck(err) return doc.String() }
[ "func", "TmplToString", "(", "tmpl", "string", ",", "data", "interface", "{", "}", ")", "string", "{", "t", ":=", "template", ".", "New", "(", "\"tmpl\"", ")", ".", "Funcs", "(", "BeeFuncMap", "(", ")", ")", "\n", "template", ".", "Must", "(", "t", ".", "Parse", "(", "tmpl", ")", ")", "\n", "var", "doc", "bytes", ".", "Buffer", "\n", "err", ":=", "t", ".", "Execute", "(", "&", "doc", ",", "data", ")", "\n", "MustCheck", "(", "err", ")", "\n", "return", "doc", ".", "String", "(", ")", "\n", "}" ]
// TmplToString parses a text template and return the result as a string.
[ "TmplToString", "parses", "a", "text", "template", "and", "return", "the", "result", "as", "a", "string", "." ]
6a86284cec9a17f9aae6fe82ecf3c436aafed68d
https://github.com/beego/bee/blob/6a86284cec9a17f9aae6fe82ecf3c436aafed68d/utils/utils.go#L277-L286
train
beego/bee
utils/utils.go
GetFileModTime
func GetFileModTime(path string) int64 { path = strings.Replace(path, "\\", "/", -1) f, err := os.Open(path) if err != nil { beeLogger.Log.Errorf("Failed to open file on '%s': %s", path, err) return time.Now().Unix() } defer f.Close() fi, err := f.Stat() if err != nil { beeLogger.Log.Errorf("Failed to get file stats: %s", err) return time.Now().Unix() } return fi.ModTime().Unix() }
go
func GetFileModTime(path string) int64 { path = strings.Replace(path, "\\", "/", -1) f, err := os.Open(path) if err != nil { beeLogger.Log.Errorf("Failed to open file on '%s': %s", path, err) return time.Now().Unix() } defer f.Close() fi, err := f.Stat() if err != nil { beeLogger.Log.Errorf("Failed to get file stats: %s", err) return time.Now().Unix() } return fi.ModTime().Unix() }
[ "func", "GetFileModTime", "(", "path", "string", ")", "int64", "{", "path", "=", "strings", ".", "Replace", "(", "path", ",", "\"\\\\\"", ",", "\\\\", ",", "\"/\"", ")", "\n", "-", "1", "\n", "f", ",", "err", ":=", "os", ".", "Open", "(", "path", ")", "\n", "if", "err", "!=", "nil", "{", "beeLogger", ".", "Log", ".", "Errorf", "(", "\"Failed to open file on '%s': %s\"", ",", "path", ",", "err", ")", "\n", "return", "time", ".", "Now", "(", ")", ".", "Unix", "(", ")", "\n", "}", "\n", "defer", "f", ".", "Close", "(", ")", "\n", "fi", ",", "err", ":=", "f", ".", "Stat", "(", ")", "\n", "if", "err", "!=", "nil", "{", "beeLogger", ".", "Log", ".", "Errorf", "(", "\"Failed to get file stats: %s\"", ",", "err", ")", "\n", "return", "time", ".", "Now", "(", ")", ".", "Unix", "(", ")", "\n", "}", "\n", "}" ]
// GetFileModTime returns unix timestamp of `os.File.ModTime` for the given path.
[ "GetFileModTime", "returns", "unix", "timestamp", "of", "os", ".", "File", ".", "ModTime", "for", "the", "given", "path", "." ]
6a86284cec9a17f9aae6fe82ecf3c436aafed68d
https://github.com/beego/bee/blob/6a86284cec9a17f9aae6fe82ecf3c436aafed68d/utils/utils.go#L411-L427
train
beego/bee
cmd/commands/migrate/migrate.go
RunMigration
func RunMigration(cmd *commands.Command, args []string) int { currpath, _ := os.Getwd() gps := utils.GetGOPATHs() if len(gps) == 0 { beeLogger.Log.Fatal("GOPATH environment variable is not set or empty") } gopath := gps[0] beeLogger.Log.Debugf("GOPATH: %s", utils.FILE(), utils.LINE(), gopath) // Getting command line arguments if len(args) != 0 { cmd.Flag.Parse(args[1:]) } if mDriver == "" { mDriver = utils.DocValue(config.Conf.Database.Driver) if mDriver == "" { mDriver = "mysql" } } if mConn == "" { mConn = utils.DocValue(config.Conf.Database.Conn) if mConn == "" { mConn = "root:@tcp(127.0.0.1:3306)/test" } } if mDir == "" { mDir = utils.DocValue(config.Conf.Database.Dir) if mDir == "" { mDir = utils.DocValue(path.Join(currpath, "database", "migrations")) } } beeLogger.Log.Infof("Using '%s' as 'driver'", mDriver) //Log sensitive connection information only when DEBUG is set to true. beeLogger.Log.Debugf("Conn: %s", utils.FILE(), utils.LINE(), mConn) beeLogger.Log.Infof("Using '%s' as 'dir'", mDir) driverStr, connStr, dirStr := string(mDriver), string(mConn), string(mDir) dirRune := []rune(dirStr) if dirRune[0] != '/' && dirRune[1] != ':' { dirStr = path.Join(currpath, dirStr) } if len(args) == 0 { // run all outstanding migrations beeLogger.Log.Info("Running all outstanding migrations") MigrateUpdate(currpath, driverStr, connStr, dirStr) } else { mcmd := args[0] switch mcmd { case "rollback": beeLogger.Log.Info("Rolling back the last migration operation") MigrateRollback(currpath, driverStr, connStr, dirStr) case "reset": beeLogger.Log.Info("Reseting all migrations") MigrateReset(currpath, driverStr, connStr, dirStr) case "refresh": beeLogger.Log.Info("Refreshing all migrations") MigrateRefresh(currpath, driverStr, connStr, dirStr) default: beeLogger.Log.Fatal("Command is missing") } } beeLogger.Log.Success("Migration successful!") return 0 }
go
func RunMigration(cmd *commands.Command, args []string) int { currpath, _ := os.Getwd() gps := utils.GetGOPATHs() if len(gps) == 0 { beeLogger.Log.Fatal("GOPATH environment variable is not set or empty") } gopath := gps[0] beeLogger.Log.Debugf("GOPATH: %s", utils.FILE(), utils.LINE(), gopath) // Getting command line arguments if len(args) != 0 { cmd.Flag.Parse(args[1:]) } if mDriver == "" { mDriver = utils.DocValue(config.Conf.Database.Driver) if mDriver == "" { mDriver = "mysql" } } if mConn == "" { mConn = utils.DocValue(config.Conf.Database.Conn) if mConn == "" { mConn = "root:@tcp(127.0.0.1:3306)/test" } } if mDir == "" { mDir = utils.DocValue(config.Conf.Database.Dir) if mDir == "" { mDir = utils.DocValue(path.Join(currpath, "database", "migrations")) } } beeLogger.Log.Infof("Using '%s' as 'driver'", mDriver) //Log sensitive connection information only when DEBUG is set to true. beeLogger.Log.Debugf("Conn: %s", utils.FILE(), utils.LINE(), mConn) beeLogger.Log.Infof("Using '%s' as 'dir'", mDir) driverStr, connStr, dirStr := string(mDriver), string(mConn), string(mDir) dirRune := []rune(dirStr) if dirRune[0] != '/' && dirRune[1] != ':' { dirStr = path.Join(currpath, dirStr) } if len(args) == 0 { // run all outstanding migrations beeLogger.Log.Info("Running all outstanding migrations") MigrateUpdate(currpath, driverStr, connStr, dirStr) } else { mcmd := args[0] switch mcmd { case "rollback": beeLogger.Log.Info("Rolling back the last migration operation") MigrateRollback(currpath, driverStr, connStr, dirStr) case "reset": beeLogger.Log.Info("Reseting all migrations") MigrateReset(currpath, driverStr, connStr, dirStr) case "refresh": beeLogger.Log.Info("Refreshing all migrations") MigrateRefresh(currpath, driverStr, connStr, dirStr) default: beeLogger.Log.Fatal("Command is missing") } } beeLogger.Log.Success("Migration successful!") return 0 }
[ "func", "RunMigration", "(", "cmd", "*", "commands", ".", "Command", ",", "args", "[", "]", "string", ")", "int", "{", "currpath", ",", "_", ":=", "os", ".", "Getwd", "(", ")", "\n", "gps", ":=", "utils", ".", "GetGOPATHs", "(", ")", "\n", "if", "len", "(", "gps", ")", "==", "0", "{", "beeLogger", ".", "Log", ".", "Fatal", "(", "\"GOPATH environment variable is not set or empty\"", ")", "\n", "}", "\n", "gopath", ":=", "gps", "[", "0", "]", "\n", "beeLogger", ".", "Log", ".", "Debugf", "(", "\"GOPATH: %s\"", ",", "utils", ".", "FILE", "(", ")", ",", "utils", ".", "LINE", "(", ")", ",", "gopath", ")", "\n", "if", "len", "(", "args", ")", "!=", "0", "{", "cmd", ".", "Flag", ".", "Parse", "(", "args", "[", "1", ":", "]", ")", "\n", "}", "\n", "if", "mDriver", "==", "\"\"", "{", "mDriver", "=", "utils", ".", "DocValue", "(", "config", ".", "Conf", ".", "Database", ".", "Driver", ")", "\n", "if", "mDriver", "==", "\"\"", "{", "mDriver", "=", "\"mysql\"", "\n", "}", "\n", "}", "\n", "if", "mConn", "==", "\"\"", "{", "mConn", "=", "utils", ".", "DocValue", "(", "config", ".", "Conf", ".", "Database", ".", "Conn", ")", "\n", "if", "mConn", "==", "\"\"", "{", "mConn", "=", "\"root:@tcp(127.0.0.1:3306)/test\"", "\n", "}", "\n", "}", "\n", "if", "mDir", "==", "\"\"", "{", "mDir", "=", "utils", ".", "DocValue", "(", "config", ".", "Conf", ".", "Database", ".", "Dir", ")", "\n", "if", "mDir", "==", "\"\"", "{", "mDir", "=", "utils", ".", "DocValue", "(", "path", ".", "Join", "(", "currpath", ",", "\"database\"", ",", "\"migrations\"", ")", ")", "\n", "}", "\n", "}", "\n", "beeLogger", ".", "Log", ".", "Infof", "(", "\"Using '%s' as 'driver'\"", ",", "mDriver", ")", "\n", "beeLogger", ".", "Log", ".", "Debugf", "(", "\"Conn: %s\"", ",", "utils", ".", "FILE", "(", ")", ",", "utils", ".", "LINE", "(", ")", ",", "mConn", ")", "\n", "beeLogger", ".", "Log", ".", "Infof", "(", "\"Using '%s' as 'dir'\"", ",", "mDir", ")", "\n", "driverStr", ",", "connStr", ",", "dirStr", ":=", "string", "(", "mDriver", ")", ",", "string", "(", "mConn", ")", ",", "string", "(", "mDir", ")", "\n", "dirRune", ":=", "[", "]", "rune", "(", "dirStr", ")", "\n", "if", "dirRune", "[", "0", "]", "!=", "'/'", "&&", "dirRune", "[", "1", "]", "!=", "':'", "{", "dirStr", "=", "path", ".", "Join", "(", "currpath", ",", "dirStr", ")", "\n", "}", "\n", "if", "len", "(", "args", ")", "==", "0", "{", "beeLogger", ".", "Log", ".", "Info", "(", "\"Running all outstanding migrations\"", ")", "\n", "MigrateUpdate", "(", "currpath", ",", "driverStr", ",", "connStr", ",", "dirStr", ")", "\n", "}", "else", "{", "mcmd", ":=", "args", "[", "0", "]", "\n", "switch", "mcmd", "{", "case", "\"rollback\"", ":", "beeLogger", ".", "Log", ".", "Info", "(", "\"Rolling back the last migration operation\"", ")", "\n", "MigrateRollback", "(", "currpath", ",", "driverStr", ",", "connStr", ",", "dirStr", ")", "\n", "case", "\"reset\"", ":", "beeLogger", ".", "Log", ".", "Info", "(", "\"Reseting all migrations\"", ")", "\n", "MigrateReset", "(", "currpath", ",", "driverStr", ",", "connStr", ",", "dirStr", ")", "\n", "case", "\"refresh\"", ":", "beeLogger", ".", "Log", ".", "Info", "(", "\"Refreshing all migrations\"", ")", "\n", "MigrateRefresh", "(", "currpath", ",", "driverStr", ",", "connStr", ",", "dirStr", ")", "\n", "default", ":", "beeLogger", ".", "Log", ".", "Fatal", "(", "\"Command is missing\"", ")", "\n", "}", "\n", "}", "\n", "beeLogger", ".", "Log", ".", "Success", "(", "\"Migration successful!\"", ")", "\n", "return", "0", "\n", "}" ]
// runMigration is the entry point for starting a migration
[ "runMigration", "is", "the", "entry", "point", "for", "starting", "a", "migration" ]
6a86284cec9a17f9aae6fe82ecf3c436aafed68d
https://github.com/beego/bee/blob/6a86284cec9a17f9aae6fe82ecf3c436aafed68d/cmd/commands/migrate/migrate.go#L71-L140
train
beego/bee
cmd/commands/migrate/migrate.go
migrate
func migrate(goal, currpath, driver, connStr, dir string) { if dir == "" { dir = path.Join(currpath, "database", "migrations") } postfix := "" if runtime.GOOS == "windows" { postfix = ".exe" } binary := "m" + postfix source := binary + ".go" // Connect to database db, err := sql.Open(driver, connStr) if err != nil { beeLogger.Log.Fatalf("Could not connect to database using '%s': %s", connStr, err) } defer db.Close() checkForSchemaUpdateTable(db, driver) latestName, latestTime := getLatestMigration(db, goal) writeMigrationSourceFile(dir, source, driver, connStr, latestTime, latestName, goal) buildMigrationBinary(dir, binary) runMigrationBinary(dir, binary) removeTempFile(dir, source) removeTempFile(dir, binary) }
go
func migrate(goal, currpath, driver, connStr, dir string) { if dir == "" { dir = path.Join(currpath, "database", "migrations") } postfix := "" if runtime.GOOS == "windows" { postfix = ".exe" } binary := "m" + postfix source := binary + ".go" // Connect to database db, err := sql.Open(driver, connStr) if err != nil { beeLogger.Log.Fatalf("Could not connect to database using '%s': %s", connStr, err) } defer db.Close() checkForSchemaUpdateTable(db, driver) latestName, latestTime := getLatestMigration(db, goal) writeMigrationSourceFile(dir, source, driver, connStr, latestTime, latestName, goal) buildMigrationBinary(dir, binary) runMigrationBinary(dir, binary) removeTempFile(dir, source) removeTempFile(dir, binary) }
[ "func", "migrate", "(", "goal", ",", "currpath", ",", "driver", ",", "connStr", ",", "dir", "string", ")", "{", "if", "dir", "==", "\"\"", "{", "dir", "=", "path", ".", "Join", "(", "currpath", ",", "\"database\"", ",", "\"migrations\"", ")", "\n", "}", "\n", "postfix", ":=", "\"\"", "\n", "if", "runtime", ".", "GOOS", "==", "\"windows\"", "{", "postfix", "=", "\".exe\"", "\n", "}", "\n", "binary", ":=", "\"m\"", "+", "postfix", "\n", "source", ":=", "binary", "+", "\".go\"", "\n", "db", ",", "err", ":=", "sql", ".", "Open", "(", "driver", ",", "connStr", ")", "\n", "if", "err", "!=", "nil", "{", "beeLogger", ".", "Log", ".", "Fatalf", "(", "\"Could not connect to database using '%s': %s\"", ",", "connStr", ",", "err", ")", "\n", "}", "\n", "defer", "db", ".", "Close", "(", ")", "\n", "checkForSchemaUpdateTable", "(", "db", ",", "driver", ")", "\n", "latestName", ",", "latestTime", ":=", "getLatestMigration", "(", "db", ",", "goal", ")", "\n", "writeMigrationSourceFile", "(", "dir", ",", "source", ",", "driver", ",", "connStr", ",", "latestTime", ",", "latestName", ",", "goal", ")", "\n", "buildMigrationBinary", "(", "dir", ",", "binary", ")", "\n", "runMigrationBinary", "(", "dir", ",", "binary", ")", "\n", "removeTempFile", "(", "dir", ",", "source", ")", "\n", "removeTempFile", "(", "dir", ",", "binary", ")", "\n", "}" ]
// migrate generates source code, build it, and invoke the binary who does the actual migration
[ "migrate", "generates", "source", "code", "build", "it", "and", "invoke", "the", "binary", "who", "does", "the", "actual", "migration" ]
6a86284cec9a17f9aae6fe82ecf3c436aafed68d
https://github.com/beego/bee/blob/6a86284cec9a17f9aae6fe82ecf3c436aafed68d/cmd/commands/migrate/migrate.go#L143-L168
train
beego/bee
cmd/commands/migrate/migrate.go
checkForSchemaUpdateTable
func checkForSchemaUpdateTable(db *sql.DB, driver string) { showTableSQL := showMigrationsTableSQL(driver) if rows, err := db.Query(showTableSQL); err != nil { beeLogger.Log.Fatalf("Could not show migrations table: %s", err) } else if !rows.Next() { // No migrations table, create new ones createTableSQL := createMigrationsTableSQL(driver) beeLogger.Log.Infof("Creating 'migrations' table...") if _, err := db.Query(createTableSQL); err != nil { beeLogger.Log.Fatalf("Could not create migrations table: %s", err) } } // Checking that migrations table schema are expected selectTableSQL := selectMigrationsTableSQL(driver) if rows, err := db.Query(selectTableSQL); err != nil { beeLogger.Log.Fatalf("Could not show columns of migrations table: %s", err) } else { for rows.Next() { var fieldBytes, typeBytes, nullBytes, keyBytes, defaultBytes, extraBytes []byte if err := rows.Scan(&fieldBytes, &typeBytes, &nullBytes, &keyBytes, &defaultBytes, &extraBytes); err != nil { beeLogger.Log.Fatalf("Could not read column information: %s", err) } fieldStr, typeStr, nullStr, keyStr, defaultStr, extraStr := string(fieldBytes), string(typeBytes), string(nullBytes), string(keyBytes), string(defaultBytes), string(extraBytes) if fieldStr == "id_migration" { if keyStr != "PRI" || extraStr != "auto_increment" { beeLogger.Log.Hint("Expecting KEY: PRI, EXTRA: auto_increment") beeLogger.Log.Fatalf("Column migration.id_migration type mismatch: KEY: %s, EXTRA: %s", keyStr, extraStr) } } else if fieldStr == "name" { if !strings.HasPrefix(typeStr, "varchar") || nullStr != "YES" { beeLogger.Log.Hint("Expecting TYPE: varchar, NULL: YES") beeLogger.Log.Fatalf("Column migration.name type mismatch: TYPE: %s, NULL: %s", typeStr, nullStr) } } else if fieldStr == "created_at" { if typeStr != "timestamp" || defaultStr != "CURRENT_TIMESTAMP" { beeLogger.Log.Hint("Expecting TYPE: timestamp, DEFAULT: CURRENT_TIMESTAMP") beeLogger.Log.Fatalf("Column migration.timestamp type mismatch: TYPE: %s, DEFAULT: %s", typeStr, defaultStr) } } } } }
go
func checkForSchemaUpdateTable(db *sql.DB, driver string) { showTableSQL := showMigrationsTableSQL(driver) if rows, err := db.Query(showTableSQL); err != nil { beeLogger.Log.Fatalf("Could not show migrations table: %s", err) } else if !rows.Next() { // No migrations table, create new ones createTableSQL := createMigrationsTableSQL(driver) beeLogger.Log.Infof("Creating 'migrations' table...") if _, err := db.Query(createTableSQL); err != nil { beeLogger.Log.Fatalf("Could not create migrations table: %s", err) } } // Checking that migrations table schema are expected selectTableSQL := selectMigrationsTableSQL(driver) if rows, err := db.Query(selectTableSQL); err != nil { beeLogger.Log.Fatalf("Could not show columns of migrations table: %s", err) } else { for rows.Next() { var fieldBytes, typeBytes, nullBytes, keyBytes, defaultBytes, extraBytes []byte if err := rows.Scan(&fieldBytes, &typeBytes, &nullBytes, &keyBytes, &defaultBytes, &extraBytes); err != nil { beeLogger.Log.Fatalf("Could not read column information: %s", err) } fieldStr, typeStr, nullStr, keyStr, defaultStr, extraStr := string(fieldBytes), string(typeBytes), string(nullBytes), string(keyBytes), string(defaultBytes), string(extraBytes) if fieldStr == "id_migration" { if keyStr != "PRI" || extraStr != "auto_increment" { beeLogger.Log.Hint("Expecting KEY: PRI, EXTRA: auto_increment") beeLogger.Log.Fatalf("Column migration.id_migration type mismatch: KEY: %s, EXTRA: %s", keyStr, extraStr) } } else if fieldStr == "name" { if !strings.HasPrefix(typeStr, "varchar") || nullStr != "YES" { beeLogger.Log.Hint("Expecting TYPE: varchar, NULL: YES") beeLogger.Log.Fatalf("Column migration.name type mismatch: TYPE: %s, NULL: %s", typeStr, nullStr) } } else if fieldStr == "created_at" { if typeStr != "timestamp" || defaultStr != "CURRENT_TIMESTAMP" { beeLogger.Log.Hint("Expecting TYPE: timestamp, DEFAULT: CURRENT_TIMESTAMP") beeLogger.Log.Fatalf("Column migration.timestamp type mismatch: TYPE: %s, DEFAULT: %s", typeStr, defaultStr) } } } } }
[ "func", "checkForSchemaUpdateTable", "(", "db", "*", "sql", ".", "DB", ",", "driver", "string", ")", "{", "showTableSQL", ":=", "showMigrationsTableSQL", "(", "driver", ")", "\n", "if", "rows", ",", "err", ":=", "db", ".", "Query", "(", "showTableSQL", ")", ";", "err", "!=", "nil", "{", "beeLogger", ".", "Log", ".", "Fatalf", "(", "\"Could not show migrations table: %s\"", ",", "err", ")", "\n", "}", "else", "if", "!", "rows", ".", "Next", "(", ")", "{", "createTableSQL", ":=", "createMigrationsTableSQL", "(", "driver", ")", "\n", "beeLogger", ".", "Log", ".", "Infof", "(", "\"Creating 'migrations' table...\"", ")", "\n", "if", "_", ",", "err", ":=", "db", ".", "Query", "(", "createTableSQL", ")", ";", "err", "!=", "nil", "{", "beeLogger", ".", "Log", ".", "Fatalf", "(", "\"Could not create migrations table: %s\"", ",", "err", ")", "\n", "}", "\n", "}", "\n", "selectTableSQL", ":=", "selectMigrationsTableSQL", "(", "driver", ")", "\n", "if", "rows", ",", "err", ":=", "db", ".", "Query", "(", "selectTableSQL", ")", ";", "err", "!=", "nil", "{", "beeLogger", ".", "Log", ".", "Fatalf", "(", "\"Could not show columns of migrations table: %s\"", ",", "err", ")", "\n", "}", "else", "{", "for", "rows", ".", "Next", "(", ")", "{", "var", "fieldBytes", ",", "typeBytes", ",", "nullBytes", ",", "keyBytes", ",", "defaultBytes", ",", "extraBytes", "[", "]", "byte", "\n", "if", "err", ":=", "rows", ".", "Scan", "(", "&", "fieldBytes", ",", "&", "typeBytes", ",", "&", "nullBytes", ",", "&", "keyBytes", ",", "&", "defaultBytes", ",", "&", "extraBytes", ")", ";", "err", "!=", "nil", "{", "beeLogger", ".", "Log", ".", "Fatalf", "(", "\"Could not read column information: %s\"", ",", "err", ")", "\n", "}", "\n", "fieldStr", ",", "typeStr", ",", "nullStr", ",", "keyStr", ",", "defaultStr", ",", "extraStr", ":=", "string", "(", "fieldBytes", ")", ",", "string", "(", "typeBytes", ")", ",", "string", "(", "nullBytes", ")", ",", "string", "(", "keyBytes", ")", ",", "string", "(", "defaultBytes", ")", ",", "string", "(", "extraBytes", ")", "\n", "if", "fieldStr", "==", "\"id_migration\"", "{", "if", "keyStr", "!=", "\"PRI\"", "||", "extraStr", "!=", "\"auto_increment\"", "{", "beeLogger", ".", "Log", ".", "Hint", "(", "\"Expecting KEY: PRI, EXTRA: auto_increment\"", ")", "\n", "beeLogger", ".", "Log", ".", "Fatalf", "(", "\"Column migration.id_migration type mismatch: KEY: %s, EXTRA: %s\"", ",", "keyStr", ",", "extraStr", ")", "\n", "}", "\n", "}", "else", "if", "fieldStr", "==", "\"name\"", "{", "if", "!", "strings", ".", "HasPrefix", "(", "typeStr", ",", "\"varchar\"", ")", "||", "nullStr", "!=", "\"YES\"", "{", "beeLogger", ".", "Log", ".", "Hint", "(", "\"Expecting TYPE: varchar, NULL: YES\"", ")", "\n", "beeLogger", ".", "Log", ".", "Fatalf", "(", "\"Column migration.name type mismatch: TYPE: %s, NULL: %s\"", ",", "typeStr", ",", "nullStr", ")", "\n", "}", "\n", "}", "else", "if", "fieldStr", "==", "\"created_at\"", "{", "if", "typeStr", "!=", "\"timestamp\"", "||", "defaultStr", "!=", "\"CURRENT_TIMESTAMP\"", "{", "beeLogger", ".", "Log", ".", "Hint", "(", "\"Expecting TYPE: timestamp, DEFAULT: CURRENT_TIMESTAMP\"", ")", "\n", "beeLogger", ".", "Log", ".", "Fatalf", "(", "\"Column migration.timestamp type mismatch: TYPE: %s, DEFAULT: %s\"", ",", "typeStr", ",", "defaultStr", ")", "\n", "}", "\n", "}", "\n", "}", "\n", "}", "\n", "}" ]
// checkForSchemaUpdateTable checks the existence of migrations table. // It checks for the proper table structures and creates the table using MYSQL_MIGRATION_DDL if it does not exist.
[ "checkForSchemaUpdateTable", "checks", "the", "existence", "of", "migrations", "table", ".", "It", "checks", "for", "the", "proper", "table", "structures", "and", "creates", "the", "table", "using", "MYSQL_MIGRATION_DDL", "if", "it", "does", "not", "exist", "." ]
6a86284cec9a17f9aae6fe82ecf3c436aafed68d
https://github.com/beego/bee/blob/6a86284cec9a17f9aae6fe82ecf3c436aafed68d/cmd/commands/migrate/migrate.go#L172-L217
train
beego/bee
cmd/commands/migrate/migrate.go
writeMigrationSourceFile
func writeMigrationSourceFile(dir, source, driver, connStr string, latestTime int64, latestName string, task string) { changeDir(dir) if f, err := os.OpenFile(source, os.O_CREATE|os.O_EXCL|os.O_RDWR, 0666); err != nil { beeLogger.Log.Fatalf("Could not create file: %s", err) } else { content := strings.Replace(MigrationMainTPL, "{{DBDriver}}", driver, -1) content = strings.Replace(content, "{{DriverRepo}}", driverImportStatement(driver), -1) content = strings.Replace(content, "{{ConnStr}}", connStr, -1) content = strings.Replace(content, "{{LatestTime}}", strconv.FormatInt(latestTime, 10), -1) content = strings.Replace(content, "{{LatestName}}", latestName, -1) content = strings.Replace(content, "{{Task}}", task, -1) if _, err := f.WriteString(content); err != nil { beeLogger.Log.Fatalf("Could not write to file: %s", err) } utils.CloseFile(f) } }
go
func writeMigrationSourceFile(dir, source, driver, connStr string, latestTime int64, latestName string, task string) { changeDir(dir) if f, err := os.OpenFile(source, os.O_CREATE|os.O_EXCL|os.O_RDWR, 0666); err != nil { beeLogger.Log.Fatalf("Could not create file: %s", err) } else { content := strings.Replace(MigrationMainTPL, "{{DBDriver}}", driver, -1) content = strings.Replace(content, "{{DriverRepo}}", driverImportStatement(driver), -1) content = strings.Replace(content, "{{ConnStr}}", connStr, -1) content = strings.Replace(content, "{{LatestTime}}", strconv.FormatInt(latestTime, 10), -1) content = strings.Replace(content, "{{LatestName}}", latestName, -1) content = strings.Replace(content, "{{Task}}", task, -1) if _, err := f.WriteString(content); err != nil { beeLogger.Log.Fatalf("Could not write to file: %s", err) } utils.CloseFile(f) } }
[ "func", "writeMigrationSourceFile", "(", "dir", ",", "source", ",", "driver", ",", "connStr", "string", ",", "latestTime", "int64", ",", "latestName", "string", ",", "task", "string", ")", "{", "changeDir", "(", "dir", ")", "\n", "if", "f", ",", "err", ":=", "os", ".", "OpenFile", "(", "source", ",", "os", ".", "O_CREATE", "|", "os", ".", "O_EXCL", "|", "os", ".", "O_RDWR", ",", "0666", ")", ";", "err", "!=", "nil", "{", "beeLogger", ".", "Log", ".", "Fatalf", "(", "\"Could not create file: %s\"", ",", "err", ")", "\n", "}", "else", "{", "content", ":=", "strings", ".", "Replace", "(", "MigrationMainTPL", ",", "\"{{DBDriver}}\"", ",", "driver", ",", "-", "1", ")", "\n", "content", "=", "strings", ".", "Replace", "(", "content", ",", "\"{{DriverRepo}}\"", ",", "driverImportStatement", "(", "driver", ")", ",", "-", "1", ")", "\n", "content", "=", "strings", ".", "Replace", "(", "content", ",", "\"{{ConnStr}}\"", ",", "connStr", ",", "-", "1", ")", "\n", "content", "=", "strings", ".", "Replace", "(", "content", ",", "\"{{LatestTime}}\"", ",", "strconv", ".", "FormatInt", "(", "latestTime", ",", "10", ")", ",", "-", "1", ")", "\n", "content", "=", "strings", ".", "Replace", "(", "content", ",", "\"{{LatestName}}\"", ",", "latestName", ",", "-", "1", ")", "\n", "content", "=", "strings", ".", "Replace", "(", "content", ",", "\"{{Task}}\"", ",", "task", ",", "-", "1", ")", "\n", "if", "_", ",", "err", ":=", "f", ".", "WriteString", "(", "content", ")", ";", "err", "!=", "nil", "{", "beeLogger", ".", "Log", ".", "Fatalf", "(", "\"Could not write to file: %s\"", ",", "err", ")", "\n", "}", "\n", "utils", ".", "CloseFile", "(", "f", ")", "\n", "}", "\n", "}" ]
// writeMigrationSourceFile create the source file based on MIGRATION_MAIN_TPL
[ "writeMigrationSourceFile", "create", "the", "source", "file", "based", "on", "MIGRATION_MAIN_TPL" ]
6a86284cec9a17f9aae6fe82ecf3c436aafed68d
https://github.com/beego/bee/blob/6a86284cec9a17f9aae6fe82ecf3c436aafed68d/cmd/commands/migrate/migrate.go#L291-L307
train
beego/bee
cmd/commands/migrate/migrate.go
changeDir
func changeDir(dir string) { if err := os.Chdir(dir); err != nil { beeLogger.Log.Fatalf("Could not find migration directory: %s", err) } }
go
func changeDir(dir string) { if err := os.Chdir(dir); err != nil { beeLogger.Log.Fatalf("Could not find migration directory: %s", err) } }
[ "func", "changeDir", "(", "dir", "string", ")", "{", "if", "err", ":=", "os", ".", "Chdir", "(", "dir", ")", ";", "err", "!=", "nil", "{", "beeLogger", ".", "Log", ".", "Fatalf", "(", "\"Could not find migration directory: %s\"", ",", "err", ")", "\n", "}", "\n", "}" ]
// changeDir changes working directory to dir. // It exits the system when encouter an error
[ "changeDir", "changes", "working", "directory", "to", "dir", ".", "It", "exits", "the", "system", "when", "encouter", "an", "error" ]
6a86284cec9a17f9aae6fe82ecf3c436aafed68d
https://github.com/beego/bee/blob/6a86284cec9a17f9aae6fe82ecf3c436aafed68d/cmd/commands/migrate/migrate.go#L339-L343
train
beego/bee
cmd/commands/migrate/migrate.go
removeTempFile
func removeTempFile(dir, file string) { changeDir(dir) if err := os.Remove(file); err != nil { beeLogger.Log.Warnf("Could not remove temporary file: %s", err) } }
go
func removeTempFile(dir, file string) { changeDir(dir) if err := os.Remove(file); err != nil { beeLogger.Log.Warnf("Could not remove temporary file: %s", err) } }
[ "func", "removeTempFile", "(", "dir", ",", "file", "string", ")", "{", "changeDir", "(", "dir", ")", "\n", "if", "err", ":=", "os", ".", "Remove", "(", "file", ")", ";", "err", "!=", "nil", "{", "beeLogger", ".", "Log", ".", "Warnf", "(", "\"Could not remove temporary file: %s\"", ",", "err", ")", "\n", "}", "\n", "}" ]
// removeTempFile removes a file in dir
[ "removeTempFile", "removes", "a", "file", "in", "dir" ]
6a86284cec9a17f9aae6fe82ecf3c436aafed68d
https://github.com/beego/bee/blob/6a86284cec9a17f9aae6fe82ecf3c436aafed68d/cmd/commands/migrate/migrate.go#L346-L351
train
beego/bee
cmd/commands/migrate/migrate.go
formatShellErrOutput
func formatShellErrOutput(o string) { for _, line := range strings.Split(o, "\n") { if line != "" { beeLogger.Log.Errorf("|> %s", line) } } }
go
func formatShellErrOutput(o string) { for _, line := range strings.Split(o, "\n") { if line != "" { beeLogger.Log.Errorf("|> %s", line) } } }
[ "func", "formatShellErrOutput", "(", "o", "string", ")", "{", "for", "_", ",", "line", ":=", "range", "strings", ".", "Split", "(", "o", ",", "\"\\n\"", ")", "\\n", "\n", "}" ]
// formatShellErrOutput formats the error shell output
[ "formatShellErrOutput", "formats", "the", "error", "shell", "output" ]
6a86284cec9a17f9aae6fe82ecf3c436aafed68d
https://github.com/beego/bee/blob/6a86284cec9a17f9aae6fe82ecf3c436aafed68d/cmd/commands/migrate/migrate.go#L354-L360
train
beego/bee
cmd/commands/migrate/migrate.go
formatShellOutput
func formatShellOutput(o string) { for _, line := range strings.Split(o, "\n") { if line != "" { beeLogger.Log.Infof("|> %s", line) } } }
go
func formatShellOutput(o string) { for _, line := range strings.Split(o, "\n") { if line != "" { beeLogger.Log.Infof("|> %s", line) } } }
[ "func", "formatShellOutput", "(", "o", "string", ")", "{", "for", "_", ",", "line", ":=", "range", "strings", ".", "Split", "(", "o", ",", "\"\\n\"", ")", "\\n", "\n", "}" ]
// formatShellOutput formats the normal shell output
[ "formatShellOutput", "formats", "the", "normal", "shell", "output" ]
6a86284cec9a17f9aae6fe82ecf3c436aafed68d
https://github.com/beego/bee/blob/6a86284cec9a17f9aae6fe82ecf3c436aafed68d/cmd/commands/migrate/migrate.go#L363-L369
train
beego/bee
cmd/commands/migrate/migrate.go
MigrateUpdate
func MigrateUpdate(currpath, driver, connStr, dir string) { migrate("upgrade", currpath, driver, connStr, dir) }
go
func MigrateUpdate(currpath, driver, connStr, dir string) { migrate("upgrade", currpath, driver, connStr, dir) }
[ "func", "MigrateUpdate", "(", "currpath", ",", "driver", ",", "connStr", ",", "dir", "string", ")", "{", "migrate", "(", "\"upgrade\"", ",", "currpath", ",", "driver", ",", "connStr", ",", "dir", ")", "\n", "}" ]
// MigrateUpdate does the schema update
[ "MigrateUpdate", "does", "the", "schema", "update" ]
6a86284cec9a17f9aae6fe82ecf3c436aafed68d
https://github.com/beego/bee/blob/6a86284cec9a17f9aae6fe82ecf3c436aafed68d/cmd/commands/migrate/migrate.go#L438-L440
train
beego/bee
cmd/commands/migrate/migrate.go
MigrateRollback
func MigrateRollback(currpath, driver, connStr, dir string) { migrate("rollback", currpath, driver, connStr, dir) }
go
func MigrateRollback(currpath, driver, connStr, dir string) { migrate("rollback", currpath, driver, connStr, dir) }
[ "func", "MigrateRollback", "(", "currpath", ",", "driver", ",", "connStr", ",", "dir", "string", ")", "{", "migrate", "(", "\"rollback\"", ",", "currpath", ",", "driver", ",", "connStr", ",", "dir", ")", "\n", "}" ]
// MigrateRollback rolls back the latest migration
[ "MigrateRollback", "rolls", "back", "the", "latest", "migration" ]
6a86284cec9a17f9aae6fe82ecf3c436aafed68d
https://github.com/beego/bee/blob/6a86284cec9a17f9aae6fe82ecf3c436aafed68d/cmd/commands/migrate/migrate.go#L443-L445
train
beego/bee
cmd/commands/migrate/migrate.go
MigrateReset
func MigrateReset(currpath, driver, connStr, dir string) { migrate("reset", currpath, driver, connStr, dir) }
go
func MigrateReset(currpath, driver, connStr, dir string) { migrate("reset", currpath, driver, connStr, dir) }
[ "func", "MigrateReset", "(", "currpath", ",", "driver", ",", "connStr", ",", "dir", "string", ")", "{", "migrate", "(", "\"reset\"", ",", "currpath", ",", "driver", ",", "connStr", ",", "dir", ")", "\n", "}" ]
// MigrateReset rolls back all migrations
[ "MigrateReset", "rolls", "back", "all", "migrations" ]
6a86284cec9a17f9aae6fe82ecf3c436aafed68d
https://github.com/beego/bee/blob/6a86284cec9a17f9aae6fe82ecf3c436aafed68d/cmd/commands/migrate/migrate.go#L448-L450
train
beego/bee
cmd/commands/migrate/migrate.go
MigrateRefresh
func MigrateRefresh(currpath, driver, connStr, dir string) { migrate("refresh", currpath, driver, connStr, dir) }
go
func MigrateRefresh(currpath, driver, connStr, dir string) { migrate("refresh", currpath, driver, connStr, dir) }
[ "func", "MigrateRefresh", "(", "currpath", ",", "driver", ",", "connStr", ",", "dir", "string", ")", "{", "migrate", "(", "\"refresh\"", ",", "currpath", ",", "driver", ",", "connStr", ",", "dir", ")", "\n", "}" ]
// MigrateRefresh rolls back all migrations and start over again
[ "MigrateRefresh", "rolls", "back", "all", "migrations", "and", "start", "over", "again" ]
6a86284cec9a17f9aae6fe82ecf3c436aafed68d
https://github.com/beego/bee/blob/6a86284cec9a17f9aae6fe82ecf3c436aafed68d/cmd/commands/migrate/migrate.go#L453-L455
train
beego/bee
cmd/commands/run/run.go
isExcluded
func isExcluded(filePath string) bool { for _, p := range excludedPaths { absP, err := path.Abs(p) if err != nil { beeLogger.Log.Errorf("Cannot get absolute path of '%s'", p) continue } absFilePath, err := path.Abs(filePath) if err != nil { beeLogger.Log.Errorf("Cannot get absolute path of '%s'", filePath) break } if strings.HasPrefix(absFilePath, absP) { beeLogger.Log.Infof("'%s' is not being watched", filePath) return true } } return false }
go
func isExcluded(filePath string) bool { for _, p := range excludedPaths { absP, err := path.Abs(p) if err != nil { beeLogger.Log.Errorf("Cannot get absolute path of '%s'", p) continue } absFilePath, err := path.Abs(filePath) if err != nil { beeLogger.Log.Errorf("Cannot get absolute path of '%s'", filePath) break } if strings.HasPrefix(absFilePath, absP) { beeLogger.Log.Infof("'%s' is not being watched", filePath) return true } } return false }
[ "func", "isExcluded", "(", "filePath", "string", ")", "bool", "{", "for", "_", ",", "p", ":=", "range", "excludedPaths", "{", "absP", ",", "err", ":=", "path", ".", "Abs", "(", "p", ")", "\n", "if", "err", "!=", "nil", "{", "beeLogger", ".", "Log", ".", "Errorf", "(", "\"Cannot get absolute path of '%s'\"", ",", "p", ")", "\n", "continue", "\n", "}", "\n", "absFilePath", ",", "err", ":=", "path", ".", "Abs", "(", "filePath", ")", "\n", "if", "err", "!=", "nil", "{", "beeLogger", ".", "Log", ".", "Errorf", "(", "\"Cannot get absolute path of '%s'\"", ",", "filePath", ")", "\n", "break", "\n", "}", "\n", "if", "strings", ".", "HasPrefix", "(", "absFilePath", ",", "absP", ")", "{", "beeLogger", ".", "Log", ".", "Infof", "(", "\"'%s' is not being watched\"", ",", "filePath", ")", "\n", "return", "true", "\n", "}", "\n", "}", "\n", "return", "false", "\n", "}" ]
// If a file is excluded
[ "If", "a", "file", "is", "excluded" ]
6a86284cec9a17f9aae6fe82ecf3c436aafed68d
https://github.com/beego/bee/blob/6a86284cec9a17f9aae6fe82ecf3c436aafed68d/cmd/commands/run/run.go#L235-L253
train
beego/bee
logger/colors/color.go
NewModeColorWriter
func NewModeColorWriter(w io.Writer, mode outputMode) io.Writer { if _, ok := w.(*colorWriter); !ok { return &colorWriter{ w: w, mode: mode, } } return w }
go
func NewModeColorWriter(w io.Writer, mode outputMode) io.Writer { if _, ok := w.(*colorWriter); !ok { return &colorWriter{ w: w, mode: mode, } } return w }
[ "func", "NewModeColorWriter", "(", "w", "io", ".", "Writer", ",", "mode", "outputMode", ")", "io", ".", "Writer", "{", "if", "_", ",", "ok", ":=", "w", ".", "(", "*", "colorWriter", ")", ";", "!", "ok", "{", "return", "&", "colorWriter", "{", "w", ":", "w", ",", "mode", ":", "mode", ",", "}", "\n", "}", "\n", "return", "w", "\n", "}" ]
// NewModeColorWriter create and initializes a new ansiColorWriter // by specifying the outputMode.
[ "NewModeColorWriter", "create", "and", "initializes", "a", "new", "ansiColorWriter", "by", "specifying", "the", "outputMode", "." ]
6a86284cec9a17f9aae6fe82ecf3c436aafed68d
https://github.com/beego/bee/blob/6a86284cec9a17f9aae6fe82ecf3c436aafed68d/logger/colors/color.go#L46-L54
train
beego/bee
cmd/commands/version/version.go
ShowShortVersionBanner
func ShowShortVersionBanner() { output := colors.NewColorWriter(os.Stdout) InitBanner(output, bytes.NewBufferString(colors.MagentaBold(shortVersionBanner))) }
go
func ShowShortVersionBanner() { output := colors.NewColorWriter(os.Stdout) InitBanner(output, bytes.NewBufferString(colors.MagentaBold(shortVersionBanner))) }
[ "func", "ShowShortVersionBanner", "(", ")", "{", "output", ":=", "colors", ".", "NewColorWriter", "(", "os", ".", "Stdout", ")", "\n", "InitBanner", "(", "output", ",", "bytes", ".", "NewBufferString", "(", "colors", ".", "MagentaBold", "(", "shortVersionBanner", ")", ")", ")", "\n", "}" ]
// ShowShortVersionBanner prints the short version banner.
[ "ShowShortVersionBanner", "prints", "the", "short", "version", "banner", "." ]
6a86284cec9a17f9aae6fe82ecf3c436aafed68d
https://github.com/beego/bee/blob/6a86284cec9a17f9aae6fe82ecf3c436aafed68d/cmd/commands/version/version.go#L115-L118
train
beego/bee
cmd/commands/run/watch.go
NewWatcher
func NewWatcher(paths []string, files []string, isgenerate bool) { watcher, err := fsnotify.NewWatcher() if err != nil { beeLogger.Log.Fatalf("Failed to create watcher: %s", err) } go func() { for { select { case e := <-watcher.Events: isBuild := true if ifStaticFile(e.Name) && config.Conf.EnableReload { sendReload(e.String()) continue } // Skip ignored files if shouldIgnoreFile(e.Name) { continue } if !shouldWatchFileWithExtension(e.Name) { continue } mt := utils.GetFileModTime(e.Name) if t := eventTime[e.Name]; mt == t { beeLogger.Log.Hintf(colors.Bold("Skipping: ")+"%s", e.String()) isBuild = false } eventTime[e.Name] = mt if isBuild { beeLogger.Log.Hintf("Event fired: %s", e) go func() { // Wait 1s before autobuild until there is no file change. scheduleTime = time.Now().Add(1 * time.Second) time.Sleep(time.Until(scheduleTime)) AutoBuild(files, isgenerate) if config.Conf.EnableReload { // Wait 100ms more before refreshing the browser time.Sleep(100 * time.Millisecond) sendReload(e.String()) } }() } case err := <-watcher.Errors: beeLogger.Log.Warnf("Watcher error: %s", err.Error()) // No need to exit here } } }() beeLogger.Log.Info("Initializing watcher...") for _, path := range paths { beeLogger.Log.Hintf(colors.Bold("Watching: ")+"%s", path) err = watcher.Add(path) if err != nil { beeLogger.Log.Fatalf("Failed to watch directory: %s", err) } } }
go
func NewWatcher(paths []string, files []string, isgenerate bool) { watcher, err := fsnotify.NewWatcher() if err != nil { beeLogger.Log.Fatalf("Failed to create watcher: %s", err) } go func() { for { select { case e := <-watcher.Events: isBuild := true if ifStaticFile(e.Name) && config.Conf.EnableReload { sendReload(e.String()) continue } // Skip ignored files if shouldIgnoreFile(e.Name) { continue } if !shouldWatchFileWithExtension(e.Name) { continue } mt := utils.GetFileModTime(e.Name) if t := eventTime[e.Name]; mt == t { beeLogger.Log.Hintf(colors.Bold("Skipping: ")+"%s", e.String()) isBuild = false } eventTime[e.Name] = mt if isBuild { beeLogger.Log.Hintf("Event fired: %s", e) go func() { // Wait 1s before autobuild until there is no file change. scheduleTime = time.Now().Add(1 * time.Second) time.Sleep(time.Until(scheduleTime)) AutoBuild(files, isgenerate) if config.Conf.EnableReload { // Wait 100ms more before refreshing the browser time.Sleep(100 * time.Millisecond) sendReload(e.String()) } }() } case err := <-watcher.Errors: beeLogger.Log.Warnf("Watcher error: %s", err.Error()) // No need to exit here } } }() beeLogger.Log.Info("Initializing watcher...") for _, path := range paths { beeLogger.Log.Hintf(colors.Bold("Watching: ")+"%s", path) err = watcher.Add(path) if err != nil { beeLogger.Log.Fatalf("Failed to watch directory: %s", err) } } }
[ "func", "NewWatcher", "(", "paths", "[", "]", "string", ",", "files", "[", "]", "string", ",", "isgenerate", "bool", ")", "{", "watcher", ",", "err", ":=", "fsnotify", ".", "NewWatcher", "(", ")", "\n", "if", "err", "!=", "nil", "{", "beeLogger", ".", "Log", ".", "Fatalf", "(", "\"Failed to create watcher: %s\"", ",", "err", ")", "\n", "}", "\n", "go", "func", "(", ")", "{", "for", "{", "select", "{", "case", "e", ":=", "<-", "watcher", ".", "Events", ":", "isBuild", ":=", "true", "\n", "if", "ifStaticFile", "(", "e", ".", "Name", ")", "&&", "config", ".", "Conf", ".", "EnableReload", "{", "sendReload", "(", "e", ".", "String", "(", ")", ")", "\n", "continue", "\n", "}", "\n", "if", "shouldIgnoreFile", "(", "e", ".", "Name", ")", "{", "continue", "\n", "}", "\n", "if", "!", "shouldWatchFileWithExtension", "(", "e", ".", "Name", ")", "{", "continue", "\n", "}", "\n", "mt", ":=", "utils", ".", "GetFileModTime", "(", "e", ".", "Name", ")", "\n", "if", "t", ":=", "eventTime", "[", "e", ".", "Name", "]", ";", "mt", "==", "t", "{", "beeLogger", ".", "Log", ".", "Hintf", "(", "colors", ".", "Bold", "(", "\"Skipping: \"", ")", "+", "\"%s\"", ",", "e", ".", "String", "(", ")", ")", "\n", "isBuild", "=", "false", "\n", "}", "\n", "eventTime", "[", "e", ".", "Name", "]", "=", "mt", "\n", "if", "isBuild", "{", "beeLogger", ".", "Log", ".", "Hintf", "(", "\"Event fired: %s\"", ",", "e", ")", "\n", "go", "func", "(", ")", "{", "scheduleTime", "=", "time", ".", "Now", "(", ")", ".", "Add", "(", "1", "*", "time", ".", "Second", ")", "\n", "time", ".", "Sleep", "(", "time", ".", "Until", "(", "scheduleTime", ")", ")", "\n", "AutoBuild", "(", "files", ",", "isgenerate", ")", "\n", "if", "config", ".", "Conf", ".", "EnableReload", "{", "time", ".", "Sleep", "(", "100", "*", "time", ".", "Millisecond", ")", "\n", "sendReload", "(", "e", ".", "String", "(", ")", ")", "\n", "}", "\n", "}", "(", ")", "\n", "}", "\n", "case", "err", ":=", "<-", "watcher", ".", "Errors", ":", "beeLogger", ".", "Log", ".", "Warnf", "(", "\"Watcher error: %s\"", ",", "err", ".", "Error", "(", ")", ")", "\n", "}", "\n", "}", "\n", "}", "(", ")", "\n", "beeLogger", ".", "Log", ".", "Info", "(", "\"Initializing watcher...\"", ")", "\n", "for", "_", ",", "path", ":=", "range", "paths", "{", "beeLogger", ".", "Log", ".", "Hintf", "(", "colors", ".", "Bold", "(", "\"Watching: \"", ")", "+", "\"%s\"", ",", "path", ")", "\n", "err", "=", "watcher", ".", "Add", "(", "path", ")", "\n", "if", "err", "!=", "nil", "{", "beeLogger", ".", "Log", ".", "Fatalf", "(", "\"Failed to watch directory: %s\"", ",", "err", ")", "\n", "}", "\n", "}", "\n", "}" ]
// NewWatcher starts an fsnotify Watcher on the specified paths
[ "NewWatcher", "starts", "an", "fsnotify", "Watcher", "on", "the", "specified", "paths" ]
6a86284cec9a17f9aae6fe82ecf3c436aafed68d
https://github.com/beego/bee/blob/6a86284cec9a17f9aae6fe82ecf3c436aafed68d/cmd/commands/run/watch.go#L51-L112
train
beego/bee
cmd/commands/run/watch.go
AutoBuild
func AutoBuild(files []string, isgenerate bool) { state.Lock() defer state.Unlock() os.Chdir(currpath) cmdName := "go" var ( err error stderr bytes.Buffer ) // For applications use full import path like "github.com/.../.." // are able to use "go install" to reduce build time. if config.Conf.GoInstall { icmd := exec.Command(cmdName, "install", "-v") icmd.Stdout = os.Stdout icmd.Stderr = os.Stderr icmd.Env = append(os.Environ(), "GOGC=off") icmd.Run() } if isgenerate { beeLogger.Log.Info("Generating the docs...") icmd := exec.Command("bee", "generate", "docs") icmd.Env = append(os.Environ(), "GOGC=off") err = icmd.Run() if err != nil { utils.Notify("", "Failed to generate the docs.") beeLogger.Log.Errorf("Failed to generate the docs.") return } beeLogger.Log.Success("Docs generated!") } appName := appname if err == nil { if runtime.GOOS == "windows" { appName += ".exe" } args := []string{"build"} args = append(args, "-o", appName) if buildTags != "" { args = append(args, "-tags", buildTags) } args = append(args, files...) bcmd := exec.Command(cmdName, args...) bcmd.Env = append(os.Environ(), "GOGC=off") bcmd.Stderr = &stderr err = bcmd.Run() if err != nil { utils.Notify(stderr.String(), "Build Failed") beeLogger.Log.Errorf("Failed to build the application: %s", stderr.String()) return } } beeLogger.Log.Success("Built Successfully!") Restart(appName) }
go
func AutoBuild(files []string, isgenerate bool) { state.Lock() defer state.Unlock() os.Chdir(currpath) cmdName := "go" var ( err error stderr bytes.Buffer ) // For applications use full import path like "github.com/.../.." // are able to use "go install" to reduce build time. if config.Conf.GoInstall { icmd := exec.Command(cmdName, "install", "-v") icmd.Stdout = os.Stdout icmd.Stderr = os.Stderr icmd.Env = append(os.Environ(), "GOGC=off") icmd.Run() } if isgenerate { beeLogger.Log.Info("Generating the docs...") icmd := exec.Command("bee", "generate", "docs") icmd.Env = append(os.Environ(), "GOGC=off") err = icmd.Run() if err != nil { utils.Notify("", "Failed to generate the docs.") beeLogger.Log.Errorf("Failed to generate the docs.") return } beeLogger.Log.Success("Docs generated!") } appName := appname if err == nil { if runtime.GOOS == "windows" { appName += ".exe" } args := []string{"build"} args = append(args, "-o", appName) if buildTags != "" { args = append(args, "-tags", buildTags) } args = append(args, files...) bcmd := exec.Command(cmdName, args...) bcmd.Env = append(os.Environ(), "GOGC=off") bcmd.Stderr = &stderr err = bcmd.Run() if err != nil { utils.Notify(stderr.String(), "Build Failed") beeLogger.Log.Errorf("Failed to build the application: %s", stderr.String()) return } } beeLogger.Log.Success("Built Successfully!") Restart(appName) }
[ "func", "AutoBuild", "(", "files", "[", "]", "string", ",", "isgenerate", "bool", ")", "{", "state", ".", "Lock", "(", ")", "\n", "defer", "state", ".", "Unlock", "(", ")", "\n", "os", ".", "Chdir", "(", "currpath", ")", "\n", "cmdName", ":=", "\"go\"", "\n", "var", "(", "err", "error", "\n", "stderr", "bytes", ".", "Buffer", "\n", ")", "\n", "if", "config", ".", "Conf", ".", "GoInstall", "{", "icmd", ":=", "exec", ".", "Command", "(", "cmdName", ",", "\"install\"", ",", "\"-v\"", ")", "\n", "icmd", ".", "Stdout", "=", "os", ".", "Stdout", "\n", "icmd", ".", "Stderr", "=", "os", ".", "Stderr", "\n", "icmd", ".", "Env", "=", "append", "(", "os", ".", "Environ", "(", ")", ",", "\"GOGC=off\"", ")", "\n", "icmd", ".", "Run", "(", ")", "\n", "}", "\n", "if", "isgenerate", "{", "beeLogger", ".", "Log", ".", "Info", "(", "\"Generating the docs...\"", ")", "\n", "icmd", ":=", "exec", ".", "Command", "(", "\"bee\"", ",", "\"generate\"", ",", "\"docs\"", ")", "\n", "icmd", ".", "Env", "=", "append", "(", "os", ".", "Environ", "(", ")", ",", "\"GOGC=off\"", ")", "\n", "err", "=", "icmd", ".", "Run", "(", ")", "\n", "if", "err", "!=", "nil", "{", "utils", ".", "Notify", "(", "\"\"", ",", "\"Failed to generate the docs.\"", ")", "\n", "beeLogger", ".", "Log", ".", "Errorf", "(", "\"Failed to generate the docs.\"", ")", "\n", "return", "\n", "}", "\n", "beeLogger", ".", "Log", ".", "Success", "(", "\"Docs generated!\"", ")", "\n", "}", "\n", "appName", ":=", "appname", "\n", "if", "err", "==", "nil", "{", "if", "runtime", ".", "GOOS", "==", "\"windows\"", "{", "appName", "+=", "\".exe\"", "\n", "}", "\n", "args", ":=", "[", "]", "string", "{", "\"build\"", "}", "\n", "args", "=", "append", "(", "args", ",", "\"-o\"", ",", "appName", ")", "\n", "if", "buildTags", "!=", "\"\"", "{", "args", "=", "append", "(", "args", ",", "\"-tags\"", ",", "buildTags", ")", "\n", "}", "\n", "args", "=", "append", "(", "args", ",", "files", "...", ")", "\n", "bcmd", ":=", "exec", ".", "Command", "(", "cmdName", ",", "args", "...", ")", "\n", "bcmd", ".", "Env", "=", "append", "(", "os", ".", "Environ", "(", ")", ",", "\"GOGC=off\"", ")", "\n", "bcmd", ".", "Stderr", "=", "&", "stderr", "\n", "err", "=", "bcmd", ".", "Run", "(", ")", "\n", "if", "err", "!=", "nil", "{", "utils", ".", "Notify", "(", "stderr", ".", "String", "(", ")", ",", "\"Build Failed\"", ")", "\n", "beeLogger", ".", "Log", ".", "Errorf", "(", "\"Failed to build the application: %s\"", ",", "stderr", ".", "String", "(", ")", ")", "\n", "return", "\n", "}", "\n", "}", "\n", "beeLogger", ".", "Log", ".", "Success", "(", "\"Built Successfully!\"", ")", "\n", "Restart", "(", "appName", ")", "\n", "}" ]
// AutoBuild builds the specified set of files
[ "AutoBuild", "builds", "the", "specified", "set", "of", "files" ]
6a86284cec9a17f9aae6fe82ecf3c436aafed68d
https://github.com/beego/bee/blob/6a86284cec9a17f9aae6fe82ecf3c436aafed68d/cmd/commands/run/watch.go#L115-L176
train
beego/bee
cmd/commands/run/watch.go
Kill
func Kill() { defer func() { if e := recover(); e != nil { beeLogger.Log.Infof("Kill recover: %s", e) } }() if cmd != nil && cmd.Process != nil { // Windows does not support Interrupt if runtime.GOOS == "windows" { cmd.Process.Signal(os.Kill) } else { cmd.Process.Signal(os.Interrupt) } ch := make(chan struct{}, 1) go func() { cmd.Wait() ch <- struct{}{} }() select { case <-ch: return case <-time.After(10 * time.Second): beeLogger.Log.Info("Timeout. Force kill cmd process") err := cmd.Process.Kill() if err != nil { beeLogger.Log.Errorf("Error while killing cmd process: %s", err) } return } } }
go
func Kill() { defer func() { if e := recover(); e != nil { beeLogger.Log.Infof("Kill recover: %s", e) } }() if cmd != nil && cmd.Process != nil { // Windows does not support Interrupt if runtime.GOOS == "windows" { cmd.Process.Signal(os.Kill) } else { cmd.Process.Signal(os.Interrupt) } ch := make(chan struct{}, 1) go func() { cmd.Wait() ch <- struct{}{} }() select { case <-ch: return case <-time.After(10 * time.Second): beeLogger.Log.Info("Timeout. Force kill cmd process") err := cmd.Process.Kill() if err != nil { beeLogger.Log.Errorf("Error while killing cmd process: %s", err) } return } } }
[ "func", "Kill", "(", ")", "{", "defer", "func", "(", ")", "{", "if", "e", ":=", "recover", "(", ")", ";", "e", "!=", "nil", "{", "beeLogger", ".", "Log", ".", "Infof", "(", "\"Kill recover: %s\"", ",", "e", ")", "\n", "}", "\n", "}", "(", ")", "\n", "if", "cmd", "!=", "nil", "&&", "cmd", ".", "Process", "!=", "nil", "{", "if", "runtime", ".", "GOOS", "==", "\"windows\"", "{", "cmd", ".", "Process", ".", "Signal", "(", "os", ".", "Kill", ")", "\n", "}", "else", "{", "cmd", ".", "Process", ".", "Signal", "(", "os", ".", "Interrupt", ")", "\n", "}", "\n", "ch", ":=", "make", "(", "chan", "struct", "{", "}", ",", "1", ")", "\n", "go", "func", "(", ")", "{", "cmd", ".", "Wait", "(", ")", "\n", "ch", "<-", "struct", "{", "}", "{", "}", "\n", "}", "(", ")", "\n", "select", "{", "case", "<-", "ch", ":", "return", "\n", "case", "<-", "time", ".", "After", "(", "10", "*", "time", ".", "Second", ")", ":", "beeLogger", ".", "Log", ".", "Info", "(", "\"Timeout. Force kill cmd process\"", ")", "\n", "err", ":=", "cmd", ".", "Process", ".", "Kill", "(", ")", "\n", "if", "err", "!=", "nil", "{", "beeLogger", ".", "Log", ".", "Errorf", "(", "\"Error while killing cmd process: %s\"", ",", "err", ")", "\n", "}", "\n", "return", "\n", "}", "\n", "}", "\n", "}" ]
// Kill kills the running command process
[ "Kill", "kills", "the", "running", "command", "process" ]
6a86284cec9a17f9aae6fe82ecf3c436aafed68d
https://github.com/beego/bee/blob/6a86284cec9a17f9aae6fe82ecf3c436aafed68d/cmd/commands/run/watch.go#L179-L211
train
beego/bee
cmd/commands/run/watch.go
Restart
func Restart(appname string) { beeLogger.Log.Debugf("Kill running process", utils.FILE(), utils.LINE()) Kill() go Start(appname) }
go
func Restart(appname string) { beeLogger.Log.Debugf("Kill running process", utils.FILE(), utils.LINE()) Kill() go Start(appname) }
[ "func", "Restart", "(", "appname", "string", ")", "{", "beeLogger", ".", "Log", ".", "Debugf", "(", "\"Kill running process\"", ",", "utils", ".", "FILE", "(", ")", ",", "utils", ".", "LINE", "(", ")", ")", "\n", "Kill", "(", ")", "\n", "go", "Start", "(", "appname", ")", "\n", "}" ]
// Restart kills the running command process and starts it again
[ "Restart", "kills", "the", "running", "command", "process", "and", "starts", "it", "again" ]
6a86284cec9a17f9aae6fe82ecf3c436aafed68d
https://github.com/beego/bee/blob/6a86284cec9a17f9aae6fe82ecf3c436aafed68d/cmd/commands/run/watch.go#L214-L218
train
beego/bee
cmd/commands/run/watch.go
Start
func Start(appname string) { beeLogger.Log.Infof("Restarting '%s'...", appname) if !strings.Contains(appname, "./") { appname = "./" + appname } cmd = exec.Command(appname) cmd.Stdout = os.Stdout cmd.Stderr = os.Stderr if runargs != "" { r := regexp.MustCompile("'.+'|\".+\"|\\S+") m := r.FindAllString(runargs, -1) cmd.Args = append([]string{appname}, m...) } else { cmd.Args = append([]string{appname}, config.Conf.CmdArgs...) } cmd.Env = append(os.Environ(), config.Conf.Envs...) go cmd.Run() beeLogger.Log.Successf("'%s' is running...", appname) started <- true }
go
func Start(appname string) { beeLogger.Log.Infof("Restarting '%s'...", appname) if !strings.Contains(appname, "./") { appname = "./" + appname } cmd = exec.Command(appname) cmd.Stdout = os.Stdout cmd.Stderr = os.Stderr if runargs != "" { r := regexp.MustCompile("'.+'|\".+\"|\\S+") m := r.FindAllString(runargs, -1) cmd.Args = append([]string{appname}, m...) } else { cmd.Args = append([]string{appname}, config.Conf.CmdArgs...) } cmd.Env = append(os.Environ(), config.Conf.Envs...) go cmd.Run() beeLogger.Log.Successf("'%s' is running...", appname) started <- true }
[ "func", "Start", "(", "appname", "string", ")", "{", "beeLogger", ".", "Log", ".", "Infof", "(", "\"Restarting '%s'...\"", ",", "appname", ")", "\n", "if", "!", "strings", ".", "Contains", "(", "appname", ",", "\"./\"", ")", "{", "appname", "=", "\"./\"", "+", "appname", "\n", "}", "\n", "cmd", "=", "exec", ".", "Command", "(", "appname", ")", "\n", "cmd", ".", "Stdout", "=", "os", ".", "Stdout", "\n", "cmd", ".", "Stderr", "=", "os", ".", "Stderr", "\n", "if", "runargs", "!=", "\"\"", "{", "r", ":=", "regexp", ".", "MustCompile", "(", "\"'.+'|\\\".+\\\"|\\\\S+\"", ")", "\n", "\\\"", "\n", "\\\"", "\n", "}", "else", "\\\\", "\n", "m", ":=", "r", ".", "FindAllString", "(", "runargs", ",", "-", "1", ")", "\n", "cmd", ".", "Args", "=", "append", "(", "[", "]", "string", "{", "appname", "}", ",", "m", "...", ")", "\n", "{", "cmd", ".", "Args", "=", "append", "(", "[", "]", "string", "{", "appname", "}", ",", "config", ".", "Conf", ".", "CmdArgs", "...", ")", "\n", "}", "\n", "cmd", ".", "Env", "=", "append", "(", "os", ".", "Environ", "(", ")", ",", "config", ".", "Conf", ".", "Envs", "...", ")", "\n", "}" ]
// Start starts the command process
[ "Start", "starts", "the", "command", "process" ]
6a86284cec9a17f9aae6fe82ecf3c436aafed68d
https://github.com/beego/bee/blob/6a86284cec9a17f9aae6fe82ecf3c436aafed68d/cmd/commands/run/watch.go#L221-L242
train
beego/bee
cmd/commands/run/watch.go
shouldIgnoreFile
func shouldIgnoreFile(filename string) bool { for _, regex := range ignoredFilesRegExps { r, err := regexp.Compile(regex) if err != nil { beeLogger.Log.Fatalf("Could not compile regular expression: %s", err) } if r.MatchString(filename) { return true } continue } return false }
go
func shouldIgnoreFile(filename string) bool { for _, regex := range ignoredFilesRegExps { r, err := regexp.Compile(regex) if err != nil { beeLogger.Log.Fatalf("Could not compile regular expression: %s", err) } if r.MatchString(filename) { return true } continue } return false }
[ "func", "shouldIgnoreFile", "(", "filename", "string", ")", "bool", "{", "for", "_", ",", "regex", ":=", "range", "ignoredFilesRegExps", "{", "r", ",", "err", ":=", "regexp", ".", "Compile", "(", "regex", ")", "\n", "if", "err", "!=", "nil", "{", "beeLogger", ".", "Log", ".", "Fatalf", "(", "\"Could not compile regular expression: %s\"", ",", "err", ")", "\n", "}", "\n", "if", "r", ".", "MatchString", "(", "filename", ")", "{", "return", "true", "\n", "}", "\n", "continue", "\n", "}", "\n", "return", "false", "\n", "}" ]
// shouldIgnoreFile ignores filenames generated by Emacs, Vim or SublimeText. // It returns true if the file should be ignored, false otherwise.
[ "shouldIgnoreFile", "ignores", "filenames", "generated", "by", "Emacs", "Vim", "or", "SublimeText", ".", "It", "returns", "true", "if", "the", "file", "should", "be", "ignored", "false", "otherwise", "." ]
6a86284cec9a17f9aae6fe82ecf3c436aafed68d
https://github.com/beego/bee/blob/6a86284cec9a17f9aae6fe82ecf3c436aafed68d/cmd/commands/run/watch.go#L255-L267
train
beego/bee
cmd/commands/run/watch.go
shouldWatchFileWithExtension
func shouldWatchFileWithExtension(name string) bool { for _, s := range watchExts { if strings.HasSuffix(name, s) { return true } } return false }
go
func shouldWatchFileWithExtension(name string) bool { for _, s := range watchExts { if strings.HasSuffix(name, s) { return true } } return false }
[ "func", "shouldWatchFileWithExtension", "(", "name", "string", ")", "bool", "{", "for", "_", ",", "s", ":=", "range", "watchExts", "{", "if", "strings", ".", "HasSuffix", "(", "name", ",", "s", ")", "{", "return", "true", "\n", "}", "\n", "}", "\n", "return", "false", "\n", "}" ]
// shouldWatchFileWithExtension returns true if the name of the file // hash a suffix that should be watched.
[ "shouldWatchFileWithExtension", "returns", "true", "if", "the", "name", "of", "the", "file", "hash", "a", "suffix", "that", "should", "be", "watched", "." ]
6a86284cec9a17f9aae6fe82ecf3c436aafed68d
https://github.com/beego/bee/blob/6a86284cec9a17f9aae6fe82ecf3c436aafed68d/cmd/commands/run/watch.go#L271-L278
train
beego/bee
logger/logger.go
GetBeeLogger
func GetBeeLogger(w io.Writer) *BeeLogger { once.Do(func() { var ( err error simpleLogFormat = `{{Now "2006/01/02 15:04:05"}} {{.Level}} ▶ {{.ID}} {{.Message}}{{EndLine}}` debugLogFormat = `{{Now "2006/01/02 15:04:05"}} {{.Level}} ▶ {{.ID}} {{.Filename}}:{{.LineNo}} {{.Message}}{{EndLine}}` ) // Initialize and parse logging templates funcs := template.FuncMap{ "Now": Now, "EndLine": EndLine, } logRecordTemplate, err = template.New("simpleLogFormat").Funcs(funcs).Parse(simpleLogFormat) if err != nil { panic(err) } debugLogRecordTemplate, err = template.New("debugLogFormat").Funcs(funcs).Parse(debugLogFormat) if err != nil { panic(err) } instance = &BeeLogger{output: colors.NewColorWriter(w)} }) return instance }
go
func GetBeeLogger(w io.Writer) *BeeLogger { once.Do(func() { var ( err error simpleLogFormat = `{{Now "2006/01/02 15:04:05"}} {{.Level}} ▶ {{.ID}} {{.Message}}{{EndLine}}` debugLogFormat = `{{Now "2006/01/02 15:04:05"}} {{.Level}} ▶ {{.ID}} {{.Filename}}:{{.LineNo}} {{.Message}}{{EndLine}}` ) // Initialize and parse logging templates funcs := template.FuncMap{ "Now": Now, "EndLine": EndLine, } logRecordTemplate, err = template.New("simpleLogFormat").Funcs(funcs).Parse(simpleLogFormat) if err != nil { panic(err) } debugLogRecordTemplate, err = template.New("debugLogFormat").Funcs(funcs).Parse(debugLogFormat) if err != nil { panic(err) } instance = &BeeLogger{output: colors.NewColorWriter(w)} }) return instance }
[ "func", "GetBeeLogger", "(", "w", "io", ".", "Writer", ")", "*", "BeeLogger", "{", "once", ".", "Do", "(", "func", "(", ")", "{", "var", "(", "err", "error", "\n", "simpleLogFormat", "=", "`{{Now \"2006/01/02 15:04:05\"}} {{.Level}} ▶ {{.ID}} {{.Message}}{{EndLine}}`", "\n", "debugLogFormat", "=", "`{{Now \"2006/01/02 15:04:05\"}} {{.Level}} ▶ {{.ID}} {{.Filename}}:{{.LineNo}} {{.Message}}{{EndLine}}`", "\n", ")", "\n", "funcs", ":=", "template", ".", "FuncMap", "{", "\"Now\"", ":", "Now", ",", "\"EndLine\"", ":", "EndLine", ",", "}", "\n", "logRecordTemplate", ",", "err", "=", "template", ".", "New", "(", "\"simpleLogFormat\"", ")", ".", "Funcs", "(", "funcs", ")", ".", "Parse", "(", "simpleLogFormat", ")", "\n", "if", "err", "!=", "nil", "{", "panic", "(", "err", ")", "\n", "}", "\n", "debugLogRecordTemplate", ",", "err", "=", "template", ".", "New", "(", "\"debugLogFormat\"", ")", ".", "Funcs", "(", "funcs", ")", ".", "Parse", "(", "debugLogFormat", ")", "\n", "if", "err", "!=", "nil", "{", "panic", "(", "err", ")", "\n", "}", "\n", "instance", "=", "&", "BeeLogger", "{", "output", ":", "colors", ".", "NewColorWriter", "(", "w", ")", "}", "\n", "}", ")", "\n", "return", "instance", "\n", "}" ]
// GetBeeLogger initializes the logger instance with a NewColorWriter output // and returns a singleton
[ "GetBeeLogger", "initializes", "the", "logger", "instance", "with", "a", "NewColorWriter", "output", "and", "returns", "a", "singleton" ]
6a86284cec9a17f9aae6fe82ecf3c436aafed68d
https://github.com/beego/bee/blob/6a86284cec9a17f9aae6fe82ecf3c436aafed68d/logger/logger.go#L77-L102
train
beego/bee
logger/logger.go
SetOutput
func (l *BeeLogger) SetOutput(w io.Writer) { l.mu.Lock() defer l.mu.Unlock() l.output = colors.NewColorWriter(w) }
go
func (l *BeeLogger) SetOutput(w io.Writer) { l.mu.Lock() defer l.mu.Unlock() l.output = colors.NewColorWriter(w) }
[ "func", "(", "l", "*", "BeeLogger", ")", "SetOutput", "(", "w", "io", ".", "Writer", ")", "{", "l", ".", "mu", ".", "Lock", "(", ")", "\n", "defer", "l", ".", "mu", ".", "Unlock", "(", ")", "\n", "l", ".", "output", "=", "colors", ".", "NewColorWriter", "(", "w", ")", "\n", "}" ]
// SetOutput sets the logger output destination
[ "SetOutput", "sets", "the", "logger", "output", "destination" ]
6a86284cec9a17f9aae6fe82ecf3c436aafed68d
https://github.com/beego/bee/blob/6a86284cec9a17f9aae6fe82ecf3c436aafed68d/logger/logger.go#L105-L109
train
beego/bee
logger/logger.go
mustLog
func (l *BeeLogger) mustLog(level int, message string, args ...interface{}) { if level > logLevel { return } // Acquire the lock l.mu.Lock() defer l.mu.Unlock() // Create the logging record and pass into the output record := LogRecord{ ID: fmt.Sprintf("%04d", atomic.AddUint64(&sequenceNo, 1)), Level: l.getColorLevel(level), Message: fmt.Sprintf(message, args...), } err := logRecordTemplate.Execute(l.output, record) if err != nil { panic(err) } }
go
func (l *BeeLogger) mustLog(level int, message string, args ...interface{}) { if level > logLevel { return } // Acquire the lock l.mu.Lock() defer l.mu.Unlock() // Create the logging record and pass into the output record := LogRecord{ ID: fmt.Sprintf("%04d", atomic.AddUint64(&sequenceNo, 1)), Level: l.getColorLevel(level), Message: fmt.Sprintf(message, args...), } err := logRecordTemplate.Execute(l.output, record) if err != nil { panic(err) } }
[ "func", "(", "l", "*", "BeeLogger", ")", "mustLog", "(", "level", "int", ",", "message", "string", ",", "args", "...", "interface", "{", "}", ")", "{", "if", "level", ">", "logLevel", "{", "return", "\n", "}", "\n", "l", ".", "mu", ".", "Lock", "(", ")", "\n", "defer", "l", ".", "mu", ".", "Unlock", "(", ")", "\n", "record", ":=", "LogRecord", "{", "ID", ":", "fmt", ".", "Sprintf", "(", "\"%04d\"", ",", "atomic", ".", "AddUint64", "(", "&", "sequenceNo", ",", "1", ")", ")", ",", "Level", ":", "l", ".", "getColorLevel", "(", "level", ")", ",", "Message", ":", "fmt", ".", "Sprintf", "(", "message", ",", "args", "...", ")", ",", "}", "\n", "err", ":=", "logRecordTemplate", ".", "Execute", "(", "l", ".", "output", ",", "record", ")", "\n", "if", "err", "!=", "nil", "{", "panic", "(", "err", ")", "\n", "}", "\n", "}" ]
// mustLog logs the message according to the specified level and arguments. // It panics in case of an error.
[ "mustLog", "logs", "the", "message", "according", "to", "the", "specified", "level", "and", "arguments", ".", "It", "panics", "in", "case", "of", "an", "error", "." ]
6a86284cec9a17f9aae6fe82ecf3c436aafed68d
https://github.com/beego/bee/blob/6a86284cec9a17f9aae6fe82ecf3c436aafed68d/logger/logger.go#L169-L188
train
beego/bee
logger/logger.go
mustLogDebug
func (l *BeeLogger) mustLogDebug(message string, file string, line int, args ...interface{}) { if !debugMode { return } // Change the output to Stderr l.SetOutput(os.Stderr) // Create the log record record := LogRecord{ ID: fmt.Sprintf("%04d", atomic.AddUint64(&sequenceNo, 1)), Level: l.getColorLevel(levelDebug), Message: fmt.Sprintf(message, args...), LineNo: line, Filename: filepath.Base(file), } err := debugLogRecordTemplate.Execute(l.output, record) if err != nil { panic(err) } }
go
func (l *BeeLogger) mustLogDebug(message string, file string, line int, args ...interface{}) { if !debugMode { return } // Change the output to Stderr l.SetOutput(os.Stderr) // Create the log record record := LogRecord{ ID: fmt.Sprintf("%04d", atomic.AddUint64(&sequenceNo, 1)), Level: l.getColorLevel(levelDebug), Message: fmt.Sprintf(message, args...), LineNo: line, Filename: filepath.Base(file), } err := debugLogRecordTemplate.Execute(l.output, record) if err != nil { panic(err) } }
[ "func", "(", "l", "*", "BeeLogger", ")", "mustLogDebug", "(", "message", "string", ",", "file", "string", ",", "line", "int", ",", "args", "...", "interface", "{", "}", ")", "{", "if", "!", "debugMode", "{", "return", "\n", "}", "\n", "l", ".", "SetOutput", "(", "os", ".", "Stderr", ")", "\n", "record", ":=", "LogRecord", "{", "ID", ":", "fmt", ".", "Sprintf", "(", "\"%04d\"", ",", "atomic", ".", "AddUint64", "(", "&", "sequenceNo", ",", "1", ")", ")", ",", "Level", ":", "l", ".", "getColorLevel", "(", "levelDebug", ")", ",", "Message", ":", "fmt", ".", "Sprintf", "(", "message", ",", "args", "...", ")", ",", "LineNo", ":", "line", ",", "Filename", ":", "filepath", ".", "Base", "(", "file", ")", ",", "}", "\n", "err", ":=", "debugLogRecordTemplate", ".", "Execute", "(", "l", ".", "output", ",", "record", ")", "\n", "if", "err", "!=", "nil", "{", "panic", "(", "err", ")", "\n", "}", "\n", "}" ]
// mustLogDebug logs a debug message only if debug mode // is enabled. i.e. DEBUG_ENABLED="1"
[ "mustLogDebug", "logs", "a", "debug", "message", "only", "if", "debug", "mode", "is", "enabled", ".", "i", ".", "e", ".", "DEBUG_ENABLED", "=", "1" ]
6a86284cec9a17f9aae6fe82ecf3c436aafed68d
https://github.com/beego/bee/blob/6a86284cec9a17f9aae6fe82ecf3c436aafed68d/logger/logger.go#L192-L212
train
beego/bee
logger/logger.go
Debug
func (l *BeeLogger) Debug(message string, file string, line int) { l.mustLogDebug(message, file, line) }
go
func (l *BeeLogger) Debug(message string, file string, line int) { l.mustLogDebug(message, file, line) }
[ "func", "(", "l", "*", "BeeLogger", ")", "Debug", "(", "message", "string", ",", "file", "string", ",", "line", "int", ")", "{", "l", ".", "mustLogDebug", "(", "message", ",", "file", ",", "line", ")", "\n", "}" ]
// Debug outputs a debug log message
[ "Debug", "outputs", "a", "debug", "log", "message" ]
6a86284cec9a17f9aae6fe82ecf3c436aafed68d
https://github.com/beego/bee/blob/6a86284cec9a17f9aae6fe82ecf3c436aafed68d/logger/logger.go#L215-L217
train
beego/bee
logger/logger.go
Debugf
func (l *BeeLogger) Debugf(message string, file string, line int, vars ...interface{}) { l.mustLogDebug(message, file, line, vars...) }
go
func (l *BeeLogger) Debugf(message string, file string, line int, vars ...interface{}) { l.mustLogDebug(message, file, line, vars...) }
[ "func", "(", "l", "*", "BeeLogger", ")", "Debugf", "(", "message", "string", ",", "file", "string", ",", "line", "int", ",", "vars", "...", "interface", "{", "}", ")", "{", "l", ".", "mustLogDebug", "(", "message", ",", "file", ",", "line", ",", "vars", "...", ")", "\n", "}" ]
// Debugf outputs a formatted debug log message
[ "Debugf", "outputs", "a", "formatted", "debug", "log", "message" ]
6a86284cec9a17f9aae6fe82ecf3c436aafed68d
https://github.com/beego/bee/blob/6a86284cec9a17f9aae6fe82ecf3c436aafed68d/logger/logger.go#L220-L222
train
beego/bee
logger/logger.go
Infof
func (l *BeeLogger) Infof(message string, vars ...interface{}) { l.mustLog(levelInfo, message, vars...) }
go
func (l *BeeLogger) Infof(message string, vars ...interface{}) { l.mustLog(levelInfo, message, vars...) }
[ "func", "(", "l", "*", "BeeLogger", ")", "Infof", "(", "message", "string", ",", "vars", "...", "interface", "{", "}", ")", "{", "l", ".", "mustLog", "(", "levelInfo", ",", "message", ",", "vars", "...", ")", "\n", "}" ]
// Infof outputs a formatted information log message
[ "Infof", "outputs", "a", "formatted", "information", "log", "message" ]
6a86284cec9a17f9aae6fe82ecf3c436aafed68d
https://github.com/beego/bee/blob/6a86284cec9a17f9aae6fe82ecf3c436aafed68d/logger/logger.go#L230-L232
train