repo
stringlengths
5
54
path
stringlengths
4
155
func_name
stringlengths
1
118
original_string
stringlengths
52
85.5k
language
stringclasses
1 value
code
stringlengths
52
85.5k
code_tokens
list
docstring
stringlengths
6
2.61k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
85
252
partition
stringclasses
1 value
hoisie/web
server.go
Process
func (s *Server) Process(c http.ResponseWriter, req *http.Request) { route := s.routeHandler(req, c) if route != nil { route.httpHandler.ServeHTTP(c, req) } }
go
func (s *Server) Process(c http.ResponseWriter, req *http.Request) { route := s.routeHandler(req, c) if route != nil { route.httpHandler.ServeHTTP(c, req) } }
[ "func", "(", "s", "*", "Server", ")", "Process", "(", "c", "http", ".", "ResponseWriter", ",", "req", "*", "http", ".", "Request", ")", "{", "route", ":=", "s", ".", "routeHandler", "(", "req", ",", "c", ")", "\n", "if", "route", "!=", "nil", "{"...
// Process invokes the routing system for server s
[ "Process", "invokes", "the", "routing", "system", "for", "server", "s" ]
a498c022b2c0babab2bf9c0400754190b24c8c39
https://github.com/hoisie/web/blob/a498c022b2c0babab2bf9c0400754190b24c8c39/server.go#L102-L107
train
hoisie/web
server.go
Get
func (s *Server) Get(route string, handler interface{}) { s.addRoute(route, "GET", handler) }
go
func (s *Server) Get(route string, handler interface{}) { s.addRoute(route, "GET", handler) }
[ "func", "(", "s", "*", "Server", ")", "Get", "(", "route", "string", ",", "handler", "interface", "{", "}", ")", "{", "s", ".", "addRoute", "(", "route", ",", "\"", "\"", ",", "handler", ")", "\n", "}" ]
// Get adds a handler for the 'GET' http method for server s.
[ "Get", "adds", "a", "handler", "for", "the", "GET", "http", "method", "for", "server", "s", "." ]
a498c022b2c0babab2bf9c0400754190b24c8c39
https://github.com/hoisie/web/blob/a498c022b2c0babab2bf9c0400754190b24c8c39/server.go#L110-L112
train
hoisie/web
server.go
Post
func (s *Server) Post(route string, handler interface{}) { s.addRoute(route, "POST", handler) }
go
func (s *Server) Post(route string, handler interface{}) { s.addRoute(route, "POST", handler) }
[ "func", "(", "s", "*", "Server", ")", "Post", "(", "route", "string", ",", "handler", "interface", "{", "}", ")", "{", "s", ".", "addRoute", "(", "route", ",", "\"", "\"", ",", "handler", ")", "\n", "}" ]
// Post adds a handler for the 'POST' http method for server s.
[ "Post", "adds", "a", "handler", "for", "the", "POST", "http", "method", "for", "server", "s", "." ]
a498c022b2c0babab2bf9c0400754190b24c8c39
https://github.com/hoisie/web/blob/a498c022b2c0babab2bf9c0400754190b24c8c39/server.go#L115-L117
train
hoisie/web
server.go
Put
func (s *Server) Put(route string, handler interface{}) { s.addRoute(route, "PUT", handler) }
go
func (s *Server) Put(route string, handler interface{}) { s.addRoute(route, "PUT", handler) }
[ "func", "(", "s", "*", "Server", ")", "Put", "(", "route", "string", ",", "handler", "interface", "{", "}", ")", "{", "s", ".", "addRoute", "(", "route", ",", "\"", "\"", ",", "handler", ")", "\n", "}" ]
// Put adds a handler for the 'PUT' http method for server s.
[ "Put", "adds", "a", "handler", "for", "the", "PUT", "http", "method", "for", "server", "s", "." ]
a498c022b2c0babab2bf9c0400754190b24c8c39
https://github.com/hoisie/web/blob/a498c022b2c0babab2bf9c0400754190b24c8c39/server.go#L120-L122
train
hoisie/web
server.go
Delete
func (s *Server) Delete(route string, handler interface{}) { s.addRoute(route, "DELETE", handler) }
go
func (s *Server) Delete(route string, handler interface{}) { s.addRoute(route, "DELETE", handler) }
[ "func", "(", "s", "*", "Server", ")", "Delete", "(", "route", "string", ",", "handler", "interface", "{", "}", ")", "{", "s", ".", "addRoute", "(", "route", ",", "\"", "\"", ",", "handler", ")", "\n", "}" ]
// Delete adds a handler for the 'DELETE' http method for server s.
[ "Delete", "adds", "a", "handler", "for", "the", "DELETE", "http", "method", "for", "server", "s", "." ]
a498c022b2c0babab2bf9c0400754190b24c8c39
https://github.com/hoisie/web/blob/a498c022b2c0babab2bf9c0400754190b24c8c39/server.go#L125-L127
train
hoisie/web
server.go
Match
func (s *Server) Match(method string, route string, handler interface{}) { s.addRoute(route, method, handler) }
go
func (s *Server) Match(method string, route string, handler interface{}) { s.addRoute(route, method, handler) }
[ "func", "(", "s", "*", "Server", ")", "Match", "(", "method", "string", ",", "route", "string", ",", "handler", "interface", "{", "}", ")", "{", "s", ".", "addRoute", "(", "route", ",", "method", ",", "handler", ")", "\n", "}" ]
// Match adds a handler for an arbitrary http method for server s.
[ "Match", "adds", "a", "handler", "for", "an", "arbitrary", "http", "method", "for", "server", "s", "." ]
a498c022b2c0babab2bf9c0400754190b24c8c39
https://github.com/hoisie/web/blob/a498c022b2c0babab2bf9c0400754190b24c8c39/server.go#L130-L132
train
hoisie/web
server.go
Run
func (s *Server) Run(addr string) { s.initServer() mux := http.NewServeMux() if s.Config.Profiler { mux.Handle("/debug/pprof/cmdline", http.HandlerFunc(pprof.Cmdline)) mux.Handle("/debug/pprof/profile", http.HandlerFunc(pprof.Profile)) mux.Handle("/debug/pprof/heap", pprof.Handler("heap")) mux.Handle("/debug/pprof/symbol", http.HandlerFunc(pprof.Symbol)) } mux.Handle("/", s) l, err := net.Listen("tcp", addr) if err != nil { log.Fatal("ListenAndServe:", err) } s.Logger.Printf("web.go serving %s\n", l.Addr()) s.l = l err = http.Serve(s.l, mux) s.l.Close() }
go
func (s *Server) Run(addr string) { s.initServer() mux := http.NewServeMux() if s.Config.Profiler { mux.Handle("/debug/pprof/cmdline", http.HandlerFunc(pprof.Cmdline)) mux.Handle("/debug/pprof/profile", http.HandlerFunc(pprof.Profile)) mux.Handle("/debug/pprof/heap", pprof.Handler("heap")) mux.Handle("/debug/pprof/symbol", http.HandlerFunc(pprof.Symbol)) } mux.Handle("/", s) l, err := net.Listen("tcp", addr) if err != nil { log.Fatal("ListenAndServe:", err) } s.Logger.Printf("web.go serving %s\n", l.Addr()) s.l = l err = http.Serve(s.l, mux) s.l.Close() }
[ "func", "(", "s", "*", "Server", ")", "Run", "(", "addr", "string", ")", "{", "s", ".", "initServer", "(", ")", "\n\n", "mux", ":=", "http", ".", "NewServeMux", "(", ")", "\n", "if", "s", ".", "Config", ".", "Profiler", "{", "mux", ".", "Handle",...
// Run starts the web application and serves HTTP requests for s
[ "Run", "starts", "the", "web", "application", "and", "serves", "HTTP", "requests", "for", "s" ]
a498c022b2c0babab2bf9c0400754190b24c8c39
https://github.com/hoisie/web/blob/a498c022b2c0babab2bf9c0400754190b24c8c39/server.go#L145-L167
train
hoisie/web
server.go
RunFcgi
func (s *Server) RunFcgi(addr string) { s.initServer() s.Logger.Printf("web.go serving fcgi %s\n", addr) s.listenAndServeFcgi(addr) }
go
func (s *Server) RunFcgi(addr string) { s.initServer() s.Logger.Printf("web.go serving fcgi %s\n", addr) s.listenAndServeFcgi(addr) }
[ "func", "(", "s", "*", "Server", ")", "RunFcgi", "(", "addr", "string", ")", "{", "s", ".", "initServer", "(", ")", "\n", "s", ".", "Logger", ".", "Printf", "(", "\"", "\\n", "\"", ",", "addr", ")", "\n", "s", ".", "listenAndServeFcgi", "(", "add...
// RunFcgi starts the web application and serves FastCGI requests for s.
[ "RunFcgi", "starts", "the", "web", "application", "and", "serves", "FastCGI", "requests", "for", "s", "." ]
a498c022b2c0babab2bf9c0400754190b24c8c39
https://github.com/hoisie/web/blob/a498c022b2c0babab2bf9c0400754190b24c8c39/server.go#L170-L174
train
hoisie/web
server.go
RunScgi
func (s *Server) RunScgi(addr string) { s.initServer() s.Logger.Printf("web.go serving scgi %s\n", addr) s.listenAndServeScgi(addr) }
go
func (s *Server) RunScgi(addr string) { s.initServer() s.Logger.Printf("web.go serving scgi %s\n", addr) s.listenAndServeScgi(addr) }
[ "func", "(", "s", "*", "Server", ")", "RunScgi", "(", "addr", "string", ")", "{", "s", ".", "initServer", "(", ")", "\n", "s", ".", "Logger", ".", "Printf", "(", "\"", "\\n", "\"", ",", "addr", ")", "\n", "s", ".", "listenAndServeScgi", "(", "add...
// RunScgi starts the web application and serves SCGI requests for s.
[ "RunScgi", "starts", "the", "web", "application", "and", "serves", "SCGI", "requests", "for", "s", "." ]
a498c022b2c0babab2bf9c0400754190b24c8c39
https://github.com/hoisie/web/blob/a498c022b2c0babab2bf9c0400754190b24c8c39/server.go#L177-L181
train
hoisie/web
server.go
RunTLS
func (s *Server) RunTLS(addr string, config *tls.Config) error { s.initServer() mux := http.NewServeMux() mux.Handle("/", s) l, err := tls.Listen("tcp", addr, config) if err != nil { log.Fatal("Listen:", err) return err } s.Logger.Printf("web.go serving %s\n", l.Addr()) s.l = l return http.Serve(s.l, mux) }
go
func (s *Server) RunTLS(addr string, config *tls.Config) error { s.initServer() mux := http.NewServeMux() mux.Handle("/", s) l, err := tls.Listen("tcp", addr, config) if err != nil { log.Fatal("Listen:", err) return err } s.Logger.Printf("web.go serving %s\n", l.Addr()) s.l = l return http.Serve(s.l, mux) }
[ "func", "(", "s", "*", "Server", ")", "RunTLS", "(", "addr", "string", ",", "config", "*", "tls", ".", "Config", ")", "error", "{", "s", ".", "initServer", "(", ")", "\n", "mux", ":=", "http", ".", "NewServeMux", "(", ")", "\n", "mux", ".", "Hand...
// RunTLS starts the web application and serves HTTPS requests for s.
[ "RunTLS", "starts", "the", "web", "application", "and", "serves", "HTTPS", "requests", "for", "s", "." ]
a498c022b2c0babab2bf9c0400754190b24c8c39
https://github.com/hoisie/web/blob/a498c022b2c0babab2bf9c0400754190b24c8c39/server.go#L184-L198
train
hoisie/web
server.go
requiresContext
func requiresContext(handlerType reflect.Type) bool { //if the method doesn't take arguments, no if handlerType.NumIn() == 0 { return false } //if the first argument is not a pointer, no a0 := handlerType.In(0) if a0.Kind() != reflect.Ptr { return false } //if the first argument is a context, yes if a0.Elem() == contextType { return true } return false }
go
func requiresContext(handlerType reflect.Type) bool { //if the method doesn't take arguments, no if handlerType.NumIn() == 0 { return false } //if the first argument is not a pointer, no a0 := handlerType.In(0) if a0.Kind() != reflect.Ptr { return false } //if the first argument is a context, yes if a0.Elem() == contextType { return true } return false }
[ "func", "requiresContext", "(", "handlerType", "reflect", ".", "Type", ")", "bool", "{", "//if the method doesn't take arguments, no", "if", "handlerType", ".", "NumIn", "(", ")", "==", "0", "{", "return", "false", "\n", "}", "\n\n", "//if the first argument is not ...
// requiresContext determines whether 'handlerType' contains // an argument to 'web.Ctx' as its first argument
[ "requiresContext", "determines", "whether", "handlerType", "contains", "an", "argument", "to", "web", ".", "Ctx", "as", "its", "first", "argument" ]
a498c022b2c0babab2bf9c0400754190b24c8c39
https://github.com/hoisie/web/blob/a498c022b2c0babab2bf9c0400754190b24c8c39/server.go#L233-L250
train
hoisie/web
helpers.go
webTime
func webTime(t time.Time) string { ftime := t.Format(time.RFC1123) if strings.HasSuffix(ftime, "UTC") { ftime = ftime[0:len(ftime)-3] + "GMT" } return ftime }
go
func webTime(t time.Time) string { ftime := t.Format(time.RFC1123) if strings.HasSuffix(ftime, "UTC") { ftime = ftime[0:len(ftime)-3] + "GMT" } return ftime }
[ "func", "webTime", "(", "t", "time", ".", "Time", ")", "string", "{", "ftime", ":=", "t", ".", "Format", "(", "time", ".", "RFC1123", ")", "\n", "if", "strings", ".", "HasSuffix", "(", "ftime", ",", "\"", "\"", ")", "{", "ftime", "=", "ftime", "[...
// internal utility methods
[ "internal", "utility", "methods" ]
a498c022b2c0babab2bf9c0400754190b24c8c39
https://github.com/hoisie/web/blob/a498c022b2c0babab2bf9c0400754190b24c8c39/helpers.go#L16-L22
train
hoisie/web
helpers.go
Urlencode
func Urlencode(data map[string]string) string { var buf bytes.Buffer for k, v := range data { buf.WriteString(url.QueryEscape(k)) buf.WriteByte('=') buf.WriteString(url.QueryEscape(v)) buf.WriteByte('&') } s := buf.String() return s[0 : len(s)-1] }
go
func Urlencode(data map[string]string) string { var buf bytes.Buffer for k, v := range data { buf.WriteString(url.QueryEscape(k)) buf.WriteByte('=') buf.WriteString(url.QueryEscape(v)) buf.WriteByte('&') } s := buf.String() return s[0 : len(s)-1] }
[ "func", "Urlencode", "(", "data", "map", "[", "string", "]", "string", ")", "string", "{", "var", "buf", "bytes", ".", "Buffer", "\n", "for", "k", ",", "v", ":=", "range", "data", "{", "buf", ".", "WriteString", "(", "url", ".", "QueryEscape", "(", ...
// Urlencode is a helper method that converts a map into URL-encoded form data. // It is a useful when constructing HTTP POST requests.
[ "Urlencode", "is", "a", "helper", "method", "that", "converts", "a", "map", "into", "URL", "-", "encoded", "form", "data", ".", "It", "is", "a", "useful", "when", "constructing", "HTTP", "POST", "requests", "." ]
a498c022b2c0babab2bf9c0400754190b24c8c39
https://github.com/hoisie/web/blob/a498c022b2c0babab2bf9c0400754190b24c8c39/helpers.go#L47-L57
train
hoisie/web
helpers.go
Slug
func Slug(s string, sep string) string { if s == "" { return "" } slug := slugRegex.ReplaceAllString(s, sep) if slug == "" { return "" } quoted := regexp.QuoteMeta(sep) sepRegex := regexp.MustCompile("(" + quoted + "){2,}") slug = sepRegex.ReplaceAllString(slug, sep) sepEnds := regexp.MustCompile("^" + quoted + "|" + quoted + "$") slug = sepEnds.ReplaceAllString(slug, "") return strings.ToLower(slug) }
go
func Slug(s string, sep string) string { if s == "" { return "" } slug := slugRegex.ReplaceAllString(s, sep) if slug == "" { return "" } quoted := regexp.QuoteMeta(sep) sepRegex := regexp.MustCompile("(" + quoted + "){2,}") slug = sepRegex.ReplaceAllString(slug, sep) sepEnds := regexp.MustCompile("^" + quoted + "|" + quoted + "$") slug = sepEnds.ReplaceAllString(slug, "") return strings.ToLower(slug) }
[ "func", "Slug", "(", "s", "string", ",", "sep", "string", ")", "string", "{", "if", "s", "==", "\"", "\"", "{", "return", "\"", "\"", "\n", "}", "\n", "slug", ":=", "slugRegex", ".", "ReplaceAllString", "(", "s", ",", "sep", ")", "\n", "if", "slu...
// Slug is a helper function that returns the URL slug for string s. // It's used to return clean, URL-friendly strings that can be // used in routing.
[ "Slug", "is", "a", "helper", "function", "that", "returns", "the", "URL", "slug", "for", "string", "s", ".", "It", "s", "used", "to", "return", "clean", "URL", "-", "friendly", "strings", "that", "can", "be", "used", "in", "routing", "." ]
a498c022b2c0babab2bf9c0400754190b24c8c39
https://github.com/hoisie/web/blob/a498c022b2c0babab2bf9c0400754190b24c8c39/helpers.go#L64-L78
train
hoisie/web
helpers.go
GetBasicAuth
func (ctx *Context) GetBasicAuth() (string, string, error) { if len(ctx.Request.Header["Authorization"]) == 0 { return "", "", errors.New("No Authorization header provided") } authHeader := ctx.Request.Header["Authorization"][0] authString := strings.Split(string(authHeader), " ") if authString[0] != "Basic" { return "", "", errors.New("Not Basic Authentication") } decodedAuth, err := base64.StdEncoding.DecodeString(authString[1]) if err != nil { return "", "", err } authSlice := strings.Split(string(decodedAuth), ":") if len(authSlice) != 2 { return "", "", errors.New("Error delimiting authString into username/password. Malformed input: " + authString[1]) } return authSlice[0], authSlice[1], nil }
go
func (ctx *Context) GetBasicAuth() (string, string, error) { if len(ctx.Request.Header["Authorization"]) == 0 { return "", "", errors.New("No Authorization header provided") } authHeader := ctx.Request.Header["Authorization"][0] authString := strings.Split(string(authHeader), " ") if authString[0] != "Basic" { return "", "", errors.New("Not Basic Authentication") } decodedAuth, err := base64.StdEncoding.DecodeString(authString[1]) if err != nil { return "", "", err } authSlice := strings.Split(string(decodedAuth), ":") if len(authSlice) != 2 { return "", "", errors.New("Error delimiting authString into username/password. Malformed input: " + authString[1]) } return authSlice[0], authSlice[1], nil }
[ "func", "(", "ctx", "*", "Context", ")", "GetBasicAuth", "(", ")", "(", "string", ",", "string", ",", "error", ")", "{", "if", "len", "(", "ctx", ".", "Request", ".", "Header", "[", "\"", "\"", "]", ")", "==", "0", "{", "return", "\"", "\"", ",...
// GetBasicAuth returns the decoded user and password from the context's // 'Authorization' header.
[ "GetBasicAuth", "returns", "the", "decoded", "user", "and", "password", "from", "the", "context", "s", "Authorization", "header", "." ]
a498c022b2c0babab2bf9c0400754190b24c8c39
https://github.com/hoisie/web/blob/a498c022b2c0babab2bf9c0400754190b24c8c39/helpers.go#L96-L114
train
magefile/mage
sh/helpers.go
Rm
func Rm(path string) error { err := os.RemoveAll(path) if err == nil || os.IsNotExist(err) { return nil } return fmt.Errorf(`failed to remove %s: %v`, path, err) }
go
func Rm(path string) error { err := os.RemoveAll(path) if err == nil || os.IsNotExist(err) { return nil } return fmt.Errorf(`failed to remove %s: %v`, path, err) }
[ "func", "Rm", "(", "path", "string", ")", "error", "{", "err", ":=", "os", ".", "RemoveAll", "(", "path", ")", "\n", "if", "err", "==", "nil", "||", "os", ".", "IsNotExist", "(", "err", ")", "{", "return", "nil", "\n", "}", "\n", "return", "fmt",...
// Rm removes the given file or directory even if non-empty. It will not return // an error if the target doesn't exist, only if the target cannot be removed.
[ "Rm", "removes", "the", "given", "file", "or", "directory", "even", "if", "non", "-", "empty", ".", "It", "will", "not", "return", "an", "error", "if", "the", "target", "doesn", "t", "exist", "only", "if", "the", "target", "cannot", "be", "removed", "....
5bc3a8ab86d5a23d6eb3bdbcd60e79ac4d9ad0ed
https://github.com/magefile/mage/blob/5bc3a8ab86d5a23d6eb3bdbcd60e79ac4d9ad0ed/sh/helpers.go#L11-L17
train
magefile/mage
sh/helpers.go
Copy
func Copy(dst string, src string) error { from, err := os.Open(src) if err != nil { return fmt.Errorf(`can't copy %s: %v`, src, err) } defer from.Close() finfo, err := from.Stat() if err != nil { return fmt.Errorf(`can't stat %s: %v`, src, err) } to, err := os.OpenFile(dst, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, finfo.Mode()) if err != nil { return fmt.Errorf(`can't copy to %s: %v`, dst, err) } defer to.Close() _, err = io.Copy(to, from) if err != nil { return fmt.Errorf(`error copying %s to %s: %v`, src, dst, err) } return nil }
go
func Copy(dst string, src string) error { from, err := os.Open(src) if err != nil { return fmt.Errorf(`can't copy %s: %v`, src, err) } defer from.Close() finfo, err := from.Stat() if err != nil { return fmt.Errorf(`can't stat %s: %v`, src, err) } to, err := os.OpenFile(dst, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, finfo.Mode()) if err != nil { return fmt.Errorf(`can't copy to %s: %v`, dst, err) } defer to.Close() _, err = io.Copy(to, from) if err != nil { return fmt.Errorf(`error copying %s to %s: %v`, src, dst, err) } return nil }
[ "func", "Copy", "(", "dst", "string", ",", "src", "string", ")", "error", "{", "from", ",", "err", ":=", "os", ".", "Open", "(", "src", ")", "\n", "if", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "`can't copy %s: %v`", ",", "src"...
// Copy robustly copies the source file to the destination, overwriting the destination if necessary.
[ "Copy", "robustly", "copies", "the", "source", "file", "to", "the", "destination", "overwriting", "the", "destination", "if", "necessary", "." ]
5bc3a8ab86d5a23d6eb3bdbcd60e79ac4d9ad0ed
https://github.com/magefile/mage/blob/5bc3a8ab86d5a23d6eb3bdbcd60e79ac4d9ad0ed/sh/helpers.go#L20-L40
train
magefile/mage
internal/run.go
EnvWithCurrentGOOS
func EnvWithCurrentGOOS() ([]string, error) { vals, err := splitEnv(os.Environ()) if err != nil { return nil, err } vals["GOOS"] = runtime.GOOS vals["GOARCH"] = runtime.GOARCH return joinEnv(vals), nil }
go
func EnvWithCurrentGOOS() ([]string, error) { vals, err := splitEnv(os.Environ()) if err != nil { return nil, err } vals["GOOS"] = runtime.GOOS vals["GOARCH"] = runtime.GOARCH return joinEnv(vals), nil }
[ "func", "EnvWithCurrentGOOS", "(", ")", "(", "[", "]", "string", ",", "error", ")", "{", "vals", ",", "err", ":=", "splitEnv", "(", "os", ".", "Environ", "(", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", ...
// EnvWithCurrentGOOS returns a copy of os.Environ with the GOOS and GOARCH set // to runtime.GOOS and runtime.GOARCH.
[ "EnvWithCurrentGOOS", "returns", "a", "copy", "of", "os", ".", "Environ", "with", "the", "GOOS", "and", "GOARCH", "set", "to", "runtime", ".", "GOOS", "and", "runtime", ".", "GOARCH", "." ]
5bc3a8ab86d5a23d6eb3bdbcd60e79ac4d9ad0ed
https://github.com/magefile/mage/blob/5bc3a8ab86d5a23d6eb3bdbcd60e79ac4d9ad0ed/internal/run.go#L86-L94
train
magefile/mage
mg/runtime.go
Verbose
func Verbose() bool { b, _ := strconv.ParseBool(os.Getenv(VerboseEnv)) return b }
go
func Verbose() bool { b, _ := strconv.ParseBool(os.Getenv(VerboseEnv)) return b }
[ "func", "Verbose", "(", ")", "bool", "{", "b", ",", "_", ":=", "strconv", ".", "ParseBool", "(", "os", ".", "Getenv", "(", "VerboseEnv", ")", ")", "\n", "return", "b", "\n", "}" ]
// Verbose reports whether a magefile was run with the verbose flag.
[ "Verbose", "reports", "whether", "a", "magefile", "was", "run", "with", "the", "verbose", "flag", "." ]
5bc3a8ab86d5a23d6eb3bdbcd60e79ac4d9ad0ed
https://github.com/magefile/mage/blob/5bc3a8ab86d5a23d6eb3bdbcd60e79ac4d9ad0ed/mg/runtime.go#L31-L34
train
magefile/mage
mg/runtime.go
Debug
func Debug() bool { b, _ := strconv.ParseBool(os.Getenv(DebugEnv)) return b }
go
func Debug() bool { b, _ := strconv.ParseBool(os.Getenv(DebugEnv)) return b }
[ "func", "Debug", "(", ")", "bool", "{", "b", ",", "_", ":=", "strconv", ".", "ParseBool", "(", "os", ".", "Getenv", "(", "DebugEnv", ")", ")", "\n", "return", "b", "\n", "}" ]
// Debug reports whether a magefile was run with the verbose flag.
[ "Debug", "reports", "whether", "a", "magefile", "was", "run", "with", "the", "verbose", "flag", "." ]
5bc3a8ab86d5a23d6eb3bdbcd60e79ac4d9ad0ed
https://github.com/magefile/mage/blob/5bc3a8ab86d5a23d6eb3bdbcd60e79ac4d9ad0ed/mg/runtime.go#L37-L40
train
magefile/mage
mg/runtime.go
IgnoreDefault
func IgnoreDefault() bool { b, _ := strconv.ParseBool(os.Getenv(IgnoreDefaultEnv)) return b }
go
func IgnoreDefault() bool { b, _ := strconv.ParseBool(os.Getenv(IgnoreDefaultEnv)) return b }
[ "func", "IgnoreDefault", "(", ")", "bool", "{", "b", ",", "_", ":=", "strconv", ".", "ParseBool", "(", "os", ".", "Getenv", "(", "IgnoreDefaultEnv", ")", ")", "\n", "return", "b", "\n", "}" ]
// IgnoreDefault reports whether the user has requested to ignore the default target // in the magefile.
[ "IgnoreDefault", "reports", "whether", "the", "user", "has", "requested", "to", "ignore", "the", "default", "target", "in", "the", "magefile", "." ]
5bc3a8ab86d5a23d6eb3bdbcd60e79ac4d9ad0ed
https://github.com/magefile/mage/blob/5bc3a8ab86d5a23d6eb3bdbcd60e79ac4d9ad0ed/mg/runtime.go#L53-L56
train
magefile/mage
mg/deps.go
SerialDeps
func SerialDeps(fns ...interface{}) { types := checkFns(fns) ctx := context.Background() for i := range fns { runDeps(ctx, types[i:i+1], fns[i:i+1]) } }
go
func SerialDeps(fns ...interface{}) { types := checkFns(fns) ctx := context.Background() for i := range fns { runDeps(ctx, types[i:i+1], fns[i:i+1]) } }
[ "func", "SerialDeps", "(", "fns", "...", "interface", "{", "}", ")", "{", "types", ":=", "checkFns", "(", "fns", ")", "\n", "ctx", ":=", "context", ".", "Background", "(", ")", "\n", "for", "i", ":=", "range", "fns", "{", "runDeps", "(", "ctx", ","...
// SerialDeps is like Deps except it runs each dependency serially, instead of // in parallel. This can be useful for resource intensive dependencies that // shouldn't be run at the same time.
[ "SerialDeps", "is", "like", "Deps", "except", "it", "runs", "each", "dependency", "serially", "instead", "of", "in", "parallel", ".", "This", "can", "be", "useful", "for", "resource", "intensive", "dependencies", "that", "shouldn", "t", "be", "run", "at", "t...
5bc3a8ab86d5a23d6eb3bdbcd60e79ac4d9ad0ed
https://github.com/magefile/mage/blob/5bc3a8ab86d5a23d6eb3bdbcd60e79ac4d9ad0ed/mg/deps.go#L57-L63
train
magefile/mage
mg/deps.go
SerialCtxDeps
func SerialCtxDeps(ctx context.Context, fns ...interface{}) { types := checkFns(fns) for i := range fns { runDeps(ctx, types[i:i+1], fns[i:i+1]) } }
go
func SerialCtxDeps(ctx context.Context, fns ...interface{}) { types := checkFns(fns) for i := range fns { runDeps(ctx, types[i:i+1], fns[i:i+1]) } }
[ "func", "SerialCtxDeps", "(", "ctx", "context", ".", "Context", ",", "fns", "...", "interface", "{", "}", ")", "{", "types", ":=", "checkFns", "(", "fns", ")", "\n", "for", "i", ":=", "range", "fns", "{", "runDeps", "(", "ctx", ",", "types", "[", "...
// SerialCtxDeps is like CtxDeps except it runs each dependency serially, // instead of in parallel. This can be useful for resource intensive // dependencies that shouldn't be run at the same time.
[ "SerialCtxDeps", "is", "like", "CtxDeps", "except", "it", "runs", "each", "dependency", "serially", "instead", "of", "in", "parallel", ".", "This", "can", "be", "useful", "for", "resource", "intensive", "dependencies", "that", "shouldn", "t", "be", "run", "at"...
5bc3a8ab86d5a23d6eb3bdbcd60e79ac4d9ad0ed
https://github.com/magefile/mage/blob/5bc3a8ab86d5a23d6eb3bdbcd60e79ac4d9ad0ed/mg/deps.go#L68-L73
train
magefile/mage
mg/deps.go
runDeps
func runDeps(ctx context.Context, types []funcType, fns []interface{}) { mu := &sync.Mutex{} var errs []string var exit int wg := &sync.WaitGroup{} for i, f := range fns { fn := addDep(ctx, types[i], f) wg.Add(1) go func() { defer func() { if v := recover(); v != nil { mu.Lock() if err, ok := v.(error); ok { exit = changeExit(exit, ExitStatus(err)) } else { exit = changeExit(exit, 1) } errs = append(errs, fmt.Sprint(v)) mu.Unlock() } wg.Done() }() if err := fn.run(); err != nil { mu.Lock() errs = append(errs, fmt.Sprint(err)) exit = changeExit(exit, ExitStatus(err)) mu.Unlock() } }() } wg.Wait() if len(errs) > 0 { panic(Fatal(exit, strings.Join(errs, "\n"))) } }
go
func runDeps(ctx context.Context, types []funcType, fns []interface{}) { mu := &sync.Mutex{} var errs []string var exit int wg := &sync.WaitGroup{} for i, f := range fns { fn := addDep(ctx, types[i], f) wg.Add(1) go func() { defer func() { if v := recover(); v != nil { mu.Lock() if err, ok := v.(error); ok { exit = changeExit(exit, ExitStatus(err)) } else { exit = changeExit(exit, 1) } errs = append(errs, fmt.Sprint(v)) mu.Unlock() } wg.Done() }() if err := fn.run(); err != nil { mu.Lock() errs = append(errs, fmt.Sprint(err)) exit = changeExit(exit, ExitStatus(err)) mu.Unlock() } }() } wg.Wait() if len(errs) > 0 { panic(Fatal(exit, strings.Join(errs, "\n"))) } }
[ "func", "runDeps", "(", "ctx", "context", ".", "Context", ",", "types", "[", "]", "funcType", ",", "fns", "[", "]", "interface", "{", "}", ")", "{", "mu", ":=", "&", "sync", ".", "Mutex", "{", "}", "\n", "var", "errs", "[", "]", "string", "\n", ...
// runDeps assumes you've already called checkFns.
[ "runDeps", "assumes", "you", "ve", "already", "called", "checkFns", "." ]
5bc3a8ab86d5a23d6eb3bdbcd60e79ac4d9ad0ed
https://github.com/magefile/mage/blob/5bc3a8ab86d5a23d6eb3bdbcd60e79ac4d9ad0ed/mg/deps.go#L94-L129
train
magefile/mage
mg/deps.go
funcCheck
func funcCheck(fn interface{}) (funcType, error) { switch fn.(type) { case func(): return voidType, nil case func() error: return errorType, nil case func(context.Context): return contextVoidType, nil case func(context.Context) error: return contextErrorType, nil } err := fmt.Errorf("Invalid type for dependent function: %T. Dependencies must be func(), func() error, func(context.Context), func(context.Context) error, or the same method on an mg.Namespace.", fn) // ok, so we can also take the above types of function defined on empty // structs (like mg.Namespace). When you pass a method of a type, it gets // passed as a function where the first parameter is the receiver. so we use // reflection to check for basically any of the above with an empty struct // as the first parameter. t := reflect.TypeOf(fn) if t.Kind() != reflect.Func { return invalidType, err } if t.NumOut() > 1 { return invalidType, err } if t.NumOut() == 1 && t.Out(0) == reflect.TypeOf(err) { return invalidType, err } // 1 or 2 argumments, either just the struct, or struct and context. if t.NumIn() == 0 || t.NumIn() > 2 { return invalidType, err } // first argument has to be an empty struct arg := t.In(0) if arg.Kind() != reflect.Struct { return invalidType, err } if arg.NumField() != 0 { return invalidType, err } if t.NumIn() == 1 { if t.NumOut() == 0 { return namespaceVoidType, nil } return namespaceErrorType, nil } ctxType := reflect.TypeOf(context.Background()) if t.In(1) == ctxType { return invalidType, err } if t.NumOut() == 0 { return namespaceContextVoidType, nil } return namespaceContextErrorType, nil }
go
func funcCheck(fn interface{}) (funcType, error) { switch fn.(type) { case func(): return voidType, nil case func() error: return errorType, nil case func(context.Context): return contextVoidType, nil case func(context.Context) error: return contextErrorType, nil } err := fmt.Errorf("Invalid type for dependent function: %T. Dependencies must be func(), func() error, func(context.Context), func(context.Context) error, or the same method on an mg.Namespace.", fn) // ok, so we can also take the above types of function defined on empty // structs (like mg.Namespace). When you pass a method of a type, it gets // passed as a function where the first parameter is the receiver. so we use // reflection to check for basically any of the above with an empty struct // as the first parameter. t := reflect.TypeOf(fn) if t.Kind() != reflect.Func { return invalidType, err } if t.NumOut() > 1 { return invalidType, err } if t.NumOut() == 1 && t.Out(0) == reflect.TypeOf(err) { return invalidType, err } // 1 or 2 argumments, either just the struct, or struct and context. if t.NumIn() == 0 || t.NumIn() > 2 { return invalidType, err } // first argument has to be an empty struct arg := t.In(0) if arg.Kind() != reflect.Struct { return invalidType, err } if arg.NumField() != 0 { return invalidType, err } if t.NumIn() == 1 { if t.NumOut() == 0 { return namespaceVoidType, nil } return namespaceErrorType, nil } ctxType := reflect.TypeOf(context.Background()) if t.In(1) == ctxType { return invalidType, err } if t.NumOut() == 0 { return namespaceContextVoidType, nil } return namespaceContextErrorType, nil }
[ "func", "funcCheck", "(", "fn", "interface", "{", "}", ")", "(", "funcType", ",", "error", ")", "{", "switch", "fn", ".", "(", "type", ")", "{", "case", "func", "(", ")", ":", "return", "voidType", ",", "nil", "\n", "case", "func", "(", ")", "err...
// funcCheck tests if a function is one of funcType
[ "funcCheck", "tests", "if", "a", "function", "is", "one", "of", "funcType" ]
5bc3a8ab86d5a23d6eb3bdbcd60e79ac4d9ad0ed
https://github.com/magefile/mage/blob/5bc3a8ab86d5a23d6eb3bdbcd60e79ac4d9ad0ed/mg/deps.go#L218-L278
train
magefile/mage
mg/deps.go
funcTypeWrap
func funcTypeWrap(t funcType, fn interface{}) func(context.Context) error { switch f := fn.(type) { case func(): return func(context.Context) error { f() return nil } case func() error: return func(context.Context) error { return f() } case func(context.Context): return func(ctx context.Context) error { f(ctx) return nil } case func(context.Context) error: return f } args := []reflect.Value{reflect.ValueOf(struct{}{})} switch t { case namespaceVoidType: return func(context.Context) error { v := reflect.ValueOf(fn) v.Call(args) return nil } case namespaceErrorType: return func(context.Context) error { v := reflect.ValueOf(fn) ret := v.Call(args) val := ret[0].Interface() if val == nil { return nil } return val.(error) } case namespaceContextVoidType: return func(ctx context.Context) error { v := reflect.ValueOf(fn) v.Call(append(args, reflect.ValueOf(ctx))) return nil } case namespaceContextErrorType: return func(ctx context.Context) error { v := reflect.ValueOf(fn) ret := v.Call(append(args, reflect.ValueOf(ctx))) val := ret[0].Interface() if val == nil { return nil } return val.(error) } default: panic(fmt.Errorf("Don't know how to deal with dep of type %T", fn)) } }
go
func funcTypeWrap(t funcType, fn interface{}) func(context.Context) error { switch f := fn.(type) { case func(): return func(context.Context) error { f() return nil } case func() error: return func(context.Context) error { return f() } case func(context.Context): return func(ctx context.Context) error { f(ctx) return nil } case func(context.Context) error: return f } args := []reflect.Value{reflect.ValueOf(struct{}{})} switch t { case namespaceVoidType: return func(context.Context) error { v := reflect.ValueOf(fn) v.Call(args) return nil } case namespaceErrorType: return func(context.Context) error { v := reflect.ValueOf(fn) ret := v.Call(args) val := ret[0].Interface() if val == nil { return nil } return val.(error) } case namespaceContextVoidType: return func(ctx context.Context) error { v := reflect.ValueOf(fn) v.Call(append(args, reflect.ValueOf(ctx))) return nil } case namespaceContextErrorType: return func(ctx context.Context) error { v := reflect.ValueOf(fn) ret := v.Call(append(args, reflect.ValueOf(ctx))) val := ret[0].Interface() if val == nil { return nil } return val.(error) } default: panic(fmt.Errorf("Don't know how to deal with dep of type %T", fn)) } }
[ "func", "funcTypeWrap", "(", "t", "funcType", ",", "fn", "interface", "{", "}", ")", "func", "(", "context", ".", "Context", ")", "error", "{", "switch", "f", ":=", "fn", ".", "(", "type", ")", "{", "case", "func", "(", ")", ":", "return", "func", ...
// funcTypeWrap wraps a valid FuncType to FuncContextError
[ "funcTypeWrap", "wraps", "a", "valid", "FuncType", "to", "FuncContextError" ]
5bc3a8ab86d5a23d6eb3bdbcd60e79ac4d9ad0ed
https://github.com/magefile/mage/blob/5bc3a8ab86d5a23d6eb3bdbcd60e79ac4d9ad0ed/mg/deps.go#L281-L337
train
magefile/mage
mage/main.go
Main
func Main() int { return ParseAndRun(os.Stdout, os.Stderr, os.Stdin, os.Args[1:]) }
go
func Main() int { return ParseAndRun(os.Stdout, os.Stderr, os.Stdin, os.Args[1:]) }
[ "func", "Main", "(", ")", "int", "{", "return", "ParseAndRun", "(", "os", ".", "Stdout", ",", "os", ".", "Stderr", ",", "os", ".", "Stdin", ",", "os", ".", "Args", "[", "1", ":", "]", ")", "\n", "}" ]
// Main is the entrypoint for running mage. It exists external to mage's main // function to allow it to be used from other programs, specifically so you can // go run a simple file that run's mage's Main.
[ "Main", "is", "the", "entrypoint", "for", "running", "mage", ".", "It", "exists", "external", "to", "mage", "s", "main", "function", "to", "allow", "it", "to", "be", "used", "from", "other", "programs", "specifically", "so", "you", "can", "go", "run", "a...
5bc3a8ab86d5a23d6eb3bdbcd60e79ac4d9ad0ed
https://github.com/magefile/mage/blob/5bc3a8ab86d5a23d6eb3bdbcd60e79ac4d9ad0ed/mage/main.go#L90-L92
train
magefile/mage
mage/main.go
Magefiles
func Magefiles(magePath, goos, goarch, goCmd string, stderr io.Writer, isDebug bool) ([]string, error) { start := time.Now() defer func() { debug.Println("time to scan for Magefiles:", time.Since(start)) }() fail := func(err error) ([]string, error) { return nil, err } env, err := internal.EnvWithGOOS(goos, goarch) if err != nil { return nil, err } debug.Println("getting all non-mage files in", magePath) // // first, grab all the files with no build tags specified.. this is actually // // our exclude list of things without the mage build tag. cmd := exec.Command(goCmd, "list", "-e", "-f", `{{join .GoFiles "||"}}`) cmd.Env = env if isDebug { cmd.Stderr = stderr } cmd.Dir = magePath b, err := cmd.Output() if err != nil { return fail(fmt.Errorf("failed to list non-mage gofiles: %v", err)) } list := strings.TrimSpace(string(b)) debug.Println("found non-mage files", list) exclude := map[string]bool{} for _, f := range strings.Split(list, "||") { if f != "" { debug.Printf("marked file as non-mage: %q", f) exclude[f] = true } } debug.Println("getting all files plus mage files") cmd = exec.Command(goCmd, "list", "-tags=mage", "-e", "-f", `{{join .GoFiles "||"}}`) cmd.Env = env if isDebug { cmd.Stderr = stderr } cmd.Dir = magePath b, err = cmd.Output() if err != nil { return fail(fmt.Errorf("failed to list mage gofiles: %v", err)) } list = strings.TrimSpace(string(b)) files := []string{} for _, f := range strings.Split(list, "||") { if f != "" && !exclude[f] { files = append(files, f) } } for i := range files { files[i] = filepath.Join(magePath, files[i]) } return files, nil }
go
func Magefiles(magePath, goos, goarch, goCmd string, stderr io.Writer, isDebug bool) ([]string, error) { start := time.Now() defer func() { debug.Println("time to scan for Magefiles:", time.Since(start)) }() fail := func(err error) ([]string, error) { return nil, err } env, err := internal.EnvWithGOOS(goos, goarch) if err != nil { return nil, err } debug.Println("getting all non-mage files in", magePath) // // first, grab all the files with no build tags specified.. this is actually // // our exclude list of things without the mage build tag. cmd := exec.Command(goCmd, "list", "-e", "-f", `{{join .GoFiles "||"}}`) cmd.Env = env if isDebug { cmd.Stderr = stderr } cmd.Dir = magePath b, err := cmd.Output() if err != nil { return fail(fmt.Errorf("failed to list non-mage gofiles: %v", err)) } list := strings.TrimSpace(string(b)) debug.Println("found non-mage files", list) exclude := map[string]bool{} for _, f := range strings.Split(list, "||") { if f != "" { debug.Printf("marked file as non-mage: %q", f) exclude[f] = true } } debug.Println("getting all files plus mage files") cmd = exec.Command(goCmd, "list", "-tags=mage", "-e", "-f", `{{join .GoFiles "||"}}`) cmd.Env = env if isDebug { cmd.Stderr = stderr } cmd.Dir = magePath b, err = cmd.Output() if err != nil { return fail(fmt.Errorf("failed to list mage gofiles: %v", err)) } list = strings.TrimSpace(string(b)) files := []string{} for _, f := range strings.Split(list, "||") { if f != "" && !exclude[f] { files = append(files, f) } } for i := range files { files[i] = filepath.Join(magePath, files[i]) } return files, nil }
[ "func", "Magefiles", "(", "magePath", ",", "goos", ",", "goarch", ",", "goCmd", "string", ",", "stderr", "io", ".", "Writer", ",", "isDebug", "bool", ")", "(", "[", "]", "string", ",", "error", ")", "{", "start", ":=", "time", ".", "Now", "(", ")",...
// Magefiles returns the list of magefiles in dir.
[ "Magefiles", "returns", "the", "list", "of", "magefiles", "in", "dir", "." ]
5bc3a8ab86d5a23d6eb3bdbcd60e79ac4d9ad0ed
https://github.com/magefile/mage/blob/5bc3a8ab86d5a23d6eb3bdbcd60e79ac4d9ad0ed/mage/main.go#L411-L471
train
magefile/mage
mage/main.go
Compile
func Compile(goos, goarch, magePath, goCmd, compileTo string, gofiles []string, isDebug bool, stderr, stdout io.Writer) error { debug.Println("compiling to", compileTo) debug.Println("compiling using gocmd:", goCmd) if isDebug { internal.RunDebug(goCmd, "version") internal.RunDebug(goCmd, "env") } environ, err := internal.EnvWithGOOS(goos, goarch) if err != nil { return err } // strip off the path since we're setting the path in the build command for i := range gofiles { gofiles[i] = filepath.Base(gofiles[i]) } debug.Printf("running %s build -o %s %s", goCmd, compileTo, strings.Join(gofiles, " ")) c := exec.Command(goCmd, append([]string{"build", "-o", compileTo}, gofiles...)...) c.Env = environ c.Stderr = stderr c.Stdout = stdout c.Dir = magePath start := time.Now() err = c.Run() debug.Println("time to compile Magefile:", time.Since(start)) if err != nil { return errors.New("error compiling magefiles") } return nil }
go
func Compile(goos, goarch, magePath, goCmd, compileTo string, gofiles []string, isDebug bool, stderr, stdout io.Writer) error { debug.Println("compiling to", compileTo) debug.Println("compiling using gocmd:", goCmd) if isDebug { internal.RunDebug(goCmd, "version") internal.RunDebug(goCmd, "env") } environ, err := internal.EnvWithGOOS(goos, goarch) if err != nil { return err } // strip off the path since we're setting the path in the build command for i := range gofiles { gofiles[i] = filepath.Base(gofiles[i]) } debug.Printf("running %s build -o %s %s", goCmd, compileTo, strings.Join(gofiles, " ")) c := exec.Command(goCmd, append([]string{"build", "-o", compileTo}, gofiles...)...) c.Env = environ c.Stderr = stderr c.Stdout = stdout c.Dir = magePath start := time.Now() err = c.Run() debug.Println("time to compile Magefile:", time.Since(start)) if err != nil { return errors.New("error compiling magefiles") } return nil }
[ "func", "Compile", "(", "goos", ",", "goarch", ",", "magePath", ",", "goCmd", ",", "compileTo", "string", ",", "gofiles", "[", "]", "string", ",", "isDebug", "bool", ",", "stderr", ",", "stdout", "io", ".", "Writer", ")", "error", "{", "debug", ".", ...
// Compile uses the go tool to compile the files into an executable at path.
[ "Compile", "uses", "the", "go", "tool", "to", "compile", "the", "files", "into", "an", "executable", "at", "path", "." ]
5bc3a8ab86d5a23d6eb3bdbcd60e79ac4d9ad0ed
https://github.com/magefile/mage/blob/5bc3a8ab86d5a23d6eb3bdbcd60e79ac4d9ad0ed/mage/main.go#L474-L502
train
magefile/mage
mage/main.go
GenerateMainfile
func GenerateMainfile(binaryName, path string, info *parse.PkgInfo) error { debug.Println("Creating mainfile at", path) f, err := os.Create(path) if err != nil { return fmt.Errorf("error creating generated mainfile: %v", err) } defer f.Close() data := mainfileTemplateData{ Description: info.Description, Funcs: info.Funcs, Aliases: info.Aliases, Imports: info.Imports, BinaryName: binaryName, } if info.DefaultFunc != nil { data.DefaultFunc = *info.DefaultFunc } debug.Println("writing new file at", path) if err := mainfileTemplate.Execute(f, data); err != nil { return fmt.Errorf("can't execute mainfile template: %v", err) } if err := f.Close(); err != nil { return fmt.Errorf("error closing generated mainfile: %v", err) } // we set an old modtime on the generated mainfile so that the go tool // won't think it has changed more recently than the compiled binary. longAgo := time.Now().Add(-time.Hour * 24 * 365 * 10) if err := os.Chtimes(path, longAgo, longAgo); err != nil { return fmt.Errorf("error setting old modtime on generated mainfile: %v", err) } return nil }
go
func GenerateMainfile(binaryName, path string, info *parse.PkgInfo) error { debug.Println("Creating mainfile at", path) f, err := os.Create(path) if err != nil { return fmt.Errorf("error creating generated mainfile: %v", err) } defer f.Close() data := mainfileTemplateData{ Description: info.Description, Funcs: info.Funcs, Aliases: info.Aliases, Imports: info.Imports, BinaryName: binaryName, } if info.DefaultFunc != nil { data.DefaultFunc = *info.DefaultFunc } debug.Println("writing new file at", path) if err := mainfileTemplate.Execute(f, data); err != nil { return fmt.Errorf("can't execute mainfile template: %v", err) } if err := f.Close(); err != nil { return fmt.Errorf("error closing generated mainfile: %v", err) } // we set an old modtime on the generated mainfile so that the go tool // won't think it has changed more recently than the compiled binary. longAgo := time.Now().Add(-time.Hour * 24 * 365 * 10) if err := os.Chtimes(path, longAgo, longAgo); err != nil { return fmt.Errorf("error setting old modtime on generated mainfile: %v", err) } return nil }
[ "func", "GenerateMainfile", "(", "binaryName", ",", "path", "string", ",", "info", "*", "parse", ".", "PkgInfo", ")", "error", "{", "debug", ".", "Println", "(", "\"", "\"", ",", "path", ")", "\n\n", "f", ",", "err", ":=", "os", ".", "Create", "(", ...
// GenerateMainfile generates the mage mainfile at path.
[ "GenerateMainfile", "generates", "the", "mage", "mainfile", "at", "path", "." ]
5bc3a8ab86d5a23d6eb3bdbcd60e79ac4d9ad0ed
https://github.com/magefile/mage/blob/5bc3a8ab86d5a23d6eb3bdbcd60e79ac4d9ad0ed/mage/main.go#L505-L539
train
magefile/mage
mage/main.go
ExeName
func ExeName(goCmd, cacheDir string, files []string) (string, error) { var hashes []string for _, s := range files { h, err := hashFile(s) if err != nil { return "", err } hashes = append(hashes, h) } // hash the mainfile template to ensure if it gets updated, we make a new // binary. hashes = append(hashes, fmt.Sprintf("%x", sha1.Sum([]byte(mageMainfileTplString)))) sort.Strings(hashes) ver, err := internal.OutputDebug(goCmd, "version") if err != nil { return "", err } hash := sha1.Sum([]byte(strings.Join(hashes, "") + magicRebuildKey + ver)) filename := fmt.Sprintf("%x", hash) out := filepath.Join(cacheDir, filename) if runtime.GOOS == "windows" { out += ".exe" } return out, nil }
go
func ExeName(goCmd, cacheDir string, files []string) (string, error) { var hashes []string for _, s := range files { h, err := hashFile(s) if err != nil { return "", err } hashes = append(hashes, h) } // hash the mainfile template to ensure if it gets updated, we make a new // binary. hashes = append(hashes, fmt.Sprintf("%x", sha1.Sum([]byte(mageMainfileTplString)))) sort.Strings(hashes) ver, err := internal.OutputDebug(goCmd, "version") if err != nil { return "", err } hash := sha1.Sum([]byte(strings.Join(hashes, "") + magicRebuildKey + ver)) filename := fmt.Sprintf("%x", hash) out := filepath.Join(cacheDir, filename) if runtime.GOOS == "windows" { out += ".exe" } return out, nil }
[ "func", "ExeName", "(", "goCmd", ",", "cacheDir", "string", ",", "files", "[", "]", "string", ")", "(", "string", ",", "error", ")", "{", "var", "hashes", "[", "]", "string", "\n", "for", "_", ",", "s", ":=", "range", "files", "{", "h", ",", "err...
// ExeName reports the executable filename that this version of Mage would // create for the given magefiles.
[ "ExeName", "reports", "the", "executable", "filename", "that", "this", "version", "of", "Mage", "would", "create", "for", "the", "given", "magefiles", "." ]
5bc3a8ab86d5a23d6eb3bdbcd60e79ac4d9ad0ed
https://github.com/magefile/mage/blob/5bc3a8ab86d5a23d6eb3bdbcd60e79ac4d9ad0ed/mage/main.go#L543-L568
train
magefile/mage
mage/main.go
RunCompiled
func RunCompiled(inv Invocation, exePath string, errlog *log.Logger) int { debug.Println("running binary", exePath) c := exec.Command(exePath, inv.Args...) c.Stderr = inv.Stderr c.Stdout = inv.Stdout c.Stdin = inv.Stdin c.Dir = inv.Dir // intentionally pass through unaltered os.Environ here.. your magefile has // to deal with it. c.Env = os.Environ() if inv.Verbose { c.Env = append(c.Env, "MAGEFILE_VERBOSE=1") } if inv.List { c.Env = append(c.Env, "MAGEFILE_LIST=1") } if inv.Help { c.Env = append(c.Env, "MAGEFILE_HELP=1") } if inv.Debug { c.Env = append(c.Env, "MAGEFILE_DEBUG=1") } if inv.GoCmd != "" { c.Env = append(c.Env, fmt.Sprintf("MAGEFILE_GOCMD=%s", inv.GoCmd)) } if inv.Timeout > 0 { c.Env = append(c.Env, fmt.Sprintf("MAGEFILE_TIMEOUT=%s", inv.Timeout.String())) } debug.Print("running magefile with mage vars:\n", strings.Join(filter(c.Env, "MAGEFILE"), "\n")) err := c.Run() if !sh.CmdRan(err) { errlog.Printf("failed to run compiled magefile: %v", err) } return sh.ExitStatus(err) }
go
func RunCompiled(inv Invocation, exePath string, errlog *log.Logger) int { debug.Println("running binary", exePath) c := exec.Command(exePath, inv.Args...) c.Stderr = inv.Stderr c.Stdout = inv.Stdout c.Stdin = inv.Stdin c.Dir = inv.Dir // intentionally pass through unaltered os.Environ here.. your magefile has // to deal with it. c.Env = os.Environ() if inv.Verbose { c.Env = append(c.Env, "MAGEFILE_VERBOSE=1") } if inv.List { c.Env = append(c.Env, "MAGEFILE_LIST=1") } if inv.Help { c.Env = append(c.Env, "MAGEFILE_HELP=1") } if inv.Debug { c.Env = append(c.Env, "MAGEFILE_DEBUG=1") } if inv.GoCmd != "" { c.Env = append(c.Env, fmt.Sprintf("MAGEFILE_GOCMD=%s", inv.GoCmd)) } if inv.Timeout > 0 { c.Env = append(c.Env, fmt.Sprintf("MAGEFILE_TIMEOUT=%s", inv.Timeout.String())) } debug.Print("running magefile with mage vars:\n", strings.Join(filter(c.Env, "MAGEFILE"), "\n")) err := c.Run() if !sh.CmdRan(err) { errlog.Printf("failed to run compiled magefile: %v", err) } return sh.ExitStatus(err) }
[ "func", "RunCompiled", "(", "inv", "Invocation", ",", "exePath", "string", ",", "errlog", "*", "log", ".", "Logger", ")", "int", "{", "debug", ".", "Println", "(", "\"", "\"", ",", "exePath", ")", "\n", "c", ":=", "exec", ".", "Command", "(", "exePat...
// RunCompiled runs an already-compiled mage command with the given args,
[ "RunCompiled", "runs", "an", "already", "-", "compiled", "mage", "command", "with", "the", "given", "args" ]
5bc3a8ab86d5a23d6eb3bdbcd60e79ac4d9ad0ed
https://github.com/magefile/mage/blob/5bc3a8ab86d5a23d6eb3bdbcd60e79ac4d9ad0ed/mage/main.go#L600-L634
train
magefile/mage
mage/main.go
removeContents
func removeContents(dir string) error { debug.Println("removing all files in", dir) files, err := ioutil.ReadDir(dir) if err != nil { if os.IsNotExist(err) { return nil } return err } for _, f := range files { if f.IsDir() { continue } err = os.Remove(filepath.Join(dir, f.Name())) if err != nil { return err } } return nil }
go
func removeContents(dir string) error { debug.Println("removing all files in", dir) files, err := ioutil.ReadDir(dir) if err != nil { if os.IsNotExist(err) { return nil } return err } for _, f := range files { if f.IsDir() { continue } err = os.Remove(filepath.Join(dir, f.Name())) if err != nil { return err } } return nil }
[ "func", "removeContents", "(", "dir", "string", ")", "error", "{", "debug", ".", "Println", "(", "\"", "\"", ",", "dir", ")", "\n", "files", ",", "err", ":=", "ioutil", ".", "ReadDir", "(", "dir", ")", "\n", "if", "err", "!=", "nil", "{", "if", "...
// removeContents removes all files but not any subdirectories in the given // directory.
[ "removeContents", "removes", "all", "files", "but", "not", "any", "subdirectories", "in", "the", "given", "directory", "." ]
5bc3a8ab86d5a23d6eb3bdbcd60e79ac4d9ad0ed
https://github.com/magefile/mage/blob/5bc3a8ab86d5a23d6eb3bdbcd60e79ac4d9ad0ed/mage/main.go#L648-L668
train
magefile/mage
magefile.go
Install
func Install() error { name := "mage" if runtime.GOOS == "windows" { name += ".exe" } gocmd := mg.GoCmd() // use GOBIN if set in the environment, otherwise fall back to first path // in GOPATH environment string bin, err := sh.Output(gocmd, "env", "GOBIN") if err != nil { return fmt.Errorf("can't determine GOBIN: %v", err) } if bin == "" { gopath, err := sh.Output(gocmd, "env", "GOPATH") if err != nil { return fmt.Errorf("can't determine GOPATH: %v", err) } paths := strings.Split(gopath, string([]rune{os.PathListSeparator})) bin = filepath.Join(paths[0], "bin") } // specifically don't mkdirall, if you have an invalid gopath in the first // place, that's not on us to fix. if err := os.Mkdir(bin, 0700); err != nil && !os.IsExist(err) { return fmt.Errorf("failed to create %q: %v", bin, err) } path := filepath.Join(bin, name) // we use go build here because if someone built with go get, then `go // install` turns into a no-op, and `go install -a` fails on people's // machines that have go installed in a non-writeable directory (such as // normal OS installs in /usr/bin) return sh.RunV(gocmd, "build", "-o", path, "-ldflags="+flags(), "github.com/magefile/mage") }
go
func Install() error { name := "mage" if runtime.GOOS == "windows" { name += ".exe" } gocmd := mg.GoCmd() // use GOBIN if set in the environment, otherwise fall back to first path // in GOPATH environment string bin, err := sh.Output(gocmd, "env", "GOBIN") if err != nil { return fmt.Errorf("can't determine GOBIN: %v", err) } if bin == "" { gopath, err := sh.Output(gocmd, "env", "GOPATH") if err != nil { return fmt.Errorf("can't determine GOPATH: %v", err) } paths := strings.Split(gopath, string([]rune{os.PathListSeparator})) bin = filepath.Join(paths[0], "bin") } // specifically don't mkdirall, if you have an invalid gopath in the first // place, that's not on us to fix. if err := os.Mkdir(bin, 0700); err != nil && !os.IsExist(err) { return fmt.Errorf("failed to create %q: %v", bin, err) } path := filepath.Join(bin, name) // we use go build here because if someone built with go get, then `go // install` turns into a no-op, and `go install -a` fails on people's // machines that have go installed in a non-writeable directory (such as // normal OS installs in /usr/bin) return sh.RunV(gocmd, "build", "-o", path, "-ldflags="+flags(), "github.com/magefile/mage") }
[ "func", "Install", "(", ")", "error", "{", "name", ":=", "\"", "\"", "\n", "if", "runtime", ".", "GOOS", "==", "\"", "\"", "{", "name", "+=", "\"", "\"", "\n", "}", "\n\n", "gocmd", ":=", "mg", ".", "GoCmd", "(", ")", "\n", "// use GOBIN if set in ...
// Runs "go install" for mage. This generates the version info the binary.
[ "Runs", "go", "install", "for", "mage", ".", "This", "generates", "the", "version", "info", "the", "binary", "." ]
5bc3a8ab86d5a23d6eb3bdbcd60e79ac4d9ad0ed
https://github.com/magefile/mage/blob/5bc3a8ab86d5a23d6eb3bdbcd60e79ac4d9ad0ed/magefile.go#L23-L56
train
magefile/mage
magefile.go
Release
func Release() (err error) { tag := os.Getenv("TAG") if !releaseTag.MatchString(tag) { return errors.New("TAG environment variable must be in semver v1.x.x format, but was " + tag) } if err := sh.RunV("git", "tag", "-a", tag, "-m", tag); err != nil { return err } if err := sh.RunV("git", "push", "origin", tag); err != nil { return err } defer func() { if err != nil { sh.RunV("git", "tag", "--delete", "$TAG") sh.RunV("git", "push", "--delete", "origin", "$TAG") } }() return sh.RunV("goreleaser") }
go
func Release() (err error) { tag := os.Getenv("TAG") if !releaseTag.MatchString(tag) { return errors.New("TAG environment variable must be in semver v1.x.x format, but was " + tag) } if err := sh.RunV("git", "tag", "-a", tag, "-m", tag); err != nil { return err } if err := sh.RunV("git", "push", "origin", tag); err != nil { return err } defer func() { if err != nil { sh.RunV("git", "tag", "--delete", "$TAG") sh.RunV("git", "push", "--delete", "origin", "$TAG") } }() return sh.RunV("goreleaser") }
[ "func", "Release", "(", ")", "(", "err", "error", ")", "{", "tag", ":=", "os", ".", "Getenv", "(", "\"", "\"", ")", "\n", "if", "!", "releaseTag", ".", "MatchString", "(", "tag", ")", "{", "return", "errors", ".", "New", "(", "\"", "\"", "+", "...
// Generates a new release. Expects the TAG environment variable to be set, // which will create a new tag with that name.
[ "Generates", "a", "new", "release", ".", "Expects", "the", "TAG", "environment", "variable", "to", "be", "set", "which", "will", "create", "a", "new", "tag", "with", "that", "name", "." ]
5bc3a8ab86d5a23d6eb3bdbcd60e79ac4d9ad0ed
https://github.com/magefile/mage/blob/5bc3a8ab86d5a23d6eb3bdbcd60e79ac4d9ad0ed/magefile.go#L62-L81
train
magefile/mage
parse/parse.go
ID
func (f Function) ID() string { path := "<current>" if f.ImportPath != "" { path = f.ImportPath } receiver := "" if f.Receiver != "" { receiver = f.Receiver + "." } return fmt.Sprintf("%s.%s%s", path, receiver, f.Name) }
go
func (f Function) ID() string { path := "<current>" if f.ImportPath != "" { path = f.ImportPath } receiver := "" if f.Receiver != "" { receiver = f.Receiver + "." } return fmt.Sprintf("%s.%s%s", path, receiver, f.Name) }
[ "func", "(", "f", "Function", ")", "ID", "(", ")", "string", "{", "path", ":=", "\"", "\"", "\n", "if", "f", ".", "ImportPath", "!=", "\"", "\"", "{", "path", "=", "f", ".", "ImportPath", "\n", "}", "\n", "receiver", ":=", "\"", "\"", "\n", "if...
// ID returns user-readable information about where this function is defined.
[ "ID", "returns", "user", "-", "readable", "information", "about", "where", "this", "function", "is", "defined", "." ]
5bc3a8ab86d5a23d6eb3bdbcd60e79ac4d9ad0ed
https://github.com/magefile/mage/blob/5bc3a8ab86d5a23d6eb3bdbcd60e79ac4d9ad0ed/parse/parse.go#L54-L64
train
magefile/mage
parse/parse.go
TargetName
func (f Function) TargetName() string { var names []string for _, s := range []string{f.PkgAlias, f.Receiver, f.Name} { if s != "" { names = append(names, s) } } return strings.Join(names, ":") }
go
func (f Function) TargetName() string { var names []string for _, s := range []string{f.PkgAlias, f.Receiver, f.Name} { if s != "" { names = append(names, s) } } return strings.Join(names, ":") }
[ "func", "(", "f", "Function", ")", "TargetName", "(", ")", "string", "{", "var", "names", "[", "]", "string", "\n\n", "for", "_", ",", "s", ":=", "range", "[", "]", "string", "{", "f", ".", "PkgAlias", ",", "f", ".", "Receiver", ",", "f", ".", ...
// TargetName returns the name of the target as it should appear when used from // the mage cli. It is always lowercase.
[ "TargetName", "returns", "the", "name", "of", "the", "target", "as", "it", "should", "appear", "when", "used", "from", "the", "mage", "cli", ".", "It", "is", "always", "lowercase", "." ]
5bc3a8ab86d5a23d6eb3bdbcd60e79ac4d9ad0ed
https://github.com/magefile/mage/blob/5bc3a8ab86d5a23d6eb3bdbcd60e79ac4d9ad0ed/parse/parse.go#L68-L77
train
magefile/mage
parse/parse.go
PrimaryPackage
func PrimaryPackage(gocmd, path string, files []string) (*PkgInfo, error) { info, err := Package(path, files) if err != nil { return nil, err } if err := setImports(gocmd, info); err != nil { return nil, err } setDefault(info) setAliases(info) return info, nil }
go
func PrimaryPackage(gocmd, path string, files []string) (*PkgInfo, error) { info, err := Package(path, files) if err != nil { return nil, err } if err := setImports(gocmd, info); err != nil { return nil, err } setDefault(info) setAliases(info) return info, nil }
[ "func", "PrimaryPackage", "(", "gocmd", ",", "path", "string", ",", "files", "[", "]", "string", ")", "(", "*", "PkgInfo", ",", "error", ")", "{", "info", ",", "err", ":=", "Package", "(", "path", ",", "files", ")", "\n", "if", "err", "!=", "nil", ...
// PrimaryPackage parses a package. If files is non-empty, it will only parse the files given.
[ "PrimaryPackage", "parses", "a", "package", ".", "If", "files", "is", "non", "-", "empty", "it", "will", "only", "parse", "the", "files", "given", "." ]
5bc3a8ab86d5a23d6eb3bdbcd60e79ac4d9ad0ed
https://github.com/magefile/mage/blob/5bc3a8ab86d5a23d6eb3bdbcd60e79ac4d9ad0ed/parse/parse.go#L129-L142
train
magefile/mage
parse/parse.go
Package
func Package(path string, files []string) (*PkgInfo, error) { start := time.Now() defer func() { debug.Println("time parse Magefiles:", time.Since(start)) }() fset := token.NewFileSet() pkg, err := getPackage(path, files, fset) if err != nil { return nil, err } p := doc.New(pkg, "./", 0) pi := &PkgInfo{ AstPkg: pkg, DocPkg: p, Description: toOneLine(p.Doc), } setNamespaces(pi) setFuncs(pi) hasDupes, names := checkDupeTargets(pi) if hasDupes { msg := "Build targets must be case insensitive, thus the following targets conflict:\n" for _, v := range names { if len(v) > 1 { msg += " " + strings.Join(v, ", ") + "\n" } } return nil, errors.New(msg) } return pi, nil }
go
func Package(path string, files []string) (*PkgInfo, error) { start := time.Now() defer func() { debug.Println("time parse Magefiles:", time.Since(start)) }() fset := token.NewFileSet() pkg, err := getPackage(path, files, fset) if err != nil { return nil, err } p := doc.New(pkg, "./", 0) pi := &PkgInfo{ AstPkg: pkg, DocPkg: p, Description: toOneLine(p.Doc), } setNamespaces(pi) setFuncs(pi) hasDupes, names := checkDupeTargets(pi) if hasDupes { msg := "Build targets must be case insensitive, thus the following targets conflict:\n" for _, v := range names { if len(v) > 1 { msg += " " + strings.Join(v, ", ") + "\n" } } return nil, errors.New(msg) } return pi, nil }
[ "func", "Package", "(", "path", "string", ",", "files", "[", "]", "string", ")", "(", "*", "PkgInfo", ",", "error", ")", "{", "start", ":=", "time", ".", "Now", "(", ")", "\n", "defer", "func", "(", ")", "{", "debug", ".", "Println", "(", "\"", ...
// Package compiles information about a mage package.
[ "Package", "compiles", "information", "about", "a", "mage", "package", "." ]
5bc3a8ab86d5a23d6eb3bdbcd60e79ac4d9ad0ed
https://github.com/magefile/mage/blob/5bc3a8ab86d5a23d6eb3bdbcd60e79ac4d9ad0ed/parse/parse.go#L186-L218
train
magefile/mage
parse/parse.go
checkDupeTargets
func checkDupeTargets(info *PkgInfo) (hasDupes bool, names map[string][]string) { names = map[string][]string{} lowers := map[string]bool{} for _, f := range info.Funcs { low := strings.ToLower(f.Name) if f.Receiver != "" { low = strings.ToLower(f.Receiver) + ":" + low } if lowers[low] { hasDupes = true } lowers[low] = true names[low] = append(names[low], f.Name) } return hasDupes, names }
go
func checkDupeTargets(info *PkgInfo) (hasDupes bool, names map[string][]string) { names = map[string][]string{} lowers := map[string]bool{} for _, f := range info.Funcs { low := strings.ToLower(f.Name) if f.Receiver != "" { low = strings.ToLower(f.Receiver) + ":" + low } if lowers[low] { hasDupes = true } lowers[low] = true names[low] = append(names[low], f.Name) } return hasDupes, names }
[ "func", "checkDupeTargets", "(", "info", "*", "PkgInfo", ")", "(", "hasDupes", "bool", ",", "names", "map", "[", "string", "]", "[", "]", "string", ")", "{", "names", "=", "map", "[", "string", "]", "[", "]", "string", "{", "}", "\n", "lowers", ":=...
// checkDupeTargets checks a package for duplicate target names.
[ "checkDupeTargets", "checks", "a", "package", "for", "duplicate", "target", "names", "." ]
5bc3a8ab86d5a23d6eb3bdbcd60e79ac4d9ad0ed
https://github.com/magefile/mage/blob/5bc3a8ab86d5a23d6eb3bdbcd60e79ac4d9ad0ed/parse/parse.go#L463-L478
train
magefile/mage
parse/parse.go
sanitizeSynopsis
func sanitizeSynopsis(f *doc.Func) string { synopsis := doc.Synopsis(f.Doc) // If the synopsis begins with the function name, remove it. This is done to // not repeat the text. // From: // clean Clean removes the temporarily generated files // To: // clean removes the temporarily generated files if syns := strings.Split(synopsis, " "); strings.EqualFold(f.Name, syns[0]) { return strings.Join(syns[1:], " ") } return synopsis }
go
func sanitizeSynopsis(f *doc.Func) string { synopsis := doc.Synopsis(f.Doc) // If the synopsis begins with the function name, remove it. This is done to // not repeat the text. // From: // clean Clean removes the temporarily generated files // To: // clean removes the temporarily generated files if syns := strings.Split(synopsis, " "); strings.EqualFold(f.Name, syns[0]) { return strings.Join(syns[1:], " ") } return synopsis }
[ "func", "sanitizeSynopsis", "(", "f", "*", "doc", ".", "Func", ")", "string", "{", "synopsis", ":=", "doc", ".", "Synopsis", "(", "f", ".", "Doc", ")", "\n\n", "// If the synopsis begins with the function name, remove it. This is done to", "// not repeat the text.", "...
// sanitizeSynopsis sanitizes function Doc to create a summary.
[ "sanitizeSynopsis", "sanitizes", "function", "Doc", "to", "create", "a", "summary", "." ]
5bc3a8ab86d5a23d6eb3bdbcd60e79ac4d9ad0ed
https://github.com/magefile/mage/blob/5bc3a8ab86d5a23d6eb3bdbcd60e79ac4d9ad0ed/parse/parse.go#L481-L495
train
magefile/mage
parse/parse.go
getPackage
func getPackage(path string, files []string, fset *token.FileSet) (*ast.Package, error) { var filter func(f os.FileInfo) bool if len(files) > 0 { fm := make(map[string]bool, len(files)) for _, f := range files { fm[f] = true } filter = func(f os.FileInfo) bool { return fm[f.Name()] } } pkgs, err := parser.ParseDir(fset, path, filter, parser.ParseComments) if err != nil { return nil, fmt.Errorf("failed to parse directory: %v", err) } for name, pkg := range pkgs { if !strings.HasSuffix(name, "_test") { return pkg, nil } } return nil, fmt.Errorf("no non-test packages found in %s", path) }
go
func getPackage(path string, files []string, fset *token.FileSet) (*ast.Package, error) { var filter func(f os.FileInfo) bool if len(files) > 0 { fm := make(map[string]bool, len(files)) for _, f := range files { fm[f] = true } filter = func(f os.FileInfo) bool { return fm[f.Name()] } } pkgs, err := parser.ParseDir(fset, path, filter, parser.ParseComments) if err != nil { return nil, fmt.Errorf("failed to parse directory: %v", err) } for name, pkg := range pkgs { if !strings.HasSuffix(name, "_test") { return pkg, nil } } return nil, fmt.Errorf("no non-test packages found in %s", path) }
[ "func", "getPackage", "(", "path", "string", ",", "files", "[", "]", "string", ",", "fset", "*", "token", ".", "FileSet", ")", "(", "*", "ast", ".", "Package", ",", "error", ")", "{", "var", "filter", "func", "(", "f", "os", ".", "FileInfo", ")", ...
// getPackage returns the non-test package at the given path.
[ "getPackage", "returns", "the", "non", "-", "test", "package", "at", "the", "given", "path", "." ]
5bc3a8ab86d5a23d6eb3bdbcd60e79ac4d9ad0ed
https://github.com/magefile/mage/blob/5bc3a8ab86d5a23d6eb3bdbcd60e79ac4d9ad0ed/parse/parse.go#L657-L681
train
magefile/mage
mg/errors.go
Fatal
func Fatal(code int, args ...interface{}) error { return fatalErr{ code: code, error: errors.New(fmt.Sprint(args...)), } }
go
func Fatal(code int, args ...interface{}) error { return fatalErr{ code: code, error: errors.New(fmt.Sprint(args...)), } }
[ "func", "Fatal", "(", "code", "int", ",", "args", "...", "interface", "{", "}", ")", "error", "{", "return", "fatalErr", "{", "code", ":", "code", ",", "error", ":", "errors", ".", "New", "(", "fmt", ".", "Sprint", "(", "args", "...", ")", ")", "...
// Fatal returns an error that will cause mage to print out the // given args and exit with the given exit code.
[ "Fatal", "returns", "an", "error", "that", "will", "cause", "mage", "to", "print", "out", "the", "given", "args", "and", "exit", "with", "the", "given", "exit", "code", "." ]
5bc3a8ab86d5a23d6eb3bdbcd60e79ac4d9ad0ed
https://github.com/magefile/mage/blob/5bc3a8ab86d5a23d6eb3bdbcd60e79ac4d9ad0ed/mg/errors.go#L23-L28
train
magefile/mage
mg/errors.go
Fatalf
func Fatalf(code int, format string, args ...interface{}) error { return fatalErr{ code: code, error: fmt.Errorf(format, args...), } }
go
func Fatalf(code int, format string, args ...interface{}) error { return fatalErr{ code: code, error: fmt.Errorf(format, args...), } }
[ "func", "Fatalf", "(", "code", "int", ",", "format", "string", ",", "args", "...", "interface", "{", "}", ")", "error", "{", "return", "fatalErr", "{", "code", ":", "code", ",", "error", ":", "fmt", ".", "Errorf", "(", "format", ",", "args", "...", ...
// Fatalf returns an error that will cause mage to print out the // given message and exit with the given exit code.
[ "Fatalf", "returns", "an", "error", "that", "will", "cause", "mage", "to", "print", "out", "the", "given", "message", "and", "exit", "with", "the", "given", "exit", "code", "." ]
5bc3a8ab86d5a23d6eb3bdbcd60e79ac4d9ad0ed
https://github.com/magefile/mage/blob/5bc3a8ab86d5a23d6eb3bdbcd60e79ac4d9ad0ed/mg/errors.go#L32-L37
train
magefile/mage
target/target.go
Dir
func Dir(dst string, sources ...string) (bool, error) { stat, err := os.Stat(os.ExpandEnv(dst)) if os.IsNotExist(err) { return true, nil } if err != nil { return false, err } srcTime := stat.ModTime() if stat.IsDir() { srcTime, err = calDirModTimeRecursive(dst, stat) if err != nil { return false, err } } dt, err := loadTargets(expand(sources)) if err != nil { return false, err } t, err := dt.modTimeDir() if err != nil { return false, err } if t.After(srcTime) { return true, nil } return false, nil }
go
func Dir(dst string, sources ...string) (bool, error) { stat, err := os.Stat(os.ExpandEnv(dst)) if os.IsNotExist(err) { return true, nil } if err != nil { return false, err } srcTime := stat.ModTime() if stat.IsDir() { srcTime, err = calDirModTimeRecursive(dst, stat) if err != nil { return false, err } } dt, err := loadTargets(expand(sources)) if err != nil { return false, err } t, err := dt.modTimeDir() if err != nil { return false, err } if t.After(srcTime) { return true, nil } return false, nil }
[ "func", "Dir", "(", "dst", "string", ",", "sources", "...", "string", ")", "(", "bool", ",", "error", ")", "{", "stat", ",", "err", ":=", "os", ".", "Stat", "(", "os", ".", "ExpandEnv", "(", "dst", ")", ")", "\n", "if", "os", ".", "IsNotExist", ...
// Dir reports whether any of the sources have been modified more recently than // the destination. If a source or destination is a directory, modtimes of // files under those directories are compared instead. If the destination file // doesn't exist, it always returns true and nil. It's an error if any of the // sources don't exist.
[ "Dir", "reports", "whether", "any", "of", "the", "sources", "have", "been", "modified", "more", "recently", "than", "the", "destination", ".", "If", "a", "source", "or", "destination", "is", "a", "directory", "modtimes", "of", "files", "under", "those", "dir...
5bc3a8ab86d5a23d6eb3bdbcd60e79ac4d9ad0ed
https://github.com/magefile/mage/blob/5bc3a8ab86d5a23d6eb3bdbcd60e79ac4d9ad0ed/target/target.go#L79-L106
train
magefile/mage
sh/cmd.go
OutCmd
func OutCmd(cmd string, args ...string) func(args ...string) (string, error) { return func(args2 ...string) (string, error) { return Output(cmd, append(args, args2...)...) } }
go
func OutCmd(cmd string, args ...string) func(args ...string) (string, error) { return func(args2 ...string) (string, error) { return Output(cmd, append(args, args2...)...) } }
[ "func", "OutCmd", "(", "cmd", "string", ",", "args", "...", "string", ")", "func", "(", "args", "...", "string", ")", "(", "string", ",", "error", ")", "{", "return", "func", "(", "args2", "...", "string", ")", "(", "string", ",", "error", ")", "{"...
// OutCmd is like RunCmd except the command returns the output of the // command.
[ "OutCmd", "is", "like", "RunCmd", "except", "the", "command", "returns", "the", "output", "of", "the", "command", "." ]
5bc3a8ab86d5a23d6eb3bdbcd60e79ac4d9ad0ed
https://github.com/magefile/mage/blob/5bc3a8ab86d5a23d6eb3bdbcd60e79ac4d9ad0ed/sh/cmd.go#L42-L46
train
magefile/mage
sh/cmd.go
Run
func Run(cmd string, args ...string) error { return RunWith(nil, cmd, args...) }
go
func Run(cmd string, args ...string) error { return RunWith(nil, cmd, args...) }
[ "func", "Run", "(", "cmd", "string", ",", "args", "...", "string", ")", "error", "{", "return", "RunWith", "(", "nil", ",", "cmd", ",", "args", "...", ")", "\n", "}" ]
// Run is like RunWith, but doesn't specify any environment variables.
[ "Run", "is", "like", "RunWith", "but", "doesn", "t", "specify", "any", "environment", "variables", "." ]
5bc3a8ab86d5a23d6eb3bdbcd60e79ac4d9ad0ed
https://github.com/magefile/mage/blob/5bc3a8ab86d5a23d6eb3bdbcd60e79ac4d9ad0ed/sh/cmd.go#L49-L51
train
magefile/mage
sh/cmd.go
RunV
func RunV(cmd string, args ...string) error { _, err := Exec(nil, os.Stdout, os.Stderr, cmd, args...) return err }
go
func RunV(cmd string, args ...string) error { _, err := Exec(nil, os.Stdout, os.Stderr, cmd, args...) return err }
[ "func", "RunV", "(", "cmd", "string", ",", "args", "...", "string", ")", "error", "{", "_", ",", "err", ":=", "Exec", "(", "nil", ",", "os", ".", "Stdout", ",", "os", ".", "Stderr", ",", "cmd", ",", "args", "...", ")", "\n", "return", "err", "\...
// RunV is like Run, but always sends the command's stdout to os.Stdout.
[ "RunV", "is", "like", "Run", "but", "always", "sends", "the", "command", "s", "stdout", "to", "os", ".", "Stdout", "." ]
5bc3a8ab86d5a23d6eb3bdbcd60e79ac4d9ad0ed
https://github.com/magefile/mage/blob/5bc3a8ab86d5a23d6eb3bdbcd60e79ac4d9ad0ed/sh/cmd.go#L54-L57
train
magefile/mage
sh/cmd.go
RunWith
func RunWith(env map[string]string, cmd string, args ...string) error { var output io.Writer if mg.Verbose() { output = os.Stdout } _, err := Exec(env, output, os.Stderr, cmd, args...) return err }
go
func RunWith(env map[string]string, cmd string, args ...string) error { var output io.Writer if mg.Verbose() { output = os.Stdout } _, err := Exec(env, output, os.Stderr, cmd, args...) return err }
[ "func", "RunWith", "(", "env", "map", "[", "string", "]", "string", ",", "cmd", "string", ",", "args", "...", "string", ")", "error", "{", "var", "output", "io", ".", "Writer", "\n", "if", "mg", ".", "Verbose", "(", ")", "{", "output", "=", "os", ...
// RunWith runs the given command, directing stderr to this program's stderr and // printing stdout to stdout if mage was run with -v. It adds adds env to the // environment variables for the command being run. Environment variables should // be in the format name=value.
[ "RunWith", "runs", "the", "given", "command", "directing", "stderr", "to", "this", "program", "s", "stderr", "and", "printing", "stdout", "to", "stdout", "if", "mage", "was", "run", "with", "-", "v", ".", "It", "adds", "adds", "env", "to", "the", "enviro...
5bc3a8ab86d5a23d6eb3bdbcd60e79ac4d9ad0ed
https://github.com/magefile/mage/blob/5bc3a8ab86d5a23d6eb3bdbcd60e79ac4d9ad0ed/sh/cmd.go#L63-L70
train
magefile/mage
sh/cmd.go
Output
func Output(cmd string, args ...string) (string, error) { buf := &bytes.Buffer{} _, err := Exec(nil, buf, os.Stderr, cmd, args...) return strings.TrimSuffix(buf.String(), "\n"), err }
go
func Output(cmd string, args ...string) (string, error) { buf := &bytes.Buffer{} _, err := Exec(nil, buf, os.Stderr, cmd, args...) return strings.TrimSuffix(buf.String(), "\n"), err }
[ "func", "Output", "(", "cmd", "string", ",", "args", "...", "string", ")", "(", "string", ",", "error", ")", "{", "buf", ":=", "&", "bytes", ".", "Buffer", "{", "}", "\n", "_", ",", "err", ":=", "Exec", "(", "nil", ",", "buf", ",", "os", ".", ...
// Output runs the command and returns the text from stdout.
[ "Output", "runs", "the", "command", "and", "returns", "the", "text", "from", "stdout", "." ]
5bc3a8ab86d5a23d6eb3bdbcd60e79ac4d9ad0ed
https://github.com/magefile/mage/blob/5bc3a8ab86d5a23d6eb3bdbcd60e79ac4d9ad0ed/sh/cmd.go#L73-L77
train
magefile/mage
sh/cmd.go
OutputWith
func OutputWith(env map[string]string, cmd string, args ...string) (string, error) { buf := &bytes.Buffer{} _, err := Exec(env, buf, os.Stderr, cmd, args...) return strings.TrimSuffix(buf.String(), "\n"), err }
go
func OutputWith(env map[string]string, cmd string, args ...string) (string, error) { buf := &bytes.Buffer{} _, err := Exec(env, buf, os.Stderr, cmd, args...) return strings.TrimSuffix(buf.String(), "\n"), err }
[ "func", "OutputWith", "(", "env", "map", "[", "string", "]", "string", ",", "cmd", "string", ",", "args", "...", "string", ")", "(", "string", ",", "error", ")", "{", "buf", ":=", "&", "bytes", ".", "Buffer", "{", "}", "\n", "_", ",", "err", ":="...
// OutputWith is like RunWith, but returns what is written to stdout.
[ "OutputWith", "is", "like", "RunWith", "but", "returns", "what", "is", "written", "to", "stdout", "." ]
5bc3a8ab86d5a23d6eb3bdbcd60e79ac4d9ad0ed
https://github.com/magefile/mage/blob/5bc3a8ab86d5a23d6eb3bdbcd60e79ac4d9ad0ed/sh/cmd.go#L80-L84
train
appleboy/gin-jwt
auth_jwt.go
New
func New(m *GinJWTMiddleware) (*GinJWTMiddleware, error) { if err := m.MiddlewareInit(); err != nil { return nil, err } return m, nil }
go
func New(m *GinJWTMiddleware) (*GinJWTMiddleware, error) { if err := m.MiddlewareInit(); err != nil { return nil, err } return m, nil }
[ "func", "New", "(", "m", "*", "GinJWTMiddleware", ")", "(", "*", "GinJWTMiddleware", ",", "error", ")", "{", "if", "err", ":=", "m", ".", "MiddlewareInit", "(", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "ret...
// New for check error with GinJWTMiddleware
[ "New", "for", "check", "error", "with", "GinJWTMiddleware" ]
633d983b91f09beefb1128c4558d4642a379c602
https://github.com/appleboy/gin-jwt/blob/633d983b91f09beefb1128c4558d4642a379c602/auth_jwt.go#L193-L199
train
appleboy/gin-jwt
auth_jwt.go
MiddlewareInit
func (mw *GinJWTMiddleware) MiddlewareInit() error { if mw.TokenLookup == "" { mw.TokenLookup = "header:Authorization" } if mw.SigningAlgorithm == "" { mw.SigningAlgorithm = "HS256" } if mw.Timeout == 0 { mw.Timeout = time.Hour } if mw.TimeFunc == nil { mw.TimeFunc = time.Now } mw.TokenHeadName = strings.TrimSpace(mw.TokenHeadName) if len(mw.TokenHeadName) == 0 { mw.TokenHeadName = "Bearer" } if mw.Authorizator == nil { mw.Authorizator = func(data interface{}, c *gin.Context) bool { return true } } if mw.Unauthorized == nil { mw.Unauthorized = func(c *gin.Context, code int, message string) { c.JSON(code, gin.H{ "code": code, "message": message, }) } } if mw.LoginResponse == nil { mw.LoginResponse = func(c *gin.Context, code int, token string, expire time.Time) { c.JSON(http.StatusOK, gin.H{ "code": http.StatusOK, "token": token, "expire": expire.Format(time.RFC3339), }) } } if mw.RefreshResponse == nil { mw.RefreshResponse = func(c *gin.Context, code int, token string, expire time.Time) { c.JSON(http.StatusOK, gin.H{ "code": http.StatusOK, "token": token, "expire": expire.Format(time.RFC3339), }) } } if mw.IdentityKey == "" { mw.IdentityKey = IdentityKey } if mw.IdentityHandler == nil { mw.IdentityHandler = func(c *gin.Context) interface{} { claims := ExtractClaims(c) return claims[mw.IdentityKey] } } if mw.HTTPStatusMessageFunc == nil { mw.HTTPStatusMessageFunc = func(e error, c *gin.Context) string { return e.Error() } } if mw.Realm == "" { mw.Realm = "gin jwt" } if mw.CookieName == "" { mw.CookieName = "jwt" } if mw.usingPublicKeyAlgo() { return mw.readKeys() } if mw.Key == nil { return ErrMissingSecretKey } return nil }
go
func (mw *GinJWTMiddleware) MiddlewareInit() error { if mw.TokenLookup == "" { mw.TokenLookup = "header:Authorization" } if mw.SigningAlgorithm == "" { mw.SigningAlgorithm = "HS256" } if mw.Timeout == 0 { mw.Timeout = time.Hour } if mw.TimeFunc == nil { mw.TimeFunc = time.Now } mw.TokenHeadName = strings.TrimSpace(mw.TokenHeadName) if len(mw.TokenHeadName) == 0 { mw.TokenHeadName = "Bearer" } if mw.Authorizator == nil { mw.Authorizator = func(data interface{}, c *gin.Context) bool { return true } } if mw.Unauthorized == nil { mw.Unauthorized = func(c *gin.Context, code int, message string) { c.JSON(code, gin.H{ "code": code, "message": message, }) } } if mw.LoginResponse == nil { mw.LoginResponse = func(c *gin.Context, code int, token string, expire time.Time) { c.JSON(http.StatusOK, gin.H{ "code": http.StatusOK, "token": token, "expire": expire.Format(time.RFC3339), }) } } if mw.RefreshResponse == nil { mw.RefreshResponse = func(c *gin.Context, code int, token string, expire time.Time) { c.JSON(http.StatusOK, gin.H{ "code": http.StatusOK, "token": token, "expire": expire.Format(time.RFC3339), }) } } if mw.IdentityKey == "" { mw.IdentityKey = IdentityKey } if mw.IdentityHandler == nil { mw.IdentityHandler = func(c *gin.Context) interface{} { claims := ExtractClaims(c) return claims[mw.IdentityKey] } } if mw.HTTPStatusMessageFunc == nil { mw.HTTPStatusMessageFunc = func(e error, c *gin.Context) string { return e.Error() } } if mw.Realm == "" { mw.Realm = "gin jwt" } if mw.CookieName == "" { mw.CookieName = "jwt" } if mw.usingPublicKeyAlgo() { return mw.readKeys() } if mw.Key == nil { return ErrMissingSecretKey } return nil }
[ "func", "(", "mw", "*", "GinJWTMiddleware", ")", "MiddlewareInit", "(", ")", "error", "{", "if", "mw", ".", "TokenLookup", "==", "\"", "\"", "{", "mw", ".", "TokenLookup", "=", "\"", "\"", "\n", "}", "\n\n", "if", "mw", ".", "SigningAlgorithm", "==", ...
// MiddlewareInit initialize jwt configs.
[ "MiddlewareInit", "initialize", "jwt", "configs", "." ]
633d983b91f09beefb1128c4558d4642a379c602
https://github.com/appleboy/gin-jwt/blob/633d983b91f09beefb1128c4558d4642a379c602/auth_jwt.go#L248-L339
train
appleboy/gin-jwt
auth_jwt.go
MiddlewareFunc
func (mw *GinJWTMiddleware) MiddlewareFunc() gin.HandlerFunc { return func(c *gin.Context) { mw.middlewareImpl(c) } }
go
func (mw *GinJWTMiddleware) MiddlewareFunc() gin.HandlerFunc { return func(c *gin.Context) { mw.middlewareImpl(c) } }
[ "func", "(", "mw", "*", "GinJWTMiddleware", ")", "MiddlewareFunc", "(", ")", "gin", ".", "HandlerFunc", "{", "return", "func", "(", "c", "*", "gin", ".", "Context", ")", "{", "mw", ".", "middlewareImpl", "(", "c", ")", "\n", "}", "\n", "}" ]
// MiddlewareFunc makes GinJWTMiddleware implement the Middleware interface.
[ "MiddlewareFunc", "makes", "GinJWTMiddleware", "implement", "the", "Middleware", "interface", "." ]
633d983b91f09beefb1128c4558d4642a379c602
https://github.com/appleboy/gin-jwt/blob/633d983b91f09beefb1128c4558d4642a379c602/auth_jwt.go#L342-L346
train
appleboy/gin-jwt
auth_jwt.go
GetClaimsFromJWT
func (mw *GinJWTMiddleware) GetClaimsFromJWT(c *gin.Context) (MapClaims, error) { token, err := mw.ParseToken(c) if err != nil { return nil, err } if mw.SendAuthorization { if v, ok := c.Get("JWT_TOKEN"); ok { c.Header("Authorization", mw.TokenHeadName+" "+v.(string)) } } claims := MapClaims{} for key, value := range token.Claims.(jwt.MapClaims) { claims[key] = value } return claims, nil }
go
func (mw *GinJWTMiddleware) GetClaimsFromJWT(c *gin.Context) (MapClaims, error) { token, err := mw.ParseToken(c) if err != nil { return nil, err } if mw.SendAuthorization { if v, ok := c.Get("JWT_TOKEN"); ok { c.Header("Authorization", mw.TokenHeadName+" "+v.(string)) } } claims := MapClaims{} for key, value := range token.Claims.(jwt.MapClaims) { claims[key] = value } return claims, nil }
[ "func", "(", "mw", "*", "GinJWTMiddleware", ")", "GetClaimsFromJWT", "(", "c", "*", "gin", ".", "Context", ")", "(", "MapClaims", ",", "error", ")", "{", "token", ",", "err", ":=", "mw", ".", "ParseToken", "(", "c", ")", "\n\n", "if", "err", "!=", ...
// GetClaimsFromJWT get claims from JWT token
[ "GetClaimsFromJWT", "get", "claims", "from", "JWT", "token" ]
633d983b91f09beefb1128c4558d4642a379c602
https://github.com/appleboy/gin-jwt/blob/633d983b91f09beefb1128c4558d4642a379c602/auth_jwt.go#L386-L405
train
appleboy/gin-jwt
auth_jwt.go
RefreshToken
func (mw *GinJWTMiddleware) RefreshToken(c *gin.Context) (string, time.Time, error) { claims, err := mw.CheckIfTokenExpire(c) if err != nil { return "", time.Now(), err } // Create the token newToken := jwt.New(jwt.GetSigningMethod(mw.SigningAlgorithm)) newClaims := newToken.Claims.(jwt.MapClaims) for key := range claims { newClaims[key] = claims[key] } expire := mw.TimeFunc().Add(mw.Timeout) newClaims["exp"] = expire.Unix() newClaims["orig_iat"] = mw.TimeFunc().Unix() tokenString, err := mw.signedString(newToken) if err != nil { return "", time.Now(), err } // set cookie if mw.SendCookie { maxage := int(expire.Unix() - time.Now().Unix()) c.SetCookie( mw.CookieName, tokenString, maxage, "/", mw.CookieDomain, mw.SecureCookie, mw.CookieHTTPOnly, ) } return tokenString, expire, nil }
go
func (mw *GinJWTMiddleware) RefreshToken(c *gin.Context) (string, time.Time, error) { claims, err := mw.CheckIfTokenExpire(c) if err != nil { return "", time.Now(), err } // Create the token newToken := jwt.New(jwt.GetSigningMethod(mw.SigningAlgorithm)) newClaims := newToken.Claims.(jwt.MapClaims) for key := range claims { newClaims[key] = claims[key] } expire := mw.TimeFunc().Add(mw.Timeout) newClaims["exp"] = expire.Unix() newClaims["orig_iat"] = mw.TimeFunc().Unix() tokenString, err := mw.signedString(newToken) if err != nil { return "", time.Now(), err } // set cookie if mw.SendCookie { maxage := int(expire.Unix() - time.Now().Unix()) c.SetCookie( mw.CookieName, tokenString, maxage, "/", mw.CookieDomain, mw.SecureCookie, mw.CookieHTTPOnly, ) } return tokenString, expire, nil }
[ "func", "(", "mw", "*", "GinJWTMiddleware", ")", "RefreshToken", "(", "c", "*", "gin", ".", "Context", ")", "(", "string", ",", "time", ".", "Time", ",", "error", ")", "{", "claims", ",", "err", ":=", "mw", ".", "CheckIfTokenExpire", "(", "c", ")", ...
// RefreshToken refresh token and check if token is expired
[ "RefreshToken", "refresh", "token", "and", "check", "if", "token", "is", "expired" ]
633d983b91f09beefb1128c4558d4642a379c602
https://github.com/appleboy/gin-jwt/blob/633d983b91f09beefb1128c4558d4642a379c602/auth_jwt.go#L485-L523
train
appleboy/gin-jwt
auth_jwt.go
CheckIfTokenExpire
func (mw *GinJWTMiddleware) CheckIfTokenExpire(c *gin.Context) (jwt.MapClaims, error) { token, err := mw.ParseToken(c) if err != nil { // If we receive an error, and the error is anything other than a single // ValidationErrorExpired, we want to return the error. // If the error is just ValidationErrorExpired, we want to continue, as we can still // refresh the token if it's within the MaxRefresh time. // (see https://github.com/appleboy/gin-jwt/issues/176) validationErr, ok := err.(*jwt.ValidationError) if !ok || validationErr.Errors != jwt.ValidationErrorExpired { return nil, err } } claims := token.Claims.(jwt.MapClaims) origIat := int64(claims["orig_iat"].(float64)) if origIat < mw.TimeFunc().Add(-mw.MaxRefresh).Unix() { return nil, ErrExpiredToken } return claims, nil }
go
func (mw *GinJWTMiddleware) CheckIfTokenExpire(c *gin.Context) (jwt.MapClaims, error) { token, err := mw.ParseToken(c) if err != nil { // If we receive an error, and the error is anything other than a single // ValidationErrorExpired, we want to return the error. // If the error is just ValidationErrorExpired, we want to continue, as we can still // refresh the token if it's within the MaxRefresh time. // (see https://github.com/appleboy/gin-jwt/issues/176) validationErr, ok := err.(*jwt.ValidationError) if !ok || validationErr.Errors != jwt.ValidationErrorExpired { return nil, err } } claims := token.Claims.(jwt.MapClaims) origIat := int64(claims["orig_iat"].(float64)) if origIat < mw.TimeFunc().Add(-mw.MaxRefresh).Unix() { return nil, ErrExpiredToken } return claims, nil }
[ "func", "(", "mw", "*", "GinJWTMiddleware", ")", "CheckIfTokenExpire", "(", "c", "*", "gin", ".", "Context", ")", "(", "jwt", ".", "MapClaims", ",", "error", ")", "{", "token", ",", "err", ":=", "mw", ".", "ParseToken", "(", "c", ")", "\n\n", "if", ...
// CheckIfTokenExpire check if token expire
[ "CheckIfTokenExpire", "check", "if", "token", "expire" ]
633d983b91f09beefb1128c4558d4642a379c602
https://github.com/appleboy/gin-jwt/blob/633d983b91f09beefb1128c4558d4642a379c602/auth_jwt.go#L526-L550
train
appleboy/gin-jwt
auth_jwt.go
TokenGenerator
func (mw *GinJWTMiddleware) TokenGenerator(data interface{}) (string, time.Time, error) { token := jwt.New(jwt.GetSigningMethod(mw.SigningAlgorithm)) claims := token.Claims.(jwt.MapClaims) if mw.PayloadFunc != nil { for key, value := range mw.PayloadFunc(data) { claims[key] = value } } expire := mw.TimeFunc().UTC().Add(mw.Timeout) claims["exp"] = expire.Unix() claims["orig_iat"] = mw.TimeFunc().Unix() tokenString, err := mw.signedString(token) if err != nil { return "", time.Time{}, err } return tokenString, expire, nil }
go
func (mw *GinJWTMiddleware) TokenGenerator(data interface{}) (string, time.Time, error) { token := jwt.New(jwt.GetSigningMethod(mw.SigningAlgorithm)) claims := token.Claims.(jwt.MapClaims) if mw.PayloadFunc != nil { for key, value := range mw.PayloadFunc(data) { claims[key] = value } } expire := mw.TimeFunc().UTC().Add(mw.Timeout) claims["exp"] = expire.Unix() claims["orig_iat"] = mw.TimeFunc().Unix() tokenString, err := mw.signedString(token) if err != nil { return "", time.Time{}, err } return tokenString, expire, nil }
[ "func", "(", "mw", "*", "GinJWTMiddleware", ")", "TokenGenerator", "(", "data", "interface", "{", "}", ")", "(", "string", ",", "time", ".", "Time", ",", "error", ")", "{", "token", ":=", "jwt", ".", "New", "(", "jwt", ".", "GetSigningMethod", "(", "...
// TokenGenerator method that clients can use to get a jwt token.
[ "TokenGenerator", "method", "that", "clients", "can", "use", "to", "get", "a", "jwt", "token", "." ]
633d983b91f09beefb1128c4558d4642a379c602
https://github.com/appleboy/gin-jwt/blob/633d983b91f09beefb1128c4558d4642a379c602/auth_jwt.go#L553-L572
train
appleboy/gin-jwt
auth_jwt.go
ParseToken
func (mw *GinJWTMiddleware) ParseToken(c *gin.Context) (*jwt.Token, error) { var token string var err error methods := strings.Split(mw.TokenLookup, ",") for _, method := range methods { if len(token) > 0 { break } parts := strings.Split(strings.TrimSpace(method), ":") k := strings.TrimSpace(parts[0]) v := strings.TrimSpace(parts[1]) switch k { case "header": token, err = mw.jwtFromHeader(c, v) case "query": token, err = mw.jwtFromQuery(c, v) case "cookie": token, err = mw.jwtFromCookie(c, v) case "param": token, err = mw.jwtFromParam(c, v) } } if err != nil { return nil, err } return jwt.Parse(token, func(t *jwt.Token) (interface{}, error) { if jwt.GetSigningMethod(mw.SigningAlgorithm) != t.Method { return nil, ErrInvalidSigningAlgorithm } if mw.usingPublicKeyAlgo() { return mw.pubKey, nil } // save token string if vaild c.Set("JWT_TOKEN", token) return mw.Key, nil }) }
go
func (mw *GinJWTMiddleware) ParseToken(c *gin.Context) (*jwt.Token, error) { var token string var err error methods := strings.Split(mw.TokenLookup, ",") for _, method := range methods { if len(token) > 0 { break } parts := strings.Split(strings.TrimSpace(method), ":") k := strings.TrimSpace(parts[0]) v := strings.TrimSpace(parts[1]) switch k { case "header": token, err = mw.jwtFromHeader(c, v) case "query": token, err = mw.jwtFromQuery(c, v) case "cookie": token, err = mw.jwtFromCookie(c, v) case "param": token, err = mw.jwtFromParam(c, v) } } if err != nil { return nil, err } return jwt.Parse(token, func(t *jwt.Token) (interface{}, error) { if jwt.GetSigningMethod(mw.SigningAlgorithm) != t.Method { return nil, ErrInvalidSigningAlgorithm } if mw.usingPublicKeyAlgo() { return mw.pubKey, nil } // save token string if vaild c.Set("JWT_TOKEN", token) return mw.Key, nil }) }
[ "func", "(", "mw", "*", "GinJWTMiddleware", ")", "ParseToken", "(", "c", "*", "gin", ".", "Context", ")", "(", "*", "jwt", ".", "Token", ",", "error", ")", "{", "var", "token", "string", "\n", "var", "err", "error", "\n\n", "methods", ":=", "strings"...
// ParseToken parse jwt token from gin context
[ "ParseToken", "parse", "jwt", "token", "from", "gin", "context" ]
633d983b91f09beefb1128c4558d4642a379c602
https://github.com/appleboy/gin-jwt/blob/633d983b91f09beefb1128c4558d4642a379c602/auth_jwt.go#L620-L661
train
appleboy/gin-jwt
auth_jwt.go
ParseTokenString
func (mw *GinJWTMiddleware) ParseTokenString(token string) (*jwt.Token, error) { return jwt.Parse(token, func(t *jwt.Token) (interface{}, error) { if jwt.GetSigningMethod(mw.SigningAlgorithm) != t.Method { return nil, ErrInvalidSigningAlgorithm } if mw.usingPublicKeyAlgo() { return mw.pubKey, nil } return mw.Key, nil }) }
go
func (mw *GinJWTMiddleware) ParseTokenString(token string) (*jwt.Token, error) { return jwt.Parse(token, func(t *jwt.Token) (interface{}, error) { if jwt.GetSigningMethod(mw.SigningAlgorithm) != t.Method { return nil, ErrInvalidSigningAlgorithm } if mw.usingPublicKeyAlgo() { return mw.pubKey, nil } return mw.Key, nil }) }
[ "func", "(", "mw", "*", "GinJWTMiddleware", ")", "ParseTokenString", "(", "token", "string", ")", "(", "*", "jwt", ".", "Token", ",", "error", ")", "{", "return", "jwt", ".", "Parse", "(", "token", ",", "func", "(", "t", "*", "jwt", ".", "Token", "...
// ParseTokenString parse jwt token string
[ "ParseTokenString", "parse", "jwt", "token", "string" ]
633d983b91f09beefb1128c4558d4642a379c602
https://github.com/appleboy/gin-jwt/blob/633d983b91f09beefb1128c4558d4642a379c602/auth_jwt.go#L664-L675
train
appleboy/gin-jwt
auth_jwt.go
ExtractClaims
func ExtractClaims(c *gin.Context) MapClaims { claims, exists := c.Get("JWT_PAYLOAD") if !exists { return make(MapClaims) } return claims.(MapClaims) }
go
func ExtractClaims(c *gin.Context) MapClaims { claims, exists := c.Get("JWT_PAYLOAD") if !exists { return make(MapClaims) } return claims.(MapClaims) }
[ "func", "ExtractClaims", "(", "c", "*", "gin", ".", "Context", ")", "MapClaims", "{", "claims", ",", "exists", ":=", "c", ".", "Get", "(", "\"", "\"", ")", "\n", "if", "!", "exists", "{", "return", "make", "(", "MapClaims", ")", "\n", "}", "\n\n", ...
// ExtractClaims help to extract the JWT claims
[ "ExtractClaims", "help", "to", "extract", "the", "JWT", "claims" ]
633d983b91f09beefb1128c4558d4642a379c602
https://github.com/appleboy/gin-jwt/blob/633d983b91f09beefb1128c4558d4642a379c602/auth_jwt.go#L687-L694
train
appleboy/gin-jwt
auth_jwt.go
ExtractClaimsFromToken
func ExtractClaimsFromToken(token *jwt.Token) MapClaims { if token == nil { return make(MapClaims) } claims := MapClaims{} for key, value := range token.Claims.(jwt.MapClaims) { claims[key] = value } return claims }
go
func ExtractClaimsFromToken(token *jwt.Token) MapClaims { if token == nil { return make(MapClaims) } claims := MapClaims{} for key, value := range token.Claims.(jwt.MapClaims) { claims[key] = value } return claims }
[ "func", "ExtractClaimsFromToken", "(", "token", "*", "jwt", ".", "Token", ")", "MapClaims", "{", "if", "token", "==", "nil", "{", "return", "make", "(", "MapClaims", ")", "\n", "}", "\n\n", "claims", ":=", "MapClaims", "{", "}", "\n", "for", "key", ","...
// ExtractClaimsFromToken help to extract the JWT claims from token
[ "ExtractClaimsFromToken", "help", "to", "extract", "the", "JWT", "claims", "from", "token" ]
633d983b91f09beefb1128c4558d4642a379c602
https://github.com/appleboy/gin-jwt/blob/633d983b91f09beefb1128c4558d4642a379c602/auth_jwt.go#L697-L708
train
appleboy/gin-jwt
auth_jwt.go
GetToken
func GetToken(c *gin.Context) string { token, exists := c.Get("JWT_TOKEN") if !exists { return "" } return token.(string) }
go
func GetToken(c *gin.Context) string { token, exists := c.Get("JWT_TOKEN") if !exists { return "" } return token.(string) }
[ "func", "GetToken", "(", "c", "*", "gin", ".", "Context", ")", "string", "{", "token", ",", "exists", ":=", "c", ".", "Get", "(", "\"", "\"", ")", "\n", "if", "!", "exists", "{", "return", "\"", "\"", "\n", "}", "\n\n", "return", "token", ".", ...
// GetToken help to get the JWT token string
[ "GetToken", "help", "to", "get", "the", "JWT", "token", "string" ]
633d983b91f09beefb1128c4558d4642a379c602
https://github.com/appleboy/gin-jwt/blob/633d983b91f09beefb1128c4558d4642a379c602/auth_jwt.go#L711-L718
train
brianvoe/gofakeit
user_agent.go
UserAgent
func UserAgent() string { randNum := randIntRange(0, 4) switch randNum { case 0: return ChromeUserAgent() case 1: return FirefoxUserAgent() case 2: return SafariUserAgent() case 3: return OperaUserAgent() default: return ChromeUserAgent() } }
go
func UserAgent() string { randNum := randIntRange(0, 4) switch randNum { case 0: return ChromeUserAgent() case 1: return FirefoxUserAgent() case 2: return SafariUserAgent() case 3: return OperaUserAgent() default: return ChromeUserAgent() } }
[ "func", "UserAgent", "(", ")", "string", "{", "randNum", ":=", "randIntRange", "(", "0", ",", "4", ")", "\n", "switch", "randNum", "{", "case", "0", ":", "return", "ChromeUserAgent", "(", ")", "\n", "case", "1", ":", "return", "FirefoxUserAgent", "(", ...
// UserAgent will generate a random broswer user agent
[ "UserAgent", "will", "generate", "a", "random", "broswer", "user", "agent" ]
a5ac7cef41d64b726c51e8826e02dad0c34f55b4
https://github.com/brianvoe/gofakeit/blob/a5ac7cef41d64b726c51e8826e02dad0c34f55b4/user_agent.go#L6-L20
train
brianvoe/gofakeit
user_agent.go
ChromeUserAgent
func ChromeUserAgent() string { randNum1 := strconv.Itoa(randIntRange(531, 536)) + strconv.Itoa(randIntRange(0, 2)) randNum2 := strconv.Itoa(randIntRange(36, 40)) randNum3 := strconv.Itoa(randIntRange(800, 899)) return "Mozilla/5.0 " + "(" + randomPlatform() + ") AppleWebKit/" + randNum1 + " (KHTML, like Gecko) Chrome/" + randNum2 + ".0." + randNum3 + ".0 Mobile Safari/" + randNum1 }
go
func ChromeUserAgent() string { randNum1 := strconv.Itoa(randIntRange(531, 536)) + strconv.Itoa(randIntRange(0, 2)) randNum2 := strconv.Itoa(randIntRange(36, 40)) randNum3 := strconv.Itoa(randIntRange(800, 899)) return "Mozilla/5.0 " + "(" + randomPlatform() + ") AppleWebKit/" + randNum1 + " (KHTML, like Gecko) Chrome/" + randNum2 + ".0." + randNum3 + ".0 Mobile Safari/" + randNum1 }
[ "func", "ChromeUserAgent", "(", ")", "string", "{", "randNum1", ":=", "strconv", ".", "Itoa", "(", "randIntRange", "(", "531", ",", "536", ")", ")", "+", "strconv", ".", "Itoa", "(", "randIntRange", "(", "0", ",", "2", ")", ")", "\n", "randNum2", ":=...
// ChromeUserAgent will generate a random chrome browser user agent string
[ "ChromeUserAgent", "will", "generate", "a", "random", "chrome", "browser", "user", "agent", "string" ]
a5ac7cef41d64b726c51e8826e02dad0c34f55b4
https://github.com/brianvoe/gofakeit/blob/a5ac7cef41d64b726c51e8826e02dad0c34f55b4/user_agent.go#L23-L28
train
brianvoe/gofakeit
user_agent.go
FirefoxUserAgent
func FirefoxUserAgent() string { ver := "Gecko/" + Date().Format("2006-02-01") + " Firefox/" + strconv.Itoa(randIntRange(35, 37)) + ".0" platforms := []string{ "(" + windowsPlatformToken() + "; " + "en-US" + "; rv:1.9." + strconv.Itoa(randIntRange(0, 3)) + ".20) " + ver, "(" + linuxPlatformToken() + "; rv:" + strconv.Itoa(randIntRange(5, 8)) + ".0) " + ver, "(" + macPlatformToken() + " rv:" + strconv.Itoa(randIntRange(2, 7)) + ".0) " + ver, } return "Mozilla/5.0 " + RandString(platforms) }
go
func FirefoxUserAgent() string { ver := "Gecko/" + Date().Format("2006-02-01") + " Firefox/" + strconv.Itoa(randIntRange(35, 37)) + ".0" platforms := []string{ "(" + windowsPlatformToken() + "; " + "en-US" + "; rv:1.9." + strconv.Itoa(randIntRange(0, 3)) + ".20) " + ver, "(" + linuxPlatformToken() + "; rv:" + strconv.Itoa(randIntRange(5, 8)) + ".0) " + ver, "(" + macPlatformToken() + " rv:" + strconv.Itoa(randIntRange(2, 7)) + ".0) " + ver, } return "Mozilla/5.0 " + RandString(platforms) }
[ "func", "FirefoxUserAgent", "(", ")", "string", "{", "ver", ":=", "\"", "\"", "+", "Date", "(", ")", ".", "Format", "(", "\"", "\"", ")", "+", "\"", "\"", "+", "strconv", ".", "Itoa", "(", "randIntRange", "(", "35", ",", "37", ")", ")", "+", "\...
// FirefoxUserAgent will generate a random firefox broswer user agent string
[ "FirefoxUserAgent", "will", "generate", "a", "random", "firefox", "broswer", "user", "agent", "string" ]
a5ac7cef41d64b726c51e8826e02dad0c34f55b4
https://github.com/brianvoe/gofakeit/blob/a5ac7cef41d64b726c51e8826e02dad0c34f55b4/user_agent.go#L31-L40
train
brianvoe/gofakeit
user_agent.go
SafariUserAgent
func SafariUserAgent() string { randNum := strconv.Itoa(randIntRange(531, 536)) + "." + strconv.Itoa(randIntRange(1, 51)) + "." + strconv.Itoa(randIntRange(1, 8)) ver := strconv.Itoa(randIntRange(4, 6)) + "." + strconv.Itoa(randIntRange(0, 2)) mobileDevices := []string{ "iPhone; CPU iPhone OS", "iPad; CPU OS", } platforms := []string{ "(Windows; U; " + windowsPlatformToken() + ") AppleWebKit/" + randNum + " (KHTML, like Gecko) Version/" + ver + " Safari/" + randNum, "(" + macPlatformToken() + " rv:" + strconv.Itoa(randIntRange(4, 7)) + ".0; en-US) AppleWebKit/" + randNum + " (KHTML, like Gecko) Version/" + ver + " Safari/" + randNum, "(" + RandString(mobileDevices) + " " + strconv.Itoa(randIntRange(7, 9)) + "_" + strconv.Itoa(randIntRange(0, 3)) + "_" + strconv.Itoa(randIntRange(1, 3)) + " like Mac OS X; " + "en-US" + ") AppleWebKit/" + randNum + " (KHTML, like Gecko) Version/" + strconv.Itoa(randIntRange(3, 5)) + ".0.5 Mobile/8B" + strconv.Itoa(randIntRange(111, 120)) + " Safari/6" + randNum, } return "Mozilla/5.0 " + RandString(platforms) }
go
func SafariUserAgent() string { randNum := strconv.Itoa(randIntRange(531, 536)) + "." + strconv.Itoa(randIntRange(1, 51)) + "." + strconv.Itoa(randIntRange(1, 8)) ver := strconv.Itoa(randIntRange(4, 6)) + "." + strconv.Itoa(randIntRange(0, 2)) mobileDevices := []string{ "iPhone; CPU iPhone OS", "iPad; CPU OS", } platforms := []string{ "(Windows; U; " + windowsPlatformToken() + ") AppleWebKit/" + randNum + " (KHTML, like Gecko) Version/" + ver + " Safari/" + randNum, "(" + macPlatformToken() + " rv:" + strconv.Itoa(randIntRange(4, 7)) + ".0; en-US) AppleWebKit/" + randNum + " (KHTML, like Gecko) Version/" + ver + " Safari/" + randNum, "(" + RandString(mobileDevices) + " " + strconv.Itoa(randIntRange(7, 9)) + "_" + strconv.Itoa(randIntRange(0, 3)) + "_" + strconv.Itoa(randIntRange(1, 3)) + " like Mac OS X; " + "en-US" + ") AppleWebKit/" + randNum + " (KHTML, like Gecko) Version/" + strconv.Itoa(randIntRange(3, 5)) + ".0.5 Mobile/8B" + strconv.Itoa(randIntRange(111, 120)) + " Safari/6" + randNum, } return "Mozilla/5.0 " + RandString(platforms) }
[ "func", "SafariUserAgent", "(", ")", "string", "{", "randNum", ":=", "strconv", ".", "Itoa", "(", "randIntRange", "(", "531", ",", "536", ")", ")", "+", "\"", "\"", "+", "strconv", ".", "Itoa", "(", "randIntRange", "(", "1", ",", "51", ")", ")", "+...
// SafariUserAgent will generate a random safari browser user agent string
[ "SafariUserAgent", "will", "generate", "a", "random", "safari", "browser", "user", "agent", "string" ]
a5ac7cef41d64b726c51e8826e02dad0c34f55b4
https://github.com/brianvoe/gofakeit/blob/a5ac7cef41d64b726c51e8826e02dad0c34f55b4/user_agent.go#L43-L59
train
brianvoe/gofakeit
user_agent.go
OperaUserAgent
func OperaUserAgent() string { platform := "(" + randomPlatform() + "; en-US) Presto/2." + strconv.Itoa(randIntRange(8, 13)) + "." + strconv.Itoa(randIntRange(160, 355)) + " Version/" + strconv.Itoa(randIntRange(10, 13)) + ".00" return "Opera/" + strconv.Itoa(randIntRange(8, 10)) + "." + strconv.Itoa(randIntRange(10, 99)) + " " + platform }
go
func OperaUserAgent() string { platform := "(" + randomPlatform() + "; en-US) Presto/2." + strconv.Itoa(randIntRange(8, 13)) + "." + strconv.Itoa(randIntRange(160, 355)) + " Version/" + strconv.Itoa(randIntRange(10, 13)) + ".00" return "Opera/" + strconv.Itoa(randIntRange(8, 10)) + "." + strconv.Itoa(randIntRange(10, 99)) + " " + platform }
[ "func", "OperaUserAgent", "(", ")", "string", "{", "platform", ":=", "\"", "\"", "+", "randomPlatform", "(", ")", "+", "\"", "\"", "+", "strconv", ".", "Itoa", "(", "randIntRange", "(", "8", ",", "13", ")", ")", "+", "\"", "\"", "+", "strconv", "."...
// OperaUserAgent will generate a random opera browser user agent string
[ "OperaUserAgent", "will", "generate", "a", "random", "opera", "browser", "user", "agent", "string" ]
a5ac7cef41d64b726c51e8826e02dad0c34f55b4
https://github.com/brianvoe/gofakeit/blob/a5ac7cef41d64b726c51e8826e02dad0c34f55b4/user_agent.go#L62-L66
train
brianvoe/gofakeit
user_agent.go
macPlatformToken
func macPlatformToken() string { return "Macintosh; " + getRandValue([]string{"computer", "mac_processor"}) + " Mac OS X 10_" + strconv.Itoa(randIntRange(5, 9)) + "_" + strconv.Itoa(randIntRange(0, 10)) }
go
func macPlatformToken() string { return "Macintosh; " + getRandValue([]string{"computer", "mac_processor"}) + " Mac OS X 10_" + strconv.Itoa(randIntRange(5, 9)) + "_" + strconv.Itoa(randIntRange(0, 10)) }
[ "func", "macPlatformToken", "(", ")", "string", "{", "return", "\"", "\"", "+", "getRandValue", "(", "[", "]", "string", "{", "\"", "\"", ",", "\"", "\"", "}", ")", "+", "\"", "\"", "+", "strconv", ".", "Itoa", "(", "randIntRange", "(", "5", ",", ...
// macPlatformToken will generate a random mac platform
[ "macPlatformToken", "will", "generate", "a", "random", "mac", "platform" ]
a5ac7cef41d64b726c51e8826e02dad0c34f55b4
https://github.com/brianvoe/gofakeit/blob/a5ac7cef41d64b726c51e8826e02dad0c34f55b4/user_agent.go#L74-L76
train
brianvoe/gofakeit
address.go
Address
func Address() *AddressInfo { street := Street() city := City() state := State() zip := Zip() return &AddressInfo{ Address: street + ", " + city + ", " + state + " " + zip, Street: street, City: city, State: state, Zip: zip, Country: Country(), Latitude: Latitude(), Longitude: Longitude(), } }
go
func Address() *AddressInfo { street := Street() city := City() state := State() zip := Zip() return &AddressInfo{ Address: street + ", " + city + ", " + state + " " + zip, Street: street, City: city, State: state, Zip: zip, Country: Country(), Latitude: Latitude(), Longitude: Longitude(), } }
[ "func", "Address", "(", ")", "*", "AddressInfo", "{", "street", ":=", "Street", "(", ")", "\n", "city", ":=", "City", "(", ")", "\n", "state", ":=", "State", "(", ")", "\n", "zip", ":=", "Zip", "(", ")", "\n\n", "return", "&", "AddressInfo", "{", ...
// Address will generate a struct of address information
[ "Address", "will", "generate", "a", "struct", "of", "address", "information" ]
a5ac7cef41d64b726c51e8826e02dad0c34f55b4
https://github.com/brianvoe/gofakeit/blob/a5ac7cef41d64b726c51e8826e02dad0c34f55b4/address.go#L22-L38
train
brianvoe/gofakeit
address.go
Street
func Street() (street string) { switch randInt := randIntRange(1, 2); randInt { case 1: street = StreetNumber() + " " + StreetPrefix() + " " + StreetName() + StreetSuffix() case 2: street = StreetNumber() + " " + StreetName() + StreetSuffix() } return }
go
func Street() (street string) { switch randInt := randIntRange(1, 2); randInt { case 1: street = StreetNumber() + " " + StreetPrefix() + " " + StreetName() + StreetSuffix() case 2: street = StreetNumber() + " " + StreetName() + StreetSuffix() } return }
[ "func", "Street", "(", ")", "(", "street", "string", ")", "{", "switch", "randInt", ":=", "randIntRange", "(", "1", ",", "2", ")", ";", "randInt", "{", "case", "1", ":", "street", "=", "StreetNumber", "(", ")", "+", "\"", "\"", "+", "StreetPrefix", ...
// Street will generate a random address street string
[ "Street", "will", "generate", "a", "random", "address", "street", "string" ]
a5ac7cef41d64b726c51e8826e02dad0c34f55b4
https://github.com/brianvoe/gofakeit/blob/a5ac7cef41d64b726c51e8826e02dad0c34f55b4/address.go#L41-L50
train
brianvoe/gofakeit
address.go
City
func City() (city string) { switch randInt := randIntRange(1, 3); randInt { case 1: city = FirstName() + StreetSuffix() case 2: city = LastName() + StreetSuffix() case 3: city = StreetPrefix() + " " + LastName() } return }
go
func City() (city string) { switch randInt := randIntRange(1, 3); randInt { case 1: city = FirstName() + StreetSuffix() case 2: city = LastName() + StreetSuffix() case 3: city = StreetPrefix() + " " + LastName() } return }
[ "func", "City", "(", ")", "(", "city", "string", ")", "{", "switch", "randInt", ":=", "randIntRange", "(", "1", ",", "3", ")", ";", "randInt", "{", "case", "1", ":", "city", "=", "FirstName", "(", ")", "+", "StreetSuffix", "(", ")", "\n", "case", ...
// City will generate a random city string
[ "City", "will", "generate", "a", "random", "city", "string" ]
a5ac7cef41d64b726c51e8826e02dad0c34f55b4
https://github.com/brianvoe/gofakeit/blob/a5ac7cef41d64b726c51e8826e02dad0c34f55b4/address.go#L73-L84
train
brianvoe/gofakeit
address.go
LongitudeInRange
func LongitudeInRange(min, max float64) (float64, error) { if min > max || min < -180 || min > 180 || max < -180 || max > 180 { return 0, errors.New("input range is invalid") } return randFloat64Range(min, max), nil }
go
func LongitudeInRange(min, max float64) (float64, error) { if min > max || min < -180 || min > 180 || max < -180 || max > 180 { return 0, errors.New("input range is invalid") } return randFloat64Range(min, max), nil }
[ "func", "LongitudeInRange", "(", "min", ",", "max", "float64", ")", "(", "float64", ",", "error", ")", "{", "if", "min", ">", "max", "||", "min", "<", "-", "180", "||", "min", ">", "180", "||", "max", "<", "-", "180", "||", "max", ">", "180", "...
// LongitudeInRange will generate a random longitude within the input range
[ "LongitudeInRange", "will", "generate", "a", "random", "longitude", "within", "the", "input", "range" ]
a5ac7cef41d64b726c51e8826e02dad0c34f55b4
https://github.com/brianvoe/gofakeit/blob/a5ac7cef41d64b726c51e8826e02dad0c34f55b4/address.go#L126-L131
train
brianvoe/gofakeit
misc.go
getRandValue
func getRandValue(dataVal []string) string { if !dataCheck(dataVal) { return "" } return data.Data[dataVal[0]][dataVal[1]][rand.Intn(len(data.Data[dataVal[0]][dataVal[1]]))] }
go
func getRandValue(dataVal []string) string { if !dataCheck(dataVal) { return "" } return data.Data[dataVal[0]][dataVal[1]][rand.Intn(len(data.Data[dataVal[0]][dataVal[1]]))] }
[ "func", "getRandValue", "(", "dataVal", "[", "]", "string", ")", "string", "{", "if", "!", "dataCheck", "(", "dataVal", ")", "{", "return", "\"", "\"", "\n", "}", "\n", "return", "data", ".", "Data", "[", "dataVal", "[", "0", "]", "]", "[", "dataVa...
// Get Random Value
[ "Get", "Random", "Value" ]
a5ac7cef41d64b726c51e8826e02dad0c34f55b4
https://github.com/brianvoe/gofakeit/blob/a5ac7cef41d64b726c51e8826e02dad0c34f55b4/misc.go#L41-L46
train
brianvoe/gofakeit
misc.go
getRandIntValue
func getRandIntValue(dataVal []string) int { if !intDataCheck(dataVal) { return 0 } return data.IntData[dataVal[0]][dataVal[1]][rand.Intn(len(data.IntData[dataVal[0]][dataVal[1]]))] }
go
func getRandIntValue(dataVal []string) int { if !intDataCheck(dataVal) { return 0 } return data.IntData[dataVal[0]][dataVal[1]][rand.Intn(len(data.IntData[dataVal[0]][dataVal[1]]))] }
[ "func", "getRandIntValue", "(", "dataVal", "[", "]", "string", ")", "int", "{", "if", "!", "intDataCheck", "(", "dataVal", ")", "{", "return", "0", "\n", "}", "\n", "return", "data", ".", "IntData", "[", "dataVal", "[", "0", "]", "]", "[", "dataVal",...
// Get Random Integer Value
[ "Get", "Random", "Integer", "Value" ]
a5ac7cef41d64b726c51e8826e02dad0c34f55b4
https://github.com/brianvoe/gofakeit/blob/a5ac7cef41d64b726c51e8826e02dad0c34f55b4/misc.go#L49-L54
train
brianvoe/gofakeit
misc.go
replaceWithLetters
func replaceWithLetters(str string) string { if str == "" { return str } bytestr := []byte(str) for i := 0; i < len(bytestr); i++ { if bytestr[i] == questionmark { bytestr[i] = byte(randLetter()) } } return string(bytestr) }
go
func replaceWithLetters(str string) string { if str == "" { return str } bytestr := []byte(str) for i := 0; i < len(bytestr); i++ { if bytestr[i] == questionmark { bytestr[i] = byte(randLetter()) } } return string(bytestr) }
[ "func", "replaceWithLetters", "(", "str", "string", ")", "string", "{", "if", "str", "==", "\"", "\"", "{", "return", "str", "\n", "}", "\n", "bytestr", ":=", "[", "]", "byte", "(", "str", ")", "\n", "for", "i", ":=", "0", ";", "i", "<", "len", ...
// Replace ? with ASCII lowercase letters
[ "Replace", "?", "with", "ASCII", "lowercase", "letters" ]
a5ac7cef41d64b726c51e8826e02dad0c34f55b4
https://github.com/brianvoe/gofakeit/blob/a5ac7cef41d64b726c51e8826e02dad0c34f55b4/misc.go#L75-L87
train
brianvoe/gofakeit
misc.go
randIntRange
func randIntRange(min, max int) int { if min == max { return min } return rand.Intn((max+1)-min) + min }
go
func randIntRange(min, max int) int { if min == max { return min } return rand.Intn((max+1)-min) + min }
[ "func", "randIntRange", "(", "min", ",", "max", "int", ")", "int", "{", "if", "min", "==", "max", "{", "return", "min", "\n", "}", "\n", "return", "rand", ".", "Intn", "(", "(", "max", "+", "1", ")", "-", "min", ")", "+", "min", "\n", "}" ]
// Generate random integer between min and max
[ "Generate", "random", "integer", "between", "min", "and", "max" ]
a5ac7cef41d64b726c51e8826e02dad0c34f55b4
https://github.com/brianvoe/gofakeit/blob/a5ac7cef41d64b726c51e8826e02dad0c34f55b4/misc.go#L100-L105
train
brianvoe/gofakeit
misc.go
Categories
func Categories() map[string][]string { types := make(map[string][]string) for category, subCategoriesMap := range data.Data { subCategories := make([]string, 0) for subType := range subCategoriesMap { subCategories = append(subCategories, subType) } types[category] = subCategories } return types }
go
func Categories() map[string][]string { types := make(map[string][]string) for category, subCategoriesMap := range data.Data { subCategories := make([]string, 0) for subType := range subCategoriesMap { subCategories = append(subCategories, subType) } types[category] = subCategories } return types }
[ "func", "Categories", "(", ")", "map", "[", "string", "]", "[", "]", "string", "{", "types", ":=", "make", "(", "map", "[", "string", "]", "[", "]", "string", ")", "\n", "for", "category", ",", "subCategoriesMap", ":=", "range", "data", ".", "Data", ...
// Categories will return a map string array of available data categories and sub categories
[ "Categories", "will", "return", "a", "map", "string", "array", "of", "available", "data", "categories", "and", "sub", "categories" ]
a5ac7cef41d64b726c51e8826e02dad0c34f55b4
https://github.com/brianvoe/gofakeit/blob/a5ac7cef41d64b726c51e8826e02dad0c34f55b4/misc.go#L122-L132
train
brianvoe/gofakeit
password.go
Password
func Password(lower bool, upper bool, numeric bool, special bool, space bool, num int) string { // Make sure the num minimun is at least 5 if num < 5 { num = 5 } i := 0 b := make([]byte, num) var passString string if lower { passString += lowerStr b[i] = lowerStr[rand.Int63()%int64(len(lowerStr))] i++ } if upper { passString += upperStr b[i] = upperStr[rand.Int63()%int64(len(upperStr))] i++ } if numeric { passString += numericStr b[i] = numericStr[rand.Int63()%int64(len(numericStr))] i++ } if special { passString += specialStr b[i] = specialStr[rand.Int63()%int64(len(specialStr))] i++ } if space { passString += spaceStr b[i] = spaceStr[rand.Int63()%int64(len(spaceStr))] i++ } // Set default if empty if passString == "" { passString = lowerStr + numericStr } // Loop through and add it up for i <= num-1 { b[i] = passString[rand.Int63()%int64(len(passString))] i++ } // Shuffle bytes for i := range b { j := rand.Intn(i + 1) b[i], b[j] = b[j], b[i] } return string(b) }
go
func Password(lower bool, upper bool, numeric bool, special bool, space bool, num int) string { // Make sure the num minimun is at least 5 if num < 5 { num = 5 } i := 0 b := make([]byte, num) var passString string if lower { passString += lowerStr b[i] = lowerStr[rand.Int63()%int64(len(lowerStr))] i++ } if upper { passString += upperStr b[i] = upperStr[rand.Int63()%int64(len(upperStr))] i++ } if numeric { passString += numericStr b[i] = numericStr[rand.Int63()%int64(len(numericStr))] i++ } if special { passString += specialStr b[i] = specialStr[rand.Int63()%int64(len(specialStr))] i++ } if space { passString += spaceStr b[i] = spaceStr[rand.Int63()%int64(len(spaceStr))] i++ } // Set default if empty if passString == "" { passString = lowerStr + numericStr } // Loop through and add it up for i <= num-1 { b[i] = passString[rand.Int63()%int64(len(passString))] i++ } // Shuffle bytes for i := range b { j := rand.Intn(i + 1) b[i], b[j] = b[j], b[i] } return string(b) }
[ "func", "Password", "(", "lower", "bool", ",", "upper", "bool", ",", "numeric", "bool", ",", "special", "bool", ",", "space", "bool", ",", "num", "int", ")", "string", "{", "// Make sure the num minimun is at least 5", "if", "num", "<", "5", "{", "num", "=...
// Password will generate a random password // Minimum number length of 5 if less than
[ "Password", "will", "generate", "a", "random", "password", "Minimum", "number", "length", "of", "5", "if", "less", "than" ]
a5ac7cef41d64b726c51e8826e02dad0c34f55b4
https://github.com/brianvoe/gofakeit/blob/a5ac7cef41d64b726c51e8826e02dad0c34f55b4/password.go#L15-L68
train
brianvoe/gofakeit
currency.go
Currency
func Currency() *CurrencyInfo { index := rand.Intn(len(data.Data["currency"]["short"])) return &CurrencyInfo{ Short: data.Data["currency"]["short"][index], Long: data.Data["currency"]["long"][index], } }
go
func Currency() *CurrencyInfo { index := rand.Intn(len(data.Data["currency"]["short"])) return &CurrencyInfo{ Short: data.Data["currency"]["short"][index], Long: data.Data["currency"]["long"][index], } }
[ "func", "Currency", "(", ")", "*", "CurrencyInfo", "{", "index", ":=", "rand", ".", "Intn", "(", "len", "(", "data", ".", "Data", "[", "\"", "\"", "]", "[", "\"", "\"", "]", ")", ")", "\n", "return", "&", "CurrencyInfo", "{", "Short", ":", "data"...
// Currency will generate a struct with random currency information
[ "Currency", "will", "generate", "a", "struct", "with", "random", "currency", "information" ]
a5ac7cef41d64b726c51e8826e02dad0c34f55b4
https://github.com/brianvoe/gofakeit/blob/a5ac7cef41d64b726c51e8826e02dad0c34f55b4/currency.go#L17-L23
train
brianvoe/gofakeit
currency.go
Price
func Price(min, max float64) float64 { return math.Floor(randFloat64Range(min, max)*100) / 100 }
go
func Price(min, max float64) float64 { return math.Floor(randFloat64Range(min, max)*100) / 100 }
[ "func", "Price", "(", "min", ",", "max", "float64", ")", "float64", "{", "return", "math", ".", "Floor", "(", "randFloat64Range", "(", "min", ",", "max", ")", "*", "100", ")", "/", "100", "\n", "}" ]
// Price will take in a min and max value and return a formatted price
[ "Price", "will", "take", "in", "a", "min", "and", "max", "value", "and", "return", "a", "formatted", "price" ]
a5ac7cef41d64b726c51e8826e02dad0c34f55b4
https://github.com/brianvoe/gofakeit/blob/a5ac7cef41d64b726c51e8826e02dad0c34f55b4/currency.go#L36-L38
train
brianvoe/gofakeit
words.go
Paragraph
func Paragraph(paragraphCount int, sentenceCount int, wordCount int, separator string) string { return paragraphGenerator(paragrapOptions{paragraphCount, sentenceCount, wordCount, separator}, Sentence) }
go
func Paragraph(paragraphCount int, sentenceCount int, wordCount int, separator string) string { return paragraphGenerator(paragrapOptions{paragraphCount, sentenceCount, wordCount, separator}, Sentence) }
[ "func", "Paragraph", "(", "paragraphCount", "int", ",", "sentenceCount", "int", ",", "wordCount", "int", ",", "separator", "string", ")", "string", "{", "return", "paragraphGenerator", "(", "paragrapOptions", "{", "paragraphCount", ",", "sentenceCount", ",", "word...
// Paragraph will generate a random paragraphGenerator // Set Paragraph Count // Set Sentence Count // Set Word Count // Set Paragraph Separator
[ "Paragraph", "will", "generate", "a", "random", "paragraphGenerator", "Set", "Paragraph", "Count", "Set", "Sentence", "Count", "Set", "Word", "Count", "Set", "Paragraph", "Separator" ]
a5ac7cef41d64b726c51e8826e02dad0c34f55b4
https://github.com/brianvoe/gofakeit/blob/a5ac7cef41d64b726c51e8826e02dad0c34f55b4/words.go#L36-L38
train
brianvoe/gofakeit
payment.go
CreditCard
func CreditCard() *CreditCardInfo { return &CreditCardInfo{ Type: CreditCardType(), Number: CreditCardNumber(), Exp: CreditCardExp(), Cvv: CreditCardCvv(), } }
go
func CreditCard() *CreditCardInfo { return &CreditCardInfo{ Type: CreditCardType(), Number: CreditCardNumber(), Exp: CreditCardExp(), Cvv: CreditCardCvv(), } }
[ "func", "CreditCard", "(", ")", "*", "CreditCardInfo", "{", "return", "&", "CreditCardInfo", "{", "Type", ":", "CreditCardType", "(", ")", ",", "Number", ":", "CreditCardNumber", "(", ")", ",", "Exp", ":", "CreditCardExp", "(", ")", ",", "Cvv", ":", "Cre...
// CreditCard will generate a struct full of credit card information
[ "CreditCard", "will", "generate", "a", "struct", "full", "of", "credit", "card", "information" ]
a5ac7cef41d64b726c51e8826e02dad0c34f55b4
https://github.com/brianvoe/gofakeit/blob/a5ac7cef41d64b726c51e8826e02dad0c34f55b4/payment.go#L17-L24
train
brianvoe/gofakeit
payment.go
CreditCardNumber
func CreditCardNumber() int { integer, _ := strconv.Atoi(replaceWithNumbers(getRandValue([]string{"payment", "number"}))) return integer }
go
func CreditCardNumber() int { integer, _ := strconv.Atoi(replaceWithNumbers(getRandValue([]string{"payment", "number"}))) return integer }
[ "func", "CreditCardNumber", "(", ")", "int", "{", "integer", ",", "_", ":=", "strconv", ".", "Atoi", "(", "replaceWithNumbers", "(", "getRandValue", "(", "[", "]", "string", "{", "\"", "\"", ",", "\"", "\"", "}", ")", ")", ")", "\n", "return", "integ...
// CreditCardNumber will generate a random credit card number int
[ "CreditCardNumber", "will", "generate", "a", "random", "credit", "card", "number", "int" ]
a5ac7cef41d64b726c51e8826e02dad0c34f55b4
https://github.com/brianvoe/gofakeit/blob/a5ac7cef41d64b726c51e8826e02dad0c34f55b4/payment.go#L32-L35
train
brianvoe/gofakeit
payment.go
CreditCardNumberLuhn
func CreditCardNumberLuhn() int { cc := "" for i := 0; i < 100000; i++ { cc = replaceWithNumbers(getRandValue([]string{"payment", "number"})) if luhn(cc) { break } } integer, _ := strconv.Atoi(cc) return integer }
go
func CreditCardNumberLuhn() int { cc := "" for i := 0; i < 100000; i++ { cc = replaceWithNumbers(getRandValue([]string{"payment", "number"})) if luhn(cc) { break } } integer, _ := strconv.Atoi(cc) return integer }
[ "func", "CreditCardNumberLuhn", "(", ")", "int", "{", "cc", ":=", "\"", "\"", "\n", "for", "i", ":=", "0", ";", "i", "<", "100000", ";", "i", "++", "{", "cc", "=", "replaceWithNumbers", "(", "getRandValue", "(", "[", "]", "string", "{", "\"", "\"",...
// CreditCardNumberLuhn will generate a random credit card number int that passes luhn test
[ "CreditCardNumberLuhn", "will", "generate", "a", "random", "credit", "card", "number", "int", "that", "passes", "luhn", "test" ]
a5ac7cef41d64b726c51e8826e02dad0c34f55b4
https://github.com/brianvoe/gofakeit/blob/a5ac7cef41d64b726c51e8826e02dad0c34f55b4/payment.go#L38-L48
train
brianvoe/gofakeit
payment.go
CreditCardExp
func CreditCardExp() string { month := strconv.Itoa(randIntRange(1, 12)) if len(month) == 1 { month = "0" + month } return month + "/" + strconv.Itoa(randIntRange(currentYear+1, currentYear+10)) }
go
func CreditCardExp() string { month := strconv.Itoa(randIntRange(1, 12)) if len(month) == 1 { month = "0" + month } return month + "/" + strconv.Itoa(randIntRange(currentYear+1, currentYear+10)) }
[ "func", "CreditCardExp", "(", ")", "string", "{", "month", ":=", "strconv", ".", "Itoa", "(", "randIntRange", "(", "1", ",", "12", ")", ")", "\n", "if", "len", "(", "month", ")", "==", "1", "{", "month", "=", "\"", "\"", "+", "month", "\n", "}", ...
// CreditCardExp will generate a random credit card expiration date string // Exp date will always be a future date
[ "CreditCardExp", "will", "generate", "a", "random", "credit", "card", "expiration", "date", "string", "Exp", "date", "will", "always", "be", "a", "future", "date" ]
a5ac7cef41d64b726c51e8826e02dad0c34f55b4
https://github.com/brianvoe/gofakeit/blob/a5ac7cef41d64b726c51e8826e02dad0c34f55b4/payment.go#L52-L58
train
brianvoe/gofakeit
payment.go
luhn
func luhn(s string) bool { var t = [...]int{0, 2, 4, 6, 8, 1, 3, 5, 7, 9} odd := len(s) & 1 var sum int for i, c := range s { if c < '0' || c > '9' { return false } if i&1 == odd { sum += t[c-'0'] } else { sum += int(c - '0') } } return sum%10 == 0 }
go
func luhn(s string) bool { var t = [...]int{0, 2, 4, 6, 8, 1, 3, 5, 7, 9} odd := len(s) & 1 var sum int for i, c := range s { if c < '0' || c > '9' { return false } if i&1 == odd { sum += t[c-'0'] } else { sum += int(c - '0') } } return sum%10 == 0 }
[ "func", "luhn", "(", "s", "string", ")", "bool", "{", "var", "t", "=", "[", "...", "]", "int", "{", "0", ",", "2", ",", "4", ",", "6", ",", "8", ",", "1", ",", "3", ",", "5", ",", "7", ",", "9", "}", "\n", "odd", ":=", "len", "(", "s"...
// luhn check is used for checking if credit card is valid
[ "luhn", "check", "is", "used", "for", "checking", "if", "credit", "card", "is", "valid" ]
a5ac7cef41d64b726c51e8826e02dad0c34f55b4
https://github.com/brianvoe/gofakeit/blob/a5ac7cef41d64b726c51e8826e02dad0c34f55b4/payment.go#L66-L81
train
brianvoe/gofakeit
color.go
HexColor
func HexColor() string { color := make([]byte, 6) hashQuestion := []byte("?#") for i := 0; i < 6; i++ { color[i] = hashQuestion[rand.Intn(2)] } return "#" + replaceWithLetters(replaceWithNumbers(string(color))) // color := "" // for i := 1; i <= 6; i++ { // color += RandString([]string{"?", "#"}) // } // // Replace # with number // color = replaceWithNumbers(color) // // Replace ? with letter // for strings.Count(color, "?") > 0 { // color = strings.Replace(color, "?", RandString(letters), 1) // } // return "#" + color }
go
func HexColor() string { color := make([]byte, 6) hashQuestion := []byte("?#") for i := 0; i < 6; i++ { color[i] = hashQuestion[rand.Intn(2)] } return "#" + replaceWithLetters(replaceWithNumbers(string(color))) // color := "" // for i := 1; i <= 6; i++ { // color += RandString([]string{"?", "#"}) // } // // Replace # with number // color = replaceWithNumbers(color) // // Replace ? with letter // for strings.Count(color, "?") > 0 { // color = strings.Replace(color, "?", RandString(letters), 1) // } // return "#" + color }
[ "func", "HexColor", "(", ")", "string", "{", "color", ":=", "make", "(", "[", "]", "byte", ",", "6", ")", "\n", "hashQuestion", ":=", "[", "]", "byte", "(", "\"", "\"", ")", "\n", "for", "i", ":=", "0", ";", "i", "<", "6", ";", "i", "++", "...
// HexColor will generate a random hexadecimal color string
[ "HexColor", "will", "generate", "a", "random", "hexadecimal", "color", "string" ]
a5ac7cef41d64b726c51e8826e02dad0c34f55b4
https://github.com/brianvoe/gofakeit/blob/a5ac7cef41d64b726c51e8826e02dad0c34f55b4/color.go#L16-L39
train
brianvoe/gofakeit
string.go
ShuffleStrings
func ShuffleStrings(a []string) { swap := func(i, j int) { a[i], a[j] = a[j], a[i] } //to avoid upgrading to 1.10 I copied the algorithm n := len(a) if n <= 1 { return } //if size is > int32 probably it will never finish, or ran out of entropy i := n - 1 for ; i > 0; i-- { j := int(rand.Int31n(int32(i + 1))) swap(i, j) } }
go
func ShuffleStrings(a []string) { swap := func(i, j int) { a[i], a[j] = a[j], a[i] } //to avoid upgrading to 1.10 I copied the algorithm n := len(a) if n <= 1 { return } //if size is > int32 probably it will never finish, or ran out of entropy i := n - 1 for ; i > 0; i-- { j := int(rand.Int31n(int32(i + 1))) swap(i, j) } }
[ "func", "ShuffleStrings", "(", "a", "[", "]", "string", ")", "{", "swap", ":=", "func", "(", "i", ",", "j", "int", ")", "{", "a", "[", "i", "]", ",", "a", "[", "j", "]", "=", "a", "[", "j", "]", ",", "a", "[", "i", "]", "\n", "}", "\n",...
// ShuffleStrings will randomize a slice of strings
[ "ShuffleStrings", "will", "randomize", "a", "slice", "of", "strings" ]
a5ac7cef41d64b726c51e8826e02dad0c34f55b4
https://github.com/brianvoe/gofakeit/blob/a5ac7cef41d64b726c51e8826e02dad0c34f55b4/string.go#L23-L39
train
brianvoe/gofakeit
string.go
RandString
func RandString(a []string) string { size := len(a) if size == 0 { return "" } return a[rand.Intn(size)] }
go
func RandString(a []string) string { size := len(a) if size == 0 { return "" } return a[rand.Intn(size)] }
[ "func", "RandString", "(", "a", "[", "]", "string", ")", "string", "{", "size", ":=", "len", "(", "a", ")", "\n", "if", "size", "==", "0", "{", "return", "\"", "\"", "\n", "}", "\n", "return", "a", "[", "rand", ".", "Intn", "(", "size", ")", ...
// RandString will take in a slice of string and return a randomly selected value
[ "RandString", "will", "take", "in", "a", "slice", "of", "string", "and", "return", "a", "randomly", "selected", "value" ]
a5ac7cef41d64b726c51e8826e02dad0c34f55b4
https://github.com/brianvoe/gofakeit/blob/a5ac7cef41d64b726c51e8826e02dad0c34f55b4/string.go#L42-L48
train
brianvoe/gofakeit
vehicle.go
Vehicle
func Vehicle() *VehicleInfo { return &VehicleInfo{ VehicleType: VehicleType(), Fuel: FuelType(), TransmissionGear: TransmissionGearType(), Brand: CarMaker(), Model: CarModel(), Year: Year(), } }
go
func Vehicle() *VehicleInfo { return &VehicleInfo{ VehicleType: VehicleType(), Fuel: FuelType(), TransmissionGear: TransmissionGearType(), Brand: CarMaker(), Model: CarModel(), Year: Year(), } }
[ "func", "Vehicle", "(", ")", "*", "VehicleInfo", "{", "return", "&", "VehicleInfo", "{", "VehicleType", ":", "VehicleType", "(", ")", ",", "Fuel", ":", "FuelType", "(", ")", ",", "TransmissionGear", ":", "TransmissionGearType", "(", ")", ",", "Brand", ":",...
// Vehicle will generate a struct with vehicle information
[ "Vehicle", "will", "generate", "a", "struct", "with", "vehicle", "information" ]
a5ac7cef41d64b726c51e8826e02dad0c34f55b4
https://github.com/brianvoe/gofakeit/blob/a5ac7cef41d64b726c51e8826e02dad0c34f55b4/vehicle.go#L20-L30
train
brianvoe/gofakeit
hipster.go
HipsterParagraph
func HipsterParagraph(paragraphCount int, sentenceCount int, wordCount int, separator string) string { return paragraphGenerator(paragrapOptions{paragraphCount, sentenceCount, wordCount, separator}, HipsterSentence) }
go
func HipsterParagraph(paragraphCount int, sentenceCount int, wordCount int, separator string) string { return paragraphGenerator(paragrapOptions{paragraphCount, sentenceCount, wordCount, separator}, HipsterSentence) }
[ "func", "HipsterParagraph", "(", "paragraphCount", "int", ",", "sentenceCount", "int", ",", "wordCount", "int", ",", "separator", "string", ")", "string", "{", "return", "paragraphGenerator", "(", "paragrapOptions", "{", "paragraphCount", ",", "sentenceCount", ",", ...
// HipsterParagraph will generate a random paragraphGenerator // Set Paragraph Count // Set Sentence Count // Set Word Count // Set Paragraph Separator
[ "HipsterParagraph", "will", "generate", "a", "random", "paragraphGenerator", "Set", "Paragraph", "Count", "Set", "Sentence", "Count", "Set", "Word", "Count", "Set", "Paragraph", "Separator" ]
a5ac7cef41d64b726c51e8826e02dad0c34f55b4
https://github.com/brianvoe/gofakeit/blob/a5ac7cef41d64b726c51e8826e02dad0c34f55b4/hipster.go#L18-L20
train
brianvoe/gofakeit
hacker.go
HackerPhrase
func HackerPhrase() string { words := strings.Split(Generate(getRandValue([]string{"hacker", "phrase"})), " ") words[0] = strings.Title(words[0]) return strings.Join(words, " ") }
go
func HackerPhrase() string { words := strings.Split(Generate(getRandValue([]string{"hacker", "phrase"})), " ") words[0] = strings.Title(words[0]) return strings.Join(words, " ") }
[ "func", "HackerPhrase", "(", ")", "string", "{", "words", ":=", "strings", ".", "Split", "(", "Generate", "(", "getRandValue", "(", "[", "]", "string", "{", "\"", "\"", ",", "\"", "\"", "}", ")", ")", ",", "\"", "\"", ")", "\n", "words", "[", "0"...
// HackerPhrase will return a random hacker sentence
[ "HackerPhrase", "will", "return", "a", "random", "hacker", "sentence" ]
a5ac7cef41d64b726c51e8826e02dad0c34f55b4
https://github.com/brianvoe/gofakeit/blob/a5ac7cef41d64b726c51e8826e02dad0c34f55b4/hacker.go#L6-L10
train
brianvoe/gofakeit
number.go
ShuffleInts
func ShuffleInts(a []int) { for i := range a { j := rand.Intn(i + 1) a[i], a[j] = a[j], a[i] } }
go
func ShuffleInts(a []int) { for i := range a { j := rand.Intn(i + 1) a[i], a[j] = a[j], a[i] } }
[ "func", "ShuffleInts", "(", "a", "[", "]", "int", ")", "{", "for", "i", ":=", "range", "a", "{", "j", ":=", "rand", ".", "Intn", "(", "i", "+", "1", ")", "\n", "a", "[", "i", "]", ",", "a", "[", "j", "]", "=", "a", "[", "j", "]", ",", ...
// ShuffleInts will randomize a slice of ints
[ "ShuffleInts", "will", "randomize", "a", "slice", "of", "ints" ]
a5ac7cef41d64b726c51e8826e02dad0c34f55b4
https://github.com/brianvoe/gofakeit/blob/a5ac7cef41d64b726c51e8826e02dad0c34f55b4/number.go#L79-L84
train
brianvoe/gofakeit
job.go
Job
func Job() *JobInfo { return &JobInfo{ Company: Company(), Title: JobTitle(), Descriptor: JobDescriptor(), Level: JobLevel(), } }
go
func Job() *JobInfo { return &JobInfo{ Company: Company(), Title: JobTitle(), Descriptor: JobDescriptor(), Level: JobLevel(), } }
[ "func", "Job", "(", ")", "*", "JobInfo", "{", "return", "&", "JobInfo", "{", "Company", ":", "Company", "(", ")", ",", "Title", ":", "JobTitle", "(", ")", ",", "Descriptor", ":", "JobDescriptor", "(", ")", ",", "Level", ":", "JobLevel", "(", ")", "...
// Job will generate a struct with random job information
[ "Job", "will", "generate", "a", "struct", "with", "random", "job", "information" ]
a5ac7cef41d64b726c51e8826e02dad0c34f55b4
https://github.com/brianvoe/gofakeit/blob/a5ac7cef41d64b726c51e8826e02dad0c34f55b4/job.go#L12-L19
train
brianvoe/gofakeit
contact.go
Email
func Email() string { var email string email = getRandValue([]string{"person", "first"}) + getRandValue([]string{"person", "last"}) email += "@" email += getRandValue([]string{"person", "last"}) + "." + getRandValue([]string{"internet", "domain_suffix"}) return strings.ToLower(email) }
go
func Email() string { var email string email = getRandValue([]string{"person", "first"}) + getRandValue([]string{"person", "last"}) email += "@" email += getRandValue([]string{"person", "last"}) + "." + getRandValue([]string{"internet", "domain_suffix"}) return strings.ToLower(email) }
[ "func", "Email", "(", ")", "string", "{", "var", "email", "string", "\n\n", "email", "=", "getRandValue", "(", "[", "]", "string", "{", "\"", "\"", ",", "\"", "\"", "}", ")", "+", "getRandValue", "(", "[", "]", "string", "{", "\"", "\"", ",", "\"...
// Email will generate a random email string
[ "Email", "will", "generate", "a", "random", "email", "string" ]
a5ac7cef41d64b726c51e8826e02dad0c34f55b4
https://github.com/brianvoe/gofakeit/blob/a5ac7cef41d64b726c51e8826e02dad0c34f55b4/contact.go#L32-L40
train
brianvoe/gofakeit
person.go
Person
func Person() *PersonInfo { return &PersonInfo{ FirstName: FirstName(), LastName: LastName(), Gender: Gender(), SSN: SSN(), Image: ImageURL(300, 300) + "/people", Job: Job(), Address: Address(), Contact: Contact(), CreditCard: CreditCard(), } }
go
func Person() *PersonInfo { return &PersonInfo{ FirstName: FirstName(), LastName: LastName(), Gender: Gender(), SSN: SSN(), Image: ImageURL(300, 300) + "/people", Job: Job(), Address: Address(), Contact: Contact(), CreditCard: CreditCard(), } }
[ "func", "Person", "(", ")", "*", "PersonInfo", "{", "return", "&", "PersonInfo", "{", "FirstName", ":", "FirstName", "(", ")", ",", "LastName", ":", "LastName", "(", ")", ",", "Gender", ":", "Gender", "(", ")", ",", "SSN", ":", "SSN", "(", ")", ","...
// Person will generate a struct with person information
[ "Person", "will", "generate", "a", "struct", "with", "person", "information" ]
a5ac7cef41d64b726c51e8826e02dad0c34f55b4
https://github.com/brianvoe/gofakeit/blob/a5ac7cef41d64b726c51e8826e02dad0c34f55b4/person.go#L33-L45
train
brianvoe/gofakeit
company.go
Company
func Company() (company string) { switch randInt := randIntRange(1, 3); randInt { case 1: company = LastName() + ", " + LastName() + " and " + LastName() case 2: company = LastName() + "-" + LastName() case 3: company = LastName() + " " + CompanySuffix() } return }
go
func Company() (company string) { switch randInt := randIntRange(1, 3); randInt { case 1: company = LastName() + ", " + LastName() + " and " + LastName() case 2: company = LastName() + "-" + LastName() case 3: company = LastName() + " " + CompanySuffix() } return }
[ "func", "Company", "(", ")", "(", "company", "string", ")", "{", "switch", "randInt", ":=", "randIntRange", "(", "1", ",", "3", ")", ";", "randInt", "{", "case", "1", ":", "company", "=", "LastName", "(", ")", "+", "\"", "\"", "+", "LastName", "(",...
// Company will generate a random company name string
[ "Company", "will", "generate", "a", "random", "company", "name", "string" ]
a5ac7cef41d64b726c51e8826e02dad0c34f55b4
https://github.com/brianvoe/gofakeit/blob/a5ac7cef41d64b726c51e8826e02dad0c34f55b4/company.go#L4-L15
train
brianvoe/gofakeit
datetime.go
Date
func Date() time.Time { return time.Date(Year(), time.Month(Number(0, 12)), Day(), Hour(), Minute(), Second(), NanoSecond(), time.UTC) }
go
func Date() time.Time { return time.Date(Year(), time.Month(Number(0, 12)), Day(), Hour(), Minute(), Second(), NanoSecond(), time.UTC) }
[ "func", "Date", "(", ")", "time", ".", "Time", "{", "return", "time", ".", "Date", "(", "Year", "(", ")", ",", "time", ".", "Month", "(", "Number", "(", "0", ",", "12", ")", ")", ",", "Day", "(", ")", ",", "Hour", "(", ")", ",", "Minute", "...
// Date will generate a random time.Time struct
[ "Date", "will", "generate", "a", "random", "time", ".", "Time", "struct" ]
a5ac7cef41d64b726c51e8826e02dad0c34f55b4
https://github.com/brianvoe/gofakeit/blob/a5ac7cef41d64b726c51e8826e02dad0c34f55b4/datetime.go#L9-L11
train
brianvoe/gofakeit
datetime.go
DateRange
func DateRange(start, end time.Time) time.Time { return time.Unix(0, int64(Number(int(start.UnixNano()), int(end.UnixNano())))).UTC() }
go
func DateRange(start, end time.Time) time.Time { return time.Unix(0, int64(Number(int(start.UnixNano()), int(end.UnixNano())))).UTC() }
[ "func", "DateRange", "(", "start", ",", "end", "time", ".", "Time", ")", "time", ".", "Time", "{", "return", "time", ".", "Unix", "(", "0", ",", "int64", "(", "Number", "(", "int", "(", "start", ".", "UnixNano", "(", ")", ")", ",", "int", "(", ...
// DateRange will generate a random time.Time struct between a start and end date
[ "DateRange", "will", "generate", "a", "random", "time", ".", "Time", "struct", "between", "a", "start", "and", "end", "date" ]
a5ac7cef41d64b726c51e8826e02dad0c34f55b4
https://github.com/brianvoe/gofakeit/blob/a5ac7cef41d64b726c51e8826e02dad0c34f55b4/datetime.go#L14-L16
train