repo stringlengths 5 67 | sha stringlengths 40 40 | path stringlengths 4 234 | url stringlengths 85 339 | language stringclasses 6 values | split stringclasses 3 values | doc stringlengths 3 51.2k | sign stringlengths 5 8.01k | problem stringlengths 13 51.2k | output stringlengths 0 3.87M |
|---|---|---|---|---|---|---|---|---|---|
asaskevich/govalidator | f61b66f89f4a311bef65f13e575bcf1a2ffadda6 | utils.go | https://github.com/asaskevich/govalidator/blob/f61b66f89f4a311bef65f13e575bcf1a2ffadda6/utils.go#L54-L58 | go | train | // WhiteList remove characters that do not appear in the whitelist. | func WhiteList(str, chars string) string | // WhiteList remove characters that do not appear in the whitelist.
func WhiteList(str, chars string) string | {
pattern := "[^" + chars + "]+"
r, _ := regexp.Compile(pattern)
return r.ReplaceAllString(str, "")
} |
asaskevich/govalidator | f61b66f89f4a311bef65f13e575bcf1a2ffadda6 | utils.go | https://github.com/asaskevich/govalidator/blob/f61b66f89f4a311bef65f13e575bcf1a2ffadda6/utils.go#L69-L77 | go | train | // StripLow remove characters with a numerical value < 32 and 127, mostly control characters.
// If keep_new_lines is true, newline characters are preserved (\n and \r, hex 0xA and 0xD). | func StripLow(str string, keepNewLines bool) string | // StripLow remove characters with a numerical value < 32 and 127, mostly control characters.
// If keep_new_lines is true, newline characters are preserved (\n and \r, hex 0xA and 0xD).
func StripLow(str string, keepNewLines bool) string | {
chars := ""
if keepNewLines {
chars = "\x00-\x09\x0B\x0C\x0E-\x1F\x7F"
} else {
chars = "\x00-\x1F\x7F"
}
return BlackList(str, chars)
} |
asaskevich/govalidator | f61b66f89f4a311bef65f13e575bcf1a2ffadda6 | utils.go | https://github.com/asaskevich/govalidator/blob/f61b66f89f4a311bef65f13e575bcf1a2ffadda6/utils.go#L80-L83 | go | train | // ReplacePattern replace regular expression pattern in string | func ReplacePattern(str, pattern, replace string) string | // ReplacePattern replace regular expression pattern in string
func ReplacePattern(str, pattern, replace string) string | {
r, _ := regexp.Compile(pattern)
return r.ReplaceAllString(str, replace)
} |
asaskevich/govalidator | f61b66f89f4a311bef65f13e575bcf1a2ffadda6 | utils.go | https://github.com/asaskevich/govalidator/blob/f61b66f89f4a311bef65f13e575bcf1a2ffadda6/utils.go#L101-L103 | go | train | // UnderscoreToCamelCase converts from underscore separated form to camel case form.
// Ex.: my_func => MyFunc | func UnderscoreToCamelCase(s string) string | // UnderscoreToCamelCase converts from underscore separated form to camel case form.
// Ex.: my_func => MyFunc
func UnderscoreToCamelCase(s string) string | {
return strings.Replace(strings.Title(strings.Replace(strings.ToLower(s), "_", " ", -1)), " ", "", -1)
} |
asaskevich/govalidator | f61b66f89f4a311bef65f13e575bcf1a2ffadda6 | utils.go | https://github.com/asaskevich/govalidator/blob/f61b66f89f4a311bef65f13e575bcf1a2ffadda6/utils.go#L107-L121 | go | train | // CamelCaseToUnderscore converts from camel case form to underscore separated form.
// Ex.: MyFunc => my_func | func CamelCaseToUnderscore(str string) string | // CamelCaseToUnderscore converts from camel case form to underscore separated form.
// Ex.: MyFunc => my_func
func CamelCaseToUnderscore(str string) string | {
var output []rune
var segment []rune
for _, r := range str {
// not treat number as separate segment
if !unicode.IsLower(r) && string(r) != "_" && !unicode.IsNumber(r) {
output = addSegment(output, segment)
segment = nil
}
segment = append(segment, unicode.ToLower(r))
}
output = addSegment(output, segment)
return string(output)
} |
asaskevich/govalidator | f61b66f89f4a311bef65f13e575bcf1a2ffadda6 | utils.go | https://github.com/asaskevich/govalidator/blob/f61b66f89f4a311bef65f13e575bcf1a2ffadda6/utils.go#L124-L130 | go | train | // Reverse return reversed string | func Reverse(s string) string | // Reverse return reversed string
func Reverse(s string) string | {
r := []rune(s)
for i, j := 0, len(r)-1; i < j; i, j = i+1, j-1 {
r[i], r[j] = r[j], r[i]
}
return string(r)
} |
asaskevich/govalidator | f61b66f89f4a311bef65f13e575bcf1a2ffadda6 | utils.go | https://github.com/asaskevich/govalidator/blob/f61b66f89f4a311bef65f13e575bcf1a2ffadda6/utils.go#L138-L144 | go | train | // GetLine return specified line of multiline string | func GetLine(s string, index int) (string, error) | // GetLine return specified line of multiline string
func GetLine(s string, index int) (string, error) | {
lines := GetLines(s)
if index < 0 || index >= len(lines) {
return "", errors.New("line index out of bounds")
}
return lines[index], nil
} |
asaskevich/govalidator | f61b66f89f4a311bef65f13e575bcf1a2ffadda6 | utils.go | https://github.com/asaskevich/govalidator/blob/f61b66f89f4a311bef65f13e575bcf1a2ffadda6/utils.go#L152-L168 | go | train | // SafeFileName return safe string that can be used in file names | func SafeFileName(str string) string | // SafeFileName return safe string that can be used in file names
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
} |
asaskevich/govalidator | f61b66f89f4a311bef65f13e575bcf1a2ffadda6 | utils.go | https://github.com/asaskevich/govalidator/blob/f61b66f89f4a311bef65f13e575bcf1a2ffadda6/utils.go#L176-L188 | go | train | // NormalizeEmail canonicalize an email address.
// The local part of the email address is lowercased for all domains; the hostname is always lowercased and
// the local part of the email address is always lowercased for hosts that are known to be case-insensitive (currently only GMail).
// Normalization follows special rules for known providers: currently, GMail addresses have dots removed in the local part and
// are stripped of tags (e.g. some.one+tag@gmail.com becomes someone@gmail.com) and all @googlemail.com addresses are
// normalized to @gmail.com. | func NormalizeEmail(str string) (string, error) | // NormalizeEmail canonicalize an email address.
// The local part of the email address is lowercased for all domains; the hostname is always lowercased and
// the local part of the email address is always lowercased for hosts that are known to be case-insensitive (currently only GMail).
// Normalization follows special rules for known providers: currently, GMail addresses have dots removed in the local part and
// are stripped of tags (e.g. some.one+tag@gmail.com becomes someone@gmail.com) and all @googlemail.com addresses are
// normalized to @gmail.com.
func NormalizeEmail(str string) (string, error) | {
if !IsEmail(str) {
return "", fmt.Errorf("%s is not an email", str)
}
parts := strings.Split(str, "@")
parts[0] = strings.ToLower(parts[0])
parts[1] = strings.ToLower(parts[1])
if parts[1] == "gmail.com" || parts[1] == "googlemail.com" {
parts[1] = "gmail.com"
parts[0] = strings.Split(ReplacePattern(parts[0], `\.`, ""), "+")[0]
}
return strings.Join(parts, "@"), nil
} |
asaskevich/govalidator | f61b66f89f4a311bef65f13e575bcf1a2ffadda6 | utils.go | https://github.com/asaskevich/govalidator/blob/f61b66f89f4a311bef65f13e575bcf1a2ffadda6/utils.go#L191-L211 | go | train | // Truncate a string to the closest length without breaking words. | func Truncate(str string, length int, ending string) string | // Truncate a string to the closest length without breaking words.
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
} |
asaskevich/govalidator | f61b66f89f4a311bef65f13e575bcf1a2ffadda6 | utils.go | https://github.com/asaskevich/govalidator/blob/f61b66f89f4a311bef65f13e575bcf1a2ffadda6/utils.go#L214-L216 | go | train | // PadLeft pad left side of string if size of string is less then indicated pad length | func PadLeft(str string, padStr string, padLen int) string | // PadLeft pad left side of string if size of string is less then indicated pad length
func PadLeft(str string, padStr string, padLen int) string | {
return buildPadStr(str, padStr, padLen, true, false)
} |
asaskevich/govalidator | f61b66f89f4a311bef65f13e575bcf1a2ffadda6 | utils.go | https://github.com/asaskevich/govalidator/blob/f61b66f89f4a311bef65f13e575bcf1a2ffadda6/utils.go#L224-L226 | go | train | // PadBoth pad sides of string if size of string is less then indicated pad length | func PadBoth(str string, padStr string, padLen int) string | // PadBoth pad sides of string if size of string is less then indicated pad length
func PadBoth(str string, padStr string, padLen int) string | {
return buildPadStr(str, padStr, padLen, true, true)
} |
asaskevich/govalidator | f61b66f89f4a311bef65f13e575bcf1a2ffadda6 | utils.go | https://github.com/asaskevich/govalidator/blob/f61b66f89f4a311bef65f13e575bcf1a2ffadda6/utils.go#L230-L264 | go | train | // PadString either left, right or both sides, not the padding string can be unicode and more then one
// character | func buildPadStr(str string, padStr string, padLen int, padLeft bool, padRight bool) string | // PadString either left, right or both sides, not the padding string can be unicode and more then one
// character
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
} |
asaskevich/govalidator | f61b66f89f4a311bef65f13e575bcf1a2ffadda6 | utils.go | https://github.com/asaskevich/govalidator/blob/f61b66f89f4a311bef65f13e575bcf1a2ffadda6/utils.go#L267-L270 | go | train | // TruncatingErrorf removes extra args from fmt.Errorf if not formatted in the str object | func TruncatingErrorf(str string, args ...interface{}) error | // TruncatingErrorf removes extra args from fmt.Errorf if not formatted in the str object
func TruncatingErrorf(str string, args ...interface{}) error | {
n := strings.Count(str, "%s")
return fmt.Errorf(str, args[:n]...)
} |
asaskevich/govalidator | f61b66f89f4a311bef65f13e575bcf1a2ffadda6 | converter.go | https://github.com/asaskevich/govalidator/blob/f61b66f89f4a311bef65f13e575bcf1a2ffadda6/converter.go#L17-L23 | go | train | // ToJSON convert the input to a valid JSON string | func ToJSON(obj interface{}) (string, error) | // ToJSON convert the input to a valid JSON string
func ToJSON(obj interface{}) (string, error) | {
res, err := json.Marshal(obj)
if err != nil {
res = []byte("")
}
return string(res), err
} |
asaskevich/govalidator | f61b66f89f4a311bef65f13e575bcf1a2ffadda6 | converter.go | https://github.com/asaskevich/govalidator/blob/f61b66f89f4a311bef65f13e575bcf1a2ffadda6/converter.go#L26-L32 | go | train | // ToFloat convert the input string to a float, or 0.0 if the input is not a float. | func ToFloat(str string) (float64, error) | // ToFloat convert the input string to a float, or 0.0 if the input is not a float.
func ToFloat(str string) (float64, error) | {
res, err := strconv.ParseFloat(str, 64)
if err != nil {
res = 0.0
}
return res, err
} |
asaskevich/govalidator | f61b66f89f4a311bef65f13e575bcf1a2ffadda6 | converter.go | https://github.com/asaskevich/govalidator/blob/f61b66f89f4a311bef65f13e575bcf1a2ffadda6/converter.go#L35-L59 | go | train | // ToInt convert the input string or any int type to an integer type 64, or 0 if the input is not an integer. | func ToInt(value interface{}) (res int64, err error) | // ToInt convert the input string or any int type to an integer type 64, or 0 if the input is not an integer.
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
} |
asaskevich/govalidator | f61b66f89f4a311bef65f13e575bcf1a2ffadda6 | numerics.go | https://github.com/asaskevich/govalidator/blob/f61b66f89f4a311bef65f13e575bcf1a2ffadda6/numerics.go#L45-L53 | go | train | // InRange returns true if value lies between left and right border | func InRangeInt(value, left, right interface{}) bool | // InRange returns true if value lies between left and right border
func InRangeInt(value, left, right interface{}) bool | {
value64, _ := ToInt(value)
left64, _ := ToInt(left)
right64, _ := ToInt(right)
if left64 > right64 {
left64, right64 = right64, left64
}
return value64 >= left64 && value64 <= right64
} |
asaskevich/govalidator | f61b66f89f4a311bef65f13e575bcf1a2ffadda6 | numerics.go | https://github.com/asaskevich/govalidator/blob/f61b66f89f4a311bef65f13e575bcf1a2ffadda6/numerics.go#L56-L61 | go | train | // InRange returns true if value lies between left and right border | func InRangeFloat32(value, left, right float32) bool | // InRange returns true if value lies between left and right border
func InRangeFloat32(value, left, right float32) bool | {
if left > right {
left, right = right, left
}
return value >= left && value <= right
} |
asaskevich/govalidator | f61b66f89f4a311bef65f13e575bcf1a2ffadda6 | numerics.go | https://github.com/asaskevich/govalidator/blob/f61b66f89f4a311bef65f13e575bcf1a2ffadda6/numerics.go#L64-L69 | go | train | // InRange returns true if value lies between left and right border | func InRangeFloat64(value, left, right float64) bool | // InRange returns true if value lies between left and right border
func InRangeFloat64(value, left, right float64) bool | {
if left > right {
left, right = right, left
}
return value >= left && value <= right
} |
asaskevich/govalidator | f61b66f89f4a311bef65f13e575bcf1a2ffadda6 | numerics.go | https://github.com/asaskevich/govalidator/blob/f61b66f89f4a311bef65f13e575bcf1a2ffadda6/numerics.go#L72-L87 | go | train | // 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 | func InRange(value interface{}, left interface{}, right interface{}) bool | // 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
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
}
} |
asaskevich/govalidator | f61b66f89f4a311bef65f13e575bcf1a2ffadda6 | validator.go | https://github.com/asaskevich/govalidator/blob/f61b66f89f4a311bef65f13e575bcf1a2ffadda6/validator.go#L73-L101 | go | train | // IsExistingEmail check if the string is an email of existing domain | func IsExistingEmail(email string) bool | // IsExistingEmail check if the string is an email of existing domain
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
} |
asaskevich/govalidator | f61b66f89f4a311bef65f13e575bcf1a2ffadda6 | validator.go | https://github.com/asaskevich/govalidator/blob/f61b66f89f4a311bef65f13e575bcf1a2ffadda6/validator.go#L104-L125 | go | train | // IsURL check if the string is an URL. | func IsURL(str string) bool | // IsURL check if the string is an URL.
func IsURL(str string) bool | {
if str == "" || utf8.RuneCountInString(str) >= maxURLRuneCount || len(str) <= minURLRuneCount || strings.HasPrefix(str, ".") {
return false
}
strTemp := str
if strings.Contains(str, ":") && !strings.Contains(str, "://") {
// support no indicated urlscheme but with colon for port number
// http:// is appended so url.Parse will succeed, strTemp used so it does not impact rxURL.MatchString
strTemp = "http://" + str
}
u, err := url.Parse(strTemp)
if err != nil {
return false
}
if strings.HasPrefix(u.Host, ".") {
return false
}
if u.Host == "" && (u.Path != "" && !strings.Contains(u.Path, ".")) {
return false
}
return rxURL.MatchString(str)
} |
asaskevich/govalidator | f61b66f89f4a311bef65f13e575bcf1a2ffadda6 | validator.go | https://github.com/asaskevich/govalidator/blob/f61b66f89f4a311bef65f13e575bcf1a2ffadda6/validator.go#L130-L139 | go | train | // IsRequestURL check if the string rawurl, assuming
// it was received in an HTTP request, is a valid
// URL confirm to RFC 3986 | func IsRequestURL(rawurl string) bool | // IsRequestURL check if the string rawurl, assuming
// it was received in an HTTP request, is a valid
// URL confirm to RFC 3986
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
} |
asaskevich/govalidator | f61b66f89f4a311bef65f13e575bcf1a2ffadda6 | validator.go | https://github.com/asaskevich/govalidator/blob/f61b66f89f4a311bef65f13e575bcf1a2ffadda6/validator.go#L144-L147 | go | train | // IsRequestURI check if the string rawurl, assuming
// it was received in an HTTP request, is an
// absolute URI or an absolute path. | func IsRequestURI(rawurl string) bool | // IsRequestURI check if the string rawurl, assuming
// it was received in an HTTP request, is an
// absolute URI or an absolute path.
func IsRequestURI(rawurl string) bool | {
_, err := url.ParseRequestURI(rawurl)
return err == nil
} |
asaskevich/govalidator | f61b66f89f4a311bef65f13e575bcf1a2ffadda6 | validator.go | https://github.com/asaskevich/govalidator/blob/f61b66f89f4a311bef65f13e575bcf1a2ffadda6/validator.go#L150-L155 | go | train | // IsAlpha check if the string contains only letters (a-zA-Z). Empty string is valid. | func IsAlpha(str string) bool | // IsAlpha check if the string contains only letters (a-zA-Z). Empty string is valid.
func IsAlpha(str string) bool | {
if IsNull(str) {
return true
}
return rxAlpha.MatchString(str)
} |
asaskevich/govalidator | f61b66f89f4a311bef65f13e575bcf1a2ffadda6 | validator.go | https://github.com/asaskevich/govalidator/blob/f61b66f89f4a311bef65f13e575bcf1a2ffadda6/validator.go#L159-L171 | go | train | //IsUTFLetter check if the string contains only unicode letter characters.
//Similar to IsAlpha but for all languages. Empty string is valid. | func IsUTFLetter(str string) bool | //IsUTFLetter check if the string contains only unicode letter characters.
//Similar to IsAlpha but for all languages. Empty string is valid.
func IsUTFLetter(str string) bool | {
if IsNull(str) {
return true
}
for _, c := range str {
if !unicode.IsLetter(c) {
return false
}
}
return true
} |
asaskevich/govalidator | f61b66f89f4a311bef65f13e575bcf1a2ffadda6 | validator.go | https://github.com/asaskevich/govalidator/blob/f61b66f89f4a311bef65f13e575bcf1a2ffadda6/validator.go#L174-L179 | go | train | // IsAlphanumeric check if the string contains only letters and numbers. Empty string is valid. | func IsAlphanumeric(str string) bool | // IsAlphanumeric check if the string contains only letters and numbers. Empty string is valid.
func IsAlphanumeric(str string) bool | {
if IsNull(str) {
return true
}
return rxAlphanumeric.MatchString(str)
} |
asaskevich/govalidator | f61b66f89f4a311bef65f13e575bcf1a2ffadda6 | validator.go | https://github.com/asaskevich/govalidator/blob/f61b66f89f4a311bef65f13e575bcf1a2ffadda6/validator.go#L182-L193 | go | train | // IsUTFLetterNumeric check if the string contains only unicode letters and numbers. Empty string is valid. | func IsUTFLetterNumeric(str string) bool | // IsUTFLetterNumeric check if the string contains only unicode letters and numbers. Empty string is valid.
func IsUTFLetterNumeric(str string) bool | {
if IsNull(str) {
return true
}
for _, c := range str {
if !unicode.IsLetter(c) && !unicode.IsNumber(c) { //letters && numbers are ok
return false
}
}
return true
} |
asaskevich/govalidator | f61b66f89f4a311bef65f13e575bcf1a2ffadda6 | validator.go | https://github.com/asaskevich/govalidator/blob/f61b66f89f4a311bef65f13e575bcf1a2ffadda6/validator.go#L196-L201 | go | train | // IsNumeric check if the string contains only numbers. Empty string is valid. | func IsNumeric(str string) bool | // IsNumeric check if the string contains only numbers. Empty string is valid.
func IsNumeric(str string) bool | {
if IsNull(str) {
return true
}
return rxNumeric.MatchString(str)
} |
asaskevich/govalidator | f61b66f89f4a311bef65f13e575bcf1a2ffadda6 | validator.go | https://github.com/asaskevich/govalidator/blob/f61b66f89f4a311bef65f13e575bcf1a2ffadda6/validator.go#L205-L223 | go | train | // IsUTFNumeric check if the string contains only unicode numbers of any kind.
// Numbers can be 0-9 but also Fractions ¾,Roman Ⅸ and Hangzhou 〩. Empty string is valid. | func IsUTFNumeric(str string) bool | // IsUTFNumeric check if the string contains only unicode numbers of any kind.
// Numbers can be 0-9 but also Fractions ¾,Roman Ⅸ and Hangzhou 〩. Empty string is valid.
func IsUTFNumeric(str string) bool | {
if IsNull(str) {
return true
}
if strings.IndexAny(str, "+-") > 0 {
return false
}
if len(str) > 1 {
str = strings.TrimPrefix(str, "-")
str = strings.TrimPrefix(str, "+")
}
for _, c := range str {
if !unicode.IsNumber(c) { //numbers && minus sign are ok
return false
}
}
return true
} |
asaskevich/govalidator | f61b66f89f4a311bef65f13e575bcf1a2ffadda6 | validator.go | https://github.com/asaskevich/govalidator/blob/f61b66f89f4a311bef65f13e575bcf1a2ffadda6/validator.go#L226-L244 | go | train | // IsUTFDigit check if the string contains only unicode radix-10 decimal digits. Empty string is valid. | func IsUTFDigit(str string) bool | // IsUTFDigit check if the string contains only unicode radix-10 decimal digits. Empty string is valid.
func IsUTFDigit(str string) bool | {
if IsNull(str) {
return true
}
if strings.IndexAny(str, "+-") > 0 {
return false
}
if len(str) > 1 {
str = strings.TrimPrefix(str, "-")
str = strings.TrimPrefix(str, "+")
}
for _, c := range str {
if !unicode.IsDigit(c) { //digits && minus sign are ok
return false
}
}
return true
} |
asaskevich/govalidator | f61b66f89f4a311bef65f13e575bcf1a2ffadda6 | validator.go | https://github.com/asaskevich/govalidator/blob/f61b66f89f4a311bef65f13e575bcf1a2ffadda6/validator.go#L262-L267 | go | train | // IsLowerCase check if the string is lowercase. Empty string is valid. | func IsLowerCase(str string) bool | // IsLowerCase check if the string is lowercase. Empty string is valid.
func IsLowerCase(str string) bool | {
if IsNull(str) {
return true
}
return str == strings.ToLower(str)
} |
asaskevich/govalidator | f61b66f89f4a311bef65f13e575bcf1a2ffadda6 | validator.go | https://github.com/asaskevich/govalidator/blob/f61b66f89f4a311bef65f13e575bcf1a2ffadda6/validator.go#L270-L275 | go | train | // IsUpperCase check if the string is uppercase. Empty string is valid. | func IsUpperCase(str string) bool | // IsUpperCase check if the string is uppercase. Empty string is valid.
func IsUpperCase(str string) bool | {
if IsNull(str) {
return true
}
return str == strings.ToUpper(str)
} |
asaskevich/govalidator | f61b66f89f4a311bef65f13e575bcf1a2ffadda6 | validator.go | https://github.com/asaskevich/govalidator/blob/f61b66f89f4a311bef65f13e575bcf1a2ffadda6/validator.go#L278-L283 | go | train | // HasLowerCase check if the string contains at least 1 lowercase. Empty string is valid. | func HasLowerCase(str string) bool | // HasLowerCase check if the string contains at least 1 lowercase. Empty string is valid.
func HasLowerCase(str string) bool | {
if IsNull(str) {
return true
}
return rxHasLowerCase.MatchString(str)
} |
asaskevich/govalidator | f61b66f89f4a311bef65f13e575bcf1a2ffadda6 | validator.go | https://github.com/asaskevich/govalidator/blob/f61b66f89f4a311bef65f13e575bcf1a2ffadda6/validator.go#L286-L291 | go | train | // HasUpperCase check if the string contians as least 1 uppercase. Empty string is valid. | func HasUpperCase(str string) bool | // HasUpperCase check if the string contians as least 1 uppercase. Empty string is valid.
func HasUpperCase(str string) bool | {
if IsNull(str) {
return true
}
return rxHasUpperCase.MatchString(str)
} |
asaskevich/govalidator | f61b66f89f4a311bef65f13e575bcf1a2ffadda6 | validator.go | https://github.com/asaskevich/govalidator/blob/f61b66f89f4a311bef65f13e575bcf1a2ffadda6/validator.go#L294-L299 | go | train | // IsInt check if the string is an integer. Empty string is valid. | func IsInt(str string) bool | // IsInt check if the string is an integer. Empty string is valid.
func IsInt(str string) bool | {
if IsNull(str) {
return true
}
return rxInt.MatchString(str)
} |
asaskevich/govalidator | f61b66f89f4a311bef65f13e575bcf1a2ffadda6 | validator.go | https://github.com/asaskevich/govalidator/blob/f61b66f89f4a311bef65f13e575bcf1a2ffadda6/validator.go#L309-L317 | go | train | // IsDivisibleBy check if the string is a number that's divisible by another.
// If second argument is not valid integer or zero, it's return false.
// Otherwise, if first argument is not valid integer or zero, it's return true (Invalid string converts to zero). | func IsDivisibleBy(str, num string) bool | // IsDivisibleBy check if the string is a number that's divisible by another.
// If second argument is not valid integer or zero, it's return false.
// Otherwise, if first argument is not valid integer or zero, it's return true (Invalid string converts to zero).
func IsDivisibleBy(str, num string) bool | {
f, _ := ToFloat(str)
p := int64(f)
q, _ := ToInt(num)
if q == 0 {
return false
}
return (p == 0) || (p%q == 0)
} |
asaskevich/govalidator | f61b66f89f4a311bef65f13e575bcf1a2ffadda6 | validator.go | https://github.com/asaskevich/govalidator/blob/f61b66f89f4a311bef65f13e575bcf1a2ffadda6/validator.go#L335-L337 | go | train | // IsByteLength check if the string's length (in bytes) falls in a range. | func IsByteLength(str string, min, max int) bool | // IsByteLength check if the string's length (in bytes) falls in a range.
func IsByteLength(str string, min, max int) bool | {
return len(str) >= min && len(str) <= max
} |
asaskevich/govalidator | f61b66f89f4a311bef65f13e575bcf1a2ffadda6 | validator.go | https://github.com/asaskevich/govalidator/blob/f61b66f89f4a311bef65f13e575bcf1a2ffadda6/validator.go#L360-L386 | go | train | // IsCreditCard check if the string is a credit card. | func IsCreditCard(str string) bool | // IsCreditCard check if the string is a credit card.
func IsCreditCard(str string) bool | {
sanitized := notNumberRegexp.ReplaceAllString(str, "")
if !rxCreditCard.MatchString(sanitized) {
return false
}
var sum int64
var digit string
var tmpNum int64
var shouldDouble bool
for i := len(sanitized) - 1; i >= 0; i-- {
digit = sanitized[i:(i + 1)]
tmpNum, _ = ToInt(digit)
if shouldDouble {
tmpNum *= 2
if tmpNum >= 10 {
sum += ((tmpNum % 10) + 1)
} else {
sum += tmpNum
}
} else {
sum += tmpNum
}
shouldDouble = !shouldDouble
}
return sum%10 == 0
} |
asaskevich/govalidator | f61b66f89f4a311bef65f13e575bcf1a2ffadda6 | validator.go | https://github.com/asaskevich/govalidator/blob/f61b66f89f4a311bef65f13e575bcf1a2ffadda6/validator.go#L400-L431 | go | train | // IsISBN check if the string is an ISBN (version 10 or 13).
// If version value is not equal to 10 or 13, it will be check both variants. | func IsISBN(str string, version int) bool | // IsISBN check if the string is an ISBN (version 10 or 13).
// If version value is not equal to 10 or 13, it will be check both variants.
func IsISBN(str string, version int) bool | {
sanitized := whiteSpacesAndMinus.ReplaceAllString(str, "")
var checksum int32
var i int32
if version == 10 {
if !rxISBN10.MatchString(sanitized) {
return false
}
for i = 0; i < 9; i++ {
checksum += (i + 1) * int32(sanitized[i]-'0')
}
if sanitized[9] == 'X' {
checksum += 10 * 10
} else {
checksum += 10 * int32(sanitized[9]-'0')
}
if checksum%11 == 0 {
return true
}
return false
} else if version == 13 {
if !rxISBN13.MatchString(sanitized) {
return false
}
factor := []int32{1, 3}
for i = 0; i < 12; i++ {
checksum += factor[i%2] * int32(sanitized[i]-'0')
}
return (int32(sanitized[12]-'0'))-((10-(checksum%10))%10) == 0
}
return IsISBN(str, 10) || IsISBN(str, 13)
} |
asaskevich/govalidator | f61b66f89f4a311bef65f13e575bcf1a2ffadda6 | validator.go | https://github.com/asaskevich/govalidator/blob/f61b66f89f4a311bef65f13e575bcf1a2ffadda6/validator.go#L434-L437 | go | train | // IsJSON check if the string is valid JSON (note: uses json.Unmarshal). | func IsJSON(str string) bool | // IsJSON check if the string is valid JSON (note: uses json.Unmarshal).
func IsJSON(str string) bool | {
var js json.RawMessage
return json.Unmarshal([]byte(str), &js) == nil
} |
asaskevich/govalidator | f61b66f89f4a311bef65f13e575bcf1a2ffadda6 | validator.go | https://github.com/asaskevich/govalidator/blob/f61b66f89f4a311bef65f13e575bcf1a2ffadda6/validator.go#L440-L445 | go | train | // IsMultibyte check if the string contains one or more multibyte chars. Empty string is valid. | func IsMultibyte(str string) bool | // IsMultibyte check if the string contains one or more multibyte chars. Empty string is valid.
func IsMultibyte(str string) bool | {
if IsNull(str) {
return true
}
return rxMultibyte.MatchString(str)
} |
asaskevich/govalidator | f61b66f89f4a311bef65f13e575bcf1a2ffadda6 | validator.go | https://github.com/asaskevich/govalidator/blob/f61b66f89f4a311bef65f13e575bcf1a2ffadda6/validator.go#L448-L453 | go | train | // IsASCII check if the string contains ASCII chars only. Empty string is valid. | func IsASCII(str string) bool | // IsASCII check if the string contains ASCII chars only. Empty string is valid.
func IsASCII(str string) bool | {
if IsNull(str) {
return true
}
return rxASCII.MatchString(str)
} |
asaskevich/govalidator | f61b66f89f4a311bef65f13e575bcf1a2ffadda6 | validator.go | https://github.com/asaskevich/govalidator/blob/f61b66f89f4a311bef65f13e575bcf1a2ffadda6/validator.go#L456-L461 | go | train | // IsPrintableASCII check if the string contains printable ASCII chars only. Empty string is valid. | func IsPrintableASCII(str string) bool | // IsPrintableASCII check if the string contains printable ASCII chars only. Empty string is valid.
func IsPrintableASCII(str string) bool | {
if IsNull(str) {
return true
}
return rxPrintableASCII.MatchString(str)
} |
asaskevich/govalidator | f61b66f89f4a311bef65f13e575bcf1a2ffadda6 | validator.go | https://github.com/asaskevich/govalidator/blob/f61b66f89f4a311bef65f13e575bcf1a2ffadda6/validator.go#L464-L469 | go | train | // IsFullWidth check if the string contains any full-width chars. Empty string is valid. | func IsFullWidth(str string) bool | // IsFullWidth check if the string contains any full-width chars. Empty string is valid.
func IsFullWidth(str string) bool | {
if IsNull(str) {
return true
}
return rxFullWidth.MatchString(str)
} |
asaskevich/govalidator | f61b66f89f4a311bef65f13e575bcf1a2ffadda6 | validator.go | https://github.com/asaskevich/govalidator/blob/f61b66f89f4a311bef65f13e575bcf1a2ffadda6/validator.go#L472-L477 | go | train | // IsHalfWidth check if the string contains any half-width chars. Empty string is valid. | func IsHalfWidth(str string) bool | // IsHalfWidth check if the string contains any half-width chars. Empty string is valid.
func IsHalfWidth(str string) bool | {
if IsNull(str) {
return true
}
return rxHalfWidth.MatchString(str)
} |
asaskevich/govalidator | f61b66f89f4a311bef65f13e575bcf1a2ffadda6 | validator.go | https://github.com/asaskevich/govalidator/blob/f61b66f89f4a311bef65f13e575bcf1a2ffadda6/validator.go#L480-L485 | go | train | // IsVariableWidth check if the string contains a mixture of full and half-width chars. Empty string is valid. | func IsVariableWidth(str string) bool | // IsVariableWidth check if the string contains a mixture of full and half-width chars. Empty string is valid.
func IsVariableWidth(str string) bool | {
if IsNull(str) {
return true
}
return rxHalfWidth.MatchString(str) && rxFullWidth.MatchString(str)
} |
asaskevich/govalidator | f61b66f89f4a311bef65f13e575bcf1a2ffadda6 | validator.go | https://github.com/asaskevich/govalidator/blob/f61b66f89f4a311bef65f13e575bcf1a2ffadda6/validator.go#L493-L505 | go | train | // IsFilePath check is a string is Win or Unix file path and returns it's type. | func IsFilePath(str string) (bool, int) | // IsFilePath check is a string is Win or Unix file path and returns it's type.
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
} |
asaskevich/govalidator | f61b66f89f4a311bef65f13e575bcf1a2ffadda6 | validator.go | https://github.com/asaskevich/govalidator/blob/f61b66f89f4a311bef65f13e575bcf1a2ffadda6/validator.go#L508-L514 | go | train | // IsDataURI checks if a string is base64 encoded data URI such as an image | func IsDataURI(str string) bool | // IsDataURI checks if a string is base64 encoded data URI such as an image
func IsDataURI(str string) bool | {
dataURI := strings.Split(str, ",")
if !rxDataURI.MatchString(dataURI[0]) {
return false
}
return IsBase64(dataURI[1])
} |
asaskevich/govalidator | f61b66f89f4a311bef65f13e575bcf1a2ffadda6 | validator.go | https://github.com/asaskevich/govalidator/blob/f61b66f89f4a311bef65f13e575bcf1a2ffadda6/validator.go#L517-L524 | go | train | // IsISO3166Alpha2 checks if a string is valid two-letter country code | func IsISO3166Alpha2(str string) bool | // IsISO3166Alpha2 checks if a string is valid two-letter country code
func IsISO3166Alpha2(str string) bool | {
for _, entry := range ISO3166List {
if str == entry.Alpha2Code {
return true
}
}
return false
} |
asaskevich/govalidator | f61b66f89f4a311bef65f13e575bcf1a2ffadda6 | validator.go | https://github.com/asaskevich/govalidator/blob/f61b66f89f4a311bef65f13e575bcf1a2ffadda6/validator.go#L527-L534 | go | train | // IsISO3166Alpha3 checks if a string is valid three-letter country code | func IsISO3166Alpha3(str string) bool | // IsISO3166Alpha3 checks if a string is valid three-letter country code
func IsISO3166Alpha3(str string) bool | {
for _, entry := range ISO3166List {
if str == entry.Alpha3Code {
return true
}
}
return false
} |
asaskevich/govalidator | f61b66f89f4a311bef65f13e575bcf1a2ffadda6 | validator.go | https://github.com/asaskevich/govalidator/blob/f61b66f89f4a311bef65f13e575bcf1a2ffadda6/validator.go#L537-L544 | go | train | // IsISO693Alpha2 checks if a string is valid two-letter language code | func IsISO693Alpha2(str string) bool | // IsISO693Alpha2 checks if a string is valid two-letter language code
func IsISO693Alpha2(str string) bool | {
for _, entry := range ISO693List {
if str == entry.Alpha2Code {
return true
}
}
return false
} |
asaskevich/govalidator | f61b66f89f4a311bef65f13e575bcf1a2ffadda6 | validator.go | https://github.com/asaskevich/govalidator/blob/f61b66f89f4a311bef65f13e575bcf1a2ffadda6/validator.go#L547-L554 | go | train | // IsISO693Alpha3b checks if a string is valid three-letter language code | func IsISO693Alpha3b(str string) bool | // IsISO693Alpha3b checks if a string is valid three-letter language code
func IsISO693Alpha3b(str string) bool | {
for _, entry := range ISO693List {
if str == entry.Alpha3bCode {
return true
}
}
return false
} |
asaskevich/govalidator | f61b66f89f4a311bef65f13e575bcf1a2ffadda6 | validator.go | https://github.com/asaskevich/govalidator/blob/f61b66f89f4a311bef65f13e575bcf1a2ffadda6/validator.go#L567-L590 | go | train | // IsHash checks if a string is a hash of type algorithm.
// Algorithm is one of ['md4', 'md5', 'sha1', 'sha256', 'sha384', 'sha512', 'ripemd128', 'ripemd160', 'tiger128', 'tiger160', 'tiger192', 'crc32', 'crc32b'] | func IsHash(str string, algorithm string) bool | // IsHash checks if a string is a hash of type algorithm.
// Algorithm is one of ['md4', 'md5', 'sha1', 'sha256', 'sha384', 'sha512', 'ripemd128', 'ripemd160', 'tiger128', 'tiger160', 'tiger192', 'crc32', 'crc32b']
func IsHash(str string, algorithm string) bool | {
len := "0"
algo := strings.ToLower(algorithm)
if algo == "crc32" || algo == "crc32b" {
len = "8"
} else if algo == "md5" || algo == "md4" || algo == "ripemd128" || algo == "tiger128" {
len = "32"
} else if algo == "sha1" || algo == "ripemd160" || algo == "tiger160" {
len = "40"
} else if algo == "tiger192" {
len = "48"
} else if algo == "sha256" {
len = "64"
} else if algo == "sha384" {
len = "96"
} else if algo == "sha512" {
len = "128"
} else {
return false
}
return Matches(str, "^[a-f0-9]{"+len+"}$")
} |
asaskevich/govalidator | f61b66f89f4a311bef65f13e575bcf1a2ffadda6 | validator.go | https://github.com/asaskevich/govalidator/blob/f61b66f89f4a311bef65f13e575bcf1a2ffadda6/validator.go#L593-L600 | go | train | // IsDialString validates the given string for usage with the various Dial() functions | func IsDialString(str string) bool | // IsDialString validates the given string for usage with the various Dial() functions
func IsDialString(str string) bool | {
if h, p, err := net.SplitHostPort(str); err == nil && h != "" && p != "" && (IsDNSName(h) || IsIP(h)) && IsPort(p) {
return true
}
return false
} |
asaskevich/govalidator | f61b66f89f4a311bef65f13e575bcf1a2ffadda6 | validator.go | https://github.com/asaskevich/govalidator/blob/f61b66f89f4a311bef65f13e575bcf1a2ffadda6/validator.go#L608-L613 | go | train | // IsPort checks if a string represents a valid port | func IsPort(str string) bool | // IsPort checks if a string represents a valid port
func IsPort(str string) bool | {
if i, err := strconv.Atoi(str); err == nil && i > 0 && i < 65536 {
return true
}
return false
} |
asaskevich/govalidator | f61b66f89f4a311bef65f13e575bcf1a2ffadda6 | validator.go | https://github.com/asaskevich/govalidator/blob/f61b66f89f4a311bef65f13e575bcf1a2ffadda6/validator.go#L616-L619 | go | train | // IsIPv4 check if the string is an IP version 4. | func IsIPv4(str string) bool | // IsIPv4 check if the string is an IP version 4.
func IsIPv4(str string) bool | {
ip := net.ParseIP(str)
return ip != nil && strings.Contains(str, ".")
} |
asaskevich/govalidator | f61b66f89f4a311bef65f13e575bcf1a2ffadda6 | validator.go | https://github.com/asaskevich/govalidator/blob/f61b66f89f4a311bef65f13e575bcf1a2ffadda6/validator.go#L628-L631 | go | train | // IsCIDR check if the string is an valid CIDR notiation (IPV4 & IPV6) | func IsCIDR(str string) bool | // IsCIDR check if the string is an valid CIDR notiation (IPV4 & IPV6)
func IsCIDR(str string) bool | {
_, _, err := net.ParseCIDR(str)
return err == nil
} |
asaskevich/govalidator | f61b66f89f4a311bef65f13e575bcf1a2ffadda6 | validator.go | https://github.com/asaskevich/govalidator/blob/f61b66f89f4a311bef65f13e575bcf1a2ffadda6/validator.go#L641-L644 | go | train | // IsMAC check if a string is valid MAC address.
// Possible MAC formats:
// 01:23:45:67:89:ab
// 01:23:45:67:89:ab:cd:ef
// 01-23-45-67-89-ab
// 01-23-45-67-89-ab-cd-ef
// 0123.4567.89ab
// 0123.4567.89ab.cdef | func IsMAC(str string) bool | // IsMAC check if a string is valid MAC address.
// Possible MAC formats:
// 01:23:45:67:89:ab
// 01:23:45:67:89:ab:cd:ef
// 01-23-45-67-89-ab
// 01-23-45-67-89-ab-cd-ef
// 0123.4567.89ab
// 0123.4567.89ab.cdef
func IsMAC(str string) bool | {
_, err := net.ParseMAC(str)
return err == nil
} |
asaskevich/govalidator | f61b66f89f4a311bef65f13e575bcf1a2ffadda6 | validator.go | https://github.com/asaskevich/govalidator/blob/f61b66f89f4a311bef65f13e575bcf1a2ffadda6/validator.go#L667-L698 | go | train | // IsRsaPublicKey check if a string is valid public key with provided length | func IsRsaPublicKey(str string, keylen int) bool | // IsRsaPublicKey check if a string is valid public key with provided length
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)
} |
asaskevich/govalidator | f61b66f89f4a311bef65f13e575bcf1a2ffadda6 | validator.go | https://github.com/asaskevich/govalidator/blob/f61b66f89f4a311bef65f13e575bcf1a2ffadda6/validator.go#L738-L804 | go | train | // ValidateStruct use tags for fields.
// result will be equal to `false` if there are any errors. | func ValidateStruct(s interface{}) (bool, error) | // ValidateStruct use tags for fields.
// result will be equal to `false` if there are any errors.
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
} |
asaskevich/govalidator | f61b66f89f4a311bef65f13e575bcf1a2ffadda6 | validator.go | https://github.com/asaskevich/govalidator/blob/f61b66f89f4a311bef65f13e575bcf1a2ffadda6/validator.go#L807-L825 | go | train | // parseTagIntoMap parses a struct tag `valid:required~Some error message,length(2|3)` into map[string]string{"required": "Some error message", "length(2|3)": ""} | func parseTagIntoMap(tag string) tagOptionsMap | // parseTagIntoMap parses a struct tag `valid:required~Some error message,length(2|3)` into map[string]string{"required": "Some error message", "length(2|3)": ""}
func parseTagIntoMap(tag string) tagOptionsMap | {
optionsMap := make(tagOptionsMap)
options := strings.Split(tag, ",")
for i, option := range options {
option = strings.TrimSpace(option)
validationOptions := strings.Split(option, "~")
if !isValidTag(validationOptions[0]) {
continue
}
if len(validationOptions) == 2 {
optionsMap[validationOptions[0]] = tagOption{validationOptions[0], validationOptions[1], i}
} else {
optionsMap[validationOptions[0]] = tagOption{validationOptions[0], "", i}
}
}
return optionsMap
} |
asaskevich/govalidator | f61b66f89f4a311bef65f13e575bcf1a2ffadda6 | validator.go | https://github.com/asaskevich/govalidator/blob/f61b66f89f4a311bef65f13e575bcf1a2ffadda6/validator.go#L847-L852 | go | train | // IsSSN will validate the given string as a U.S. Social Security Number | func IsSSN(str string) bool | // IsSSN will validate the given string as a U.S. Social Security Number
func IsSSN(str string) bool | {
if str == "" || len(str) != 11 {
return false
}
return rxSSN.MatchString(str)
} |
asaskevich/govalidator | f61b66f89f4a311bef65f13e575bcf1a2ffadda6 | validator.go | https://github.com/asaskevich/govalidator/blob/f61b66f89f4a311bef65f13e575bcf1a2ffadda6/validator.go#L860-L863 | go | train | // IsTime check if string is valid according to given format | func IsTime(str string, format string) bool | // IsTime check if string is valid according to given format
func IsTime(str string, format string) bool | {
_, err := time.Parse(format, str)
return err == nil
} |
asaskevich/govalidator | f61b66f89f4a311bef65f13e575bcf1a2ffadda6 | validator.go | https://github.com/asaskevich/govalidator/blob/f61b66f89f4a311bef65f13e575bcf1a2ffadda6/validator.go#L876-L884 | go | train | // IsISO4217 check if string is valid ISO currency code | func IsISO4217(str string) bool | // IsISO4217 check if string is valid ISO currency code
func IsISO4217(str string) bool | {
for _, currency := range ISO4217List {
if str == currency {
return true
}
}
return false
} |
asaskevich/govalidator | f61b66f89f4a311bef65f13e575bcf1a2ffadda6 | validator.go | https://github.com/asaskevich/govalidator/blob/f61b66f89f4a311bef65f13e575bcf1a2ffadda6/validator.go#L887-L895 | go | train | // ByteLength check string's length | func ByteLength(str string, params ...string) bool | // ByteLength check string's length
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
} |
asaskevich/govalidator | f61b66f89f4a311bef65f13e575bcf1a2ffadda6 | validator.go | https://github.com/asaskevich/govalidator/blob/f61b66f89f4a311bef65f13e575bcf1a2ffadda6/validator.go#L905-L912 | go | train | // IsRsaPub check whether string is valid RSA key
// Alias for IsRsaPublicKey | func IsRsaPub(str string, params ...string) bool | // IsRsaPub check whether string is valid RSA key
// Alias for IsRsaPublicKey
func IsRsaPub(str string, params ...string) bool | {
if len(params) == 1 {
len, _ := ToInt(params[0])
return IsRsaPublicKey(str, int(len))
}
return false
} |
asaskevich/govalidator | f61b66f89f4a311bef65f13e575bcf1a2ffadda6 | validator.go | https://github.com/asaskevich/govalidator/blob/f61b66f89f4a311bef65f13e575bcf1a2ffadda6/validator.go#L915-L921 | go | train | // StringMatches checks if a string matches a given pattern. | func StringMatches(s string, params ...string) bool | // StringMatches checks if a string matches a given pattern.
func StringMatches(s string, params ...string) bool | {
if len(params) == 1 {
pattern := params[0]
return Matches(s, pattern)
}
return false
} |
asaskevich/govalidator | f61b66f89f4a311bef65f13e575bcf1a2ffadda6 | validator.go | https://github.com/asaskevich/govalidator/blob/f61b66f89f4a311bef65f13e575bcf1a2ffadda6/validator.go#L924-L934 | go | train | // StringLength check string's length (including multi byte strings) | func StringLength(str string, params ...string) bool | // StringLength check string's length (including multi byte strings)
func StringLength(str string, params ...string) bool | {
if len(params) == 2 {
strLength := utf8.RuneCountInString(str)
min, _ := ToInt(params[0])
max, _ := ToInt(params[1])
return strLength >= int(min) && strLength <= int(max)
}
return false
} |
asaskevich/govalidator | f61b66f89f4a311bef65f13e575bcf1a2ffadda6 | validator.go | https://github.com/asaskevich/govalidator/blob/f61b66f89f4a311bef65f13e575bcf1a2ffadda6/validator.go#L937-L946 | go | train | // Range check string's length | func Range(str string, params ...string) bool | // Range check string's length
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
} |
asaskevich/govalidator | f61b66f89f4a311bef65f13e575bcf1a2ffadda6 | validator.go | https://github.com/asaskevich/govalidator/blob/f61b66f89f4a311bef65f13e575bcf1a2ffadda6/validator.go#L961-L969 | go | train | // IsIn check if string str is a member of the set of strings params | func IsIn(str string, params ...string) bool | // IsIn check if string str is a member of the set of strings params
func IsIn(str string, params ...string) bool | {
for _, param := range params {
if str == param {
return true
}
}
return false
} |
asaskevich/govalidator | f61b66f89f4a311bef65f13e575bcf1a2ffadda6 | validator.go | https://github.com/asaskevich/govalidator/blob/f61b66f89f4a311bef65f13e575bcf1a2ffadda6/validator.go#L1239-L1244 | go | train | // 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. | func ErrorByField(e error, field string) string | // 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.
func ErrorByField(e error, field string) string | {
if e == nil {
return ""
}
return ErrorsByField(e)[field]
} |
asaskevich/govalidator | f61b66f89f4a311bef65f13e575bcf1a2ffadda6 | validator.go | https://github.com/asaskevich/govalidator/blob/f61b66f89f4a311bef65f13e575bcf1a2ffadda6/validator.go#L1248-L1268 | go | train | // ErrorsByField returns map of errors of the struct validated
// by ValidateStruct or empty map if there are no errors. | func ErrorsByField(e error) map[string]string | // ErrorsByField returns map of errors of the struct validated
// by ValidateStruct or empty map if there are no errors.
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
} |
beego/bee | 6a86284cec9a17f9aae6fe82ecf3c436aafed68d | generate/g_model.go | https://github.com/beego/bee/blob/6a86284cec9a17f9aae6fe82ecf3c436aafed68d/generate/g_model.go#L110-L138 | go | train | // fields support type
// http://beego.me/docs/mvc/model/models.md#mysql | func getType(ktype string) (kt, tag string, hasTime bool) | // fields support type
// http://beego.me/docs/mvc/model/models.md#mysql
func getType(ktype string) (kt, tag string, hasTime bool) | {
kv := strings.SplitN(ktype, ":", 2)
switch kv[0] {
case "string":
if len(kv) == 2 {
return "string", "`orm:\"size(" + kv[1] + ")\"`", false
}
return "string", "`orm:\"size(128)\"`", false
case "text":
return "string", "`orm:\"type(longtext)\"`", false
case "auto":
return "int64", "`orm:\"auto\"`", false
case "pk":
return "int64", "`orm:\"pk\"`", false
case "datetime":
return "time.Time", "`orm:\"type(datetime)\"`", true
case "int", "int8", "int16", "int32", "int64":
fallthrough
case "uint", "uint8", "uint16", "uint32", "uint64":
fallthrough
case "bool":
fallthrough
case "float32", "float64":
return kv[0], "", false
case "float":
return "float64", "", false
}
return "", "", false
} |
beego/bee | 6a86284cec9a17f9aae6fe82ecf3c436aafed68d | cmd/commands/dlv/dlv_amd64.go | https://github.com/beego/bee/blob/6a86284cec9a17f9aae6fe82ecf3c436aafed68d/cmd/commands/dlv/dlv_amd64.go#L86-L99 | go | train | // buildDebug builds a debug binary in the current working directory | func buildDebug() (string, error) | // buildDebug builds a debug binary in the current working directory
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
} |
beego/bee | 6a86284cec9a17f9aae6fe82ecf3c436aafed68d | cmd/commands/dlv/dlv_amd64.go | https://github.com/beego/bee/blob/6a86284cec9a17f9aae6fe82ecf3c436aafed68d/cmd/commands/dlv/dlv_amd64.go#L102-L124 | go | train | // loadPathsToWatch loads the paths that needs to be watched for changes | func loadPathsToWatch(paths *[]string) error | // loadPathsToWatch loads the paths that needs to be watched for changes
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
} |
beego/bee | 6a86284cec9a17f9aae6fe82ecf3c436aafed68d | cmd/commands/dlv/dlv_amd64.go | https://github.com/beego/bee/blob/6a86284cec9a17f9aae6fe82ecf3c436aafed68d/cmd/commands/dlv/dlv_amd64.go#L127-L189 | go | train | // startDelveDebugger starts the Delve debugger server | func startDelveDebugger(addr string, ch chan int) int | // startDelveDebugger starts the Delve debugger server
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
} |
beego/bee | 6a86284cec9a17f9aae6fe82ecf3c436aafed68d | cmd/commands/dlv/dlv_amd64.go | https://github.com/beego/bee/blob/6a86284cec9a17f9aae6fe82ecf3c436aafed68d/cmd/commands/dlv/dlv_amd64.go#L194-L245 | go | train | // startWatcher starts the fsnotify watcher on the passed paths | func startWatcher(paths []string, ch chan int) | // startWatcher starts the fsnotify watcher on the passed paths
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
}
}
}
} |
beego/bee | 6a86284cec9a17f9aae6fe82ecf3c436aafed68d | generate/g_migration.go | https://github.com/beego/bee/blob/6a86284cec9a17f9aae6fe82ecf3c436aafed68d/generate/g_migration.go#L192-L236 | go | train | // generateMigration generates migration file template for database schema update.
// The generated file template consists of an up() method for updating schema and
// a down() method for reverting the update. | func GenerateMigration(mname, upsql, downsql, curpath string) | // generateMigration generates migration file template for database schema update.
// The generated file template consists of an up() method for updating schema and
// a down() method for reverting the update.
func GenerateMigration(mname, upsql, downsql, curpath string) | {
w := colors.NewColorWriter(os.Stdout)
migrationFilePath := path.Join(curpath, DBPath, MPath)
if _, err := os.Stat(migrationFilePath); os.IsNotExist(err) {
// create migrations directory
if err := os.MkdirAll(migrationFilePath, 0777); err != nil {
beeLogger.Log.Fatalf("Could not create migration directory: %s", err)
}
}
// create file
today := time.Now().Format(MDateFormat)
fpath := path.Join(migrationFilePath, fmt.Sprintf("%s_%s.go", today, mname))
if f, err := os.OpenFile(fpath, os.O_CREATE|os.O_EXCL|os.O_RDWR, 0666); err == nil {
defer utils.CloseFile(f)
ddlSpec := ""
spec := ""
up := ""
down := ""
if DDL != "" {
ddlSpec = "m.ddlSpec()"
switch strings.Title(DDL.String()) {
case "Create":
spec = strings.Replace(DDLSpecCreate, "{{StructName}}", utils.CamelCase(mname)+"_"+today, -1)
case "Alter":
spec = strings.Replace(DDLSpecAlter, "{{StructName}}", utils.CamelCase(mname)+"_"+today, -1)
}
spec = strings.Replace(spec, "{{tableName}}", mname, -1)
} else {
up = strings.Replace(MigrationUp, "{{UpSQL}}", upsql, -1)
up = strings.Replace(up, "{{StructName}}", utils.CamelCase(mname)+"_"+today, -1)
down = strings.Replace(MigrationDown, "{{DownSQL}}", downsql, -1)
down = strings.Replace(down, "{{StructName}}", utils.CamelCase(mname)+"_"+today, -1)
}
header := strings.Replace(MigrationHeader, "{{StructName}}", utils.CamelCase(mname)+"_"+today, -1)
header = strings.Replace(header, "{{ddlSpec}}", ddlSpec, -1)
header = strings.Replace(header, "{{CurrTime}}", today, -1)
f.WriteString(header + spec + up + down)
// Run 'gofmt' on the generated source code
utils.FormatSourceCode(fpath)
fmt.Fprintf(w, "\t%s%screate%s\t %s%s\n", "\x1b[32m", "\x1b[1m", "\x1b[21m", fpath, "\x1b[0m")
} else {
beeLogger.Log.Fatalf("Could not create migration file: %s", err)
}
} |
beego/bee | 6a86284cec9a17f9aae6fe82ecf3c436aafed68d | generate/swaggergen/g_docs.go | https://github.com/beego/bee/blob/6a86284cec9a17f9aae6fe82ecf3c436aafed68d/generate/swaggergen/g_docs.go#L106-L139 | go | train | // ParsePackagesFromDir parses packages from a given directory | func ParsePackagesFromDir(dirpath string) | // ParsePackagesFromDir parses packages from a given directory
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)
}
} |
beego/bee | 6a86284cec9a17f9aae6fe82ecf3c436aafed68d | generate/swaggergen/g_docs.go | https://github.com/beego/bee/blob/6a86284cec9a17f9aae6fe82ecf3c436aafed68d/generate/swaggergen/g_docs.go#L159-L344 | go | train | // GenerateDocs generates documentations for a given path. | func GenerateDocs(curpath string) | // GenerateDocs generates documentations for a given path.
func GenerateDocs(curpath string) | {
fset := token.NewFileSet()
f, err := parser.ParseFile(fset, filepath.Join(curpath, "routers", "router.go"), nil, parser.ParseComments)
if err != nil {
beeLogger.Log.Fatalf("Error while parsing router.go: %s", err)
}
rootapi.Infos = swagger.Information{}
rootapi.SwaggerVersion = "2.0"
// Analyse API comments
if f.Comments != nil {
for _, c := range f.Comments {
for _, s := range strings.Split(c.Text(), "\n") {
if strings.HasPrefix(s, "@APIVersion") {
rootapi.Infos.Version = strings.TrimSpace(s[len("@APIVersion"):])
} else if strings.HasPrefix(s, "@Title") {
rootapi.Infos.Title = strings.TrimSpace(s[len("@Title"):])
} else if strings.HasPrefix(s, "@Description") {
rootapi.Infos.Description = strings.TrimSpace(s[len("@Description"):])
} else if strings.HasPrefix(s, "@TermsOfServiceUrl") {
rootapi.Infos.TermsOfService = strings.TrimSpace(s[len("@TermsOfServiceUrl"):])
} else if strings.HasPrefix(s, "@Contact") {
rootapi.Infos.Contact.EMail = strings.TrimSpace(s[len("@Contact"):])
} else if strings.HasPrefix(s, "@Name") {
rootapi.Infos.Contact.Name = strings.TrimSpace(s[len("@Name"):])
} else if strings.HasPrefix(s, "@URL") {
rootapi.Infos.Contact.URL = strings.TrimSpace(s[len("@URL"):])
} else if strings.HasPrefix(s, "@LicenseUrl") {
if rootapi.Infos.License == nil {
rootapi.Infos.License = &swagger.License{URL: strings.TrimSpace(s[len("@LicenseUrl"):])}
} else {
rootapi.Infos.License.URL = strings.TrimSpace(s[len("@LicenseUrl"):])
}
} else if strings.HasPrefix(s, "@License") {
if rootapi.Infos.License == nil {
rootapi.Infos.License = &swagger.License{Name: strings.TrimSpace(s[len("@License"):])}
} else {
rootapi.Infos.License.Name = strings.TrimSpace(s[len("@License"):])
}
} else if strings.HasPrefix(s, "@Schemes") {
rootapi.Schemes = strings.Split(strings.TrimSpace(s[len("@Schemes"):]), ",")
} else if strings.HasPrefix(s, "@Host") {
rootapi.Host = strings.TrimSpace(s[len("@Host"):])
} else if strings.HasPrefix(s, "@SecurityDefinition") {
if len(rootapi.SecurityDefinitions) == 0 {
rootapi.SecurityDefinitions = make(map[string]swagger.Security)
}
var out swagger.Security
p := getparams(strings.TrimSpace(s[len("@SecurityDefinition"):]))
if len(p) < 2 {
beeLogger.Log.Fatalf("Not enough params for security: %d\n", len(p))
}
out.Type = p[1]
switch out.Type {
case "oauth2":
if len(p) < 6 {
beeLogger.Log.Fatalf("Not enough params for oauth2: %d\n", len(p))
}
if !(p[3] == "implicit" || p[3] == "password" || p[3] == "application" || p[3] == "accessCode") {
beeLogger.Log.Fatalf("Unknown flow type: %s. Possible values are `implicit`, `password`, `application` or `accessCode`.\n", p[1])
}
out.AuthorizationURL = p[2]
out.Flow = p[3]
if len(p)%2 != 0 {
out.Description = strings.Trim(p[len(p)-1], `" `)
}
out.Scopes = make(map[string]string)
for i := 4; i < len(p)-1; i += 2 {
out.Scopes[p[i]] = strings.Trim(p[i+1], `" `)
}
case "apiKey":
if len(p) < 4 {
beeLogger.Log.Fatalf("Not enough params for apiKey: %d\n", len(p))
}
if !(p[3] == "header" || p[3] == "query") {
beeLogger.Log.Fatalf("Unknown in type: %s. Possible values are `query` or `header`.\n", p[4])
}
out.Name = p[2]
out.In = p[3]
if len(p) > 4 {
out.Description = strings.Trim(p[4], `" `)
}
case "basic":
if len(p) > 2 {
out.Description = strings.Trim(p[2], `" `)
}
default:
beeLogger.Log.Fatalf("Unknown security type: %s. Possible values are `oauth2`, `apiKey` or `basic`.\n", p[1])
}
rootapi.SecurityDefinitions[p[0]] = out
} else if strings.HasPrefix(s, "@Security") {
if len(rootapi.Security) == 0 {
rootapi.Security = make([]map[string][]string, 0)
}
rootapi.Security = append(rootapi.Security, getSecurity(s))
}
}
}
}
// Analyse controller package
for _, im := range f.Imports {
localName := ""
if im.Name != nil {
localName = im.Name.Name
}
analyseControllerPkg(path.Join(curpath, "vendor"), localName, im.Path.Value)
}
for _, d := range f.Decls {
switch specDecl := d.(type) {
case *ast.FuncDecl:
for _, l := range specDecl.Body.List {
switch stmt := l.(type) {
case *ast.AssignStmt:
for _, l := range stmt.Rhs {
if v, ok := l.(*ast.CallExpr); ok {
// Analyze NewNamespace, it will return version and the subfunction
selExpr, selOK := v.Fun.(*ast.SelectorExpr)
if !selOK || selExpr.Sel.Name != "NewNamespace" {
continue
}
version, params := analyseNewNamespace(v)
if rootapi.BasePath == "" && version != "" {
rootapi.BasePath = version
}
for _, p := range params {
switch pp := p.(type) {
case *ast.CallExpr:
var controllerName string
if selname := pp.Fun.(*ast.SelectorExpr).Sel.String(); selname == "NSNamespace" {
s, params := analyseNewNamespace(pp)
for _, sp := range params {
switch pp := sp.(type) {
case *ast.CallExpr:
if pp.Fun.(*ast.SelectorExpr).Sel.String() == "NSInclude" {
controllerName = analyseNSInclude(s, pp)
if v, ok := controllerComments[controllerName]; ok {
rootapi.Tags = append(rootapi.Tags, swagger.Tag{
Name: strings.Trim(s, "/"),
Description: v,
})
}
}
}
}
} else if selname == "NSInclude" {
controllerName = analyseNSInclude("", pp)
if v, ok := controllerComments[controllerName]; ok {
rootapi.Tags = append(rootapi.Tags, swagger.Tag{
Name: controllerName, // if the NSInclude has no prefix, we use the controllername as the tag
Description: v,
})
}
}
}
}
}
}
}
}
}
}
os.Mkdir(path.Join(curpath, "swagger"), 0755)
fd, err := os.Create(path.Join(curpath, "swagger", "swagger.json"))
if err != nil {
panic(err)
}
fdyml, err := os.Create(path.Join(curpath, "swagger", "swagger.yml"))
if err != nil {
panic(err)
}
defer fdyml.Close()
defer fd.Close()
dt, err := json.MarshalIndent(rootapi, "", " ")
dtyml, erryml := yaml.Marshal(rootapi)
if err != nil || erryml != nil {
panic(err)
}
_, err = fd.Write(dt)
_, erryml = fdyml.Write(dtyml)
if err != nil || erryml != nil {
panic(err)
}
} |
beego/bee | 6a86284cec9a17f9aae6fe82ecf3c436aafed68d | generate/swaggergen/g_docs.go | https://github.com/beego/bee/blob/6a86284cec9a17f9aae6fe82ecf3c436aafed68d/generate/swaggergen/g_docs.go#L347-L359 | go | train | // analyseNewNamespace returns version and the others params | func analyseNewNamespace(ce *ast.CallExpr) (first string, others []ast.Expr) | // analyseNewNamespace returns version and the others params
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
} |
beego/bee | 6a86284cec9a17f9aae6fe82ecf3c436aafed68d | generate/swaggergen/g_docs.go | https://github.com/beego/bee/blob/6a86284cec9a17f9aae6fe82ecf3c436aafed68d/generate/swaggergen/g_docs.go#L532-L780 | go | train | // parse the func comments | func parserComments(f *ast.FuncDecl, controllerName, pkgpath string) error | // parse the func comments
func parserComments(f *ast.FuncDecl, controllerName, pkgpath string) error | {
var routerPath string
var HTTPMethod string
opts := swagger.Operation{
Responses: make(map[string]swagger.Response),
}
funcName := f.Name.String()
comments := f.Doc
funcParamMap := buildParamMap(f.Type.Params)
//TODO: resultMap := buildParamMap(f.Type.Results)
if comments != nil && comments.List != nil {
for _, c := range comments.List {
t := strings.TrimSpace(strings.TrimPrefix(c.Text, "//"))
if strings.HasPrefix(t, "@router") {
elements := strings.TrimSpace(t[len("@router"):])
e1 := strings.SplitN(elements, " ", 2)
if len(e1) < 1 {
return errors.New("you should has router infomation")
}
routerPath = e1[0]
if len(e1) == 2 && e1[1] != "" {
e1 = strings.SplitN(e1[1], " ", 2)
HTTPMethod = strings.ToUpper(strings.Trim(e1[0], "[]"))
} else {
HTTPMethod = "GET"
}
} else if strings.HasPrefix(t, "@Title") {
opts.OperationID = controllerName + "." + strings.TrimSpace(t[len("@Title"):])
} else if strings.HasPrefix(t, "@Description") {
opts.Description = strings.TrimSpace(t[len("@Description"):])
} else if strings.HasPrefix(t, "@Summary") {
opts.Summary = strings.TrimSpace(t[len("@Summary"):])
} else if strings.HasPrefix(t, "@Success") {
ss := strings.TrimSpace(t[len("@Success"):])
rs := swagger.Response{}
respCode, pos := peekNextSplitString(ss)
ss = strings.TrimSpace(ss[pos:])
respType, pos := peekNextSplitString(ss)
if respType == "{object}" || respType == "{array}" {
isArray := respType == "{array}"
ss = strings.TrimSpace(ss[pos:])
schemaName, pos := peekNextSplitString(ss)
if schemaName == "" {
beeLogger.Log.Fatalf("[%s.%s] Schema must follow {object} or {array}", controllerName, funcName)
}
if strings.HasPrefix(schemaName, "[]") {
schemaName = schemaName[2:]
isArray = true
}
schema := swagger.Schema{}
if sType, ok := basicTypes[schemaName]; ok {
typeFormat := strings.Split(sType, ":")
schema.Type = typeFormat[0]
schema.Format = typeFormat[1]
} else {
m, mod, realTypes := getModel(schemaName)
schema.Ref = "#/definitions/" + m
if _, ok := modelsList[pkgpath+controllerName]; !ok {
modelsList[pkgpath+controllerName] = make(map[string]swagger.Schema)
}
modelsList[pkgpath+controllerName][schemaName] = mod
appendModels(pkgpath, controllerName, realTypes)
}
if isArray {
rs.Schema = &swagger.Schema{
Type: astTypeArray,
Items: &schema,
}
} else {
rs.Schema = &schema
}
rs.Description = strings.TrimSpace(ss[pos:])
} else {
rs.Description = strings.TrimSpace(ss)
}
opts.Responses[respCode] = rs
} else if strings.HasPrefix(t, "@Param") {
para := swagger.Parameter{}
p := getparams(strings.TrimSpace(t[len("@Param "):]))
if len(p) < 4 {
beeLogger.Log.Fatal(controllerName + "_" + funcName + "'s comments @Param should have at least 4 params")
}
paramNames := strings.SplitN(p[0], "=>", 2)
para.Name = paramNames[0]
funcParamName := para.Name
if len(paramNames) > 1 {
funcParamName = paramNames[1]
}
paramType, ok := funcParamMap[funcParamName]
if ok {
delete(funcParamMap, funcParamName)
}
switch p[1] {
case "query":
fallthrough
case "header":
fallthrough
case "path":
fallthrough
case "formData":
fallthrough
case "body":
break
default:
beeLogger.Log.Warnf("[%s.%s] Unknown param location: %s. Possible values are `query`, `header`, `path`, `formData` or `body`.\n", controllerName, funcName, p[1])
}
para.In = p[1]
pp := strings.Split(p[2], ".")
typ := pp[len(pp)-1]
if len(pp) >= 2 {
isArray := false
if p[1] == "body" && strings.HasPrefix(p[2], "[]") {
p[2] = p[2][2:]
isArray = true
}
m, mod, realTypes := getModel(p[2])
if isArray {
para.Schema = &swagger.Schema{
Type: astTypeArray,
Items: &swagger.Schema{
Ref: "#/definitions/" + m,
},
}
} else {
para.Schema = &swagger.Schema{
Ref: "#/definitions/" + m,
}
}
if _, ok := modelsList[pkgpath+controllerName]; !ok {
modelsList[pkgpath+controllerName] = make(map[string]swagger.Schema)
}
modelsList[pkgpath+controllerName][typ] = mod
appendModels(pkgpath, controllerName, realTypes)
} else {
if typ == "auto" {
typ = paramType
}
setParamType(¶, typ, pkgpath, controllerName)
}
switch len(p) {
case 5:
para.Required, _ = strconv.ParseBool(p[3])
para.Description = strings.Trim(p[4], `" `)
case 6:
para.Default = str2RealType(p[3], para.Type)
para.Required, _ = strconv.ParseBool(p[4])
para.Description = strings.Trim(p[5], `" `)
default:
para.Description = strings.Trim(p[3], `" `)
}
opts.Parameters = append(opts.Parameters, para)
} else if strings.HasPrefix(t, "@Failure") {
rs := swagger.Response{}
st := strings.TrimSpace(t[len("@Failure"):])
var cd []rune
var start bool
for i, s := range st {
if unicode.IsSpace(s) {
if start {
rs.Description = strings.TrimSpace(st[i+1:])
break
} else {
continue
}
}
start = true
cd = append(cd, s)
}
opts.Responses[string(cd)] = rs
} else if strings.HasPrefix(t, "@Deprecated") {
opts.Deprecated, _ = strconv.ParseBool(strings.TrimSpace(t[len("@Deprecated"):]))
} else if strings.HasPrefix(t, "@Accept") {
accepts := strings.Split(strings.TrimSpace(strings.TrimSpace(t[len("@Accept"):])), ",")
for _, a := range accepts {
switch a {
case "json":
opts.Consumes = append(opts.Consumes, ajson)
opts.Produces = append(opts.Produces, ajson)
case "xml":
opts.Consumes = append(opts.Consumes, axml)
opts.Produces = append(opts.Produces, axml)
case "plain":
opts.Consumes = append(opts.Consumes, aplain)
opts.Produces = append(opts.Produces, aplain)
case "html":
opts.Consumes = append(opts.Consumes, ahtml)
opts.Produces = append(opts.Produces, ahtml)
case "form":
opts.Consumes = append(opts.Consumes, aform)
}
}
} else if strings.HasPrefix(t, "@Security") {
if len(opts.Security) == 0 {
opts.Security = make([]map[string][]string, 0)
}
opts.Security = append(opts.Security, getSecurity(t))
}
}
}
if routerPath != "" {
//Go over function parameters which were not mapped and create swagger params for them
for name, typ := range funcParamMap {
para := swagger.Parameter{}
para.Name = name
setParamType(¶, typ, pkgpath, controllerName)
if paramInPath(name, routerPath) {
para.In = "path"
} else {
para.In = "query"
}
opts.Parameters = append(opts.Parameters, para)
}
var item *swagger.Item
if itemList, ok := controllerList[pkgpath+controllerName]; ok {
if it, ok := itemList[routerPath]; !ok {
item = &swagger.Item{}
} else {
item = it
}
} else {
controllerList[pkgpath+controllerName] = make(map[string]*swagger.Item)
item = &swagger.Item{}
}
for _, hm := range strings.Split(HTTPMethod, ",") {
switch hm {
case "GET":
item.Get = &opts
case "POST":
item.Post = &opts
case "PUT":
item.Put = &opts
case "PATCH":
item.Patch = &opts
case "DELETE":
item.Delete = &opts
case "HEAD":
item.Head = &opts
case "OPTIONS":
item.Options = &opts
}
}
controllerList[pkgpath+controllerName][routerPath] = item
}
return nil
} |
beego/bee | 6a86284cec9a17f9aae6fe82ecf3c436aafed68d | generate/swaggergen/g_docs.go | https://github.com/beego/bee/blob/6a86284cec9a17f9aae6fe82ecf3c436aafed68d/generate/swaggergen/g_docs.go#L891-L921 | go | train | // analisys params return []string
// @Param query form string true "The email for login"
// [query form string true "The email for login"] | func getparams(str string) []string | // analisys params return []string
// @Param query form string true "The email for login"
// [query form string true "The email for login"]
func getparams(str string) []string | {
var s []rune
var j int
var start bool
var r []string
var quoted int8
for _, c := range str {
if unicode.IsSpace(c) && quoted == 0 {
if !start {
continue
} else {
start = false
j++
r = append(r, string(s))
s = make([]rune, 0)
continue
}
}
start = true
if c == '"' {
quoted ^= 1
continue
}
s = append(s, c)
}
if len(s) > 0 {
r = append(r, string(s))
}
return r
} |
beego/bee | 6a86284cec9a17f9aae6fe82ecf3c436aafed68d | generate/swaggergen/g_docs.go | https://github.com/beego/bee/blob/6a86284cec9a17f9aae6fe82ecf3c436aafed68d/generate/swaggergen/g_docs.go#L997-L1075 | go | train | // parse as enum, in the package, find out all consts with the same type | func parseIdent(st *ast.Ident, k string, m *swagger.Schema, astPkgs []*ast.Package) | // parse as enum, in the package, find out all consts with the same type
func parseIdent(st *ast.Ident, k string, m *swagger.Schema, astPkgs []*ast.Package) | {
m.Title = k
basicType := fmt.Sprint(st)
if object, isStdLibObject := stdlibObject[basicType]; isStdLibObject {
basicType = object
}
if t, ok := basicTypes[basicType]; ok {
typeFormat := strings.Split(t, ":")
m.Type = typeFormat[0]
m.Format = typeFormat[1]
}
enums := make(map[int]string)
enumValues := make(map[int]interface{})
for _, pkg := range astPkgs {
for _, fl := range pkg.Files {
for _, obj := range fl.Scope.Objects {
if obj.Kind == ast.Con {
vs, ok := obj.Decl.(*ast.ValueSpec)
if !ok {
beeLogger.Log.Fatalf("Unknown type without ValueSpec: %v", vs)
}
ti, ok := vs.Type.(*ast.Ident)
if !ok {
// TODO type inference, iota not support yet
continue
}
// Only add the enums that are defined by the current identifier
if ti.Name != k {
continue
}
// For all names and values, aggregate them by it's position so that we can sort them later.
for i, val := range vs.Values {
v, ok := val.(*ast.BasicLit)
if !ok {
beeLogger.Log.Warnf("Unknown type without BasicLit: %v", v)
continue
}
enums[int(val.Pos())] = fmt.Sprintf("%s = %s", vs.Names[i].Name, v.Value)
switch v.Kind {
case token.INT:
vv, err := strconv.Atoi(v.Value)
if err != nil {
beeLogger.Log.Warnf("Unknown type with BasicLit to int: %v", v.Value)
continue
}
enumValues[int(val.Pos())] = vv
case token.FLOAT:
vv, err := strconv.ParseFloat(v.Value, 64)
if err != nil {
beeLogger.Log.Warnf("Unknown type with BasicLit to int: %v", v.Value)
continue
}
enumValues[int(val.Pos())] = vv
default:
enumValues[int(val.Pos())] = strings.Trim(v.Value, `"`)
}
}
}
}
}
}
// Sort the enums by position
if len(enums) > 0 {
var keys []int
for k := range enums {
keys = append(keys, k)
}
sort.Ints(keys)
for _, k := range keys {
m.Enum = append(m.Enum, enums[k])
}
// Automatically use the first enum value as the example.
m.Example = enumValues[keys[0]]
}
} |
beego/bee | 6a86284cec9a17f9aae6fe82ecf3c436aafed68d | generate/swaggergen/g_docs.go | https://github.com/beego/bee/blob/6a86284cec9a17f9aae6fe82ecf3c436aafed68d/generate/swaggergen/g_docs.go#L1276-L1288 | go | train | // append models | func appendModels(pkgpath, controllerName string, realTypes []string) | // append models
func appendModels(pkgpath, controllerName string, realTypes []string) | {
for _, realType := range realTypes {
if realType != "" && !isBasicType(strings.TrimLeft(realType, "[]")) &&
!strings.HasPrefix(realType, astTypeMap) && !strings.HasPrefix(realType, "&") {
if _, ok := modelsList[pkgpath+controllerName][realType]; ok {
continue
}
_, mod, newRealTypes := getModel(realType)
modelsList[pkgpath+controllerName][realType] = mod
appendModels(pkgpath, controllerName, newRealTypes)
}
}
} |
beego/bee | 6a86284cec9a17f9aae6fe82ecf3c436aafed68d | generate/g_appcode.go | https://github.com/beego/bee/blob/6a86284cec9a17f9aae6fe82ecf3c436aafed68d/generate/g_appcode.go#L190-L197 | go | train | // String returns the source code string for the Table struct | func (tb *Table) String() string | // String returns the source code string for the Table struct
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
} |
beego/bee | 6a86284cec9a17f9aae6fe82ecf3c436aafed68d | generate/g_appcode.go | https://github.com/beego/bee/blob/6a86284cec9a17f9aae6fe82ecf3c436aafed68d/generate/g_appcode.go#L201-L203 | go | train | // String returns the source code string of a field in Table struct
// It maps to a column in database table. e.g. Id int `orm:"column(id);auto"` | func (col *Column) String() string | // String returns the source code string of a field in Table struct
// It maps to a column in database table. e.g. Id int `orm:"column(id);auto"`
func (col *Column) String() string | {
return fmt.Sprintf("%s %s %s", col.Name, col.Type, col.Tag.String())
} |
beego/bee | 6a86284cec9a17f9aae6fe82ecf3c436aafed68d | generate/g_appcode.go | https://github.com/beego/bee/blob/6a86284cec9a17f9aae6fe82ecf3c436aafed68d/generate/g_appcode.go#L206-L264 | go | train | // String returns the ORM tag string for a column | func (tag *OrmTag) String() string | // String returns the ORM tag string for a column
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, ";"))
} |
beego/bee | 6a86284cec9a17f9aae6fe82ecf3c436aafed68d | generate/g_appcode.go | https://github.com/beego/bee/blob/6a86284cec9a17f9aae6fe82ecf3c436aafed68d/generate/g_appcode.go#L298-L325 | go | train | // Generate takes table, column and foreign key information from database connection
// and generate corresponding golang source files | func gen(dbms, connStr string, mode byte, selectedTableNames map[string]bool, apppath string) | // Generate takes table, column and foreign key information from database connection
// and generate corresponding golang source files
func gen(dbms, connStr string, mode byte, selectedTableNames map[string]bool, apppath string) | {
db, err := sql.Open(dbms, connStr)
if err != nil {
beeLogger.Log.Fatalf("Could not connect to '%s' database using '%s': %s", dbms, connStr, err)
}
defer db.Close()
if trans, ok := dbDriver[dbms]; ok {
beeLogger.Log.Info("Analyzing database tables...")
var tableNames []string
if len(selectedTableNames) != 0 {
for tableName := range selectedTableNames {
tableNames = append(tableNames, tableName)
}
} else {
tableNames = trans.GetTableNames(db)
}
tables := getTableObjects(tableNames, db, trans)
mvcPath := new(MvcPath)
mvcPath.ModelPath = path.Join(apppath, "models")
mvcPath.ControllerPath = path.Join(apppath, "controllers")
mvcPath.RouterPath = path.Join(apppath, "routers")
createPaths(mode, mvcPath)
pkgPath := getPackagePath(apppath)
writeSourceFiles(pkgPath, tables, mode, mvcPath)
} else {
beeLogger.Log.Fatalf("Generating app code from '%s' database is not supported yet.", dbms)
}
} |
beego/bee | 6a86284cec9a17f9aae6fe82ecf3c436aafed68d | generate/g_appcode.go | https://github.com/beego/bee/blob/6a86284cec9a17f9aae6fe82ecf3c436aafed68d/generate/g_appcode.go#L345-L364 | go | train | // getTableObjects process each table name | func getTableObjects(tableNames []string, db *sql.DB, dbTransformer DbTransformer) (tables []*Table) | // getTableObjects process each table name
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
} |
beego/bee | 6a86284cec9a17f9aae6fe82ecf3c436aafed68d | generate/g_appcode.go | https://github.com/beego/bee/blob/6a86284cec9a17f9aae6fe82ecf3c436aafed68d/generate/g_appcode.go#L414-L515 | go | train | // GetColumns retrieves columns details from
// information_schema and fill in the Column struct | func (mysqlDB *MysqlDB) GetColumns(db *sql.DB, table *Table, blackList map[string]bool) | // GetColumns retrieves columns details from
// information_schema and fill in the Column struct
func (mysqlDB *MysqlDB) GetColumns(db *sql.DB, table *Table, blackList map[string]bool) | {
// retrieve columns
colDefRows, err := db.Query(
`SELECT
column_name, data_type, column_type, is_nullable, column_default, extra, column_comment
FROM
information_schema.columns
WHERE
table_schema = database() AND table_name = ?`,
table.Name)
if err != nil {
beeLogger.Log.Fatalf("Could not query the database: %s", err)
}
defer colDefRows.Close()
for colDefRows.Next() {
// datatype as bytes so that SQL <null> values can be retrieved
var colNameBytes, dataTypeBytes, columnTypeBytes, isNullableBytes, columnDefaultBytes, extraBytes, columnCommentBytes []byte
if err := colDefRows.Scan(&colNameBytes, &dataTypeBytes, &columnTypeBytes, &isNullableBytes, &columnDefaultBytes, &extraBytes, &columnCommentBytes); err != nil {
beeLogger.Log.Fatal("Could not query INFORMATION_SCHEMA for column information")
}
colName, dataType, columnType, isNullable, columnDefault, extra, columnComment :=
string(colNameBytes), string(dataTypeBytes), string(columnTypeBytes), string(isNullableBytes), string(columnDefaultBytes), string(extraBytes), string(columnCommentBytes)
// create a column
col := new(Column)
col.Name = utils.CamelCase(colName)
col.Type, err = mysqlDB.GetGoDataType(dataType)
if err != nil {
beeLogger.Log.Fatalf("%s", err)
}
// Tag info
tag := new(OrmTag)
tag.Column = colName
tag.Comment = columnComment
if table.Pk == colName {
col.Name = "Id"
col.Type = "int"
if extra == "auto_increment" {
tag.Auto = true
} else {
tag.Pk = true
}
} else {
fkCol, isFk := table.Fk[colName]
isBl := false
if isFk {
_, isBl = blackList[fkCol.RefTable]
}
// check if the current column is a foreign key
if isFk && !isBl {
tag.RelFk = true
refStructName := fkCol.RefTable
col.Name = utils.CamelCase(colName)
col.Type = "*" + utils.CamelCase(refStructName)
} else {
// if the name of column is Id, and it's not primary key
if colName == "id" {
col.Name = "Id_RENAME"
}
if isNullable == "YES" {
tag.Null = true
}
if isSQLSignedIntType(dataType) {
sign := extractIntSignness(columnType)
if sign == "unsigned" && extra != "auto_increment" {
col.Type, err = mysqlDB.GetGoDataType(dataType + " " + sign)
if err != nil {
beeLogger.Log.Fatalf("%s", err)
}
}
}
if isSQLStringType(dataType) {
tag.Size = extractColSize(columnType)
}
if isSQLTemporalType(dataType) {
tag.Type = dataType
//check auto_now, auto_now_add
if columnDefault == "CURRENT_TIMESTAMP" && extra == "on update CURRENT_TIMESTAMP" {
tag.AutoNow = true
} else if columnDefault == "CURRENT_TIMESTAMP" {
tag.AutoNowAdd = true
}
// need to import time package
table.ImportTimePkg = true
}
if isSQLDecimal(dataType) {
tag.Digits, tag.Decimals = extractDecimal(columnType)
}
if isSQLBinaryType(dataType) {
tag.Size = extractColSize(columnType)
}
if isSQLBitType(dataType) {
tag.Size = extractColSize(columnType)
}
}
}
col.Tag = tag
table.Columns = append(table.Columns, col)
}
} |
beego/bee | 6a86284cec9a17f9aae6fe82ecf3c436aafed68d | generate/g_appcode.go | https://github.com/beego/bee/blob/6a86284cec9a17f9aae6fe82ecf3c436aafed68d/generate/g_appcode.go#L518-L523 | go | train | // GetGoDataType maps an SQL data type to Golang data type | func (*MysqlDB) GetGoDataType(sqlType string) (string, error) | // GetGoDataType maps an SQL data type to Golang data type
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)
} |
beego/bee | 6a86284cec9a17f9aae6fe82ecf3c436aafed68d | generate/g_appcode.go | https://github.com/beego/bee/blob/6a86284cec9a17f9aae6fe82ecf3c436aafed68d/generate/g_appcode.go#L526-L545 | go | train | // GetTableNames for PostgreSQL | func (*PostgresDB) GetTableNames(db *sql.DB) (tables []string) | // GetTableNames for PostgreSQL
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
} |
beego/bee | 6a86284cec9a17f9aae6fe82ecf3c436aafed68d | generate/g_appcode.go | https://github.com/beego/bee/blob/6a86284cec9a17f9aae6fe82ecf3c436aafed68d/generate/g_appcode.go#L548-L601 | go | train | // GetConstraints for PostgreSQL | func (*PostgresDB) GetConstraints(db *sql.DB, table *Table, blackList map[string]bool) | // GetConstraints for PostgreSQL
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
}
}
} |
beego/bee | 6a86284cec9a17f9aae6fe82ecf3c436aafed68d | generate/g_appcode.go | https://github.com/beego/bee/blob/6a86284cec9a17f9aae6fe82ecf3c436aafed68d/generate/g_appcode.go#L708-L713 | go | train | // GetGoDataType returns the Go type from the mapped Postgres type | func (*PostgresDB) GetGoDataType(sqlType string) (string, error) | // GetGoDataType returns the Go type from the mapped Postgres type
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)
} |
beego/bee | 6a86284cec9a17f9aae6fe82ecf3c436aafed68d | generate/g_appcode.go | https://github.com/beego/bee/blob/6a86284cec9a17f9aae6fe82ecf3c436aafed68d/generate/g_appcode.go#L716-L726 | go | train | // deleteAndRecreatePaths removes several directories completely | func createPaths(mode byte, paths *MvcPath) | // deleteAndRecreatePaths removes several directories completely
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)
}
} |
beego/bee | 6a86284cec9a17f9aae6fe82ecf3c436aafed68d | generate/g_appcode.go | https://github.com/beego/bee/blob/6a86284cec9a17f9aae6fe82ecf3c436aafed68d/generate/g_appcode.go#L731-L744 | go | train | // writeSourceFiles generates source files for model/controller/router
// It will wipe the following directories and recreate them:./models, ./controllers, ./routers
// Newly geneated files will be inside these folders. | func writeSourceFiles(pkgPath string, tables []*Table, mode byte, paths *MvcPath) | // writeSourceFiles generates source files for model/controller/router
// It will wipe the following directories and recreate them:./models, ./controllers, ./routers
// Newly geneated files will be inside these folders.
func writeSourceFiles(pkgPath string, tables []*Table, mode byte, paths *MvcPath) | {
if (OModel & mode) == OModel {
beeLogger.Log.Info("Creating model files...")
writeModelFiles(tables, paths.ModelPath)
}
if (OController & mode) == OController {
beeLogger.Log.Info("Creating controller files...")
writeControllerFiles(tables, paths.ControllerPath, pkgPath)
}
if (ORouter & mode) == ORouter {
beeLogger.Log.Info("Creating router files...")
writeRouterFile(tables, paths.RouterPath, pkgPath)
}
} |
beego/bee | 6a86284cec9a17f9aae6fe82ecf3c436aafed68d | generate/g_appcode.go | https://github.com/beego/bee/blob/6a86284cec9a17f9aae6fe82ecf3c436aafed68d/generate/g_appcode.go#L747-L800 | go | train | // writeModelFiles generates model files | func writeModelFiles(tables []*Table, mPath string) | // writeModelFiles generates model files
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)
}
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.