id
int32 0
167k
| repo
stringlengths 5
54
| path
stringlengths 4
155
| func_name
stringlengths 1
118
| original_string
stringlengths 52
85.5k
| language
stringclasses 1
value | code
stringlengths 52
85.5k
| code_tokens
sequencelengths 21
1.41k
| docstring
stringlengths 6
2.61k
| docstring_tokens
sequencelengths 3
215
| sha
stringlengths 40
40
| url
stringlengths 85
252
|
---|---|---|---|---|---|---|---|---|---|---|---|
148,900 | 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",
"(",
")",
"\n",
"defer",
"func",
"(",
")",
"{",
"debug",
".",
"Println",
"(",
"\"",
"\"",
",",
"time",
".",
"Since",
"(",
"start",
")",
")",
"\n",
"}",
"(",
")",
"\n",
"fail",
":=",
"func",
"(",
"err",
"error",
")",
"(",
"[",
"]",
"string",
",",
"error",
")",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"env",
",",
"err",
":=",
"internal",
".",
"EnvWithGOOS",
"(",
"goos",
",",
"goarch",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"debug",
".",
"Println",
"(",
"\"",
"\"",
",",
"magePath",
")",
"\n",
"// // 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",
",",
"\"",
"\"",
",",
"\"",
"\"",
",",
"\"",
"\"",
",",
"`{{join .GoFiles \"||\"}}`",
")",
"\n",
"cmd",
".",
"Env",
"=",
"env",
"\n",
"if",
"isDebug",
"{",
"cmd",
".",
"Stderr",
"=",
"stderr",
"\n",
"}",
"\n",
"cmd",
".",
"Dir",
"=",
"magePath",
"\n",
"b",
",",
"err",
":=",
"cmd",
".",
"Output",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"fail",
"(",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
")",
"\n",
"}",
"\n",
"list",
":=",
"strings",
".",
"TrimSpace",
"(",
"string",
"(",
"b",
")",
")",
"\n",
"debug",
".",
"Println",
"(",
"\"",
"\"",
",",
"list",
")",
"\n",
"exclude",
":=",
"map",
"[",
"string",
"]",
"bool",
"{",
"}",
"\n",
"for",
"_",
",",
"f",
":=",
"range",
"strings",
".",
"Split",
"(",
"list",
",",
"\"",
"\"",
")",
"{",
"if",
"f",
"!=",
"\"",
"\"",
"{",
"debug",
".",
"Printf",
"(",
"\"",
"\"",
",",
"f",
")",
"\n",
"exclude",
"[",
"f",
"]",
"=",
"true",
"\n",
"}",
"\n",
"}",
"\n",
"debug",
".",
"Println",
"(",
"\"",
"\"",
")",
"\n",
"cmd",
"=",
"exec",
".",
"Command",
"(",
"goCmd",
",",
"\"",
"\"",
",",
"\"",
"\"",
",",
"\"",
"\"",
",",
"\"",
"\"",
",",
"`{{join .GoFiles \"||\"}}`",
")",
"\n",
"cmd",
".",
"Env",
"=",
"env",
"\n\n",
"if",
"isDebug",
"{",
"cmd",
".",
"Stderr",
"=",
"stderr",
"\n",
"}",
"\n",
"cmd",
".",
"Dir",
"=",
"magePath",
"\n",
"b",
",",
"err",
"=",
"cmd",
".",
"Output",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"fail",
"(",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
")",
"\n",
"}",
"\n\n",
"list",
"=",
"strings",
".",
"TrimSpace",
"(",
"string",
"(",
"b",
")",
")",
"\n",
"files",
":=",
"[",
"]",
"string",
"{",
"}",
"\n",
"for",
"_",
",",
"f",
":=",
"range",
"strings",
".",
"Split",
"(",
"list",
",",
"\"",
"\"",
")",
"{",
"if",
"f",
"!=",
"\"",
"\"",
"&&",
"!",
"exclude",
"[",
"f",
"]",
"{",
"files",
"=",
"append",
"(",
"files",
",",
"f",
")",
"\n",
"}",
"\n",
"}",
"\n",
"for",
"i",
":=",
"range",
"files",
"{",
"files",
"[",
"i",
"]",
"=",
"filepath",
".",
"Join",
"(",
"magePath",
",",
"files",
"[",
"i",
"]",
")",
"\n",
"}",
"\n",
"return",
"files",
",",
"nil",
"\n",
"}"
] | // 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 |
148,901 | 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",
".",
"Println",
"(",
"\"",
"\"",
",",
"compileTo",
")",
"\n",
"debug",
".",
"Println",
"(",
"\"",
"\"",
",",
"goCmd",
")",
"\n",
"if",
"isDebug",
"{",
"internal",
".",
"RunDebug",
"(",
"goCmd",
",",
"\"",
"\"",
")",
"\n",
"internal",
".",
"RunDebug",
"(",
"goCmd",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"environ",
",",
"err",
":=",
"internal",
".",
"EnvWithGOOS",
"(",
"goos",
",",
"goarch",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"// strip off the path since we're setting the path in the build command",
"for",
"i",
":=",
"range",
"gofiles",
"{",
"gofiles",
"[",
"i",
"]",
"=",
"filepath",
".",
"Base",
"(",
"gofiles",
"[",
"i",
"]",
")",
"\n",
"}",
"\n",
"debug",
".",
"Printf",
"(",
"\"",
"\"",
",",
"goCmd",
",",
"compileTo",
",",
"strings",
".",
"Join",
"(",
"gofiles",
",",
"\"",
"\"",
")",
")",
"\n",
"c",
":=",
"exec",
".",
"Command",
"(",
"goCmd",
",",
"append",
"(",
"[",
"]",
"string",
"{",
"\"",
"\"",
",",
"\"",
"\"",
",",
"compileTo",
"}",
",",
"gofiles",
"...",
")",
"...",
")",
"\n",
"c",
".",
"Env",
"=",
"environ",
"\n",
"c",
".",
"Stderr",
"=",
"stderr",
"\n",
"c",
".",
"Stdout",
"=",
"stdout",
"\n",
"c",
".",
"Dir",
"=",
"magePath",
"\n",
"start",
":=",
"time",
".",
"Now",
"(",
")",
"\n",
"err",
"=",
"c",
".",
"Run",
"(",
")",
"\n",
"debug",
".",
"Println",
"(",
"\"",
"\"",
",",
"time",
".",
"Since",
"(",
"start",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] | // 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 |
148,902 | 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",
"(",
"path",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n",
"defer",
"f",
".",
"Close",
"(",
")",
"\n",
"data",
":=",
"mainfileTemplateData",
"{",
"Description",
":",
"info",
".",
"Description",
",",
"Funcs",
":",
"info",
".",
"Funcs",
",",
"Aliases",
":",
"info",
".",
"Aliases",
",",
"Imports",
":",
"info",
".",
"Imports",
",",
"BinaryName",
":",
"binaryName",
",",
"}",
"\n\n",
"if",
"info",
".",
"DefaultFunc",
"!=",
"nil",
"{",
"data",
".",
"DefaultFunc",
"=",
"*",
"info",
".",
"DefaultFunc",
"\n",
"}",
"\n\n",
"debug",
".",
"Println",
"(",
"\"",
"\"",
",",
"path",
")",
"\n",
"if",
"err",
":=",
"mainfileTemplate",
".",
"Execute",
"(",
"f",
",",
"data",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n",
"if",
"err",
":=",
"f",
".",
"Close",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n",
"// 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",
")",
"\n",
"if",
"err",
":=",
"os",
".",
"Chtimes",
"(",
"path",
",",
"longAgo",
",",
"longAgo",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] | // 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 |
148,903 | 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",
":=",
"hashFile",
"(",
"s",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\"",
"\"",
",",
"err",
"\n",
"}",
"\n",
"hashes",
"=",
"append",
"(",
"hashes",
",",
"h",
")",
"\n",
"}",
"\n",
"// hash the mainfile template to ensure if it gets updated, we make a new",
"// binary.",
"hashes",
"=",
"append",
"(",
"hashes",
",",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"sha1",
".",
"Sum",
"(",
"[",
"]",
"byte",
"(",
"mageMainfileTplString",
")",
")",
")",
")",
"\n",
"sort",
".",
"Strings",
"(",
"hashes",
")",
"\n",
"ver",
",",
"err",
":=",
"internal",
".",
"OutputDebug",
"(",
"goCmd",
",",
"\"",
"\"",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\"",
"\"",
",",
"err",
"\n",
"}",
"\n",
"hash",
":=",
"sha1",
".",
"Sum",
"(",
"[",
"]",
"byte",
"(",
"strings",
".",
"Join",
"(",
"hashes",
",",
"\"",
"\"",
")",
"+",
"magicRebuildKey",
"+",
"ver",
")",
")",
"\n",
"filename",
":=",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"hash",
")",
"\n\n",
"out",
":=",
"filepath",
".",
"Join",
"(",
"cacheDir",
",",
"filename",
")",
"\n",
"if",
"runtime",
".",
"GOOS",
"==",
"\"",
"\"",
"{",
"out",
"+=",
"\"",
"\"",
"\n",
"}",
"\n",
"return",
"out",
",",
"nil",
"\n",
"}"
] | // 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 |
148,904 | 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",
"(",
"exePath",
",",
"inv",
".",
"Args",
"...",
")",
"\n",
"c",
".",
"Stderr",
"=",
"inv",
".",
"Stderr",
"\n",
"c",
".",
"Stdout",
"=",
"inv",
".",
"Stdout",
"\n",
"c",
".",
"Stdin",
"=",
"inv",
".",
"Stdin",
"\n",
"c",
".",
"Dir",
"=",
"inv",
".",
"Dir",
"\n",
"// intentionally pass through unaltered os.Environ here.. your magefile has",
"// to deal with it.",
"c",
".",
"Env",
"=",
"os",
".",
"Environ",
"(",
")",
"\n",
"if",
"inv",
".",
"Verbose",
"{",
"c",
".",
"Env",
"=",
"append",
"(",
"c",
".",
"Env",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"if",
"inv",
".",
"List",
"{",
"c",
".",
"Env",
"=",
"append",
"(",
"c",
".",
"Env",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"if",
"inv",
".",
"Help",
"{",
"c",
".",
"Env",
"=",
"append",
"(",
"c",
".",
"Env",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"if",
"inv",
".",
"Debug",
"{",
"c",
".",
"Env",
"=",
"append",
"(",
"c",
".",
"Env",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"if",
"inv",
".",
"GoCmd",
"!=",
"\"",
"\"",
"{",
"c",
".",
"Env",
"=",
"append",
"(",
"c",
".",
"Env",
",",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"inv",
".",
"GoCmd",
")",
")",
"\n",
"}",
"\n",
"if",
"inv",
".",
"Timeout",
">",
"0",
"{",
"c",
".",
"Env",
"=",
"append",
"(",
"c",
".",
"Env",
",",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"inv",
".",
"Timeout",
".",
"String",
"(",
")",
")",
")",
"\n",
"}",
"\n",
"debug",
".",
"Print",
"(",
"\"",
"\\n",
"\"",
",",
"strings",
".",
"Join",
"(",
"filter",
"(",
"c",
".",
"Env",
",",
"\"",
"\"",
")",
",",
"\"",
"\\n",
"\"",
")",
")",
"\n",
"err",
":=",
"c",
".",
"Run",
"(",
")",
"\n",
"if",
"!",
"sh",
".",
"CmdRan",
"(",
"err",
")",
"{",
"errlog",
".",
"Printf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n",
"return",
"sh",
".",
"ExitStatus",
"(",
"err",
")",
"\n",
"}"
] | // 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 |
148,905 | 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",
"os",
".",
"IsNotExist",
"(",
"err",
")",
"{",
"return",
"nil",
"\n",
"}",
"\n",
"return",
"err",
"\n",
"}",
"\n",
"for",
"_",
",",
"f",
":=",
"range",
"files",
"{",
"if",
"f",
".",
"IsDir",
"(",
")",
"{",
"continue",
"\n",
"}",
"\n",
"err",
"=",
"os",
".",
"Remove",
"(",
"filepath",
".",
"Join",
"(",
"dir",
",",
"f",
".",
"Name",
"(",
")",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"nil",
"\n\n",
"}"
] | // 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 |
148,906 | 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 the environment, otherwise fall back to first path",
"// in GOPATH environment string",
"bin",
",",
"err",
":=",
"sh",
".",
"Output",
"(",
"gocmd",
",",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n",
"if",
"bin",
"==",
"\"",
"\"",
"{",
"gopath",
",",
"err",
":=",
"sh",
".",
"Output",
"(",
"gocmd",
",",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n",
"paths",
":=",
"strings",
".",
"Split",
"(",
"gopath",
",",
"string",
"(",
"[",
"]",
"rune",
"{",
"os",
".",
"PathListSeparator",
"}",
")",
")",
"\n",
"bin",
"=",
"filepath",
".",
"Join",
"(",
"paths",
"[",
"0",
"]",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"// 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",
"(",
"\"",
"\"",
",",
"bin",
",",
"err",
")",
"\n",
"}",
"\n",
"path",
":=",
"filepath",
".",
"Join",
"(",
"bin",
",",
"name",
")",
"\n\n",
"// 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",
",",
"\"",
"\"",
",",
"\"",
"\"",
",",
"path",
",",
"\"",
"\"",
"+",
"flags",
"(",
")",
",",
"\"",
"\"",
")",
"\n",
"}"
] | // 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 |
148,907 | 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",
"(",
"\"",
"\"",
"+",
"tag",
")",
"\n",
"}",
"\n\n",
"if",
"err",
":=",
"sh",
".",
"RunV",
"(",
"\"",
"\"",
",",
"\"",
"\"",
",",
"\"",
"\"",
",",
"tag",
",",
"\"",
"\"",
",",
"tag",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"if",
"err",
":=",
"sh",
".",
"RunV",
"(",
"\"",
"\"",
",",
"\"",
"\"",
",",
"\"",
"\"",
",",
"tag",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"defer",
"func",
"(",
")",
"{",
"if",
"err",
"!=",
"nil",
"{",
"sh",
".",
"RunV",
"(",
"\"",
"\"",
",",
"\"",
"\"",
",",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\n",
"sh",
".",
"RunV",
"(",
"\"",
"\"",
",",
"\"",
"\"",
",",
"\"",
"\"",
",",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"}",
"(",
")",
"\n",
"return",
"sh",
".",
"RunV",
"(",
"\"",
"\"",
")",
"\n",
"}"
] | // 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 |
148,908 | 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",
"f",
".",
"Receiver",
"!=",
"\"",
"\"",
"{",
"receiver",
"=",
"f",
".",
"Receiver",
"+",
"\"",
"\"",
"\n",
"}",
"\n",
"return",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"path",
",",
"receiver",
",",
"f",
".",
"Name",
")",
"\n",
"}"
] | // 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 |
148,909 | 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",
".",
"Name",
"}",
"{",
"if",
"s",
"!=",
"\"",
"\"",
"{",
"names",
"=",
"append",
"(",
"names",
",",
"s",
")",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"strings",
".",
"Join",
"(",
"names",
",",
"\"",
"\"",
")",
"\n",
"}"
] | // 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 |
148,910 | 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",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"if",
"err",
":=",
"setImports",
"(",
"gocmd",
",",
"info",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"setDefault",
"(",
"info",
")",
"\n",
"setAliases",
"(",
"info",
")",
"\n",
"return",
"info",
",",
"nil",
"\n",
"}"
] | // 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 |
148,911 | 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",
"(",
"\"",
"\"",
",",
"time",
".",
"Since",
"(",
"start",
")",
")",
"\n",
"}",
"(",
")",
"\n",
"fset",
":=",
"token",
".",
"NewFileSet",
"(",
")",
"\n",
"pkg",
",",
"err",
":=",
"getPackage",
"(",
"path",
",",
"files",
",",
"fset",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"p",
":=",
"doc",
".",
"New",
"(",
"pkg",
",",
"\"",
"\"",
",",
"0",
")",
"\n",
"pi",
":=",
"&",
"PkgInfo",
"{",
"AstPkg",
":",
"pkg",
",",
"DocPkg",
":",
"p",
",",
"Description",
":",
"toOneLine",
"(",
"p",
".",
"Doc",
")",
",",
"}",
"\n\n",
"setNamespaces",
"(",
"pi",
")",
"\n",
"setFuncs",
"(",
"pi",
")",
"\n\n",
"hasDupes",
",",
"names",
":=",
"checkDupeTargets",
"(",
"pi",
")",
"\n",
"if",
"hasDupes",
"{",
"msg",
":=",
"\"",
"\\n",
"\"",
"\n",
"for",
"_",
",",
"v",
":=",
"range",
"names",
"{",
"if",
"len",
"(",
"v",
")",
">",
"1",
"{",
"msg",
"+=",
"\"",
"\"",
"+",
"strings",
".",
"Join",
"(",
"v",
",",
"\"",
"\"",
")",
"+",
"\"",
"\\n",
"\"",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"nil",
",",
"errors",
".",
"New",
"(",
"msg",
")",
"\n",
"}",
"\n\n",
"return",
"pi",
",",
"nil",
"\n",
"}"
] | // 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 |
148,912 | 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",
":=",
"map",
"[",
"string",
"]",
"bool",
"{",
"}",
"\n",
"for",
"_",
",",
"f",
":=",
"range",
"info",
".",
"Funcs",
"{",
"low",
":=",
"strings",
".",
"ToLower",
"(",
"f",
".",
"Name",
")",
"\n",
"if",
"f",
".",
"Receiver",
"!=",
"\"",
"\"",
"{",
"low",
"=",
"strings",
".",
"ToLower",
"(",
"f",
".",
"Receiver",
")",
"+",
"\"",
"\"",
"+",
"low",
"\n",
"}",
"\n",
"if",
"lowers",
"[",
"low",
"]",
"{",
"hasDupes",
"=",
"true",
"\n",
"}",
"\n",
"lowers",
"[",
"low",
"]",
"=",
"true",
"\n",
"names",
"[",
"low",
"]",
"=",
"append",
"(",
"names",
"[",
"low",
"]",
",",
"f",
".",
"Name",
")",
"\n",
"}",
"\n",
"return",
"hasDupes",
",",
"names",
"\n",
"}"
] | // 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 |
148,913 | 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.",
"// From:",
"// clean\tClean removes the temporarily generated files",
"// To:",
"// clean \tremoves the temporarily generated files",
"if",
"syns",
":=",
"strings",
".",
"Split",
"(",
"synopsis",
",",
"\"",
"\"",
")",
";",
"strings",
".",
"EqualFold",
"(",
"f",
".",
"Name",
",",
"syns",
"[",
"0",
"]",
")",
"{",
"return",
"strings",
".",
"Join",
"(",
"syns",
"[",
"1",
":",
"]",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"return",
"synopsis",
"\n",
"}"
] | // 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 |
148,914 | 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",
")",
"bool",
"\n",
"if",
"len",
"(",
"files",
")",
">",
"0",
"{",
"fm",
":=",
"make",
"(",
"map",
"[",
"string",
"]",
"bool",
",",
"len",
"(",
"files",
")",
")",
"\n",
"for",
"_",
",",
"f",
":=",
"range",
"files",
"{",
"fm",
"[",
"f",
"]",
"=",
"true",
"\n",
"}",
"\n\n",
"filter",
"=",
"func",
"(",
"f",
"os",
".",
"FileInfo",
")",
"bool",
"{",
"return",
"fm",
"[",
"f",
".",
"Name",
"(",
")",
"]",
"\n",
"}",
"\n",
"}",
"\n\n",
"pkgs",
",",
"err",
":=",
"parser",
".",
"ParseDir",
"(",
"fset",
",",
"path",
",",
"filter",
",",
"parser",
".",
"ParseComments",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n\n",
"for",
"name",
",",
"pkg",
":=",
"range",
"pkgs",
"{",
"if",
"!",
"strings",
".",
"HasSuffix",
"(",
"name",
",",
"\"",
"\"",
")",
"{",
"return",
"pkg",
",",
"nil",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"path",
")",
"\n",
"}"
] | // 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 |
148,915 | 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",
"...",
")",
")",
",",
"}",
"\n",
"}"
] | // 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 |
148,916 | 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",
"...",
")",
",",
"}",
"\n",
"}"
] | // 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 |
148,917 | 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",
"(",
"err",
")",
"{",
"return",
"true",
",",
"nil",
"\n",
"}",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"false",
",",
"err",
"\n",
"}",
"\n",
"srcTime",
":=",
"stat",
".",
"ModTime",
"(",
")",
"\n",
"if",
"stat",
".",
"IsDir",
"(",
")",
"{",
"srcTime",
",",
"err",
"=",
"calDirModTimeRecursive",
"(",
"dst",
",",
"stat",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"false",
",",
"err",
"\n",
"}",
"\n",
"}",
"\n",
"dt",
",",
"err",
":=",
"loadTargets",
"(",
"expand",
"(",
"sources",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"false",
",",
"err",
"\n",
"}",
"\n",
"t",
",",
"err",
":=",
"dt",
".",
"modTimeDir",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"false",
",",
"err",
"\n",
"}",
"\n",
"if",
"t",
".",
"After",
"(",
"srcTime",
")",
"{",
"return",
"true",
",",
"nil",
"\n",
"}",
"\n",
"return",
"false",
",",
"nil",
"\n",
"}"
] | // 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",
"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",
"."
] | 5bc3a8ab86d5a23d6eb3bdbcd60e79ac4d9ad0ed | https://github.com/magefile/mage/blob/5bc3a8ab86d5a23d6eb3bdbcd60e79ac4d9ad0ed/target/target.go#L79-L106 |
148,918 | 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",
")",
"{",
"return",
"Output",
"(",
"cmd",
",",
"append",
"(",
"args",
",",
"args2",
"...",
")",
"...",
")",
"\n",
"}",
"\n",
"}"
] | // 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 |
148,919 | 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 |
148,920 | 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",
"\n",
"}"
] | // 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 |
148,921 | 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",
".",
"Stdout",
"\n",
"}",
"\n",
"_",
",",
"err",
":=",
"Exec",
"(",
"env",
",",
"output",
",",
"os",
".",
"Stderr",
",",
"cmd",
",",
"args",
"...",
")",
"\n",
"return",
"err",
"\n",
"}"
] | // 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",
"environment",
"variables",
"for",
"the",
"command",
"being",
"run",
".",
"Environment",
"variables",
"should",
"be",
"in",
"the",
"format",
"name",
"=",
"value",
"."
] | 5bc3a8ab86d5a23d6eb3bdbcd60e79ac4d9ad0ed | https://github.com/magefile/mage/blob/5bc3a8ab86d5a23d6eb3bdbcd60e79ac4d9ad0ed/sh/cmd.go#L63-L70 |
148,922 | 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",
".",
"Stderr",
",",
"cmd",
",",
"args",
"...",
")",
"\n",
"return",
"strings",
".",
"TrimSuffix",
"(",
"buf",
".",
"String",
"(",
")",
",",
"\"",
"\\n",
"\"",
")",
",",
"err",
"\n",
"}"
] | // 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 |
148,923 | 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",
":=",
"Exec",
"(",
"env",
",",
"buf",
",",
"os",
".",
"Stderr",
",",
"cmd",
",",
"args",
"...",
")",
"\n",
"return",
"strings",
".",
"TrimSuffix",
"(",
"buf",
".",
"String",
"(",
")",
",",
"\"",
"\\n",
"\"",
")",
",",
"err",
"\n",
"}"
] | // 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 |
148,924 | 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",
"return",
"m",
",",
"nil",
"\n",
"}"
] | // 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 |
148,925 | 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",
"==",
"\"",
"\"",
"{",
"mw",
".",
"SigningAlgorithm",
"=",
"\"",
"\"",
"\n",
"}",
"\n\n",
"if",
"mw",
".",
"Timeout",
"==",
"0",
"{",
"mw",
".",
"Timeout",
"=",
"time",
".",
"Hour",
"\n",
"}",
"\n\n",
"if",
"mw",
".",
"TimeFunc",
"==",
"nil",
"{",
"mw",
".",
"TimeFunc",
"=",
"time",
".",
"Now",
"\n",
"}",
"\n\n",
"mw",
".",
"TokenHeadName",
"=",
"strings",
".",
"TrimSpace",
"(",
"mw",
".",
"TokenHeadName",
")",
"\n",
"if",
"len",
"(",
"mw",
".",
"TokenHeadName",
")",
"==",
"0",
"{",
"mw",
".",
"TokenHeadName",
"=",
"\"",
"\"",
"\n",
"}",
"\n\n",
"if",
"mw",
".",
"Authorizator",
"==",
"nil",
"{",
"mw",
".",
"Authorizator",
"=",
"func",
"(",
"data",
"interface",
"{",
"}",
",",
"c",
"*",
"gin",
".",
"Context",
")",
"bool",
"{",
"return",
"true",
"\n",
"}",
"\n",
"}",
"\n\n",
"if",
"mw",
".",
"Unauthorized",
"==",
"nil",
"{",
"mw",
".",
"Unauthorized",
"=",
"func",
"(",
"c",
"*",
"gin",
".",
"Context",
",",
"code",
"int",
",",
"message",
"string",
")",
"{",
"c",
".",
"JSON",
"(",
"code",
",",
"gin",
".",
"H",
"{",
"\"",
"\"",
":",
"code",
",",
"\"",
"\"",
":",
"message",
",",
"}",
")",
"\n",
"}",
"\n",
"}",
"\n\n",
"if",
"mw",
".",
"LoginResponse",
"==",
"nil",
"{",
"mw",
".",
"LoginResponse",
"=",
"func",
"(",
"c",
"*",
"gin",
".",
"Context",
",",
"code",
"int",
",",
"token",
"string",
",",
"expire",
"time",
".",
"Time",
")",
"{",
"c",
".",
"JSON",
"(",
"http",
".",
"StatusOK",
",",
"gin",
".",
"H",
"{",
"\"",
"\"",
":",
"http",
".",
"StatusOK",
",",
"\"",
"\"",
":",
"token",
",",
"\"",
"\"",
":",
"expire",
".",
"Format",
"(",
"time",
".",
"RFC3339",
")",
",",
"}",
")",
"\n",
"}",
"\n",
"}",
"\n\n",
"if",
"mw",
".",
"RefreshResponse",
"==",
"nil",
"{",
"mw",
".",
"RefreshResponse",
"=",
"func",
"(",
"c",
"*",
"gin",
".",
"Context",
",",
"code",
"int",
",",
"token",
"string",
",",
"expire",
"time",
".",
"Time",
")",
"{",
"c",
".",
"JSON",
"(",
"http",
".",
"StatusOK",
",",
"gin",
".",
"H",
"{",
"\"",
"\"",
":",
"http",
".",
"StatusOK",
",",
"\"",
"\"",
":",
"token",
",",
"\"",
"\"",
":",
"expire",
".",
"Format",
"(",
"time",
".",
"RFC3339",
")",
",",
"}",
")",
"\n",
"}",
"\n",
"}",
"\n\n",
"if",
"mw",
".",
"IdentityKey",
"==",
"\"",
"\"",
"{",
"mw",
".",
"IdentityKey",
"=",
"IdentityKey",
"\n",
"}",
"\n\n",
"if",
"mw",
".",
"IdentityHandler",
"==",
"nil",
"{",
"mw",
".",
"IdentityHandler",
"=",
"func",
"(",
"c",
"*",
"gin",
".",
"Context",
")",
"interface",
"{",
"}",
"{",
"claims",
":=",
"ExtractClaims",
"(",
"c",
")",
"\n",
"return",
"claims",
"[",
"mw",
".",
"IdentityKey",
"]",
"\n",
"}",
"\n",
"}",
"\n\n",
"if",
"mw",
".",
"HTTPStatusMessageFunc",
"==",
"nil",
"{",
"mw",
".",
"HTTPStatusMessageFunc",
"=",
"func",
"(",
"e",
"error",
",",
"c",
"*",
"gin",
".",
"Context",
")",
"string",
"{",
"return",
"e",
".",
"Error",
"(",
")",
"\n",
"}",
"\n",
"}",
"\n\n",
"if",
"mw",
".",
"Realm",
"==",
"\"",
"\"",
"{",
"mw",
".",
"Realm",
"=",
"\"",
"\"",
"\n",
"}",
"\n\n",
"if",
"mw",
".",
"CookieName",
"==",
"\"",
"\"",
"{",
"mw",
".",
"CookieName",
"=",
"\"",
"\"",
"\n",
"}",
"\n\n",
"if",
"mw",
".",
"usingPublicKeyAlgo",
"(",
")",
"{",
"return",
"mw",
".",
"readKeys",
"(",
")",
"\n",
"}",
"\n\n",
"if",
"mw",
".",
"Key",
"==",
"nil",
"{",
"return",
"ErrMissingSecretKey",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] | // MiddlewareInit initialize jwt configs. | [
"MiddlewareInit",
"initialize",
"jwt",
"configs",
"."
] | 633d983b91f09beefb1128c4558d4642a379c602 | https://github.com/appleboy/gin-jwt/blob/633d983b91f09beefb1128c4558d4642a379c602/auth_jwt.go#L248-L339 |
148,926 | 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 |
148,927 | 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",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"if",
"mw",
".",
"SendAuthorization",
"{",
"if",
"v",
",",
"ok",
":=",
"c",
".",
"Get",
"(",
"\"",
"\"",
")",
";",
"ok",
"{",
"c",
".",
"Header",
"(",
"\"",
"\"",
",",
"mw",
".",
"TokenHeadName",
"+",
"\"",
"\"",
"+",
"v",
".",
"(",
"string",
")",
")",
"\n",
"}",
"\n",
"}",
"\n\n",
"claims",
":=",
"MapClaims",
"{",
"}",
"\n",
"for",
"key",
",",
"value",
":=",
"range",
"token",
".",
"Claims",
".",
"(",
"jwt",
".",
"MapClaims",
")",
"{",
"claims",
"[",
"key",
"]",
"=",
"value",
"\n",
"}",
"\n\n",
"return",
"claims",
",",
"nil",
"\n",
"}"
] | // 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 |
148,928 | 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",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\"",
"\"",
",",
"time",
".",
"Now",
"(",
")",
",",
"err",
"\n",
"}",
"\n\n",
"// Create the token",
"newToken",
":=",
"jwt",
".",
"New",
"(",
"jwt",
".",
"GetSigningMethod",
"(",
"mw",
".",
"SigningAlgorithm",
")",
")",
"\n",
"newClaims",
":=",
"newToken",
".",
"Claims",
".",
"(",
"jwt",
".",
"MapClaims",
")",
"\n\n",
"for",
"key",
":=",
"range",
"claims",
"{",
"newClaims",
"[",
"key",
"]",
"=",
"claims",
"[",
"key",
"]",
"\n",
"}",
"\n\n",
"expire",
":=",
"mw",
".",
"TimeFunc",
"(",
")",
".",
"Add",
"(",
"mw",
".",
"Timeout",
")",
"\n",
"newClaims",
"[",
"\"",
"\"",
"]",
"=",
"expire",
".",
"Unix",
"(",
")",
"\n",
"newClaims",
"[",
"\"",
"\"",
"]",
"=",
"mw",
".",
"TimeFunc",
"(",
")",
".",
"Unix",
"(",
")",
"\n",
"tokenString",
",",
"err",
":=",
"mw",
".",
"signedString",
"(",
"newToken",
")",
"\n\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\"",
"\"",
",",
"time",
".",
"Now",
"(",
")",
",",
"err",
"\n",
"}",
"\n\n",
"// set cookie",
"if",
"mw",
".",
"SendCookie",
"{",
"maxage",
":=",
"int",
"(",
"expire",
".",
"Unix",
"(",
")",
"-",
"time",
".",
"Now",
"(",
")",
".",
"Unix",
"(",
")",
")",
"\n",
"c",
".",
"SetCookie",
"(",
"mw",
".",
"CookieName",
",",
"tokenString",
",",
"maxage",
",",
"\"",
"\"",
",",
"mw",
".",
"CookieDomain",
",",
"mw",
".",
"SecureCookie",
",",
"mw",
".",
"CookieHTTPOnly",
",",
")",
"\n",
"}",
"\n\n",
"return",
"tokenString",
",",
"expire",
",",
"nil",
"\n",
"}"
] | // 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 |
148,929 | 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",
"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",
")",
"\n",
"if",
"!",
"ok",
"||",
"validationErr",
".",
"Errors",
"!=",
"jwt",
".",
"ValidationErrorExpired",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"}",
"\n\n",
"claims",
":=",
"token",
".",
"Claims",
".",
"(",
"jwt",
".",
"MapClaims",
")",
"\n\n",
"origIat",
":=",
"int64",
"(",
"claims",
"[",
"\"",
"\"",
"]",
".",
"(",
"float64",
")",
")",
"\n\n",
"if",
"origIat",
"<",
"mw",
".",
"TimeFunc",
"(",
")",
".",
"Add",
"(",
"-",
"mw",
".",
"MaxRefresh",
")",
".",
"Unix",
"(",
")",
"{",
"return",
"nil",
",",
"ErrExpiredToken",
"\n",
"}",
"\n\n",
"return",
"claims",
",",
"nil",
"\n",
"}"
] | // CheckIfTokenExpire check if token expire | [
"CheckIfTokenExpire",
"check",
"if",
"token",
"expire"
] | 633d983b91f09beefb1128c4558d4642a379c602 | https://github.com/appleboy/gin-jwt/blob/633d983b91f09beefb1128c4558d4642a379c602/auth_jwt.go#L526-L550 |
148,930 | 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",
"(",
"mw",
".",
"SigningAlgorithm",
")",
")",
"\n",
"claims",
":=",
"token",
".",
"Claims",
".",
"(",
"jwt",
".",
"MapClaims",
")",
"\n\n",
"if",
"mw",
".",
"PayloadFunc",
"!=",
"nil",
"{",
"for",
"key",
",",
"value",
":=",
"range",
"mw",
".",
"PayloadFunc",
"(",
"data",
")",
"{",
"claims",
"[",
"key",
"]",
"=",
"value",
"\n",
"}",
"\n",
"}",
"\n\n",
"expire",
":=",
"mw",
".",
"TimeFunc",
"(",
")",
".",
"UTC",
"(",
")",
".",
"Add",
"(",
"mw",
".",
"Timeout",
")",
"\n",
"claims",
"[",
"\"",
"\"",
"]",
"=",
"expire",
".",
"Unix",
"(",
")",
"\n",
"claims",
"[",
"\"",
"\"",
"]",
"=",
"mw",
".",
"TimeFunc",
"(",
")",
".",
"Unix",
"(",
")",
"\n",
"tokenString",
",",
"err",
":=",
"mw",
".",
"signedString",
"(",
"token",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\"",
"\"",
",",
"time",
".",
"Time",
"{",
"}",
",",
"err",
"\n",
"}",
"\n\n",
"return",
"tokenString",
",",
"expire",
",",
"nil",
"\n",
"}"
] | // 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 |
148,931 | 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",
".",
"Split",
"(",
"mw",
".",
"TokenLookup",
",",
"\"",
"\"",
")",
"\n",
"for",
"_",
",",
"method",
":=",
"range",
"methods",
"{",
"if",
"len",
"(",
"token",
")",
">",
"0",
"{",
"break",
"\n",
"}",
"\n",
"parts",
":=",
"strings",
".",
"Split",
"(",
"strings",
".",
"TrimSpace",
"(",
"method",
")",
",",
"\"",
"\"",
")",
"\n",
"k",
":=",
"strings",
".",
"TrimSpace",
"(",
"parts",
"[",
"0",
"]",
")",
"\n",
"v",
":=",
"strings",
".",
"TrimSpace",
"(",
"parts",
"[",
"1",
"]",
")",
"\n",
"switch",
"k",
"{",
"case",
"\"",
"\"",
":",
"token",
",",
"err",
"=",
"mw",
".",
"jwtFromHeader",
"(",
"c",
",",
"v",
")",
"\n",
"case",
"\"",
"\"",
":",
"token",
",",
"err",
"=",
"mw",
".",
"jwtFromQuery",
"(",
"c",
",",
"v",
")",
"\n",
"case",
"\"",
"\"",
":",
"token",
",",
"err",
"=",
"mw",
".",
"jwtFromCookie",
"(",
"c",
",",
"v",
")",
"\n",
"case",
"\"",
"\"",
":",
"token",
",",
"err",
"=",
"mw",
".",
"jwtFromParam",
"(",
"c",
",",
"v",
")",
"\n",
"}",
"\n",
"}",
"\n\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"return",
"jwt",
".",
"Parse",
"(",
"token",
",",
"func",
"(",
"t",
"*",
"jwt",
".",
"Token",
")",
"(",
"interface",
"{",
"}",
",",
"error",
")",
"{",
"if",
"jwt",
".",
"GetSigningMethod",
"(",
"mw",
".",
"SigningAlgorithm",
")",
"!=",
"t",
".",
"Method",
"{",
"return",
"nil",
",",
"ErrInvalidSigningAlgorithm",
"\n",
"}",
"\n",
"if",
"mw",
".",
"usingPublicKeyAlgo",
"(",
")",
"{",
"return",
"mw",
".",
"pubKey",
",",
"nil",
"\n",
"}",
"\n\n",
"// save token string if vaild",
"c",
".",
"Set",
"(",
"\"",
"\"",
",",
"token",
")",
"\n\n",
"return",
"mw",
".",
"Key",
",",
"nil",
"\n",
"}",
")",
"\n",
"}"
] | // 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 |
148,932 | 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",
")",
"(",
"interface",
"{",
"}",
",",
"error",
")",
"{",
"if",
"jwt",
".",
"GetSigningMethod",
"(",
"mw",
".",
"SigningAlgorithm",
")",
"!=",
"t",
".",
"Method",
"{",
"return",
"nil",
",",
"ErrInvalidSigningAlgorithm",
"\n",
"}",
"\n",
"if",
"mw",
".",
"usingPublicKeyAlgo",
"(",
")",
"{",
"return",
"mw",
".",
"pubKey",
",",
"nil",
"\n",
"}",
"\n\n",
"return",
"mw",
".",
"Key",
",",
"nil",
"\n",
"}",
")",
"\n",
"}"
] | // ParseTokenString parse jwt token string | [
"ParseTokenString",
"parse",
"jwt",
"token",
"string"
] | 633d983b91f09beefb1128c4558d4642a379c602 | https://github.com/appleboy/gin-jwt/blob/633d983b91f09beefb1128c4558d4642a379c602/auth_jwt.go#L664-L675 |
148,933 | 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",
"return",
"claims",
".",
"(",
"MapClaims",
")",
"\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 |
148,934 | 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",
",",
"value",
":=",
"range",
"token",
".",
"Claims",
".",
"(",
"jwt",
".",
"MapClaims",
")",
"{",
"claims",
"[",
"key",
"]",
"=",
"value",
"\n",
"}",
"\n\n",
"return",
"claims",
"\n",
"}"
] | // 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 |
148,935 | 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",
".",
"(",
"string",
")",
"\n",
"}"
] | // 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 |
148,936 | 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",
"(",
")",
"\n",
"case",
"2",
":",
"return",
"SafariUserAgent",
"(",
")",
"\n",
"case",
"3",
":",
"return",
"OperaUserAgent",
"(",
")",
"\n",
"default",
":",
"return",
"ChromeUserAgent",
"(",
")",
"\n",
"}",
"\n",
"}"
] | // 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 |
148,937 | 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",
":=",
"strconv",
".",
"Itoa",
"(",
"randIntRange",
"(",
"36",
",",
"40",
")",
")",
"\n",
"randNum3",
":=",
"strconv",
".",
"Itoa",
"(",
"randIntRange",
"(",
"800",
",",
"899",
")",
")",
"\n",
"return",
"\"",
"\"",
"+",
"\"",
"\"",
"+",
"randomPlatform",
"(",
")",
"+",
"\"",
"\"",
"+",
"randNum1",
"+",
"\"",
"\"",
"+",
"randNum2",
"+",
"\"",
"\"",
"+",
"randNum3",
"+",
"\"",
"\"",
"+",
"randNum1",
"\n",
"}"
] | // 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 |
148,938 | 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",
")",
")",
"+",
"\"",
"\"",
"\n",
"platforms",
":=",
"[",
"]",
"string",
"{",
"\"",
"\"",
"+",
"windowsPlatformToken",
"(",
")",
"+",
"\"",
"\"",
"+",
"\"",
"\"",
"+",
"\"",
"\"",
"+",
"strconv",
".",
"Itoa",
"(",
"randIntRange",
"(",
"0",
",",
"3",
")",
")",
"+",
"\"",
"\"",
"+",
"ver",
",",
"\"",
"\"",
"+",
"linuxPlatformToken",
"(",
")",
"+",
"\"",
"\"",
"+",
"strconv",
".",
"Itoa",
"(",
"randIntRange",
"(",
"5",
",",
"8",
")",
")",
"+",
"\"",
"\"",
"+",
"ver",
",",
"\"",
"\"",
"+",
"macPlatformToken",
"(",
")",
"+",
"\"",
"\"",
"+",
"strconv",
".",
"Itoa",
"(",
"randIntRange",
"(",
"2",
",",
"7",
")",
")",
"+",
"\"",
"\"",
"+",
"ver",
",",
"}",
"\n\n",
"return",
"\"",
"\"",
"+",
"RandString",
"(",
"platforms",
")",
"\n",
"}"
] | // 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 |
148,939 | 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",
")",
")",
"+",
"\"",
"\"",
"+",
"strconv",
".",
"Itoa",
"(",
"randIntRange",
"(",
"1",
",",
"8",
")",
")",
"\n",
"ver",
":=",
"strconv",
".",
"Itoa",
"(",
"randIntRange",
"(",
"4",
",",
"6",
")",
")",
"+",
"\"",
"\"",
"+",
"strconv",
".",
"Itoa",
"(",
"randIntRange",
"(",
"0",
",",
"2",
")",
")",
"\n\n",
"mobileDevices",
":=",
"[",
"]",
"string",
"{",
"\"",
"\"",
",",
"\"",
"\"",
",",
"}",
"\n\n",
"platforms",
":=",
"[",
"]",
"string",
"{",
"\"",
"\"",
"+",
"windowsPlatformToken",
"(",
")",
"+",
"\"",
"\"",
"+",
"randNum",
"+",
"\"",
"\"",
"+",
"ver",
"+",
"\"",
"\"",
"+",
"randNum",
",",
"\"",
"\"",
"+",
"macPlatformToken",
"(",
")",
"+",
"\"",
"\"",
"+",
"strconv",
".",
"Itoa",
"(",
"randIntRange",
"(",
"4",
",",
"7",
")",
")",
"+",
"\"",
"\"",
"+",
"randNum",
"+",
"\"",
"\"",
"+",
"ver",
"+",
"\"",
"\"",
"+",
"randNum",
",",
"\"",
"\"",
"+",
"RandString",
"(",
"mobileDevices",
")",
"+",
"\"",
"\"",
"+",
"strconv",
".",
"Itoa",
"(",
"randIntRange",
"(",
"7",
",",
"9",
")",
")",
"+",
"\"",
"\"",
"+",
"strconv",
".",
"Itoa",
"(",
"randIntRange",
"(",
"0",
",",
"3",
")",
")",
"+",
"\"",
"\"",
"+",
"strconv",
".",
"Itoa",
"(",
"randIntRange",
"(",
"1",
",",
"3",
")",
")",
"+",
"\"",
"\"",
"+",
"\"",
"\"",
"+",
"\"",
"\"",
"+",
"randNum",
"+",
"\"",
"\"",
"+",
"strconv",
".",
"Itoa",
"(",
"randIntRange",
"(",
"3",
",",
"5",
")",
")",
"+",
"\"",
"\"",
"+",
"strconv",
".",
"Itoa",
"(",
"randIntRange",
"(",
"111",
",",
"120",
")",
")",
"+",
"\"",
"\"",
"+",
"randNum",
",",
"}",
"\n\n",
"return",
"\"",
"\"",
"+",
"RandString",
"(",
"platforms",
")",
"\n",
"}"
] | // 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 |
148,940 | 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",
".",
"Itoa",
"(",
"randIntRange",
"(",
"160",
",",
"355",
")",
")",
"+",
"\"",
"\"",
"+",
"strconv",
".",
"Itoa",
"(",
"randIntRange",
"(",
"10",
",",
"13",
")",
")",
"+",
"\"",
"\"",
"\n\n",
"return",
"\"",
"\"",
"+",
"strconv",
".",
"Itoa",
"(",
"randIntRange",
"(",
"8",
",",
"10",
")",
")",
"+",
"\"",
"\"",
"+",
"strconv",
".",
"Itoa",
"(",
"randIntRange",
"(",
"10",
",",
"99",
")",
")",
"+",
"\"",
"\"",
"+",
"platform",
"\n",
"}"
] | // 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 |
148,941 | 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",
",",
"9",
")",
")",
"+",
"\"",
"\"",
"+",
"strconv",
".",
"Itoa",
"(",
"randIntRange",
"(",
"0",
",",
"10",
")",
")",
"\n",
"}"
] | // 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 |
148,942 | 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",
":",
"street",
"+",
"\"",
"\"",
"+",
"city",
"+",
"\"",
"\"",
"+",
"state",
"+",
"\"",
"\"",
"+",
"zip",
",",
"Street",
":",
"street",
",",
"City",
":",
"city",
",",
"State",
":",
"state",
",",
"Zip",
":",
"zip",
",",
"Country",
":",
"Country",
"(",
")",
",",
"Latitude",
":",
"Latitude",
"(",
")",
",",
"Longitude",
":",
"Longitude",
"(",
")",
",",
"}",
"\n",
"}"
] | // 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 |
148,943 | 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",
"(",
")",
"+",
"\"",
"\"",
"+",
"StreetName",
"(",
")",
"+",
"StreetSuffix",
"(",
")",
"\n",
"case",
"2",
":",
"street",
"=",
"StreetNumber",
"(",
")",
"+",
"\"",
"\"",
"+",
"StreetName",
"(",
")",
"+",
"StreetSuffix",
"(",
")",
"\n",
"}",
"\n\n",
"return",
"\n",
"}"
] | // 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 |
148,944 | 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",
"2",
":",
"city",
"=",
"LastName",
"(",
")",
"+",
"StreetSuffix",
"(",
")",
"\n",
"case",
"3",
":",
"city",
"=",
"StreetPrefix",
"(",
")",
"+",
"\"",
"\"",
"+",
"LastName",
"(",
")",
"\n",
"}",
"\n\n",
"return",
"\n",
"}"
] | // 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 |
148,945 | 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",
"{",
"return",
"0",
",",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"return",
"randFloat64Range",
"(",
"min",
",",
"max",
")",
",",
"nil",
"\n",
"}"
] | // 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 |
148,946 | 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",
"]",
"]",
"[",
"dataVal",
"[",
"1",
"]",
"]",
"[",
"rand",
".",
"Intn",
"(",
"len",
"(",
"data",
".",
"Data",
"[",
"dataVal",
"[",
"0",
"]",
"]",
"[",
"dataVal",
"[",
"1",
"]",
"]",
")",
")",
"]",
"\n",
"}"
] | // Get Random Value | [
"Get",
"Random",
"Value"
] | a5ac7cef41d64b726c51e8826e02dad0c34f55b4 | https://github.com/brianvoe/gofakeit/blob/a5ac7cef41d64b726c51e8826e02dad0c34f55b4/misc.go#L41-L46 |
148,947 | 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",
"[",
"1",
"]",
"]",
"[",
"rand",
".",
"Intn",
"(",
"len",
"(",
"data",
".",
"IntData",
"[",
"dataVal",
"[",
"0",
"]",
"]",
"[",
"dataVal",
"[",
"1",
"]",
"]",
")",
")",
"]",
"\n",
"}"
] | // Get Random Integer Value | [
"Get",
"Random",
"Integer",
"Value"
] | a5ac7cef41d64b726c51e8826e02dad0c34f55b4 | https://github.com/brianvoe/gofakeit/blob/a5ac7cef41d64b726c51e8826e02dad0c34f55b4/misc.go#L49-L54 |
148,948 | 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",
"(",
"bytestr",
")",
";",
"i",
"++",
"{",
"if",
"bytestr",
"[",
"i",
"]",
"==",
"questionmark",
"{",
"bytestr",
"[",
"i",
"]",
"=",
"byte",
"(",
"randLetter",
"(",
")",
")",
"\n",
"}",
"\n",
"}",
"\n\n",
"return",
"string",
"(",
"bytestr",
")",
"\n",
"}"
] | // Replace ? with ASCII lowercase letters | [
"Replace",
"?",
"with",
"ASCII",
"lowercase",
"letters"
] | a5ac7cef41d64b726c51e8826e02dad0c34f55b4 | https://github.com/brianvoe/gofakeit/blob/a5ac7cef41d64b726c51e8826e02dad0c34f55b4/misc.go#L75-L87 |
148,949 | 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 |
148,950 | 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",
"{",
"subCategories",
":=",
"make",
"(",
"[",
"]",
"string",
",",
"0",
")",
"\n",
"for",
"subType",
":=",
"range",
"subCategoriesMap",
"{",
"subCategories",
"=",
"append",
"(",
"subCategories",
",",
"subType",
")",
"\n",
"}",
"\n",
"types",
"[",
"category",
"]",
"=",
"subCategories",
"\n",
"}",
"\n",
"return",
"types",
"\n",
"}"
] | // 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 |
148,951 | 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",
"=",
"5",
"\n",
"}",
"\n",
"i",
":=",
"0",
"\n",
"b",
":=",
"make",
"(",
"[",
"]",
"byte",
",",
"num",
")",
"\n",
"var",
"passString",
"string",
"\n\n",
"if",
"lower",
"{",
"passString",
"+=",
"lowerStr",
"\n",
"b",
"[",
"i",
"]",
"=",
"lowerStr",
"[",
"rand",
".",
"Int63",
"(",
")",
"%",
"int64",
"(",
"len",
"(",
"lowerStr",
")",
")",
"]",
"\n",
"i",
"++",
"\n",
"}",
"\n",
"if",
"upper",
"{",
"passString",
"+=",
"upperStr",
"\n",
"b",
"[",
"i",
"]",
"=",
"upperStr",
"[",
"rand",
".",
"Int63",
"(",
")",
"%",
"int64",
"(",
"len",
"(",
"upperStr",
")",
")",
"]",
"\n",
"i",
"++",
"\n",
"}",
"\n",
"if",
"numeric",
"{",
"passString",
"+=",
"numericStr",
"\n",
"b",
"[",
"i",
"]",
"=",
"numericStr",
"[",
"rand",
".",
"Int63",
"(",
")",
"%",
"int64",
"(",
"len",
"(",
"numericStr",
")",
")",
"]",
"\n",
"i",
"++",
"\n",
"}",
"\n",
"if",
"special",
"{",
"passString",
"+=",
"specialStr",
"\n",
"b",
"[",
"i",
"]",
"=",
"specialStr",
"[",
"rand",
".",
"Int63",
"(",
")",
"%",
"int64",
"(",
"len",
"(",
"specialStr",
")",
")",
"]",
"\n",
"i",
"++",
"\n",
"}",
"\n",
"if",
"space",
"{",
"passString",
"+=",
"spaceStr",
"\n",
"b",
"[",
"i",
"]",
"=",
"spaceStr",
"[",
"rand",
".",
"Int63",
"(",
")",
"%",
"int64",
"(",
"len",
"(",
"spaceStr",
")",
")",
"]",
"\n",
"i",
"++",
"\n",
"}",
"\n\n",
"// Set default if empty",
"if",
"passString",
"==",
"\"",
"\"",
"{",
"passString",
"=",
"lowerStr",
"+",
"numericStr",
"\n",
"}",
"\n\n",
"// Loop through and add it up",
"for",
"i",
"<=",
"num",
"-",
"1",
"{",
"b",
"[",
"i",
"]",
"=",
"passString",
"[",
"rand",
".",
"Int63",
"(",
")",
"%",
"int64",
"(",
"len",
"(",
"passString",
")",
")",
"]",
"\n",
"i",
"++",
"\n",
"}",
"\n\n",
"// Shuffle bytes",
"for",
"i",
":=",
"range",
"b",
"{",
"j",
":=",
"rand",
".",
"Intn",
"(",
"i",
"+",
"1",
")",
"\n",
"b",
"[",
"i",
"]",
",",
"b",
"[",
"j",
"]",
"=",
"b",
"[",
"j",
"]",
",",
"b",
"[",
"i",
"]",
"\n",
"}",
"\n\n",
"return",
"string",
"(",
"b",
")",
"\n",
"}"
] | // 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 |
148,952 | 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",
".",
"Data",
"[",
"\"",
"\"",
"]",
"[",
"\"",
"\"",
"]",
"[",
"index",
"]",
",",
"Long",
":",
"data",
".",
"Data",
"[",
"\"",
"\"",
"]",
"[",
"\"",
"\"",
"]",
"[",
"index",
"]",
",",
"}",
"\n",
"}"
] | // 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 |
148,953 | 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 |
148,954 | 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",
",",
"wordCount",
",",
"separator",
"}",
",",
"Sentence",
")",
"\n",
"}"
] | // 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 |
148,955 | 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",
":",
"CreditCardCvv",
"(",
")",
",",
"}",
"\n",
"}"
] | // 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 |
148,956 | 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",
"integer",
"\n",
"}"
] | // 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 |
148,957 | 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",
"{",
"\"",
"\"",
",",
"\"",
"\"",
"}",
")",
")",
"\n",
"if",
"luhn",
"(",
"cc",
")",
"{",
"break",
"\n",
"}",
"\n",
"}",
"\n",
"integer",
",",
"_",
":=",
"strconv",
".",
"Atoi",
"(",
"cc",
")",
"\n",
"return",
"integer",
"\n",
"}"
] | // 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 |
148,958 | 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",
"}",
"\n",
"return",
"month",
"+",
"\"",
"\"",
"+",
"strconv",
".",
"Itoa",
"(",
"randIntRange",
"(",
"currentYear",
"+",
"1",
",",
"currentYear",
"+",
"10",
")",
")",
"\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 |
148,959 | 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",
")",
"&",
"1",
"\n",
"var",
"sum",
"int",
"\n",
"for",
"i",
",",
"c",
":=",
"range",
"s",
"{",
"if",
"c",
"<",
"'0'",
"||",
"c",
">",
"'9'",
"{",
"return",
"false",
"\n",
"}",
"\n",
"if",
"i",
"&",
"1",
"==",
"odd",
"{",
"sum",
"+=",
"t",
"[",
"c",
"-",
"'0'",
"]",
"\n",
"}",
"else",
"{",
"sum",
"+=",
"int",
"(",
"c",
"-",
"'0'",
")",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"sum",
"%",
"10",
"==",
"0",
"\n",
"}"
] | // 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 |
148,960 | 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",
"++",
"{",
"color",
"[",
"i",
"]",
"=",
"hashQuestion",
"[",
"rand",
".",
"Intn",
"(",
"2",
")",
"]",
"\n",
"}",
"\n\n",
"return",
"\"",
"\"",
"+",
"replaceWithLetters",
"(",
"replaceWithNumbers",
"(",
"string",
"(",
"color",
")",
")",
")",
"\n\n",
"// color := \"\"",
"// for i := 1; i <= 6; i++ {",
"// \tcolor += RandString([]string{\"?\", \"#\"})",
"// }",
"// // Replace # with number",
"// color = replaceWithNumbers(color)",
"// // Replace ? with letter",
"// for strings.Count(color, \"?\") > 0 {",
"// \tcolor = strings.Replace(color, \"?\", RandString(letters), 1)",
"// }",
"// return \"#\" + color",
"}"
] | // 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 |
148,961 | 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",
"//to avoid upgrading to 1.10 I copied the algorithm",
"n",
":=",
"len",
"(",
"a",
")",
"\n",
"if",
"n",
"<=",
"1",
"{",
"return",
"\n",
"}",
"\n\n",
"//if size is > int32 probably it will never finish, or ran out of entropy",
"i",
":=",
"n",
"-",
"1",
"\n",
"for",
";",
"i",
">",
"0",
";",
"i",
"--",
"{",
"j",
":=",
"int",
"(",
"rand",
".",
"Int31n",
"(",
"int32",
"(",
"i",
"+",
"1",
")",
")",
")",
"\n",
"swap",
"(",
"i",
",",
"j",
")",
"\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 |
148,962 | 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",
")",
"]",
"\n",
"}"
] | // 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 |
148,963 | 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",
":",
"CarMaker",
"(",
")",
",",
"Model",
":",
"CarModel",
"(",
")",
",",
"Year",
":",
"Year",
"(",
")",
",",
"}",
"\n\n",
"}"
] | // 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 |
148,964 | 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",
",",
"wordCount",
",",
"separator",
"}",
",",
"HipsterSentence",
")",
"\n",
"}"
] | // 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 |
148,965 | 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",
"]",
"=",
"strings",
".",
"Title",
"(",
"words",
"[",
"0",
"]",
")",
"\n",
"return",
"strings",
".",
"Join",
"(",
"words",
",",
"\"",
"\"",
")",
"\n",
"}"
] | // 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 |
148,966 | 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",
"]",
",",
"a",
"[",
"i",
"]",
"\n",
"}",
"\n",
"}"
] | // 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 |
148,967 | 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",
"(",
")",
",",
"}",
"\n",
"}"
] | // 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 |
148,968 | 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",
"{",
"\"",
"\"",
",",
"\"",
"\"",
"}",
")",
"\n",
"email",
"+=",
"\"",
"\"",
"\n",
"email",
"+=",
"getRandValue",
"(",
"[",
"]",
"string",
"{",
"\"",
"\"",
",",
"\"",
"\"",
"}",
")",
"+",
"\"",
"\"",
"+",
"getRandValue",
"(",
"[",
"]",
"string",
"{",
"\"",
"\"",
",",
"\"",
"\"",
"}",
")",
"\n\n",
"return",
"strings",
".",
"ToLower",
"(",
"email",
")",
"\n",
"}"
] | // 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 |
148,969 | 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",
"(",
")",
",",
"Image",
":",
"ImageURL",
"(",
"300",
",",
"300",
")",
"+",
"\"",
"\"",
",",
"Job",
":",
"Job",
"(",
")",
",",
"Address",
":",
"Address",
"(",
")",
",",
"Contact",
":",
"Contact",
"(",
")",
",",
"CreditCard",
":",
"CreditCard",
"(",
")",
",",
"}",
"\n",
"}"
] | // 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 |
148,970 | 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",
"(",
")",
"+",
"\"",
"\"",
"+",
"LastName",
"(",
")",
"\n",
"case",
"2",
":",
"company",
"=",
"LastName",
"(",
")",
"+",
"\"",
"\"",
"+",
"LastName",
"(",
")",
"\n",
"case",
"3",
":",
"company",
"=",
"LastName",
"(",
")",
"+",
"\"",
"\"",
"+",
"CompanySuffix",
"(",
")",
"\n",
"}",
"\n\n",
"return",
"\n",
"}"
] | // 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 |
148,971 | 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",
"(",
")",
",",
"Second",
"(",
")",
",",
"NanoSecond",
"(",
")",
",",
"time",
".",
"UTC",
")",
"\n",
"}"
] | // 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 |
148,972 | 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",
"(",
"end",
".",
"UnixNano",
"(",
")",
")",
")",
")",
")",
".",
"UTC",
"(",
")",
"\n",
"}"
] | // 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 |
148,973 | brianvoe/gofakeit | datetime.go | TimeZoneOffset | func TimeZoneOffset() float32 {
value, _ := strconv.ParseFloat(getRandValue([]string{"timezone", "offset"}), 32)
return float32(value)
} | go | func TimeZoneOffset() float32 {
value, _ := strconv.ParseFloat(getRandValue([]string{"timezone", "offset"}), 32)
return float32(value)
} | [
"func",
"TimeZoneOffset",
"(",
")",
"float32",
"{",
"value",
",",
"_",
":=",
"strconv",
".",
"ParseFloat",
"(",
"getRandValue",
"(",
"[",
"]",
"string",
"{",
"\"",
"\"",
",",
"\"",
"\"",
"}",
")",
",",
"32",
")",
"\n",
"return",
"float32",
"(",
"value",
")",
"\n",
"}"
] | // TimeZoneOffset will select a random timezone offset | [
"TimeZoneOffset",
"will",
"select",
"a",
"random",
"timezone",
"offset"
] | a5ac7cef41d64b726c51e8826e02dad0c34f55b4 | https://github.com/brianvoe/gofakeit/blob/a5ac7cef41d64b726c51e8826e02dad0c34f55b4/datetime.go#L74-L77 |
148,974 | brianvoe/gofakeit | internet.go | URL | func URL() string {
url := "http" + RandString([]string{"s", ""}) + "://www."
url += DomainName()
// Slugs
num := Number(1, 4)
slug := make([]string, num)
for i := 0; i < num; i++ {
slug[i] = BS()
}
url += "/" + strings.ToLower(strings.Join(slug, "/"))
return url
} | go | func URL() string {
url := "http" + RandString([]string{"s", ""}) + "://www."
url += DomainName()
// Slugs
num := Number(1, 4)
slug := make([]string, num)
for i := 0; i < num; i++ {
slug[i] = BS()
}
url += "/" + strings.ToLower(strings.Join(slug, "/"))
return url
} | [
"func",
"URL",
"(",
")",
"string",
"{",
"url",
":=",
"\"",
"\"",
"+",
"RandString",
"(",
"[",
"]",
"string",
"{",
"\"",
"\"",
",",
"\"",
"\"",
"}",
")",
"+",
"\"",
"\"",
"\n",
"url",
"+=",
"DomainName",
"(",
")",
"\n\n",
"// Slugs",
"num",
":=",
"Number",
"(",
"1",
",",
"4",
")",
"\n",
"slug",
":=",
"make",
"(",
"[",
"]",
"string",
",",
"num",
")",
"\n",
"for",
"i",
":=",
"0",
";",
"i",
"<",
"num",
";",
"i",
"++",
"{",
"slug",
"[",
"i",
"]",
"=",
"BS",
"(",
")",
"\n",
"}",
"\n",
"url",
"+=",
"\"",
"\"",
"+",
"strings",
".",
"ToLower",
"(",
"strings",
".",
"Join",
"(",
"slug",
",",
"\"",
"\"",
")",
")",
"\n\n",
"return",
"url",
"\n",
"}"
] | // URL will generate a random url string | [
"URL",
"will",
"generate",
"a",
"random",
"url",
"string"
] | a5ac7cef41d64b726c51e8826e02dad0c34f55b4 | https://github.com/brianvoe/gofakeit/blob/a5ac7cef41d64b726c51e8826e02dad0c34f55b4/internet.go#L20-L33 |
148,975 | brianvoe/gofakeit | internet.go | IPv4Address | func IPv4Address() string {
num := func() int { return 2 + rand.Intn(254) }
return fmt.Sprintf("%d.%d.%d.%d", num(), num(), num(), num())
} | go | func IPv4Address() string {
num := func() int { return 2 + rand.Intn(254) }
return fmt.Sprintf("%d.%d.%d.%d", num(), num(), num(), num())
} | [
"func",
"IPv4Address",
"(",
")",
"string",
"{",
"num",
":=",
"func",
"(",
")",
"int",
"{",
"return",
"2",
"+",
"rand",
".",
"Intn",
"(",
"254",
")",
"}",
"\n",
"return",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"num",
"(",
")",
",",
"num",
"(",
")",
",",
"num",
"(",
")",
",",
"num",
"(",
")",
")",
"\n",
"}"
] | // IPv4Address will generate a random version 4 ip address | [
"IPv4Address",
"will",
"generate",
"a",
"random",
"version",
"4",
"ip",
"address"
] | a5ac7cef41d64b726c51e8826e02dad0c34f55b4 | https://github.com/brianvoe/gofakeit/blob/a5ac7cef41d64b726c51e8826e02dad0c34f55b4/internet.go#L41-L44 |
148,976 | brianvoe/gofakeit | internet.go | IPv6Address | func IPv6Address() string {
num := 65536
return fmt.Sprintf("2001:cafe:%x:%x:%x:%x:%x:%x", rand.Intn(num), rand.Intn(num), rand.Intn(num), rand.Intn(num), rand.Intn(num), rand.Intn(num))
} | go | func IPv6Address() string {
num := 65536
return fmt.Sprintf("2001:cafe:%x:%x:%x:%x:%x:%x", rand.Intn(num), rand.Intn(num), rand.Intn(num), rand.Intn(num), rand.Intn(num), rand.Intn(num))
} | [
"func",
"IPv6Address",
"(",
")",
"string",
"{",
"num",
":=",
"65536",
"\n",
"return",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"rand",
".",
"Intn",
"(",
"num",
")",
",",
"rand",
".",
"Intn",
"(",
"num",
")",
",",
"rand",
".",
"Intn",
"(",
"num",
")",
",",
"rand",
".",
"Intn",
"(",
"num",
")",
",",
"rand",
".",
"Intn",
"(",
"num",
")",
",",
"rand",
".",
"Intn",
"(",
"num",
")",
")",
"\n",
"}"
] | // IPv6Address will generate a random version 6 ip address | [
"IPv6Address",
"will",
"generate",
"a",
"random",
"version",
"6",
"ip",
"address"
] | a5ac7cef41d64b726c51e8826e02dad0c34f55b4 | https://github.com/brianvoe/gofakeit/blob/a5ac7cef41d64b726c51e8826e02dad0c34f55b4/internet.go#L47-L50 |
148,977 | gorilla/handlers | cors.go | AllowedMethods | func AllowedMethods(methods []string) CORSOption {
return func(ch *cors) error {
ch.allowedMethods = []string{}
for _, v := range methods {
normalizedMethod := strings.ToUpper(strings.TrimSpace(v))
if normalizedMethod == "" {
continue
}
if !ch.isMatch(normalizedMethod, ch.allowedMethods) {
ch.allowedMethods = append(ch.allowedMethods, normalizedMethod)
}
}
return nil
}
} | go | func AllowedMethods(methods []string) CORSOption {
return func(ch *cors) error {
ch.allowedMethods = []string{}
for _, v := range methods {
normalizedMethod := strings.ToUpper(strings.TrimSpace(v))
if normalizedMethod == "" {
continue
}
if !ch.isMatch(normalizedMethod, ch.allowedMethods) {
ch.allowedMethods = append(ch.allowedMethods, normalizedMethod)
}
}
return nil
}
} | [
"func",
"AllowedMethods",
"(",
"methods",
"[",
"]",
"string",
")",
"CORSOption",
"{",
"return",
"func",
"(",
"ch",
"*",
"cors",
")",
"error",
"{",
"ch",
".",
"allowedMethods",
"=",
"[",
"]",
"string",
"{",
"}",
"\n",
"for",
"_",
",",
"v",
":=",
"range",
"methods",
"{",
"normalizedMethod",
":=",
"strings",
".",
"ToUpper",
"(",
"strings",
".",
"TrimSpace",
"(",
"v",
")",
")",
"\n",
"if",
"normalizedMethod",
"==",
"\"",
"\"",
"{",
"continue",
"\n",
"}",
"\n\n",
"if",
"!",
"ch",
".",
"isMatch",
"(",
"normalizedMethod",
",",
"ch",
".",
"allowedMethods",
")",
"{",
"ch",
".",
"allowedMethods",
"=",
"append",
"(",
"ch",
".",
"allowedMethods",
",",
"normalizedMethod",
")",
"\n",
"}",
"\n",
"}",
"\n\n",
"return",
"nil",
"\n",
"}",
"\n",
"}"
] | // AllowedMethods can be used to explicitly allow methods in the
// Access-Control-Allow-Methods header.
// This is a replacement operation so you must also
// pass GET, HEAD, and POST if you wish to support those methods. | [
"AllowedMethods",
"can",
"be",
"used",
"to",
"explicitly",
"allow",
"methods",
"in",
"the",
"Access",
"-",
"Control",
"-",
"Allow",
"-",
"Methods",
"header",
".",
"This",
"is",
"a",
"replacement",
"operation",
"so",
"you",
"must",
"also",
"pass",
"GET",
"HEAD",
"and",
"POST",
"if",
"you",
"wish",
"to",
"support",
"those",
"methods",
"."
] | ac6d24f88de4584385a0cb3a88f953d08a2f7a05 | https://github.com/gorilla/handlers/blob/ac6d24f88de4584385a0cb3a88f953d08a2f7a05/cors.go#L214-L230 |
148,978 | gorilla/handlers | cors.go | AllowedOriginValidator | func AllowedOriginValidator(fn OriginValidator) CORSOption {
return func(ch *cors) error {
ch.allowedOriginValidator = fn
return nil
}
} | go | func AllowedOriginValidator(fn OriginValidator) CORSOption {
return func(ch *cors) error {
ch.allowedOriginValidator = fn
return nil
}
} | [
"func",
"AllowedOriginValidator",
"(",
"fn",
"OriginValidator",
")",
"CORSOption",
"{",
"return",
"func",
"(",
"ch",
"*",
"cors",
")",
"error",
"{",
"ch",
".",
"allowedOriginValidator",
"=",
"fn",
"\n",
"return",
"nil",
"\n",
"}",
"\n",
"}"
] | // AllowedOriginValidator sets a function for evaluating allowed origins in CORS requests, represented by the
// 'Allow-Access-Control-Origin' HTTP header. | [
"AllowedOriginValidator",
"sets",
"a",
"function",
"for",
"evaluating",
"allowed",
"origins",
"in",
"CORS",
"requests",
"represented",
"by",
"the",
"Allow",
"-",
"Access",
"-",
"Control",
"-",
"Origin",
"HTTP",
"header",
"."
] | ac6d24f88de4584385a0cb3a88f953d08a2f7a05 | https://github.com/gorilla/handlers/blob/ac6d24f88de4584385a0cb3a88f953d08a2f7a05/cors.go#L251-L256 |
148,979 | gorilla/handlers | cors.go | ExposedHeaders | func ExposedHeaders(headers []string) CORSOption {
return func(ch *cors) error {
ch.exposedHeaders = []string{}
for _, v := range headers {
normalizedHeader := http.CanonicalHeaderKey(strings.TrimSpace(v))
if normalizedHeader == "" {
continue
}
if !ch.isMatch(normalizedHeader, ch.exposedHeaders) {
ch.exposedHeaders = append(ch.exposedHeaders, normalizedHeader)
}
}
return nil
}
} | go | func ExposedHeaders(headers []string) CORSOption {
return func(ch *cors) error {
ch.exposedHeaders = []string{}
for _, v := range headers {
normalizedHeader := http.CanonicalHeaderKey(strings.TrimSpace(v))
if normalizedHeader == "" {
continue
}
if !ch.isMatch(normalizedHeader, ch.exposedHeaders) {
ch.exposedHeaders = append(ch.exposedHeaders, normalizedHeader)
}
}
return nil
}
} | [
"func",
"ExposedHeaders",
"(",
"headers",
"[",
"]",
"string",
")",
"CORSOption",
"{",
"return",
"func",
"(",
"ch",
"*",
"cors",
")",
"error",
"{",
"ch",
".",
"exposedHeaders",
"=",
"[",
"]",
"string",
"{",
"}",
"\n",
"for",
"_",
",",
"v",
":=",
"range",
"headers",
"{",
"normalizedHeader",
":=",
"http",
".",
"CanonicalHeaderKey",
"(",
"strings",
".",
"TrimSpace",
"(",
"v",
")",
")",
"\n",
"if",
"normalizedHeader",
"==",
"\"",
"\"",
"{",
"continue",
"\n",
"}",
"\n\n",
"if",
"!",
"ch",
".",
"isMatch",
"(",
"normalizedHeader",
",",
"ch",
".",
"exposedHeaders",
")",
"{",
"ch",
".",
"exposedHeaders",
"=",
"append",
"(",
"ch",
".",
"exposedHeaders",
",",
"normalizedHeader",
")",
"\n",
"}",
"\n",
"}",
"\n\n",
"return",
"nil",
"\n",
"}",
"\n",
"}"
] | // ExposedHeaders can be used to specify headers that are available
// and will not be stripped out by the user-agent. | [
"ExposedHeaders",
"can",
"be",
"used",
"to",
"specify",
"headers",
"that",
"are",
"available",
"and",
"will",
"not",
"be",
"stripped",
"out",
"by",
"the",
"user",
"-",
"agent",
"."
] | ac6d24f88de4584385a0cb3a88f953d08a2f7a05 | https://github.com/gorilla/handlers/blob/ac6d24f88de4584385a0cb3a88f953d08a2f7a05/cors.go#L273-L289 |
148,980 | gorilla/handlers | logging.go | buildCommonLogLine | func buildCommonLogLine(req *http.Request, url url.URL, ts time.Time, status int, size int) []byte {
username := "-"
if url.User != nil {
if name := url.User.Username(); name != "" {
username = name
}
}
host, _, err := net.SplitHostPort(req.RemoteAddr)
if err != nil {
host = req.RemoteAddr
}
uri := req.RequestURI
// Requests using the CONNECT method over HTTP/2.0 must use
// the authority field (aka r.Host) to identify the target.
// Refer: https://httpwg.github.io/specs/rfc7540.html#CONNECT
if req.ProtoMajor == 2 && req.Method == "CONNECT" {
uri = req.Host
}
if uri == "" {
uri = url.RequestURI()
}
buf := make([]byte, 0, 3*(len(host)+len(username)+len(req.Method)+len(uri)+len(req.Proto)+50)/2)
buf = append(buf, host...)
buf = append(buf, " - "...)
buf = append(buf, username...)
buf = append(buf, " ["...)
buf = append(buf, ts.Format("02/Jan/2006:15:04:05 -0700")...)
buf = append(buf, `] "`...)
buf = append(buf, req.Method...)
buf = append(buf, " "...)
buf = appendQuoted(buf, uri)
buf = append(buf, " "...)
buf = append(buf, req.Proto...)
buf = append(buf, `" `...)
buf = append(buf, strconv.Itoa(status)...)
buf = append(buf, " "...)
buf = append(buf, strconv.Itoa(size)...)
return buf
} | go | func buildCommonLogLine(req *http.Request, url url.URL, ts time.Time, status int, size int) []byte {
username := "-"
if url.User != nil {
if name := url.User.Username(); name != "" {
username = name
}
}
host, _, err := net.SplitHostPort(req.RemoteAddr)
if err != nil {
host = req.RemoteAddr
}
uri := req.RequestURI
// Requests using the CONNECT method over HTTP/2.0 must use
// the authority field (aka r.Host) to identify the target.
// Refer: https://httpwg.github.io/specs/rfc7540.html#CONNECT
if req.ProtoMajor == 2 && req.Method == "CONNECT" {
uri = req.Host
}
if uri == "" {
uri = url.RequestURI()
}
buf := make([]byte, 0, 3*(len(host)+len(username)+len(req.Method)+len(uri)+len(req.Proto)+50)/2)
buf = append(buf, host...)
buf = append(buf, " - "...)
buf = append(buf, username...)
buf = append(buf, " ["...)
buf = append(buf, ts.Format("02/Jan/2006:15:04:05 -0700")...)
buf = append(buf, `] "`...)
buf = append(buf, req.Method...)
buf = append(buf, " "...)
buf = appendQuoted(buf, uri)
buf = append(buf, " "...)
buf = append(buf, req.Proto...)
buf = append(buf, `" `...)
buf = append(buf, strconv.Itoa(status)...)
buf = append(buf, " "...)
buf = append(buf, strconv.Itoa(size)...)
return buf
} | [
"func",
"buildCommonLogLine",
"(",
"req",
"*",
"http",
".",
"Request",
",",
"url",
"url",
".",
"URL",
",",
"ts",
"time",
".",
"Time",
",",
"status",
"int",
",",
"size",
"int",
")",
"[",
"]",
"byte",
"{",
"username",
":=",
"\"",
"\"",
"\n",
"if",
"url",
".",
"User",
"!=",
"nil",
"{",
"if",
"name",
":=",
"url",
".",
"User",
".",
"Username",
"(",
")",
";",
"name",
"!=",
"\"",
"\"",
"{",
"username",
"=",
"name",
"\n",
"}",
"\n",
"}",
"\n\n",
"host",
",",
"_",
",",
"err",
":=",
"net",
".",
"SplitHostPort",
"(",
"req",
".",
"RemoteAddr",
")",
"\n\n",
"if",
"err",
"!=",
"nil",
"{",
"host",
"=",
"req",
".",
"RemoteAddr",
"\n",
"}",
"\n\n",
"uri",
":=",
"req",
".",
"RequestURI",
"\n\n",
"// Requests using the CONNECT method over HTTP/2.0 must use",
"// the authority field (aka r.Host) to identify the target.",
"// Refer: https://httpwg.github.io/specs/rfc7540.html#CONNECT",
"if",
"req",
".",
"ProtoMajor",
"==",
"2",
"&&",
"req",
".",
"Method",
"==",
"\"",
"\"",
"{",
"uri",
"=",
"req",
".",
"Host",
"\n",
"}",
"\n",
"if",
"uri",
"==",
"\"",
"\"",
"{",
"uri",
"=",
"url",
".",
"RequestURI",
"(",
")",
"\n",
"}",
"\n\n",
"buf",
":=",
"make",
"(",
"[",
"]",
"byte",
",",
"0",
",",
"3",
"*",
"(",
"len",
"(",
"host",
")",
"+",
"len",
"(",
"username",
")",
"+",
"len",
"(",
"req",
".",
"Method",
")",
"+",
"len",
"(",
"uri",
")",
"+",
"len",
"(",
"req",
".",
"Proto",
")",
"+",
"50",
")",
"/",
"2",
")",
"\n",
"buf",
"=",
"append",
"(",
"buf",
",",
"host",
"...",
")",
"\n",
"buf",
"=",
"append",
"(",
"buf",
",",
"\"",
"\"",
"...",
")",
"\n",
"buf",
"=",
"append",
"(",
"buf",
",",
"username",
"...",
")",
"\n",
"buf",
"=",
"append",
"(",
"buf",
",",
"\"",
"\"",
"...",
")",
"\n",
"buf",
"=",
"append",
"(",
"buf",
",",
"ts",
".",
"Format",
"(",
"\"",
"\"",
")",
"...",
")",
"\n",
"buf",
"=",
"append",
"(",
"buf",
",",
"`] \"`",
"...",
")",
"\n",
"buf",
"=",
"append",
"(",
"buf",
",",
"req",
".",
"Method",
"...",
")",
"\n",
"buf",
"=",
"append",
"(",
"buf",
",",
"\"",
"\"",
"...",
")",
"\n",
"buf",
"=",
"appendQuoted",
"(",
"buf",
",",
"uri",
")",
"\n",
"buf",
"=",
"append",
"(",
"buf",
",",
"\"",
"\"",
"...",
")",
"\n",
"buf",
"=",
"append",
"(",
"buf",
",",
"req",
".",
"Proto",
"...",
")",
"\n",
"buf",
"=",
"append",
"(",
"buf",
",",
"`\" `",
"...",
")",
"\n",
"buf",
"=",
"append",
"(",
"buf",
",",
"strconv",
".",
"Itoa",
"(",
"status",
")",
"...",
")",
"\n",
"buf",
"=",
"append",
"(",
"buf",
",",
"\"",
"\"",
"...",
")",
"\n",
"buf",
"=",
"append",
"(",
"buf",
",",
"strconv",
".",
"Itoa",
"(",
"size",
")",
"...",
")",
"\n",
"return",
"buf",
"\n",
"}"
] | // buildCommonLogLine builds a log entry for req in Apache Common Log Format.
// ts is the timestamp with which the entry should be logged.
// status and size are used to provide the response HTTP status and size. | [
"buildCommonLogLine",
"builds",
"a",
"log",
"entry",
"for",
"req",
"in",
"Apache",
"Common",
"Log",
"Format",
".",
"ts",
"is",
"the",
"timestamp",
"with",
"which",
"the",
"entry",
"should",
"be",
"logged",
".",
"status",
"and",
"size",
"are",
"used",
"to",
"provide",
"the",
"response",
"HTTP",
"status",
"and",
"size",
"."
] | ac6d24f88de4584385a0cb3a88f953d08a2f7a05 | https://github.com/gorilla/handlers/blob/ac6d24f88de4584385a0cb3a88f953d08a2f7a05/logging.go#L151-L194 |
148,981 | gorilla/handlers | logging.go | writeLog | func writeLog(writer io.Writer, params LogFormatterParams) {
buf := buildCommonLogLine(params.Request, params.URL, params.TimeStamp, params.StatusCode, params.Size)
buf = append(buf, '\n')
writer.Write(buf)
} | go | func writeLog(writer io.Writer, params LogFormatterParams) {
buf := buildCommonLogLine(params.Request, params.URL, params.TimeStamp, params.StatusCode, params.Size)
buf = append(buf, '\n')
writer.Write(buf)
} | [
"func",
"writeLog",
"(",
"writer",
"io",
".",
"Writer",
",",
"params",
"LogFormatterParams",
")",
"{",
"buf",
":=",
"buildCommonLogLine",
"(",
"params",
".",
"Request",
",",
"params",
".",
"URL",
",",
"params",
".",
"TimeStamp",
",",
"params",
".",
"StatusCode",
",",
"params",
".",
"Size",
")",
"\n",
"buf",
"=",
"append",
"(",
"buf",
",",
"'\\n'",
")",
"\n",
"writer",
".",
"Write",
"(",
"buf",
")",
"\n",
"}"
] | // writeLog writes a log entry for req to w in Apache Common Log Format.
// ts is the timestamp with which the entry should be logged.
// status and size are used to provide the response HTTP status and size. | [
"writeLog",
"writes",
"a",
"log",
"entry",
"for",
"req",
"to",
"w",
"in",
"Apache",
"Common",
"Log",
"Format",
".",
"ts",
"is",
"the",
"timestamp",
"with",
"which",
"the",
"entry",
"should",
"be",
"logged",
".",
"status",
"and",
"size",
"are",
"used",
"to",
"provide",
"the",
"response",
"HTTP",
"status",
"and",
"size",
"."
] | ac6d24f88de4584385a0cb3a88f953d08a2f7a05 | https://github.com/gorilla/handlers/blob/ac6d24f88de4584385a0cb3a88f953d08a2f7a05/logging.go#L199-L203 |
148,982 | gorilla/handlers | logging.go | writeCombinedLog | func writeCombinedLog(writer io.Writer, params LogFormatterParams) {
buf := buildCommonLogLine(params.Request, params.URL, params.TimeStamp, params.StatusCode, params.Size)
buf = append(buf, ` "`...)
buf = appendQuoted(buf, params.Request.Referer())
buf = append(buf, `" "`...)
buf = appendQuoted(buf, params.Request.UserAgent())
buf = append(buf, '"', '\n')
writer.Write(buf)
} | go | func writeCombinedLog(writer io.Writer, params LogFormatterParams) {
buf := buildCommonLogLine(params.Request, params.URL, params.TimeStamp, params.StatusCode, params.Size)
buf = append(buf, ` "`...)
buf = appendQuoted(buf, params.Request.Referer())
buf = append(buf, `" "`...)
buf = appendQuoted(buf, params.Request.UserAgent())
buf = append(buf, '"', '\n')
writer.Write(buf)
} | [
"func",
"writeCombinedLog",
"(",
"writer",
"io",
".",
"Writer",
",",
"params",
"LogFormatterParams",
")",
"{",
"buf",
":=",
"buildCommonLogLine",
"(",
"params",
".",
"Request",
",",
"params",
".",
"URL",
",",
"params",
".",
"TimeStamp",
",",
"params",
".",
"StatusCode",
",",
"params",
".",
"Size",
")",
"\n",
"buf",
"=",
"append",
"(",
"buf",
",",
"` \"`",
"...",
")",
"\n",
"buf",
"=",
"appendQuoted",
"(",
"buf",
",",
"params",
".",
"Request",
".",
"Referer",
"(",
")",
")",
"\n",
"buf",
"=",
"append",
"(",
"buf",
",",
"`\" \"`",
"...",
")",
"\n",
"buf",
"=",
"appendQuoted",
"(",
"buf",
",",
"params",
".",
"Request",
".",
"UserAgent",
"(",
")",
")",
"\n",
"buf",
"=",
"append",
"(",
"buf",
",",
"'\"'",
",",
"'\\n'",
")",
"\n",
"writer",
".",
"Write",
"(",
"buf",
")",
"\n",
"}"
] | // writeCombinedLog writes a log entry for req to w in Apache Combined Log Format.
// ts is the timestamp with which the entry should be logged.
// status and size are used to provide the response HTTP status and size. | [
"writeCombinedLog",
"writes",
"a",
"log",
"entry",
"for",
"req",
"to",
"w",
"in",
"Apache",
"Combined",
"Log",
"Format",
".",
"ts",
"is",
"the",
"timestamp",
"with",
"which",
"the",
"entry",
"should",
"be",
"logged",
".",
"status",
"and",
"size",
"are",
"used",
"to",
"provide",
"the",
"response",
"HTTP",
"status",
"and",
"size",
"."
] | ac6d24f88de4584385a0cb3a88f953d08a2f7a05 | https://github.com/gorilla/handlers/blob/ac6d24f88de4584385a0cb3a88f953d08a2f7a05/logging.go#L208-L216 |
148,983 | gorilla/handlers | logging.go | CustomLoggingHandler | func CustomLoggingHandler(out io.Writer, h http.Handler, f LogFormatter) http.Handler {
return loggingHandler{out, h, f}
} | go | func CustomLoggingHandler(out io.Writer, h http.Handler, f LogFormatter) http.Handler {
return loggingHandler{out, h, f}
} | [
"func",
"CustomLoggingHandler",
"(",
"out",
"io",
".",
"Writer",
",",
"h",
"http",
".",
"Handler",
",",
"f",
"LogFormatter",
")",
"http",
".",
"Handler",
"{",
"return",
"loggingHandler",
"{",
"out",
",",
"h",
",",
"f",
"}",
"\n",
"}"
] | // CustomLoggingHandler provides a way to supply a custom log formatter
// while taking advantage of the mechanisms in this package | [
"CustomLoggingHandler",
"provides",
"a",
"way",
"to",
"supply",
"a",
"custom",
"log",
"formatter",
"while",
"taking",
"advantage",
"of",
"the",
"mechanisms",
"in",
"this",
"package"
] | ac6d24f88de4584385a0cb3a88f953d08a2f7a05 | https://github.com/gorilla/handlers/blob/ac6d24f88de4584385a0cb3a88f953d08a2f7a05/logging.go#L250-L252 |
148,984 | gorilla/handlers | handlers.go | isContentType | func isContentType(h http.Header, contentType string) bool {
ct := h.Get("Content-Type")
if i := strings.IndexRune(ct, ';'); i != -1 {
ct = ct[0:i]
}
return ct == contentType
} | go | func isContentType(h http.Header, contentType string) bool {
ct := h.Get("Content-Type")
if i := strings.IndexRune(ct, ';'); i != -1 {
ct = ct[0:i]
}
return ct == contentType
} | [
"func",
"isContentType",
"(",
"h",
"http",
".",
"Header",
",",
"contentType",
"string",
")",
"bool",
"{",
"ct",
":=",
"h",
".",
"Get",
"(",
"\"",
"\"",
")",
"\n",
"if",
"i",
":=",
"strings",
".",
"IndexRune",
"(",
"ct",
",",
"';'",
")",
";",
"i",
"!=",
"-",
"1",
"{",
"ct",
"=",
"ct",
"[",
"0",
":",
"i",
"]",
"\n",
"}",
"\n",
"return",
"ct",
"==",
"contentType",
"\n",
"}"
] | // isContentType validates the Content-Type header matches the supplied
// contentType. That is, its type and subtype match. | [
"isContentType",
"validates",
"the",
"Content",
"-",
"Type",
"header",
"matches",
"the",
"supplied",
"contentType",
".",
"That",
"is",
"its",
"type",
"and",
"subtype",
"match",
"."
] | ac6d24f88de4584385a0cb3a88f953d08a2f7a05 | https://github.com/gorilla/handlers/blob/ac6d24f88de4584385a0cb3a88f953d08a2f7a05/handlers.go#L112-L118 |
148,985 | gorilla/handlers | handlers.go | ContentTypeHandler | func ContentTypeHandler(h http.Handler, contentTypes ...string) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if !(r.Method == "PUT" || r.Method == "POST" || r.Method == "PATCH") {
h.ServeHTTP(w, r)
return
}
for _, ct := range contentTypes {
if isContentType(r.Header, ct) {
h.ServeHTTP(w, r)
return
}
}
http.Error(w, fmt.Sprintf("Unsupported content type %q; expected one of %q", r.Header.Get("Content-Type"), contentTypes), http.StatusUnsupportedMediaType)
})
} | go | func ContentTypeHandler(h http.Handler, contentTypes ...string) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if !(r.Method == "PUT" || r.Method == "POST" || r.Method == "PATCH") {
h.ServeHTTP(w, r)
return
}
for _, ct := range contentTypes {
if isContentType(r.Header, ct) {
h.ServeHTTP(w, r)
return
}
}
http.Error(w, fmt.Sprintf("Unsupported content type %q; expected one of %q", r.Header.Get("Content-Type"), contentTypes), http.StatusUnsupportedMediaType)
})
} | [
"func",
"ContentTypeHandler",
"(",
"h",
"http",
".",
"Handler",
",",
"contentTypes",
"...",
"string",
")",
"http",
".",
"Handler",
"{",
"return",
"http",
".",
"HandlerFunc",
"(",
"func",
"(",
"w",
"http",
".",
"ResponseWriter",
",",
"r",
"*",
"http",
".",
"Request",
")",
"{",
"if",
"!",
"(",
"r",
".",
"Method",
"==",
"\"",
"\"",
"||",
"r",
".",
"Method",
"==",
"\"",
"\"",
"||",
"r",
".",
"Method",
"==",
"\"",
"\"",
")",
"{",
"h",
".",
"ServeHTTP",
"(",
"w",
",",
"r",
")",
"\n",
"return",
"\n",
"}",
"\n\n",
"for",
"_",
",",
"ct",
":=",
"range",
"contentTypes",
"{",
"if",
"isContentType",
"(",
"r",
".",
"Header",
",",
"ct",
")",
"{",
"h",
".",
"ServeHTTP",
"(",
"w",
",",
"r",
")",
"\n",
"return",
"\n",
"}",
"\n",
"}",
"\n",
"http",
".",
"Error",
"(",
"w",
",",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"r",
".",
"Header",
".",
"Get",
"(",
"\"",
"\"",
")",
",",
"contentTypes",
")",
",",
"http",
".",
"StatusUnsupportedMediaType",
")",
"\n",
"}",
")",
"\n",
"}"
] | // ContentTypeHandler wraps and returns a http.Handler, validating the request
// content type is compatible with the contentTypes list. It writes a HTTP 415
// error if that fails.
//
// Only PUT, POST, and PATCH requests are considered. | [
"ContentTypeHandler",
"wraps",
"and",
"returns",
"a",
"http",
".",
"Handler",
"validating",
"the",
"request",
"content",
"type",
"is",
"compatible",
"with",
"the",
"contentTypes",
"list",
".",
"It",
"writes",
"a",
"HTTP",
"415",
"error",
"if",
"that",
"fails",
".",
"Only",
"PUT",
"POST",
"and",
"PATCH",
"requests",
"are",
"considered",
"."
] | ac6d24f88de4584385a0cb3a88f953d08a2f7a05 | https://github.com/gorilla/handlers/blob/ac6d24f88de4584385a0cb3a88f953d08a2f7a05/handlers.go#L125-L140 |
148,986 | gorilla/handlers | recovery.go | RecoveryLogger | func RecoveryLogger(logger RecoveryHandlerLogger) RecoveryOption {
return func(h http.Handler) {
r := h.(*recoveryHandler)
r.logger = logger
}
} | go | func RecoveryLogger(logger RecoveryHandlerLogger) RecoveryOption {
return func(h http.Handler) {
r := h.(*recoveryHandler)
r.logger = logger
}
} | [
"func",
"RecoveryLogger",
"(",
"logger",
"RecoveryHandlerLogger",
")",
"RecoveryOption",
"{",
"return",
"func",
"(",
"h",
"http",
".",
"Handler",
")",
"{",
"r",
":=",
"h",
".",
"(",
"*",
"recoveryHandler",
")",
"\n",
"r",
".",
"logger",
"=",
"logger",
"\n",
"}",
"\n",
"}"
] | // RecoveryLogger is a functional option to override
// the default logger | [
"RecoveryLogger",
"is",
"a",
"functional",
"option",
"to",
"override",
"the",
"default",
"logger"
] | ac6d24f88de4584385a0cb3a88f953d08a2f7a05 | https://github.com/gorilla/handlers/blob/ac6d24f88de4584385a0cb3a88f953d08a2f7a05/recovery.go#L54-L59 |
148,987 | gorilla/handlers | recovery.go | PrintRecoveryStack | func PrintRecoveryStack(print bool) RecoveryOption {
return func(h http.Handler) {
r := h.(*recoveryHandler)
r.printStack = print
}
} | go | func PrintRecoveryStack(print bool) RecoveryOption {
return func(h http.Handler) {
r := h.(*recoveryHandler)
r.printStack = print
}
} | [
"func",
"PrintRecoveryStack",
"(",
"print",
"bool",
")",
"RecoveryOption",
"{",
"return",
"func",
"(",
"h",
"http",
".",
"Handler",
")",
"{",
"r",
":=",
"h",
".",
"(",
"*",
"recoveryHandler",
")",
"\n",
"r",
".",
"printStack",
"=",
"print",
"\n",
"}",
"\n",
"}"
] | // PrintRecoveryStack is a functional option to enable
// or disable printing stack traces on panic. | [
"PrintRecoveryStack",
"is",
"a",
"functional",
"option",
"to",
"enable",
"or",
"disable",
"printing",
"stack",
"traces",
"on",
"panic",
"."
] | ac6d24f88de4584385a0cb3a88f953d08a2f7a05 | https://github.com/gorilla/handlers/blob/ac6d24f88de4584385a0cb3a88f953d08a2f7a05/recovery.go#L63-L68 |
148,988 | colinmarc/hdfs | internal/rpc/block_writer.go | SetDeadline | func (bw *BlockWriter) SetDeadline(t time.Time) error {
bw.deadline = t
if bw.conn != nil {
return bw.conn.SetDeadline(t)
}
// Return the error at connection time.
return nil
} | go | func (bw *BlockWriter) SetDeadline(t time.Time) error {
bw.deadline = t
if bw.conn != nil {
return bw.conn.SetDeadline(t)
}
// Return the error at connection time.
return nil
} | [
"func",
"(",
"bw",
"*",
"BlockWriter",
")",
"SetDeadline",
"(",
"t",
"time",
".",
"Time",
")",
"error",
"{",
"bw",
".",
"deadline",
"=",
"t",
"\n",
"if",
"bw",
".",
"conn",
"!=",
"nil",
"{",
"return",
"bw",
".",
"conn",
".",
"SetDeadline",
"(",
"t",
")",
"\n",
"}",
"\n\n",
"// Return the error at connection time.",
"return",
"nil",
"\n",
"}"
] | // SetDeadline sets the deadline for future Write, Flush, and Close calls. A
// zero value for t means those calls will not time out. | [
"SetDeadline",
"sets",
"the",
"deadline",
"for",
"future",
"Write",
"Flush",
"and",
"Close",
"calls",
".",
"A",
"zero",
"value",
"for",
"t",
"means",
"those",
"calls",
"will",
"not",
"time",
"out",
"."
] | 6f7e441ec688730014b4ca08657db358d7a45b87 | https://github.com/colinmarc/hdfs/blob/6f7e441ec688730014b4ca08657db358d7a45b87/internal/rpc/block_writer.go#L49-L57 |
148,989 | colinmarc/hdfs | internal/rpc/block_writer.go | Flush | func (bw *BlockWriter) Flush() error {
if bw.stream != nil {
return bw.stream.flush(true)
}
return nil
} | go | func (bw *BlockWriter) Flush() error {
if bw.stream != nil {
return bw.stream.flush(true)
}
return nil
} | [
"func",
"(",
"bw",
"*",
"BlockWriter",
")",
"Flush",
"(",
")",
"error",
"{",
"if",
"bw",
".",
"stream",
"!=",
"nil",
"{",
"return",
"bw",
".",
"stream",
".",
"flush",
"(",
"true",
")",
"\n",
"}",
"\n\n",
"return",
"nil",
"\n",
"}"
] | // Flush flushes any unwritten packets out to the datanode. | [
"Flush",
"flushes",
"any",
"unwritten",
"packets",
"out",
"to",
"the",
"datanode",
"."
] | 6f7e441ec688730014b4ca08657db358d7a45b87 | https://github.com/colinmarc/hdfs/blob/6f7e441ec688730014b4ca08657db358d7a45b87/internal/rpc/block_writer.go#L94-L100 |
148,990 | colinmarc/hdfs | internal/rpc/block_writer.go | Close | func (bw *BlockWriter) Close() error {
bw.closed = true
if bw.conn != nil {
defer bw.conn.Close()
}
if bw.stream != nil {
// TODO: handle failures, set up recovery pipeline
err := bw.stream.finish()
if err != nil {
return err
}
}
return nil
} | go | func (bw *BlockWriter) Close() error {
bw.closed = true
if bw.conn != nil {
defer bw.conn.Close()
}
if bw.stream != nil {
// TODO: handle failures, set up recovery pipeline
err := bw.stream.finish()
if err != nil {
return err
}
}
return nil
} | [
"func",
"(",
"bw",
"*",
"BlockWriter",
")",
"Close",
"(",
")",
"error",
"{",
"bw",
".",
"closed",
"=",
"true",
"\n",
"if",
"bw",
".",
"conn",
"!=",
"nil",
"{",
"defer",
"bw",
".",
"conn",
".",
"Close",
"(",
")",
"\n",
"}",
"\n\n",
"if",
"bw",
".",
"stream",
"!=",
"nil",
"{",
"// TODO: handle failures, set up recovery pipeline",
"err",
":=",
"bw",
".",
"stream",
".",
"finish",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"}",
"\n\n",
"return",
"nil",
"\n",
"}"
] | // Close implements io.Closer. It flushes any unwritten packets out to the
// datanode, and sends a final packet indicating the end of the block. The
// block must still be finalized with the namenode. | [
"Close",
"implements",
"io",
".",
"Closer",
".",
"It",
"flushes",
"any",
"unwritten",
"packets",
"out",
"to",
"the",
"datanode",
"and",
"sends",
"a",
"final",
"packet",
"indicating",
"the",
"end",
"of",
"the",
"block",
".",
"The",
"block",
"must",
"still",
"be",
"finalized",
"with",
"the",
"namenode",
"."
] | 6f7e441ec688730014b4ca08657db358d7a45b87 | https://github.com/colinmarc/hdfs/blob/6f7e441ec688730014b4ca08657db358d7a45b87/internal/rpc/block_writer.go#L105-L120 |
148,991 | colinmarc/hdfs | internal/rpc/namenode.go | NewNamenodeConnection | func NewNamenodeConnection(options NamenodeConnectionOptions) (*NamenodeConnection, error) {
// Build the list of hosts to be used for failover.
hostList := make([]*namenodeHost, len(options.Addresses))
for i, addr := range options.Addresses {
hostList[i] = &namenodeHost{address: addr}
}
var user, realm string
user = options.User
if user == "" {
if options.KerberosClient != nil {
creds := options.KerberosClient.Credentials
user = creds.Username
realm = creds.Realm
} else {
return nil, errors.New("user not specified")
}
}
// The ClientID is reused here both in the RPC headers (which requires a
// "globally unique" ID) and as the "client name" in various requests.
clientId := newClientID()
c := &NamenodeConnection{
ClientID: clientId,
ClientName: "go-hdfs-" + string(clientId),
User: user,
kerberosClient: options.KerberosClient,
kerberosServicePrincipleName: options.KerberosServicePrincipleName,
kerberosRealm: realm,
dialFunc: options.DialFunc,
hostList: hostList,
}
err := c.resolveConnection()
if err != nil {
return nil, err
}
return c, nil
} | go | func NewNamenodeConnection(options NamenodeConnectionOptions) (*NamenodeConnection, error) {
// Build the list of hosts to be used for failover.
hostList := make([]*namenodeHost, len(options.Addresses))
for i, addr := range options.Addresses {
hostList[i] = &namenodeHost{address: addr}
}
var user, realm string
user = options.User
if user == "" {
if options.KerberosClient != nil {
creds := options.KerberosClient.Credentials
user = creds.Username
realm = creds.Realm
} else {
return nil, errors.New("user not specified")
}
}
// The ClientID is reused here both in the RPC headers (which requires a
// "globally unique" ID) and as the "client name" in various requests.
clientId := newClientID()
c := &NamenodeConnection{
ClientID: clientId,
ClientName: "go-hdfs-" + string(clientId),
User: user,
kerberosClient: options.KerberosClient,
kerberosServicePrincipleName: options.KerberosServicePrincipleName,
kerberosRealm: realm,
dialFunc: options.DialFunc,
hostList: hostList,
}
err := c.resolveConnection()
if err != nil {
return nil, err
}
return c, nil
} | [
"func",
"NewNamenodeConnection",
"(",
"options",
"NamenodeConnectionOptions",
")",
"(",
"*",
"NamenodeConnection",
",",
"error",
")",
"{",
"// Build the list of hosts to be used for failover.",
"hostList",
":=",
"make",
"(",
"[",
"]",
"*",
"namenodeHost",
",",
"len",
"(",
"options",
".",
"Addresses",
")",
")",
"\n",
"for",
"i",
",",
"addr",
":=",
"range",
"options",
".",
"Addresses",
"{",
"hostList",
"[",
"i",
"]",
"=",
"&",
"namenodeHost",
"{",
"address",
":",
"addr",
"}",
"\n",
"}",
"\n\n",
"var",
"user",
",",
"realm",
"string",
"\n",
"user",
"=",
"options",
".",
"User",
"\n",
"if",
"user",
"==",
"\"",
"\"",
"{",
"if",
"options",
".",
"KerberosClient",
"!=",
"nil",
"{",
"creds",
":=",
"options",
".",
"KerberosClient",
".",
"Credentials",
"\n",
"user",
"=",
"creds",
".",
"Username",
"\n",
"realm",
"=",
"creds",
".",
"Realm",
"\n",
"}",
"else",
"{",
"return",
"nil",
",",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"}",
"\n\n",
"// The ClientID is reused here both in the RPC headers (which requires a",
"// \"globally unique\" ID) and as the \"client name\" in various requests.",
"clientId",
":=",
"newClientID",
"(",
")",
"\n",
"c",
":=",
"&",
"NamenodeConnection",
"{",
"ClientID",
":",
"clientId",
",",
"ClientName",
":",
"\"",
"\"",
"+",
"string",
"(",
"clientId",
")",
",",
"User",
":",
"user",
",",
"kerberosClient",
":",
"options",
".",
"KerberosClient",
",",
"kerberosServicePrincipleName",
":",
"options",
".",
"KerberosServicePrincipleName",
",",
"kerberosRealm",
":",
"realm",
",",
"dialFunc",
":",
"options",
".",
"DialFunc",
",",
"hostList",
":",
"hostList",
",",
"}",
"\n\n",
"err",
":=",
"c",
".",
"resolveConnection",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"return",
"c",
",",
"nil",
"\n",
"}"
] | // NewNamenodeConnectionWithOptions creates a new connection to a namenode with
// the given options and performs an initial handshake. | [
"NewNamenodeConnectionWithOptions",
"creates",
"a",
"new",
"connection",
"to",
"a",
"namenode",
"with",
"the",
"given",
"options",
"and",
"performs",
"an",
"initial",
"handshake",
"."
] | 6f7e441ec688730014b4ca08657db358d7a45b87 | https://github.com/colinmarc/hdfs/blob/6f7e441ec688730014b4ca08657db358d7a45b87/internal/rpc/namenode.go#L82-L123 |
148,992 | colinmarc/hdfs | internal/rpc/namenode.go | Execute | func (c *NamenodeConnection) Execute(method string, req proto.Message, resp proto.Message) error {
c.reqLock.Lock()
defer c.reqLock.Unlock()
c.currentRequestID++
for {
err := c.resolveConnection()
if err != nil {
return err
}
err = c.writeRequest(method, req)
if err != nil {
c.markFailure(err)
continue
}
err = c.readResponse(method, resp)
if err != nil {
// Only retry on a standby exception.
if nerr, ok := err.(*NamenodeError); ok && nerr.exception == standbyExceptionClass {
c.markFailure(err)
continue
}
return err
}
break
}
return nil
} | go | func (c *NamenodeConnection) Execute(method string, req proto.Message, resp proto.Message) error {
c.reqLock.Lock()
defer c.reqLock.Unlock()
c.currentRequestID++
for {
err := c.resolveConnection()
if err != nil {
return err
}
err = c.writeRequest(method, req)
if err != nil {
c.markFailure(err)
continue
}
err = c.readResponse(method, resp)
if err != nil {
// Only retry on a standby exception.
if nerr, ok := err.(*NamenodeError); ok && nerr.exception == standbyExceptionClass {
c.markFailure(err)
continue
}
return err
}
break
}
return nil
} | [
"func",
"(",
"c",
"*",
"NamenodeConnection",
")",
"Execute",
"(",
"method",
"string",
",",
"req",
"proto",
".",
"Message",
",",
"resp",
"proto",
".",
"Message",
")",
"error",
"{",
"c",
".",
"reqLock",
".",
"Lock",
"(",
")",
"\n",
"defer",
"c",
".",
"reqLock",
".",
"Unlock",
"(",
")",
"\n\n",
"c",
".",
"currentRequestID",
"++",
"\n\n",
"for",
"{",
"err",
":=",
"c",
".",
"resolveConnection",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"err",
"=",
"c",
".",
"writeRequest",
"(",
"method",
",",
"req",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"c",
".",
"markFailure",
"(",
"err",
")",
"\n",
"continue",
"\n",
"}",
"\n\n",
"err",
"=",
"c",
".",
"readResponse",
"(",
"method",
",",
"resp",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"// Only retry on a standby exception.",
"if",
"nerr",
",",
"ok",
":=",
"err",
".",
"(",
"*",
"NamenodeError",
")",
";",
"ok",
"&&",
"nerr",
".",
"exception",
"==",
"standbyExceptionClass",
"{",
"c",
".",
"markFailure",
"(",
"err",
")",
"\n",
"continue",
"\n",
"}",
"\n\n",
"return",
"err",
"\n",
"}",
"\n\n",
"break",
"\n",
"}",
"\n\n",
"return",
"nil",
"\n",
"}"
] | // Execute performs an rpc call. It does this by sending req over the wire and
// unmarshaling the result into resp. | [
"Execute",
"performs",
"an",
"rpc",
"call",
".",
"It",
"does",
"this",
"by",
"sending",
"req",
"over",
"the",
"wire",
"and",
"unmarshaling",
"the",
"result",
"into",
"resp",
"."
] | 6f7e441ec688730014b4ca08657db358d7a45b87 | https://github.com/colinmarc/hdfs/blob/6f7e441ec688730014b4ca08657db358d7a45b87/internal/rpc/namenode.go#L178-L211 |
148,993 | colinmarc/hdfs | internal/rpc/namenode.go | Close | func (c *NamenodeConnection) Close() error {
if c.conn != nil {
return c.conn.Close()
}
return nil
} | go | func (c *NamenodeConnection) Close() error {
if c.conn != nil {
return c.conn.Close()
}
return nil
} | [
"func",
"(",
"c",
"*",
"NamenodeConnection",
")",
"Close",
"(",
")",
"error",
"{",
"if",
"c",
".",
"conn",
"!=",
"nil",
"{",
"return",
"c",
".",
"conn",
".",
"Close",
"(",
")",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] | // Close terminates all underlying socket connections to remote server. | [
"Close",
"terminates",
"all",
"underlying",
"socket",
"connections",
"to",
"remote",
"server",
"."
] | 6f7e441ec688730014b4ca08657db358d7a45b87 | https://github.com/colinmarc/hdfs/blob/6f7e441ec688730014b4ca08657db358d7a45b87/internal/rpc/namenode.go#L326-L331 |
148,994 | colinmarc/hdfs | file_reader.go | Open | func (c *Client) Open(name string) (*FileReader, error) {
info, err := c.getFileInfo(name)
if err != nil {
return nil, &os.PathError{"open", name, interpretException(err)}
}
return &FileReader{
client: c,
name: name,
info: info,
closed: false,
}, nil
} | go | func (c *Client) Open(name string) (*FileReader, error) {
info, err := c.getFileInfo(name)
if err != nil {
return nil, &os.PathError{"open", name, interpretException(err)}
}
return &FileReader{
client: c,
name: name,
info: info,
closed: false,
}, nil
} | [
"func",
"(",
"c",
"*",
"Client",
")",
"Open",
"(",
"name",
"string",
")",
"(",
"*",
"FileReader",
",",
"error",
")",
"{",
"info",
",",
"err",
":=",
"c",
".",
"getFileInfo",
"(",
"name",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"&",
"os",
".",
"PathError",
"{",
"\"",
"\"",
",",
"name",
",",
"interpretException",
"(",
"err",
")",
"}",
"\n",
"}",
"\n\n",
"return",
"&",
"FileReader",
"{",
"client",
":",
"c",
",",
"name",
":",
"name",
",",
"info",
":",
"info",
",",
"closed",
":",
"false",
",",
"}",
",",
"nil",
"\n",
"}"
] | // Open returns an FileReader which can be used for reading. | [
"Open",
"returns",
"an",
"FileReader",
"which",
"can",
"be",
"used",
"for",
"reading",
"."
] | 6f7e441ec688730014b4ca08657db358d7a45b87 | https://github.com/colinmarc/hdfs/blob/6f7e441ec688730014b4ca08657db358d7a45b87/file_reader.go#L35-L47 |
148,995 | colinmarc/hdfs | file_reader.go | SetDeadline | func (f *FileReader) SetDeadline(t time.Time) error {
f.deadline = t
if f.blockReader != nil {
return f.blockReader.SetDeadline(t)
}
// Return the error at connection time.
return nil
} | go | func (f *FileReader) SetDeadline(t time.Time) error {
f.deadline = t
if f.blockReader != nil {
return f.blockReader.SetDeadline(t)
}
// Return the error at connection time.
return nil
} | [
"func",
"(",
"f",
"*",
"FileReader",
")",
"SetDeadline",
"(",
"t",
"time",
".",
"Time",
")",
"error",
"{",
"f",
".",
"deadline",
"=",
"t",
"\n",
"if",
"f",
".",
"blockReader",
"!=",
"nil",
"{",
"return",
"f",
".",
"blockReader",
".",
"SetDeadline",
"(",
"t",
")",
"\n",
"}",
"\n\n",
"// Return the error at connection time.",
"return",
"nil",
"\n",
"}"
] | // SetDeadline sets the deadline for future Read, ReadAt, and Checksum calls. A
// zero value for t means those calls will not time out. | [
"SetDeadline",
"sets",
"the",
"deadline",
"for",
"future",
"Read",
"ReadAt",
"and",
"Checksum",
"calls",
".",
"A",
"zero",
"value",
"for",
"t",
"means",
"those",
"calls",
"will",
"not",
"time",
"out",
"."
] | 6f7e441ec688730014b4ca08657db358d7a45b87 | https://github.com/colinmarc/hdfs/blob/6f7e441ec688730014b4ca08657db358d7a45b87/file_reader.go#L61-L69 |
148,996 | colinmarc/hdfs | file_reader.go | Seek | func (f *FileReader) Seek(offset int64, whence int) (int64, error) {
if f.closed {
return 0, io.ErrClosedPipe
}
var off int64
if whence == 0 {
off = offset
} else if whence == 1 {
off = f.offset + offset
} else if whence == 2 {
off = f.info.Size() + offset
} else {
return f.offset, fmt.Errorf("invalid whence: %d", whence)
}
if off < 0 || off > f.info.Size() {
return f.offset, fmt.Errorf("invalid resulting offset: %d", off)
}
if f.offset != off {
f.offset = off
if f.blockReader != nil {
f.blockReader.Close()
f.blockReader = nil
}
}
return f.offset, nil
} | go | func (f *FileReader) Seek(offset int64, whence int) (int64, error) {
if f.closed {
return 0, io.ErrClosedPipe
}
var off int64
if whence == 0 {
off = offset
} else if whence == 1 {
off = f.offset + offset
} else if whence == 2 {
off = f.info.Size() + offset
} else {
return f.offset, fmt.Errorf("invalid whence: %d", whence)
}
if off < 0 || off > f.info.Size() {
return f.offset, fmt.Errorf("invalid resulting offset: %d", off)
}
if f.offset != off {
f.offset = off
if f.blockReader != nil {
f.blockReader.Close()
f.blockReader = nil
}
}
return f.offset, nil
} | [
"func",
"(",
"f",
"*",
"FileReader",
")",
"Seek",
"(",
"offset",
"int64",
",",
"whence",
"int",
")",
"(",
"int64",
",",
"error",
")",
"{",
"if",
"f",
".",
"closed",
"{",
"return",
"0",
",",
"io",
".",
"ErrClosedPipe",
"\n",
"}",
"\n\n",
"var",
"off",
"int64",
"\n",
"if",
"whence",
"==",
"0",
"{",
"off",
"=",
"offset",
"\n",
"}",
"else",
"if",
"whence",
"==",
"1",
"{",
"off",
"=",
"f",
".",
"offset",
"+",
"offset",
"\n",
"}",
"else",
"if",
"whence",
"==",
"2",
"{",
"off",
"=",
"f",
".",
"info",
".",
"Size",
"(",
")",
"+",
"offset",
"\n",
"}",
"else",
"{",
"return",
"f",
".",
"offset",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"whence",
")",
"\n",
"}",
"\n\n",
"if",
"off",
"<",
"0",
"||",
"off",
">",
"f",
".",
"info",
".",
"Size",
"(",
")",
"{",
"return",
"f",
".",
"offset",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"off",
")",
"\n",
"}",
"\n\n",
"if",
"f",
".",
"offset",
"!=",
"off",
"{",
"f",
".",
"offset",
"=",
"off",
"\n",
"if",
"f",
".",
"blockReader",
"!=",
"nil",
"{",
"f",
".",
"blockReader",
".",
"Close",
"(",
")",
"\n",
"f",
".",
"blockReader",
"=",
"nil",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"f",
".",
"offset",
",",
"nil",
"\n",
"}"
] | // Seek implements io.Seeker.
//
// The seek is virtual - it starts a new block read at the new position. | [
"Seek",
"implements",
"io",
".",
"Seeker",
".",
"The",
"seek",
"is",
"virtual",
"-",
"it",
"starts",
"a",
"new",
"block",
"read",
"at",
"the",
"new",
"position",
"."
] | 6f7e441ec688730014b4ca08657db358d7a45b87 | https://github.com/colinmarc/hdfs/blob/6f7e441ec688730014b4ca08657db358d7a45b87/file_reader.go#L131-L159 |
148,997 | colinmarc/hdfs | file_writer.go | CreateFile | func (c *Client) CreateFile(name string, replication int, blockSize int64, perm os.FileMode) (*FileWriter, error) {
createReq := &hdfs.CreateRequestProto{
Src: proto.String(name),
Masked: &hdfs.FsPermissionProto{Perm: proto.Uint32(uint32(perm))},
ClientName: proto.String(c.namenode.ClientName),
CreateFlag: proto.Uint32(1),
CreateParent: proto.Bool(false),
Replication: proto.Uint32(uint32(replication)),
BlockSize: proto.Uint64(uint64(blockSize)),
}
createResp := &hdfs.CreateResponseProto{}
err := c.namenode.Execute("create", createReq, createResp)
if err != nil {
return nil, &os.PathError{"create", name, interpretException(err)}
}
return &FileWriter{
client: c,
name: name,
replication: replication,
blockSize: blockSize,
}, nil
} | go | func (c *Client) CreateFile(name string, replication int, blockSize int64, perm os.FileMode) (*FileWriter, error) {
createReq := &hdfs.CreateRequestProto{
Src: proto.String(name),
Masked: &hdfs.FsPermissionProto{Perm: proto.Uint32(uint32(perm))},
ClientName: proto.String(c.namenode.ClientName),
CreateFlag: proto.Uint32(1),
CreateParent: proto.Bool(false),
Replication: proto.Uint32(uint32(replication)),
BlockSize: proto.Uint64(uint64(blockSize)),
}
createResp := &hdfs.CreateResponseProto{}
err := c.namenode.Execute("create", createReq, createResp)
if err != nil {
return nil, &os.PathError{"create", name, interpretException(err)}
}
return &FileWriter{
client: c,
name: name,
replication: replication,
blockSize: blockSize,
}, nil
} | [
"func",
"(",
"c",
"*",
"Client",
")",
"CreateFile",
"(",
"name",
"string",
",",
"replication",
"int",
",",
"blockSize",
"int64",
",",
"perm",
"os",
".",
"FileMode",
")",
"(",
"*",
"FileWriter",
",",
"error",
")",
"{",
"createReq",
":=",
"&",
"hdfs",
".",
"CreateRequestProto",
"{",
"Src",
":",
"proto",
".",
"String",
"(",
"name",
")",
",",
"Masked",
":",
"&",
"hdfs",
".",
"FsPermissionProto",
"{",
"Perm",
":",
"proto",
".",
"Uint32",
"(",
"uint32",
"(",
"perm",
")",
")",
"}",
",",
"ClientName",
":",
"proto",
".",
"String",
"(",
"c",
".",
"namenode",
".",
"ClientName",
")",
",",
"CreateFlag",
":",
"proto",
".",
"Uint32",
"(",
"1",
")",
",",
"CreateParent",
":",
"proto",
".",
"Bool",
"(",
"false",
")",
",",
"Replication",
":",
"proto",
".",
"Uint32",
"(",
"uint32",
"(",
"replication",
")",
")",
",",
"BlockSize",
":",
"proto",
".",
"Uint64",
"(",
"uint64",
"(",
"blockSize",
")",
")",
",",
"}",
"\n",
"createResp",
":=",
"&",
"hdfs",
".",
"CreateResponseProto",
"{",
"}",
"\n\n",
"err",
":=",
"c",
".",
"namenode",
".",
"Execute",
"(",
"\"",
"\"",
",",
"createReq",
",",
"createResp",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"&",
"os",
".",
"PathError",
"{",
"\"",
"\"",
",",
"name",
",",
"interpretException",
"(",
"err",
")",
"}",
"\n",
"}",
"\n\n",
"return",
"&",
"FileWriter",
"{",
"client",
":",
"c",
",",
"name",
":",
"name",
",",
"replication",
":",
"replication",
",",
"blockSize",
":",
"blockSize",
",",
"}",
",",
"nil",
"\n",
"}"
] | // CreateFile opens a new file in HDFS with the given replication, block size,
// and permissions, and returns an io.WriteCloser for writing to it. Because of
// the way that HDFS writes are buffered and acknowledged asynchronously, it is
// very important that Close is called after all data has been written. | [
"CreateFile",
"opens",
"a",
"new",
"file",
"in",
"HDFS",
"with",
"the",
"given",
"replication",
"block",
"size",
"and",
"permissions",
"and",
"returns",
"an",
"io",
".",
"WriteCloser",
"for",
"writing",
"to",
"it",
".",
"Because",
"of",
"the",
"way",
"that",
"HDFS",
"writes",
"are",
"buffered",
"and",
"acknowledged",
"asynchronously",
"it",
"is",
"very",
"important",
"that",
"Close",
"is",
"called",
"after",
"all",
"data",
"has",
"been",
"written",
"."
] | 6f7e441ec688730014b4ca08657db358d7a45b87 | https://github.com/colinmarc/hdfs/blob/6f7e441ec688730014b4ca08657db358d7a45b87/file_writer.go#L55-L78 |
148,998 | colinmarc/hdfs | file_writer.go | Append | func (c *Client) Append(name string) (*FileWriter, error) {
_, err := c.getFileInfo(name)
if err != nil {
return nil, &os.PathError{"append", name, interpretException(err)}
}
appendReq := &hdfs.AppendRequestProto{
Src: proto.String(name),
ClientName: proto.String(c.namenode.ClientName),
}
appendResp := &hdfs.AppendResponseProto{}
err = c.namenode.Execute("append", appendReq, appendResp)
if err != nil {
return nil, &os.PathError{"append", name, interpretException(err)}
}
f := &FileWriter{
client: c,
name: name,
replication: int(appendResp.Stat.GetBlockReplication()),
blockSize: int64(appendResp.Stat.GetBlocksize()),
}
// This returns nil if there are no blocks (it's an empty file) or if the
// last block is full (so we have to start a fresh block).
block := appendResp.GetBlock()
if block == nil {
return f, nil
}
f.blockWriter = &rpc.BlockWriter{
ClientName: f.client.namenode.ClientName,
Block: block,
BlockSize: f.blockSize,
Offset: int64(block.B.GetNumBytes()),
Append: true,
UseDatanodeHostname: f.client.options.UseDatanodeHostname,
DialFunc: f.client.options.DatanodeDialFunc,
}
err = f.blockWriter.SetDeadline(f.deadline)
if err != nil {
return nil, err
}
return f, nil
} | go | func (c *Client) Append(name string) (*FileWriter, error) {
_, err := c.getFileInfo(name)
if err != nil {
return nil, &os.PathError{"append", name, interpretException(err)}
}
appendReq := &hdfs.AppendRequestProto{
Src: proto.String(name),
ClientName: proto.String(c.namenode.ClientName),
}
appendResp := &hdfs.AppendResponseProto{}
err = c.namenode.Execute("append", appendReq, appendResp)
if err != nil {
return nil, &os.PathError{"append", name, interpretException(err)}
}
f := &FileWriter{
client: c,
name: name,
replication: int(appendResp.Stat.GetBlockReplication()),
blockSize: int64(appendResp.Stat.GetBlocksize()),
}
// This returns nil if there are no blocks (it's an empty file) or if the
// last block is full (so we have to start a fresh block).
block := appendResp.GetBlock()
if block == nil {
return f, nil
}
f.blockWriter = &rpc.BlockWriter{
ClientName: f.client.namenode.ClientName,
Block: block,
BlockSize: f.blockSize,
Offset: int64(block.B.GetNumBytes()),
Append: true,
UseDatanodeHostname: f.client.options.UseDatanodeHostname,
DialFunc: f.client.options.DatanodeDialFunc,
}
err = f.blockWriter.SetDeadline(f.deadline)
if err != nil {
return nil, err
}
return f, nil
} | [
"func",
"(",
"c",
"*",
"Client",
")",
"Append",
"(",
"name",
"string",
")",
"(",
"*",
"FileWriter",
",",
"error",
")",
"{",
"_",
",",
"err",
":=",
"c",
".",
"getFileInfo",
"(",
"name",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"&",
"os",
".",
"PathError",
"{",
"\"",
"\"",
",",
"name",
",",
"interpretException",
"(",
"err",
")",
"}",
"\n",
"}",
"\n\n",
"appendReq",
":=",
"&",
"hdfs",
".",
"AppendRequestProto",
"{",
"Src",
":",
"proto",
".",
"String",
"(",
"name",
")",
",",
"ClientName",
":",
"proto",
".",
"String",
"(",
"c",
".",
"namenode",
".",
"ClientName",
")",
",",
"}",
"\n",
"appendResp",
":=",
"&",
"hdfs",
".",
"AppendResponseProto",
"{",
"}",
"\n\n",
"err",
"=",
"c",
".",
"namenode",
".",
"Execute",
"(",
"\"",
"\"",
",",
"appendReq",
",",
"appendResp",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"&",
"os",
".",
"PathError",
"{",
"\"",
"\"",
",",
"name",
",",
"interpretException",
"(",
"err",
")",
"}",
"\n",
"}",
"\n\n",
"f",
":=",
"&",
"FileWriter",
"{",
"client",
":",
"c",
",",
"name",
":",
"name",
",",
"replication",
":",
"int",
"(",
"appendResp",
".",
"Stat",
".",
"GetBlockReplication",
"(",
")",
")",
",",
"blockSize",
":",
"int64",
"(",
"appendResp",
".",
"Stat",
".",
"GetBlocksize",
"(",
")",
")",
",",
"}",
"\n\n",
"// This returns nil if there are no blocks (it's an empty file) or if the",
"// last block is full (so we have to start a fresh block).",
"block",
":=",
"appendResp",
".",
"GetBlock",
"(",
")",
"\n",
"if",
"block",
"==",
"nil",
"{",
"return",
"f",
",",
"nil",
"\n",
"}",
"\n\n",
"f",
".",
"blockWriter",
"=",
"&",
"rpc",
".",
"BlockWriter",
"{",
"ClientName",
":",
"f",
".",
"client",
".",
"namenode",
".",
"ClientName",
",",
"Block",
":",
"block",
",",
"BlockSize",
":",
"f",
".",
"blockSize",
",",
"Offset",
":",
"int64",
"(",
"block",
".",
"B",
".",
"GetNumBytes",
"(",
")",
")",
",",
"Append",
":",
"true",
",",
"UseDatanodeHostname",
":",
"f",
".",
"client",
".",
"options",
".",
"UseDatanodeHostname",
",",
"DialFunc",
":",
"f",
".",
"client",
".",
"options",
".",
"DatanodeDialFunc",
",",
"}",
"\n\n",
"err",
"=",
"f",
".",
"blockWriter",
".",
"SetDeadline",
"(",
"f",
".",
"deadline",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"return",
"f",
",",
"nil",
"\n",
"}"
] | // Append opens an existing file in HDFS and returns an io.WriteCloser for
// writing to it. Because of the way that HDFS writes are buffered and
// acknowledged asynchronously, it is very important that Close is called after
// all data has been written. | [
"Append",
"opens",
"an",
"existing",
"file",
"in",
"HDFS",
"and",
"returns",
"an",
"io",
".",
"WriteCloser",
"for",
"writing",
"to",
"it",
".",
"Because",
"of",
"the",
"way",
"that",
"HDFS",
"writes",
"are",
"buffered",
"and",
"acknowledged",
"asynchronously",
"it",
"is",
"very",
"important",
"that",
"Close",
"is",
"called",
"after",
"all",
"data",
"has",
"been",
"written",
"."
] | 6f7e441ec688730014b4ca08657db358d7a45b87 | https://github.com/colinmarc/hdfs/blob/6f7e441ec688730014b4ca08657db358d7a45b87/file_writer.go#L84-L131 |
148,999 | colinmarc/hdfs | file_writer.go | CreateEmptyFile | func (c *Client) CreateEmptyFile(name string) error {
f, err := c.Create(name)
if err != nil {
return err
}
return f.Close()
} | go | func (c *Client) CreateEmptyFile(name string) error {
f, err := c.Create(name)
if err != nil {
return err
}
return f.Close()
} | [
"func",
"(",
"c",
"*",
"Client",
")",
"CreateEmptyFile",
"(",
"name",
"string",
")",
"error",
"{",
"f",
",",
"err",
":=",
"c",
".",
"Create",
"(",
"name",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"return",
"f",
".",
"Close",
"(",
")",
"\n",
"}"
] | // CreateEmptyFile creates a empty file at the given name, with the
// permissions 0644. | [
"CreateEmptyFile",
"creates",
"a",
"empty",
"file",
"at",
"the",
"given",
"name",
"with",
"the",
"permissions",
"0644",
"."
] | 6f7e441ec688730014b4ca08657db358d7a45b87 | https://github.com/colinmarc/hdfs/blob/6f7e441ec688730014b4ca08657db358d7a45b87/file_writer.go#L135-L142 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.