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
listlengths
21
1.41k
docstring
stringlengths
6
2.61k
docstring_tokens
listlengths
3
215
sha
stringlengths
40
40
url
stringlengths
85
252
18,000
revel/cmd
utils/file.go
PanicOnError
func PanicOnError(err error, msg string) { if revErr, ok := err.(*Error); (ok && revErr != nil) || (!ok && err != nil) { Logger.Panicf("Abort: %s: %s %s", msg, revErr, err) } }
go
func PanicOnError(err error, msg string) { if revErr, ok := err.(*Error); (ok && revErr != nil) || (!ok && err != nil) { Logger.Panicf("Abort: %s: %s %s", msg, revErr, err) } }
[ "func", "PanicOnError", "(", "err", "error", ",", "msg", "string", ")", "{", "if", "revErr", ",", "ok", ":=", "err", ".", "(", "*", "Error", ")", ";", "(", "ok", "&&", "revErr", "!=", "nil", ")", "||", "(", "!", "ok", "&&", "err", "!=", "nil", ")", "{", "Logger", ".", "Panicf", "(", "\"", "\"", ",", "msg", ",", "revErr", ",", "err", ")", "\n", "}", "\n", "}" ]
// Called if panic
[ "Called", "if", "panic" ]
149f9f992be9b0957fb1ffeda43c14a123ceb43a
https://github.com/revel/cmd/blob/149f9f992be9b0957fb1ffeda43c14a123ceb43a/utils/file.go#L152-L156
18,001
revel/cmd
utils/file.go
CopyDir
func CopyDir(destDir, srcDir string, data map[string]interface{}) error { if !DirExists(srcDir) { return nil } return fsWalk(srcDir, srcDir, func(srcPath string, info os.FileInfo, err error) error { // Get the relative path from the source base, and the corresponding path in // the dest directory. relSrcPath := strings.TrimLeft(srcPath[len(srcDir):], string(os.PathSeparator)) destPath := filepath.Join(destDir, relSrcPath) // Skip dot files and dot directories. if strings.HasPrefix(relSrcPath, ".") { if info.IsDir() { return filepath.SkipDir } return nil } // Create a subdirectory if necessary. if info.IsDir() { err := os.MkdirAll(filepath.Join(destDir, relSrcPath), 0777) if !os.IsExist(err) { return NewBuildIfError(err, "Failed to create directory", "path", destDir+"/"+relSrcPath) } return nil } // If this file ends in ".template", render it as a template. if strings.HasSuffix(relSrcPath, ".template") { return RenderTemplate(destPath[:len(destPath)-len(".template")], srcPath, data) } // Else, just copy it over. return CopyFile(destPath, srcPath) }) }
go
func CopyDir(destDir, srcDir string, data map[string]interface{}) error { if !DirExists(srcDir) { return nil } return fsWalk(srcDir, srcDir, func(srcPath string, info os.FileInfo, err error) error { // Get the relative path from the source base, and the corresponding path in // the dest directory. relSrcPath := strings.TrimLeft(srcPath[len(srcDir):], string(os.PathSeparator)) destPath := filepath.Join(destDir, relSrcPath) // Skip dot files and dot directories. if strings.HasPrefix(relSrcPath, ".") { if info.IsDir() { return filepath.SkipDir } return nil } // Create a subdirectory if necessary. if info.IsDir() { err := os.MkdirAll(filepath.Join(destDir, relSrcPath), 0777) if !os.IsExist(err) { return NewBuildIfError(err, "Failed to create directory", "path", destDir+"/"+relSrcPath) } return nil } // If this file ends in ".template", render it as a template. if strings.HasSuffix(relSrcPath, ".template") { return RenderTemplate(destPath[:len(destPath)-len(".template")], srcPath, data) } // Else, just copy it over. return CopyFile(destPath, srcPath) }) }
[ "func", "CopyDir", "(", "destDir", ",", "srcDir", "string", ",", "data", "map", "[", "string", "]", "interface", "{", "}", ")", "error", "{", "if", "!", "DirExists", "(", "srcDir", ")", "{", "return", "nil", "\n", "}", "\n", "return", "fsWalk", "(", "srcDir", ",", "srcDir", ",", "func", "(", "srcPath", "string", ",", "info", "os", ".", "FileInfo", ",", "err", "error", ")", "error", "{", "// Get the relative path from the source base, and the corresponding path in", "// the dest directory.", "relSrcPath", ":=", "strings", ".", "TrimLeft", "(", "srcPath", "[", "len", "(", "srcDir", ")", ":", "]", ",", "string", "(", "os", ".", "PathSeparator", ")", ")", "\n", "destPath", ":=", "filepath", ".", "Join", "(", "destDir", ",", "relSrcPath", ")", "\n\n", "// Skip dot files and dot directories.", "if", "strings", ".", "HasPrefix", "(", "relSrcPath", ",", "\"", "\"", ")", "{", "if", "info", ".", "IsDir", "(", ")", "{", "return", "filepath", ".", "SkipDir", "\n", "}", "\n", "return", "nil", "\n", "}", "\n\n", "// Create a subdirectory if necessary.", "if", "info", ".", "IsDir", "(", ")", "{", "err", ":=", "os", ".", "MkdirAll", "(", "filepath", ".", "Join", "(", "destDir", ",", "relSrcPath", ")", ",", "0777", ")", "\n", "if", "!", "os", ".", "IsExist", "(", "err", ")", "{", "return", "NewBuildIfError", "(", "err", ",", "\"", "\"", ",", "\"", "\"", ",", "destDir", "+", "\"", "\"", "+", "relSrcPath", ")", "\n", "}", "\n", "return", "nil", "\n", "}", "\n\n", "// If this file ends in \".template\", render it as a template.", "if", "strings", ".", "HasSuffix", "(", "relSrcPath", ",", "\"", "\"", ")", "{", "return", "RenderTemplate", "(", "destPath", "[", ":", "len", "(", "destPath", ")", "-", "len", "(", "\"", "\"", ")", "]", ",", "srcPath", ",", "data", ")", "\n", "}", "\n\n", "// Else, just copy it over.", "return", "CopyFile", "(", "destPath", ",", "srcPath", ")", "\n", "}", ")", "\n", "}" ]
// copyDir copies a directory tree over to a new directory. Any files ending in // ".template" are treated as a Go template and rendered using the given data. // Additionally, the trailing ".template" is stripped from the file name. // Also, dot files and dot directories are skipped.
[ "copyDir", "copies", "a", "directory", "tree", "over", "to", "a", "new", "directory", ".", "Any", "files", "ending", "in", ".", "template", "are", "treated", "as", "a", "Go", "template", "and", "rendered", "using", "the", "given", "data", ".", "Additionally", "the", "trailing", ".", "template", "is", "stripped", "from", "the", "file", "name", ".", "Also", "dot", "files", "and", "dot", "directories", "are", "skipped", "." ]
149f9f992be9b0957fb1ffeda43c14a123ceb43a
https://github.com/revel/cmd/blob/149f9f992be9b0957fb1ffeda43c14a123ceb43a/utils/file.go#L162-L199
18,002
revel/cmd
utils/file.go
TarGzDir
func TarGzDir(destFilename, srcDir string) (name string, err error) { zipFile, err := os.Create(destFilename) if err != nil { return "", NewBuildIfError(err, "Failed to create archive", "file", destFilename) } defer func() { _ = zipFile.Close() }() gzipWriter := gzip.NewWriter(zipFile) defer func() { _ = gzipWriter.Close() }() tarWriter := tar.NewWriter(gzipWriter) defer func() { _ = tarWriter.Close() }() err = fsWalk(srcDir, srcDir, func(srcPath string, info os.FileInfo, err error) error { if info.IsDir() { return nil } srcFile, err := os.Open(srcPath) if err != nil { return NewBuildIfError(err, "Failed to read file", "file", srcPath) } defer func() { _ = srcFile.Close() }() err = tarWriter.WriteHeader(&tar.Header{ Name: strings.TrimLeft(srcPath[len(srcDir):], string(os.PathSeparator)), Size: info.Size(), Mode: int64(info.Mode()), ModTime: info.ModTime(), }) if err != nil { return NewBuildIfError(err, "Failed to write tar entry header", "file", srcPath) } _, err = io.Copy(tarWriter, srcFile) if err != nil { return NewBuildIfError(err, "Failed to copy file", "file", srcPath) } return nil }) return zipFile.Name(), err }
go
func TarGzDir(destFilename, srcDir string) (name string, err error) { zipFile, err := os.Create(destFilename) if err != nil { return "", NewBuildIfError(err, "Failed to create archive", "file", destFilename) } defer func() { _ = zipFile.Close() }() gzipWriter := gzip.NewWriter(zipFile) defer func() { _ = gzipWriter.Close() }() tarWriter := tar.NewWriter(gzipWriter) defer func() { _ = tarWriter.Close() }() err = fsWalk(srcDir, srcDir, func(srcPath string, info os.FileInfo, err error) error { if info.IsDir() { return nil } srcFile, err := os.Open(srcPath) if err != nil { return NewBuildIfError(err, "Failed to read file", "file", srcPath) } defer func() { _ = srcFile.Close() }() err = tarWriter.WriteHeader(&tar.Header{ Name: strings.TrimLeft(srcPath[len(srcDir):], string(os.PathSeparator)), Size: info.Size(), Mode: int64(info.Mode()), ModTime: info.ModTime(), }) if err != nil { return NewBuildIfError(err, "Failed to write tar entry header", "file", srcPath) } _, err = io.Copy(tarWriter, srcFile) if err != nil { return NewBuildIfError(err, "Failed to copy file", "file", srcPath) } return nil }) return zipFile.Name(), err }
[ "func", "TarGzDir", "(", "destFilename", ",", "srcDir", "string", ")", "(", "name", "string", ",", "err", "error", ")", "{", "zipFile", ",", "err", ":=", "os", ".", "Create", "(", "destFilename", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "NewBuildIfError", "(", "err", ",", "\"", "\"", ",", "\"", "\"", ",", "destFilename", ")", "\n", "}", "\n\n", "defer", "func", "(", ")", "{", "_", "=", "zipFile", ".", "Close", "(", ")", "\n", "}", "(", ")", "\n\n", "gzipWriter", ":=", "gzip", ".", "NewWriter", "(", "zipFile", ")", "\n", "defer", "func", "(", ")", "{", "_", "=", "gzipWriter", ".", "Close", "(", ")", "\n", "}", "(", ")", "\n\n", "tarWriter", ":=", "tar", ".", "NewWriter", "(", "gzipWriter", ")", "\n", "defer", "func", "(", ")", "{", "_", "=", "tarWriter", ".", "Close", "(", ")", "\n", "}", "(", ")", "\n\n", "err", "=", "fsWalk", "(", "srcDir", ",", "srcDir", ",", "func", "(", "srcPath", "string", ",", "info", "os", ".", "FileInfo", ",", "err", "error", ")", "error", "{", "if", "info", ".", "IsDir", "(", ")", "{", "return", "nil", "\n", "}", "\n\n", "srcFile", ",", "err", ":=", "os", ".", "Open", "(", "srcPath", ")", "\n", "if", "err", "!=", "nil", "{", "return", "NewBuildIfError", "(", "err", ",", "\"", "\"", ",", "\"", "\"", ",", "srcPath", ")", "\n", "}", "\n\n", "defer", "func", "(", ")", "{", "_", "=", "srcFile", ".", "Close", "(", ")", "\n", "}", "(", ")", "\n\n", "err", "=", "tarWriter", ".", "WriteHeader", "(", "&", "tar", ".", "Header", "{", "Name", ":", "strings", ".", "TrimLeft", "(", "srcPath", "[", "len", "(", "srcDir", ")", ":", "]", ",", "string", "(", "os", ".", "PathSeparator", ")", ")", ",", "Size", ":", "info", ".", "Size", "(", ")", ",", "Mode", ":", "int64", "(", "info", ".", "Mode", "(", ")", ")", ",", "ModTime", ":", "info", ".", "ModTime", "(", ")", ",", "}", ")", "\n", "if", "err", "!=", "nil", "{", "return", "NewBuildIfError", "(", "err", ",", "\"", "\"", ",", "\"", "\"", ",", "srcPath", ")", "\n", "}", "\n\n", "_", ",", "err", "=", "io", ".", "Copy", "(", "tarWriter", ",", "srcFile", ")", "\n", "if", "err", "!=", "nil", "{", "return", "NewBuildIfError", "(", "err", ",", "\"", "\"", ",", "\"", "\"", ",", "srcPath", ")", "\n", "}", "\n\n", "return", "nil", "\n", "}", ")", "\n\n", "return", "zipFile", ".", "Name", "(", ")", ",", "err", "\n", "}" ]
// Tar gz the folder
[ "Tar", "gz", "the", "folder" ]
149f9f992be9b0957fb1ffeda43c14a123ceb43a
https://github.com/revel/cmd/blob/149f9f992be9b0957fb1ffeda43c14a123ceb43a/utils/file.go#L247-L300
18,003
revel/cmd
utils/file.go
Empty
func Empty(dirname string) bool { dir, err := os.Open(dirname) if err != nil { Logger.Infof("error opening directory: %s", err) } defer func() { _ = dir.Close() }() results, _ := dir.Readdir(1) return len(results) == 0 }
go
func Empty(dirname string) bool { dir, err := os.Open(dirname) if err != nil { Logger.Infof("error opening directory: %s", err) } defer func() { _ = dir.Close() }() results, _ := dir.Readdir(1) return len(results) == 0 }
[ "func", "Empty", "(", "dirname", "string", ")", "bool", "{", "dir", ",", "err", ":=", "os", ".", "Open", "(", "dirname", ")", "\n", "if", "err", "!=", "nil", "{", "Logger", ".", "Infof", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n", "defer", "func", "(", ")", "{", "_", "=", "dir", ".", "Close", "(", ")", "\n", "}", "(", ")", "\n", "results", ",", "_", ":=", "dir", ".", "Readdir", "(", "1", ")", "\n", "return", "len", "(", "results", ")", "==", "0", "\n", "}" ]
// empty returns true if the given directory is empty. // the directory must exist.
[ "empty", "returns", "true", "if", "the", "given", "directory", "is", "empty", ".", "the", "directory", "must", "exist", "." ]
149f9f992be9b0957fb1ffeda43c14a123ceb43a
https://github.com/revel/cmd/blob/149f9f992be9b0957fb1ffeda43c14a123ceb43a/utils/file.go#L310-L320
18,004
revel/cmd
utils/file.go
FindSrcPaths
func FindSrcPaths(appImportPath, revelImportPath string, packageResolver func(pkgName string) error) (appSourcePath, revelSourcePath string, err error) { var ( gopaths = filepath.SplitList(build.Default.GOPATH) goroot = build.Default.GOROOT ) if len(gopaths) == 0 { err = errors.New("GOPATH environment variable is not set. " + "Please refer to http://golang.org/doc/code.html to configure your Go environment.") return } if ContainsString(gopaths, goroot) { err = fmt.Errorf("GOPATH (%s) must not include your GOROOT (%s). "+ "Please refer to http://golang.org/doc/code.html to configure your Go environment. ", build.Default.GOPATH, goroot) return } appPkgDir := "" appPkgSrcDir := "" if len(appImportPath)>0 { Logger.Info("Seeking app package","app",appImportPath) appPkg, err := build.Import(appImportPath, "", build.FindOnly) if err != nil { err = fmt.Errorf("Failed to import " + appImportPath + " with error %s", err.Error()) return "","",err } appPkgDir,appPkgSrcDir =appPkg.Dir, appPkg.SrcRoot } Logger.Info("Seeking remote package","using",appImportPath, "remote",revelImportPath) revelPkg, err := build.Default.Import(revelImportPath, appPkgDir, build.FindOnly) if err != nil { Logger.Info("Resolved called Seeking remote package","using",appImportPath, "remote",revelImportPath) packageResolver(revelImportPath) revelPkg, err = build.Import(revelImportPath, appPkgDir, build.FindOnly) if err != nil { err = fmt.Errorf("Failed to find Revel with error: %s", err.Error()) return } } revelSourcePath, appSourcePath = revelPkg.Dir[:len(revelPkg.Dir)-len(revelImportPath)], appPkgSrcDir return }
go
func FindSrcPaths(appImportPath, revelImportPath string, packageResolver func(pkgName string) error) (appSourcePath, revelSourcePath string, err error) { var ( gopaths = filepath.SplitList(build.Default.GOPATH) goroot = build.Default.GOROOT ) if len(gopaths) == 0 { err = errors.New("GOPATH environment variable is not set. " + "Please refer to http://golang.org/doc/code.html to configure your Go environment.") return } if ContainsString(gopaths, goroot) { err = fmt.Errorf("GOPATH (%s) must not include your GOROOT (%s). "+ "Please refer to http://golang.org/doc/code.html to configure your Go environment. ", build.Default.GOPATH, goroot) return } appPkgDir := "" appPkgSrcDir := "" if len(appImportPath)>0 { Logger.Info("Seeking app package","app",appImportPath) appPkg, err := build.Import(appImportPath, "", build.FindOnly) if err != nil { err = fmt.Errorf("Failed to import " + appImportPath + " with error %s", err.Error()) return "","",err } appPkgDir,appPkgSrcDir =appPkg.Dir, appPkg.SrcRoot } Logger.Info("Seeking remote package","using",appImportPath, "remote",revelImportPath) revelPkg, err := build.Default.Import(revelImportPath, appPkgDir, build.FindOnly) if err != nil { Logger.Info("Resolved called Seeking remote package","using",appImportPath, "remote",revelImportPath) packageResolver(revelImportPath) revelPkg, err = build.Import(revelImportPath, appPkgDir, build.FindOnly) if err != nil { err = fmt.Errorf("Failed to find Revel with error: %s", err.Error()) return } } revelSourcePath, appSourcePath = revelPkg.Dir[:len(revelPkg.Dir)-len(revelImportPath)], appPkgSrcDir return }
[ "func", "FindSrcPaths", "(", "appImportPath", ",", "revelImportPath", "string", ",", "packageResolver", "func", "(", "pkgName", "string", ")", "error", ")", "(", "appSourcePath", ",", "revelSourcePath", "string", ",", "err", "error", ")", "{", "var", "(", "gopaths", "=", "filepath", ".", "SplitList", "(", "build", ".", "Default", ".", "GOPATH", ")", "\n", "goroot", "=", "build", ".", "Default", ".", "GOROOT", "\n", ")", "\n\n", "if", "len", "(", "gopaths", ")", "==", "0", "{", "err", "=", "errors", ".", "New", "(", "\"", "\"", "+", "\"", "\"", ")", "\n", "return", "\n", "}", "\n\n", "if", "ContainsString", "(", "gopaths", ",", "goroot", ")", "{", "err", "=", "fmt", ".", "Errorf", "(", "\"", "\"", "+", "\"", "\"", ",", "build", ".", "Default", ".", "GOPATH", ",", "goroot", ")", "\n", "return", "\n\n", "}", "\n\n", "appPkgDir", ":=", "\"", "\"", "\n", "appPkgSrcDir", ":=", "\"", "\"", "\n", "if", "len", "(", "appImportPath", ")", ">", "0", "{", "Logger", ".", "Info", "(", "\"", "\"", ",", "\"", "\"", ",", "appImportPath", ")", "\n", "appPkg", ",", "err", ":=", "build", ".", "Import", "(", "appImportPath", ",", "\"", "\"", ",", "build", ".", "FindOnly", ")", "\n", "if", "err", "!=", "nil", "{", "err", "=", "fmt", ".", "Errorf", "(", "\"", "\"", "+", "appImportPath", "+", "\"", "\"", ",", "err", ".", "Error", "(", ")", ")", "\n", "return", "\"", "\"", ",", "\"", "\"", ",", "err", "\n", "}", "\n", "appPkgDir", ",", "appPkgSrcDir", "=", "appPkg", ".", "Dir", ",", "appPkg", ".", "SrcRoot", "\n", "}", "\n", "Logger", ".", "Info", "(", "\"", "\"", ",", "\"", "\"", ",", "appImportPath", ",", "\"", "\"", ",", "revelImportPath", ")", "\n", "revelPkg", ",", "err", ":=", "build", ".", "Default", ".", "Import", "(", "revelImportPath", ",", "appPkgDir", ",", "build", ".", "FindOnly", ")", "\n", "if", "err", "!=", "nil", "{", "Logger", ".", "Info", "(", "\"", "\"", ",", "\"", "\"", ",", "appImportPath", ",", "\"", "\"", ",", "revelImportPath", ")", "\n", "packageResolver", "(", "revelImportPath", ")", "\n", "revelPkg", ",", "err", "=", "build", ".", "Import", "(", "revelImportPath", ",", "appPkgDir", ",", "build", ".", "FindOnly", ")", "\n", "if", "err", "!=", "nil", "{", "err", "=", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ".", "Error", "(", ")", ")", "\n", "return", "\n", "}", "\n", "}", "\n\n", "revelSourcePath", ",", "appSourcePath", "=", "revelPkg", ".", "Dir", "[", ":", "len", "(", "revelPkg", ".", "Dir", ")", "-", "len", "(", "revelImportPath", ")", "]", ",", "appPkgSrcDir", "\n", "return", "\n", "}" ]
// Find the full source dir for the import path, uses the build.Default.GOPATH to search for the directory
[ "Find", "the", "full", "source", "dir", "for", "the", "import", "path", "uses", "the", "build", ".", "Default", ".", "GOPATH", "to", "search", "for", "the", "directory" ]
149f9f992be9b0957fb1ffeda43c14a123ceb43a
https://github.com/revel/cmd/blob/149f9f992be9b0957fb1ffeda43c14a123ceb43a/utils/file.go#L323-L368
18,005
revel/cmd
model/version.go
intOrZero
func (v *Version) intOrZero(input string) (value int) { if input != "" { value, _ = strconv.Atoi(input) } return value }
go
func (v *Version) intOrZero(input string) (value int) { if input != "" { value, _ = strconv.Atoi(input) } return value }
[ "func", "(", "v", "*", "Version", ")", "intOrZero", "(", "input", "string", ")", "(", "value", "int", ")", "{", "if", "input", "!=", "\"", "\"", "{", "value", ",", "_", "=", "strconv", ".", "Atoi", "(", "input", ")", "\n", "}", "\n", "return", "value", "\n", "}" ]
// Returns 0 or an int value for the string, errors are returned as 0
[ "Returns", "0", "or", "an", "int", "value", "for", "the", "string", "errors", "are", "returned", "as", "0" ]
149f9f992be9b0957fb1ffeda43c14a123ceb43a
https://github.com/revel/cmd/blob/149f9f992be9b0957fb1ffeda43c14a123ceb43a/model/version.go#L58-L63
18,006
revel/cmd
model/version.go
CompatibleFramework
func (v *Version) CompatibleFramework(c *CommandConfig) error { for i, rv := range frameworkCompatibleRangeList { start, _ := ParseVersion(rv[0]) end, _ := ParseVersion(rv[1]) if !v.Newer(start) || v.Newer(end) { continue } // Framework is older then 0.20, turn on historic mode if i == 0 { c.HistoricMode = true } return nil } return errors.New("Tool out of date - do a 'go get -u github.com/revel/cmd/revel'") }
go
func (v *Version) CompatibleFramework(c *CommandConfig) error { for i, rv := range frameworkCompatibleRangeList { start, _ := ParseVersion(rv[0]) end, _ := ParseVersion(rv[1]) if !v.Newer(start) || v.Newer(end) { continue } // Framework is older then 0.20, turn on historic mode if i == 0 { c.HistoricMode = true } return nil } return errors.New("Tool out of date - do a 'go get -u github.com/revel/cmd/revel'") }
[ "func", "(", "v", "*", "Version", ")", "CompatibleFramework", "(", "c", "*", "CommandConfig", ")", "error", "{", "for", "i", ",", "rv", ":=", "range", "frameworkCompatibleRangeList", "{", "start", ",", "_", ":=", "ParseVersion", "(", "rv", "[", "0", "]", ")", "\n", "end", ",", "_", ":=", "ParseVersion", "(", "rv", "[", "1", "]", ")", "\n", "if", "!", "v", ".", "Newer", "(", "start", ")", "||", "v", ".", "Newer", "(", "end", ")", "{", "continue", "\n", "}", "\n", "// Framework is older then 0.20, turn on historic mode", "if", "i", "==", "0", "{", "c", ".", "HistoricMode", "=", "true", "\n", "}", "\n", "return", "nil", "\n", "}", "\n", "return", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}" ]
// Returns true if this major revision is compatible
[ "Returns", "true", "if", "this", "major", "revision", "is", "compatible" ]
149f9f992be9b0957fb1ffeda43c14a123ceb43a
https://github.com/revel/cmd/blob/149f9f992be9b0957fb1ffeda43c14a123ceb43a/model/version.go#L66-L80
18,007
revel/cmd
model/version.go
MajorNewer
func (v *Version) MajorNewer(o *Version) bool { if v.Major != o.Major { return v.Major > o.Major } return false }
go
func (v *Version) MajorNewer(o *Version) bool { if v.Major != o.Major { return v.Major > o.Major } return false }
[ "func", "(", "v", "*", "Version", ")", "MajorNewer", "(", "o", "*", "Version", ")", "bool", "{", "if", "v", ".", "Major", "!=", "o", ".", "Major", "{", "return", "v", ".", "Major", ">", "o", ".", "Major", "\n", "}", "\n", "return", "false", "\n", "}" ]
// Returns true if this major revision is newer then the passed in
[ "Returns", "true", "if", "this", "major", "revision", "is", "newer", "then", "the", "passed", "in" ]
149f9f992be9b0957fb1ffeda43c14a123ceb43a
https://github.com/revel/cmd/blob/149f9f992be9b0957fb1ffeda43c14a123ceb43a/model/version.go#L83-L88
18,008
revel/cmd
model/version.go
MinorNewer
func (v *Version) MinorNewer(o *Version) bool { if v.Major != o.Major { return v.Major > o.Major } if v.Minor != o.Minor { return v.Minor > o.Minor } return false }
go
func (v *Version) MinorNewer(o *Version) bool { if v.Major != o.Major { return v.Major > o.Major } if v.Minor != o.Minor { return v.Minor > o.Minor } return false }
[ "func", "(", "v", "*", "Version", ")", "MinorNewer", "(", "o", "*", "Version", ")", "bool", "{", "if", "v", ".", "Major", "!=", "o", ".", "Major", "{", "return", "v", ".", "Major", ">", "o", ".", "Major", "\n", "}", "\n", "if", "v", ".", "Minor", "!=", "o", ".", "Minor", "{", "return", "v", ".", "Minor", ">", "o", ".", "Minor", "\n", "}", "\n", "return", "false", "\n", "}" ]
// Returns true if this major or major and minor revision is newer then the value passed in
[ "Returns", "true", "if", "this", "major", "or", "major", "and", "minor", "revision", "is", "newer", "then", "the", "value", "passed", "in" ]
149f9f992be9b0957fb1ffeda43c14a123ceb43a
https://github.com/revel/cmd/blob/149f9f992be9b0957fb1ffeda43c14a123ceb43a/model/version.go#L91-L99
18,009
revel/cmd
model/version.go
Newer
func (v *Version) Newer(o *Version) bool { if v.Major != o.Major { return v.Major > o.Major } if v.Minor != o.Minor { return v.Minor > o.Minor } if v.Maintenance != o.Maintenance { return v.Maintenance > o.Maintenance } return false }
go
func (v *Version) Newer(o *Version) bool { if v.Major != o.Major { return v.Major > o.Major } if v.Minor != o.Minor { return v.Minor > o.Minor } if v.Maintenance != o.Maintenance { return v.Maintenance > o.Maintenance } return false }
[ "func", "(", "v", "*", "Version", ")", "Newer", "(", "o", "*", "Version", ")", "bool", "{", "if", "v", ".", "Major", "!=", "o", ".", "Major", "{", "return", "v", ".", "Major", ">", "o", ".", "Major", "\n", "}", "\n", "if", "v", ".", "Minor", "!=", "o", ".", "Minor", "{", "return", "v", ".", "Minor", ">", "o", ".", "Minor", "\n", "}", "\n", "if", "v", ".", "Maintenance", "!=", "o", ".", "Maintenance", "{", "return", "v", ".", "Maintenance", ">", "o", ".", "Maintenance", "\n", "}", "\n", "return", "false", "\n", "}" ]
// Returns true if the version is newer then the current on
[ "Returns", "true", "if", "the", "version", "is", "newer", "then", "the", "current", "on" ]
149f9f992be9b0957fb1ffeda43c14a123ceb43a
https://github.com/revel/cmd/blob/149f9f992be9b0957fb1ffeda43c14a123ceb43a/model/version.go#L102-L113
18,010
revel/cmd
model/version.go
VersionString
func (v *Version) VersionString() string { return fmt.Sprintf("%s%d.%d.%d%s", v.Prefix, v.Major, v.Minor, v.Maintenance, v.Suffix) }
go
func (v *Version) VersionString() string { return fmt.Sprintf("%s%d.%d.%d%s", v.Prefix, v.Major, v.Minor, v.Maintenance, v.Suffix) }
[ "func", "(", "v", "*", "Version", ")", "VersionString", "(", ")", "string", "{", "return", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "v", ".", "Prefix", ",", "v", ".", "Major", ",", "v", ".", "Minor", ",", "v", ".", "Maintenance", ",", "v", ".", "Suffix", ")", "\n", "}" ]
// Convert the version to a string
[ "Convert", "the", "version", "to", "a", "string" ]
149f9f992be9b0957fb1ffeda43c14a123ceb43a
https://github.com/revel/cmd/blob/149f9f992be9b0957fb1ffeda43c14a123ceb43a/model/version.go#L116-L118
18,011
revel/cmd
model/version.go
String
func (v *Version) String() string { return fmt.Sprintf("Version: %s%d.%d.%d%s\nBuild Date: %s\n Minimium Go Version: %s", v.Prefix, v.Major, v.Minor, v.Maintenance, v.Suffix, v.BuildDate, v.MinGoVersion) }
go
func (v *Version) String() string { return fmt.Sprintf("Version: %s%d.%d.%d%s\nBuild Date: %s\n Minimium Go Version: %s", v.Prefix, v.Major, v.Minor, v.Maintenance, v.Suffix, v.BuildDate, v.MinGoVersion) }
[ "func", "(", "v", "*", "Version", ")", "String", "(", ")", "string", "{", "return", "fmt", ".", "Sprintf", "(", "\"", "\\n", "\\n", "\"", ",", "v", ".", "Prefix", ",", "v", ".", "Major", ",", "v", ".", "Minor", ",", "v", ".", "Maintenance", ",", "v", ".", "Suffix", ",", "v", ".", "BuildDate", ",", "v", ".", "MinGoVersion", ")", "\n", "}" ]
// Convert the version build date and go version to a string
[ "Convert", "the", "version", "build", "date", "and", "go", "version", "to", "a", "string" ]
149f9f992be9b0957fb1ffeda43c14a123ceb43a
https://github.com/revel/cmd/blob/149f9f992be9b0957fb1ffeda43c14a123ceb43a/model/version.go#L121-L124
18,012
revel/cmd
harness/harness.go
ServeHTTP
func (h *Harness) ServeHTTP(w http.ResponseWriter, r *http.Request) { // Don't rebuild the app for favicon requests. if lastRequestHadError > 0 && r.URL.Path == "/favicon.ico" { return } // Flush any change events and rebuild app if necessary. // Render an error page if the rebuild / restart failed. err := h.watcher.Notify() if err != nil { // In a thread safe manner update the flag so that a request for // /favicon.ico does not trigger a rebuild atomic.CompareAndSwapInt32(&lastRequestHadError, 0, 1) h.renderError(w, r, err) return } // In a thread safe manner update the flag so that a request for // /favicon.ico is allowed atomic.CompareAndSwapInt32(&lastRequestHadError, 1, 0) // Reverse proxy the request. // (Need special code for websockets, courtesy of bradfitz) if strings.EqualFold(r.Header.Get("Upgrade"), "websocket") { h.proxyWebsocket(w, r, h.serverHost) } else { h.proxy.ServeHTTP(w, r) } }
go
func (h *Harness) ServeHTTP(w http.ResponseWriter, r *http.Request) { // Don't rebuild the app for favicon requests. if lastRequestHadError > 0 && r.URL.Path == "/favicon.ico" { return } // Flush any change events and rebuild app if necessary. // Render an error page if the rebuild / restart failed. err := h.watcher.Notify() if err != nil { // In a thread safe manner update the flag so that a request for // /favicon.ico does not trigger a rebuild atomic.CompareAndSwapInt32(&lastRequestHadError, 0, 1) h.renderError(w, r, err) return } // In a thread safe manner update the flag so that a request for // /favicon.ico is allowed atomic.CompareAndSwapInt32(&lastRequestHadError, 1, 0) // Reverse proxy the request. // (Need special code for websockets, courtesy of bradfitz) if strings.EqualFold(r.Header.Get("Upgrade"), "websocket") { h.proxyWebsocket(w, r, h.serverHost) } else { h.proxy.ServeHTTP(w, r) } }
[ "func", "(", "h", "*", "Harness", ")", "ServeHTTP", "(", "w", "http", ".", "ResponseWriter", ",", "r", "*", "http", ".", "Request", ")", "{", "// Don't rebuild the app for favicon requests.", "if", "lastRequestHadError", ">", "0", "&&", "r", ".", "URL", ".", "Path", "==", "\"", "\"", "{", "return", "\n", "}", "\n\n", "// Flush any change events and rebuild app if necessary.", "// Render an error page if the rebuild / restart failed.", "err", ":=", "h", ".", "watcher", ".", "Notify", "(", ")", "\n", "if", "err", "!=", "nil", "{", "// In a thread safe manner update the flag so that a request for", "// /favicon.ico does not trigger a rebuild", "atomic", ".", "CompareAndSwapInt32", "(", "&", "lastRequestHadError", ",", "0", ",", "1", ")", "\n", "h", ".", "renderError", "(", "w", ",", "r", ",", "err", ")", "\n", "return", "\n", "}", "\n\n", "// In a thread safe manner update the flag so that a request for", "// /favicon.ico is allowed", "atomic", ".", "CompareAndSwapInt32", "(", "&", "lastRequestHadError", ",", "1", ",", "0", ")", "\n\n", "// Reverse proxy the request.", "// (Need special code for websockets, courtesy of bradfitz)", "if", "strings", ".", "EqualFold", "(", "r", ".", "Header", ".", "Get", "(", "\"", "\"", ")", ",", "\"", "\"", ")", "{", "h", ".", "proxyWebsocket", "(", "w", ",", "r", ",", "h", ".", "serverHost", ")", "\n", "}", "else", "{", "h", ".", "proxy", ".", "ServeHTTP", "(", "w", ",", "r", ")", "\n", "}", "\n", "}" ]
// ServeHTTP handles all requests. // It checks for changes to app, rebuilds if necessary, and forwards the request.
[ "ServeHTTP", "handles", "all", "requests", ".", "It", "checks", "for", "changes", "to", "app", "rebuilds", "if", "necessary", "and", "forwards", "the", "request", "." ]
149f9f992be9b0957fb1ffeda43c14a123ceb43a
https://github.com/revel/cmd/blob/149f9f992be9b0957fb1ffeda43c14a123ceb43a/harness/harness.go#L120-L148
18,013
revel/cmd
harness/harness.go
NewHarness
func NewHarness(c *model.CommandConfig, paths *model.RevelContainer, runMode string, noProxy bool) *Harness { // Get a template loader to render errors. // Prefer the app's views/errors directory, and fall back to the stock error pages. //revel.MainTemplateLoader = revel.NewTemplateLoader( // []string{filepath.Join(revel.RevelPath, "templates")}) //if err := revel.MainTemplateLoader.Refresh(); err != nil { // revel.RevelLog.Error("Template loader error", "error", err) //} addr := paths.HTTPAddr port := paths.Config.IntDefault("harness.port", 0) scheme := "http" if paths.HTTPSsl { scheme = "https" } // If the server is running on the wildcard address, use "localhost" if addr == "" { utils.Logger.Warn("No http.addr specified in the app.conf listening on localhost interface only. " + "This will not allow external access to your application") addr = "localhost" } if port == 0 { port = getFreePort() } serverURL, _ := url.ParseRequestURI(fmt.Sprintf(scheme+"://%s:%d", addr, port)) serverHarness := &Harness{ port: port, serverHost: serverURL.String()[len(scheme+"://"):], proxy: httputil.NewSingleHostReverseProxy(serverURL), mutex: &sync.Mutex{}, paths: paths, useProxy: !noProxy, config: c, runMode: runMode, } if paths.HTTPSsl { serverHarness.proxy.Transport = &http.Transport{ TLSClientConfig: &tls.Config{InsecureSkipVerify: true}, } } return serverHarness }
go
func NewHarness(c *model.CommandConfig, paths *model.RevelContainer, runMode string, noProxy bool) *Harness { // Get a template loader to render errors. // Prefer the app's views/errors directory, and fall back to the stock error pages. //revel.MainTemplateLoader = revel.NewTemplateLoader( // []string{filepath.Join(revel.RevelPath, "templates")}) //if err := revel.MainTemplateLoader.Refresh(); err != nil { // revel.RevelLog.Error("Template loader error", "error", err) //} addr := paths.HTTPAddr port := paths.Config.IntDefault("harness.port", 0) scheme := "http" if paths.HTTPSsl { scheme = "https" } // If the server is running on the wildcard address, use "localhost" if addr == "" { utils.Logger.Warn("No http.addr specified in the app.conf listening on localhost interface only. " + "This will not allow external access to your application") addr = "localhost" } if port == 0 { port = getFreePort() } serverURL, _ := url.ParseRequestURI(fmt.Sprintf(scheme+"://%s:%d", addr, port)) serverHarness := &Harness{ port: port, serverHost: serverURL.String()[len(scheme+"://"):], proxy: httputil.NewSingleHostReverseProxy(serverURL), mutex: &sync.Mutex{}, paths: paths, useProxy: !noProxy, config: c, runMode: runMode, } if paths.HTTPSsl { serverHarness.proxy.Transport = &http.Transport{ TLSClientConfig: &tls.Config{InsecureSkipVerify: true}, } } return serverHarness }
[ "func", "NewHarness", "(", "c", "*", "model", ".", "CommandConfig", ",", "paths", "*", "model", ".", "RevelContainer", ",", "runMode", "string", ",", "noProxy", "bool", ")", "*", "Harness", "{", "// Get a template loader to render errors.", "// Prefer the app's views/errors directory, and fall back to the stock error pages.", "//revel.MainTemplateLoader = revel.NewTemplateLoader(", "//\t[]string{filepath.Join(revel.RevelPath, \"templates\")})", "//if err := revel.MainTemplateLoader.Refresh(); err != nil {", "//\trevel.RevelLog.Error(\"Template loader error\", \"error\", err)", "//}", "addr", ":=", "paths", ".", "HTTPAddr", "\n", "port", ":=", "paths", ".", "Config", ".", "IntDefault", "(", "\"", "\"", ",", "0", ")", "\n", "scheme", ":=", "\"", "\"", "\n", "if", "paths", ".", "HTTPSsl", "{", "scheme", "=", "\"", "\"", "\n", "}", "\n\n", "// If the server is running on the wildcard address, use \"localhost\"", "if", "addr", "==", "\"", "\"", "{", "utils", ".", "Logger", ".", "Warn", "(", "\"", "\"", "+", "\"", "\"", ")", "\n", "addr", "=", "\"", "\"", "\n", "}", "\n\n", "if", "port", "==", "0", "{", "port", "=", "getFreePort", "(", ")", "\n", "}", "\n\n", "serverURL", ",", "_", ":=", "url", ".", "ParseRequestURI", "(", "fmt", ".", "Sprintf", "(", "scheme", "+", "\"", "\"", ",", "addr", ",", "port", ")", ")", "\n\n", "serverHarness", ":=", "&", "Harness", "{", "port", ":", "port", ",", "serverHost", ":", "serverURL", ".", "String", "(", ")", "[", "len", "(", "scheme", "+", "\"", "\"", ")", ":", "]", ",", "proxy", ":", "httputil", ".", "NewSingleHostReverseProxy", "(", "serverURL", ")", ",", "mutex", ":", "&", "sync", ".", "Mutex", "{", "}", ",", "paths", ":", "paths", ",", "useProxy", ":", "!", "noProxy", ",", "config", ":", "c", ",", "runMode", ":", "runMode", ",", "}", "\n\n", "if", "paths", ".", "HTTPSsl", "{", "serverHarness", ".", "proxy", ".", "Transport", "=", "&", "http", ".", "Transport", "{", "TLSClientConfig", ":", "&", "tls", ".", "Config", "{", "InsecureSkipVerify", ":", "true", "}", ",", "}", "\n", "}", "\n", "return", "serverHarness", "\n", "}" ]
// NewHarness method returns a reverse proxy that forwards requests // to the given port.
[ "NewHarness", "method", "returns", "a", "reverse", "proxy", "that", "forwards", "requests", "to", "the", "given", "port", "." ]
149f9f992be9b0957fb1ffeda43c14a123ceb43a
https://github.com/revel/cmd/blob/149f9f992be9b0957fb1ffeda43c14a123ceb43a/harness/harness.go#L152-L198
18,014
revel/cmd
harness/harness.go
Refresh
func (h *Harness) Refresh() (err *utils.Error) { // Allow only one thread to rebuild the process // If multiple requests to rebuild are queued only the last one is executed on // So before a build is started we wait for a second to determine if // more requests for a build are triggered. // Once no more requests are triggered the build will be processed h.mutex.Lock() defer h.mutex.Unlock() if h.app != nil { h.app.Kill() } utils.Logger.Info("Rebuild Called") var newErr error h.app, newErr = Build(h.config, h.paths) if newErr != nil { utils.Logger.Error("Build detected an error", "error", newErr) if castErr, ok := newErr.(*utils.Error); ok { return castErr } err = &utils.Error{ Title: "App failed to start up", Description: err.Error(), } return } if h.useProxy { h.app.Port = h.port if err2 := h.app.Cmd(h.runMode).Start(h.config); err2 != nil { utils.Logger.Error("Could not start application", "error", err2) if err,k :=err2.(*utils.Error);k { return err } return &utils.Error{ Title: "App failed to start up", Description: err2.Error(), } } } else { h.app = nil } return }
go
func (h *Harness) Refresh() (err *utils.Error) { // Allow only one thread to rebuild the process // If multiple requests to rebuild are queued only the last one is executed on // So before a build is started we wait for a second to determine if // more requests for a build are triggered. // Once no more requests are triggered the build will be processed h.mutex.Lock() defer h.mutex.Unlock() if h.app != nil { h.app.Kill() } utils.Logger.Info("Rebuild Called") var newErr error h.app, newErr = Build(h.config, h.paths) if newErr != nil { utils.Logger.Error("Build detected an error", "error", newErr) if castErr, ok := newErr.(*utils.Error); ok { return castErr } err = &utils.Error{ Title: "App failed to start up", Description: err.Error(), } return } if h.useProxy { h.app.Port = h.port if err2 := h.app.Cmd(h.runMode).Start(h.config); err2 != nil { utils.Logger.Error("Could not start application", "error", err2) if err,k :=err2.(*utils.Error);k { return err } return &utils.Error{ Title: "App failed to start up", Description: err2.Error(), } } } else { h.app = nil } return }
[ "func", "(", "h", "*", "Harness", ")", "Refresh", "(", ")", "(", "err", "*", "utils", ".", "Error", ")", "{", "// Allow only one thread to rebuild the process", "// If multiple requests to rebuild are queued only the last one is executed on", "// So before a build is started we wait for a second to determine if", "// more requests for a build are triggered.", "// Once no more requests are triggered the build will be processed", "h", ".", "mutex", ".", "Lock", "(", ")", "\n", "defer", "h", ".", "mutex", ".", "Unlock", "(", ")", "\n\n", "if", "h", ".", "app", "!=", "nil", "{", "h", ".", "app", ".", "Kill", "(", ")", "\n", "}", "\n\n", "utils", ".", "Logger", ".", "Info", "(", "\"", "\"", ")", "\n", "var", "newErr", "error", "\n", "h", ".", "app", ",", "newErr", "=", "Build", "(", "h", ".", "config", ",", "h", ".", "paths", ")", "\n", "if", "newErr", "!=", "nil", "{", "utils", ".", "Logger", ".", "Error", "(", "\"", "\"", ",", "\"", "\"", ",", "newErr", ")", "\n", "if", "castErr", ",", "ok", ":=", "newErr", ".", "(", "*", "utils", ".", "Error", ")", ";", "ok", "{", "return", "castErr", "\n", "}", "\n", "err", "=", "&", "utils", ".", "Error", "{", "Title", ":", "\"", "\"", ",", "Description", ":", "err", ".", "Error", "(", ")", ",", "}", "\n", "return", "\n", "}", "\n\n", "if", "h", ".", "useProxy", "{", "h", ".", "app", ".", "Port", "=", "h", ".", "port", "\n", "if", "err2", ":=", "h", ".", "app", ".", "Cmd", "(", "h", ".", "runMode", ")", ".", "Start", "(", "h", ".", "config", ")", ";", "err2", "!=", "nil", "{", "utils", ".", "Logger", ".", "Error", "(", "\"", "\"", ",", "\"", "\"", ",", "err2", ")", "\n", "if", "err", ",", "k", ":=", "err2", ".", "(", "*", "utils", ".", "Error", ")", ";", "k", "{", "return", "err", "\n", "}", "\n", "return", "&", "utils", ".", "Error", "{", "Title", ":", "\"", "\"", ",", "Description", ":", "err2", ".", "Error", "(", ")", ",", "}", "\n", "}", "\n", "}", "else", "{", "h", ".", "app", "=", "nil", "\n", "}", "\n\n", "return", "\n", "}" ]
// Refresh method rebuilds the Revel application and run it on the given port. // called by the watcher
[ "Refresh", "method", "rebuilds", "the", "Revel", "application", "and", "run", "it", "on", "the", "given", "port", ".", "called", "by", "the", "watcher" ]
149f9f992be9b0957fb1ffeda43c14a123ceb43a
https://github.com/revel/cmd/blob/149f9f992be9b0957fb1ffeda43c14a123ceb43a/harness/harness.go#L202-L247
18,015
revel/cmd
harness/harness.go
WatchDir
func (h *Harness) WatchDir(info os.FileInfo) bool { return !utils.ContainsString(doNotWatch, info.Name()) }
go
func (h *Harness) WatchDir(info os.FileInfo) bool { return !utils.ContainsString(doNotWatch, info.Name()) }
[ "func", "(", "h", "*", "Harness", ")", "WatchDir", "(", "info", "os", ".", "FileInfo", ")", "bool", "{", "return", "!", "utils", ".", "ContainsString", "(", "doNotWatch", ",", "info", ".", "Name", "(", ")", ")", "\n", "}" ]
// WatchDir method returns false to file matches with doNotWatch // otheriwse true
[ "WatchDir", "method", "returns", "false", "to", "file", "matches", "with", "doNotWatch", "otheriwse", "true" ]
149f9f992be9b0957fb1ffeda43c14a123ceb43a
https://github.com/revel/cmd/blob/149f9f992be9b0957fb1ffeda43c14a123ceb43a/harness/harness.go#L251-L253
18,016
revel/cmd
harness/harness.go
Run
func (h *Harness) Run() { var paths []string if h.paths.Config.BoolDefault("watch.gopath", false) { gopaths := filepath.SplitList(build.Default.GOPATH) paths = append(paths, gopaths...) } paths = append(paths, h.paths.CodePaths...) h.watcher = watcher.NewWatcher(h.paths, false) h.watcher.Listen(h, paths...) h.watcher.Notify() if h.useProxy { go func() { // Check the port to start on a random port if h.paths.HTTPPort == 0 { h.paths.HTTPPort = getFreePort() } addr := fmt.Sprintf("%s:%d", h.paths.HTTPAddr, h.paths.HTTPPort) utils.Logger.Infof("Proxy server is listening on %s", addr) var err error if h.paths.HTTPSsl { err = http.ListenAndServeTLS( addr, h.paths.HTTPSslCert, h.paths.HTTPSslKey, h) } else { err = http.ListenAndServe(addr, h) } if err != nil { utils.Logger.Error("Failed to start reverse proxy:", "error", err) } }() } // Kill the app on signal. ch := make(chan os.Signal) signal.Notify(ch, os.Interrupt, os.Kill) <-ch if h.app != nil { h.app.Kill() } os.Exit(1) }
go
func (h *Harness) Run() { var paths []string if h.paths.Config.BoolDefault("watch.gopath", false) { gopaths := filepath.SplitList(build.Default.GOPATH) paths = append(paths, gopaths...) } paths = append(paths, h.paths.CodePaths...) h.watcher = watcher.NewWatcher(h.paths, false) h.watcher.Listen(h, paths...) h.watcher.Notify() if h.useProxy { go func() { // Check the port to start on a random port if h.paths.HTTPPort == 0 { h.paths.HTTPPort = getFreePort() } addr := fmt.Sprintf("%s:%d", h.paths.HTTPAddr, h.paths.HTTPPort) utils.Logger.Infof("Proxy server is listening on %s", addr) var err error if h.paths.HTTPSsl { err = http.ListenAndServeTLS( addr, h.paths.HTTPSslCert, h.paths.HTTPSslKey, h) } else { err = http.ListenAndServe(addr, h) } if err != nil { utils.Logger.Error("Failed to start reverse proxy:", "error", err) } }() } // Kill the app on signal. ch := make(chan os.Signal) signal.Notify(ch, os.Interrupt, os.Kill) <-ch if h.app != nil { h.app.Kill() } os.Exit(1) }
[ "func", "(", "h", "*", "Harness", ")", "Run", "(", ")", "{", "var", "paths", "[", "]", "string", "\n", "if", "h", ".", "paths", ".", "Config", ".", "BoolDefault", "(", "\"", "\"", ",", "false", ")", "{", "gopaths", ":=", "filepath", ".", "SplitList", "(", "build", ".", "Default", ".", "GOPATH", ")", "\n", "paths", "=", "append", "(", "paths", ",", "gopaths", "...", ")", "\n", "}", "\n", "paths", "=", "append", "(", "paths", ",", "h", ".", "paths", ".", "CodePaths", "...", ")", "\n", "h", ".", "watcher", "=", "watcher", ".", "NewWatcher", "(", "h", ".", "paths", ",", "false", ")", "\n", "h", ".", "watcher", ".", "Listen", "(", "h", ",", "paths", "...", ")", "\n", "h", ".", "watcher", ".", "Notify", "(", ")", "\n\n", "if", "h", ".", "useProxy", "{", "go", "func", "(", ")", "{", "// Check the port to start on a random port", "if", "h", ".", "paths", ".", "HTTPPort", "==", "0", "{", "h", ".", "paths", ".", "HTTPPort", "=", "getFreePort", "(", ")", "\n", "}", "\n", "addr", ":=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "h", ".", "paths", ".", "HTTPAddr", ",", "h", ".", "paths", ".", "HTTPPort", ")", "\n", "utils", ".", "Logger", ".", "Infof", "(", "\"", "\"", ",", "addr", ")", "\n\n", "var", "err", "error", "\n", "if", "h", ".", "paths", ".", "HTTPSsl", "{", "err", "=", "http", ".", "ListenAndServeTLS", "(", "addr", ",", "h", ".", "paths", ".", "HTTPSslCert", ",", "h", ".", "paths", ".", "HTTPSslKey", ",", "h", ")", "\n", "}", "else", "{", "err", "=", "http", ".", "ListenAndServe", "(", "addr", ",", "h", ")", "\n", "}", "\n", "if", "err", "!=", "nil", "{", "utils", ".", "Logger", ".", "Error", "(", "\"", "\"", ",", "\"", "\"", ",", "err", ")", "\n", "}", "\n", "}", "(", ")", "\n\n", "}", "\n", "// Kill the app on signal.", "ch", ":=", "make", "(", "chan", "os", ".", "Signal", ")", "\n", "signal", ".", "Notify", "(", "ch", ",", "os", ".", "Interrupt", ",", "os", ".", "Kill", ")", "\n", "<-", "ch", "\n", "if", "h", ".", "app", "!=", "nil", "{", "h", ".", "app", ".", "Kill", "(", ")", "\n", "}", "\n", "os", ".", "Exit", "(", "1", ")", "\n", "}" ]
// Run the harness, which listens for requests and proxies them to the app // server, which it runs and rebuilds as necessary.
[ "Run", "the", "harness", "which", "listens", "for", "requests", "and", "proxies", "them", "to", "the", "app", "server", "which", "it", "runs", "and", "rebuilds", "as", "necessary", "." ]
149f9f992be9b0957fb1ffeda43c14a123ceb43a
https://github.com/revel/cmd/blob/149f9f992be9b0957fb1ffeda43c14a123ceb43a/harness/harness.go#L263-L307
18,017
revel/cmd
harness/harness.go
getFreePort
func getFreePort() (port int) { conn, err := net.Listen("tcp", ":0") if err != nil { utils.Logger.Fatal("Unable to fetch a freee port address", "error", err) } port = conn.Addr().(*net.TCPAddr).Port err = conn.Close() if err != nil { utils.Logger.Fatal("Unable to close port", "error", err) } return port }
go
func getFreePort() (port int) { conn, err := net.Listen("tcp", ":0") if err != nil { utils.Logger.Fatal("Unable to fetch a freee port address", "error", err) } port = conn.Addr().(*net.TCPAddr).Port err = conn.Close() if err != nil { utils.Logger.Fatal("Unable to close port", "error", err) } return port }
[ "func", "getFreePort", "(", ")", "(", "port", "int", ")", "{", "conn", ",", "err", ":=", "net", ".", "Listen", "(", "\"", "\"", ",", "\"", "\"", ")", "\n", "if", "err", "!=", "nil", "{", "utils", ".", "Logger", ".", "Fatal", "(", "\"", "\"", ",", "\"", "\"", ",", "err", ")", "\n", "}", "\n\n", "port", "=", "conn", ".", "Addr", "(", ")", ".", "(", "*", "net", ".", "TCPAddr", ")", ".", "Port", "\n", "err", "=", "conn", ".", "Close", "(", ")", "\n", "if", "err", "!=", "nil", "{", "utils", ".", "Logger", ".", "Fatal", "(", "\"", "\"", ",", "\"", "\"", ",", "err", ")", "\n", "}", "\n", "return", "port", "\n", "}" ]
// Find an unused port
[ "Find", "an", "unused", "port" ]
149f9f992be9b0957fb1ffeda43c14a123ceb43a
https://github.com/revel/cmd/blob/149f9f992be9b0957fb1ffeda43c14a123ceb43a/harness/harness.go#L310-L322
18,018
revel/cmd
parser/appends.go
appendStruct
func appendStruct(fileName string, specs []*model.TypeInfo, pkgImportPath string, pkg *ast.Package, decl ast.Decl, imports map[string]string, fset *token.FileSet) []*model.TypeInfo { // Filter out non-Struct type declarations. spec, found := getStructTypeDecl(decl, fset) if !found { return specs } structType := spec.Type.(*ast.StructType) // At this point we know it's a type declaration for a struct. // Fill in the rest of the info by diving into the fields. // Add it provisionally to the Controller list -- it's later filtered using field info. controllerSpec := &model.TypeInfo{ StructName: spec.Name.Name, ImportPath: pkgImportPath, PackageName: pkg.Name, } for _, field := range structType.Fields.List { // If field.Names is set, it's not an embedded type. if field.Names != nil { continue } // A direct "sub-type" has an ast.Field as either: // Ident { "AppController" } // SelectorExpr { "rev", "Controller" } // Additionally, that can be wrapped by StarExprs. fieldType := field.Type pkgName, typeName := func() (string, string) { // Drill through any StarExprs. for { if starExpr, ok := fieldType.(*ast.StarExpr); ok { fieldType = starExpr.X continue } break } // If the embedded type is in the same package, it's an Ident. if ident, ok := fieldType.(*ast.Ident); ok { return "", ident.Name } if selectorExpr, ok := fieldType.(*ast.SelectorExpr); ok { if pkgIdent, ok := selectorExpr.X.(*ast.Ident); ok { return pkgIdent.Name, selectorExpr.Sel.Name } } return "", "" }() // If a typename wasn't found, skip it. if typeName == "" { continue } // Find the import path for this type. // If it was referenced without a package name, use the current package import path. // Else, look up the package's import path by name. var importPath string if pkgName == "" { importPath = pkgImportPath } else { var ok bool if importPath, ok = imports[pkgName]; !ok { utils.Logger.Error("Error: Failed to find import path for ", "package", pkgName, "type", typeName) continue } } controllerSpec.EmbeddedTypes = append(controllerSpec.EmbeddedTypes, &model.EmbeddedTypeName{ ImportPath: importPath, StructName: typeName, }) } return append(specs, controllerSpec) }
go
func appendStruct(fileName string, specs []*model.TypeInfo, pkgImportPath string, pkg *ast.Package, decl ast.Decl, imports map[string]string, fset *token.FileSet) []*model.TypeInfo { // Filter out non-Struct type declarations. spec, found := getStructTypeDecl(decl, fset) if !found { return specs } structType := spec.Type.(*ast.StructType) // At this point we know it's a type declaration for a struct. // Fill in the rest of the info by diving into the fields. // Add it provisionally to the Controller list -- it's later filtered using field info. controllerSpec := &model.TypeInfo{ StructName: spec.Name.Name, ImportPath: pkgImportPath, PackageName: pkg.Name, } for _, field := range structType.Fields.List { // If field.Names is set, it's not an embedded type. if field.Names != nil { continue } // A direct "sub-type" has an ast.Field as either: // Ident { "AppController" } // SelectorExpr { "rev", "Controller" } // Additionally, that can be wrapped by StarExprs. fieldType := field.Type pkgName, typeName := func() (string, string) { // Drill through any StarExprs. for { if starExpr, ok := fieldType.(*ast.StarExpr); ok { fieldType = starExpr.X continue } break } // If the embedded type is in the same package, it's an Ident. if ident, ok := fieldType.(*ast.Ident); ok { return "", ident.Name } if selectorExpr, ok := fieldType.(*ast.SelectorExpr); ok { if pkgIdent, ok := selectorExpr.X.(*ast.Ident); ok { return pkgIdent.Name, selectorExpr.Sel.Name } } return "", "" }() // If a typename wasn't found, skip it. if typeName == "" { continue } // Find the import path for this type. // If it was referenced without a package name, use the current package import path. // Else, look up the package's import path by name. var importPath string if pkgName == "" { importPath = pkgImportPath } else { var ok bool if importPath, ok = imports[pkgName]; !ok { utils.Logger.Error("Error: Failed to find import path for ", "package", pkgName, "type", typeName) continue } } controllerSpec.EmbeddedTypes = append(controllerSpec.EmbeddedTypes, &model.EmbeddedTypeName{ ImportPath: importPath, StructName: typeName, }) } return append(specs, controllerSpec) }
[ "func", "appendStruct", "(", "fileName", "string", ",", "specs", "[", "]", "*", "model", ".", "TypeInfo", ",", "pkgImportPath", "string", ",", "pkg", "*", "ast", ".", "Package", ",", "decl", "ast", ".", "Decl", ",", "imports", "map", "[", "string", "]", "string", ",", "fset", "*", "token", ".", "FileSet", ")", "[", "]", "*", "model", ".", "TypeInfo", "{", "// Filter out non-Struct type declarations.", "spec", ",", "found", ":=", "getStructTypeDecl", "(", "decl", ",", "fset", ")", "\n", "if", "!", "found", "{", "return", "specs", "\n", "}", "\n\n", "structType", ":=", "spec", ".", "Type", ".", "(", "*", "ast", ".", "StructType", ")", "\n\n", "// At this point we know it's a type declaration for a struct.", "// Fill in the rest of the info by diving into the fields.", "// Add it provisionally to the Controller list -- it's later filtered using field info.", "controllerSpec", ":=", "&", "model", ".", "TypeInfo", "{", "StructName", ":", "spec", ".", "Name", ".", "Name", ",", "ImportPath", ":", "pkgImportPath", ",", "PackageName", ":", "pkg", ".", "Name", ",", "}", "\n\n", "for", "_", ",", "field", ":=", "range", "structType", ".", "Fields", ".", "List", "{", "// If field.Names is set, it's not an embedded type.", "if", "field", ".", "Names", "!=", "nil", "{", "continue", "\n", "}", "\n\n", "// A direct \"sub-type\" has an ast.Field as either:", "// Ident { \"AppController\" }", "// SelectorExpr { \"rev\", \"Controller\" }", "// Additionally, that can be wrapped by StarExprs.", "fieldType", ":=", "field", ".", "Type", "\n", "pkgName", ",", "typeName", ":=", "func", "(", ")", "(", "string", ",", "string", ")", "{", "// Drill through any StarExprs.", "for", "{", "if", "starExpr", ",", "ok", ":=", "fieldType", ".", "(", "*", "ast", ".", "StarExpr", ")", ";", "ok", "{", "fieldType", "=", "starExpr", ".", "X", "\n", "continue", "\n", "}", "\n", "break", "\n", "}", "\n\n", "// If the embedded type is in the same package, it's an Ident.", "if", "ident", ",", "ok", ":=", "fieldType", ".", "(", "*", "ast", ".", "Ident", ")", ";", "ok", "{", "return", "\"", "\"", ",", "ident", ".", "Name", "\n", "}", "\n\n", "if", "selectorExpr", ",", "ok", ":=", "fieldType", ".", "(", "*", "ast", ".", "SelectorExpr", ")", ";", "ok", "{", "if", "pkgIdent", ",", "ok", ":=", "selectorExpr", ".", "X", ".", "(", "*", "ast", ".", "Ident", ")", ";", "ok", "{", "return", "pkgIdent", ".", "Name", ",", "selectorExpr", ".", "Sel", ".", "Name", "\n", "}", "\n", "}", "\n", "return", "\"", "\"", ",", "\"", "\"", "\n", "}", "(", ")", "\n\n", "// If a typename wasn't found, skip it.", "if", "typeName", "==", "\"", "\"", "{", "continue", "\n", "}", "\n\n", "// Find the import path for this type.", "// If it was referenced without a package name, use the current package import path.", "// Else, look up the package's import path by name.", "var", "importPath", "string", "\n", "if", "pkgName", "==", "\"", "\"", "{", "importPath", "=", "pkgImportPath", "\n", "}", "else", "{", "var", "ok", "bool", "\n", "if", "importPath", ",", "ok", "=", "imports", "[", "pkgName", "]", ";", "!", "ok", "{", "utils", ".", "Logger", ".", "Error", "(", "\"", "\"", ",", "\"", "\"", ",", "pkgName", ",", "\"", "\"", ",", "typeName", ")", "\n", "continue", "\n", "}", "\n", "}", "\n\n", "controllerSpec", ".", "EmbeddedTypes", "=", "append", "(", "controllerSpec", ".", "EmbeddedTypes", ",", "&", "model", ".", "EmbeddedTypeName", "{", "ImportPath", ":", "importPath", ",", "StructName", ":", "typeName", ",", "}", ")", "\n", "}", "\n\n", "return", "append", "(", "specs", ",", "controllerSpec", ")", "\n", "}" ]
// If this Decl is a struct type definition, it is summarized and added to specs. // Else, specs is returned unchanged.
[ "If", "this", "Decl", "is", "a", "struct", "type", "definition", "it", "is", "summarized", "and", "added", "to", "specs", ".", "Else", "specs", "is", "returned", "unchanged", "." ]
149f9f992be9b0957fb1ffeda43c14a123ceb43a
https://github.com/revel/cmd/blob/149f9f992be9b0957fb1ffeda43c14a123ceb43a/parser/appends.go#L12-L90
18,019
revel/cmd
parser/appends.go
appendSourceInfo
func appendSourceInfo(srcInfo1, srcInfo2 *model.SourceInfo) *model.SourceInfo { if srcInfo1 == nil { return srcInfo2 } srcInfo1.StructSpecs = append(srcInfo1.StructSpecs, srcInfo2.StructSpecs...) srcInfo1.InitImportPaths = append(srcInfo1.InitImportPaths, srcInfo2.InitImportPaths...) for k, v := range srcInfo2.ValidationKeys { if _, ok := srcInfo1.ValidationKeys[k]; ok { utils.Logger.Warn("Warn: Key conflict when scanning validation calls:", "key", k) continue } srcInfo1.ValidationKeys[k] = v } return srcInfo1 }
go
func appendSourceInfo(srcInfo1, srcInfo2 *model.SourceInfo) *model.SourceInfo { if srcInfo1 == nil { return srcInfo2 } srcInfo1.StructSpecs = append(srcInfo1.StructSpecs, srcInfo2.StructSpecs...) srcInfo1.InitImportPaths = append(srcInfo1.InitImportPaths, srcInfo2.InitImportPaths...) for k, v := range srcInfo2.ValidationKeys { if _, ok := srcInfo1.ValidationKeys[k]; ok { utils.Logger.Warn("Warn: Key conflict when scanning validation calls:", "key", k) continue } srcInfo1.ValidationKeys[k] = v } return srcInfo1 }
[ "func", "appendSourceInfo", "(", "srcInfo1", ",", "srcInfo2", "*", "model", ".", "SourceInfo", ")", "*", "model", ".", "SourceInfo", "{", "if", "srcInfo1", "==", "nil", "{", "return", "srcInfo2", "\n", "}", "\n\n", "srcInfo1", ".", "StructSpecs", "=", "append", "(", "srcInfo1", ".", "StructSpecs", ",", "srcInfo2", ".", "StructSpecs", "...", ")", "\n", "srcInfo1", ".", "InitImportPaths", "=", "append", "(", "srcInfo1", ".", "InitImportPaths", ",", "srcInfo2", ".", "InitImportPaths", "...", ")", "\n", "for", "k", ",", "v", ":=", "range", "srcInfo2", ".", "ValidationKeys", "{", "if", "_", ",", "ok", ":=", "srcInfo1", ".", "ValidationKeys", "[", "k", "]", ";", "ok", "{", "utils", ".", "Logger", ".", "Warn", "(", "\"", "\"", ",", "\"", "\"", ",", "k", ")", "\n", "continue", "\n", "}", "\n", "srcInfo1", ".", "ValidationKeys", "[", "k", "]", "=", "v", "\n", "}", "\n", "return", "srcInfo1", "\n", "}" ]
// Combine the 2 source info models into one
[ "Combine", "the", "2", "source", "info", "models", "into", "one" ]
149f9f992be9b0957fb1ffeda43c14a123ceb43a
https://github.com/revel/cmd/blob/149f9f992be9b0957fb1ffeda43c14a123ceb43a/parser/appends.go#L208-L223
18,020
revel/cmd
utils/build_error.go
NewBuildError
func NewBuildError(message string, args ...interface{}) (b *BuildError) { Logger.Info(message, args...) b = &BuildError{} b.Message = message b.Args = args b.Stack = logger.NewCallStack() Logger.Info("Stack", "stack", b.Stack) return b }
go
func NewBuildError(message string, args ...interface{}) (b *BuildError) { Logger.Info(message, args...) b = &BuildError{} b.Message = message b.Args = args b.Stack = logger.NewCallStack() Logger.Info("Stack", "stack", b.Stack) return b }
[ "func", "NewBuildError", "(", "message", "string", ",", "args", "...", "interface", "{", "}", ")", "(", "b", "*", "BuildError", ")", "{", "Logger", ".", "Info", "(", "message", ",", "args", "...", ")", "\n", "b", "=", "&", "BuildError", "{", "}", "\n", "b", ".", "Message", "=", "message", "\n", "b", ".", "Args", "=", "args", "\n", "b", ".", "Stack", "=", "logger", ".", "NewCallStack", "(", ")", "\n", "Logger", ".", "Info", "(", "\"", "\"", ",", "\"", "\"", ",", "b", ".", "Stack", ")", "\n", "return", "b", "\n", "}" ]
// Returns a new builed error
[ "Returns", "a", "new", "builed", "error" ]
149f9f992be9b0957fb1ffeda43c14a123ceb43a
https://github.com/revel/cmd/blob/149f9f992be9b0957fb1ffeda43c14a123ceb43a/utils/build_error.go#L17-L25
18,021
revel/cmd
utils/build_error.go
NewBuildIfError
func NewBuildIfError(err error, message string, args ...interface{}) (b error) { if err != nil { if berr, ok := err.(*BuildError); ok { // This is already a build error so just append the args berr.Args = append(berr.Args, args...) return berr } else { args = append(args, "error", err.Error()) b = NewBuildError(message, args...) } } return }
go
func NewBuildIfError(err error, message string, args ...interface{}) (b error) { if err != nil { if berr, ok := err.(*BuildError); ok { // This is already a build error so just append the args berr.Args = append(berr.Args, args...) return berr } else { args = append(args, "error", err.Error()) b = NewBuildError(message, args...) } } return }
[ "func", "NewBuildIfError", "(", "err", "error", ",", "message", "string", ",", "args", "...", "interface", "{", "}", ")", "(", "b", "error", ")", "{", "if", "err", "!=", "nil", "{", "if", "berr", ",", "ok", ":=", "err", ".", "(", "*", "BuildError", ")", ";", "ok", "{", "// This is already a build error so just append the args", "berr", ".", "Args", "=", "append", "(", "berr", ".", "Args", ",", "args", "...", ")", "\n", "return", "berr", "\n", "}", "else", "{", "args", "=", "append", "(", "args", ",", "\"", "\"", ",", "err", ".", "Error", "(", ")", ")", "\n", "b", "=", "NewBuildError", "(", "message", ",", "args", "...", ")", "\n", "}", "\n", "}", "\n", "return", "\n", "}" ]
// Returns a new BuildError if err is not nil
[ "Returns", "a", "new", "BuildError", "if", "err", "is", "not", "nil" ]
149f9f992be9b0957fb1ffeda43c14a123ceb43a
https://github.com/revel/cmd/blob/149f9f992be9b0957fb1ffeda43c14a123ceb43a/utils/build_error.go#L28-L40
18,022
revel/cmd
parser/reflect.go
ProcessSource
func ProcessSource(paths *model.RevelContainer) (_ *model.SourceInfo, compileError error) { pc := &processContainer{paths: paths} for _, root := range paths.CodePaths { rootImportPath := importPathFromPath(root, paths.BasePath) if rootImportPath == "" { utils.Logger.Info("Skipping empty code path", "path", root) continue } pc.root, pc.rootImportPath = root, rootImportPath // Start walking the directory tree. compileError = utils.Walk(root, pc.processPath) if compileError != nil { return } } return pc.srcInfo, compileError }
go
func ProcessSource(paths *model.RevelContainer) (_ *model.SourceInfo, compileError error) { pc := &processContainer{paths: paths} for _, root := range paths.CodePaths { rootImportPath := importPathFromPath(root, paths.BasePath) if rootImportPath == "" { utils.Logger.Info("Skipping empty code path", "path", root) continue } pc.root, pc.rootImportPath = root, rootImportPath // Start walking the directory tree. compileError = utils.Walk(root, pc.processPath) if compileError != nil { return } } return pc.srcInfo, compileError }
[ "func", "ProcessSource", "(", "paths", "*", "model", ".", "RevelContainer", ")", "(", "_", "*", "model", ".", "SourceInfo", ",", "compileError", "error", ")", "{", "pc", ":=", "&", "processContainer", "{", "paths", ":", "paths", "}", "\n", "for", "_", ",", "root", ":=", "range", "paths", ".", "CodePaths", "{", "rootImportPath", ":=", "importPathFromPath", "(", "root", ",", "paths", ".", "BasePath", ")", "\n", "if", "rootImportPath", "==", "\"", "\"", "{", "utils", ".", "Logger", ".", "Info", "(", "\"", "\"", ",", "\"", "\"", ",", "root", ")", "\n", "continue", "\n", "}", "\n", "pc", ".", "root", ",", "pc", ".", "rootImportPath", "=", "root", ",", "rootImportPath", "\n\n", "// Start walking the directory tree.", "compileError", "=", "utils", ".", "Walk", "(", "root", ",", "pc", ".", "processPath", ")", "\n", "if", "compileError", "!=", "nil", "{", "return", "\n", "}", "\n", "}", "\n\n", "return", "pc", ".", "srcInfo", ",", "compileError", "\n", "}" ]
// ProcessSource parses the app controllers directory and // returns a list of the controller types found. // Otherwise CompileError if the parsing fails.
[ "ProcessSource", "parses", "the", "app", "controllers", "directory", "and", "returns", "a", "list", "of", "the", "controller", "types", "found", ".", "Otherwise", "CompileError", "if", "the", "parsing", "fails", "." ]
149f9f992be9b0957fb1ffeda43c14a123ceb43a
https://github.com/revel/cmd/blob/149f9f992be9b0957fb1ffeda43c14a123ceb43a/parser/reflect.go#L37-L55
18,023
revel/cmd
parser/reflect.go
processPath
func (pc *processContainer) processPath(path string, info os.FileInfo, err error) error { if err != nil { utils.Logger.Error("Error scanning app source:", "error", err) return nil } if !info.IsDir() || info.Name() == "tmp" { return nil } // Get the import path of the package. pkgImportPath := pc.rootImportPath if pc.root != path { pkgImportPath = pc.rootImportPath + "/" + filepath.ToSlash(path[len(pc.root)+1:]) } // Parse files within the path. var pkgs map[string]*ast.Package fset := token.NewFileSet() pkgs, err = parser.ParseDir( fset, path, func(f os.FileInfo) bool { return !f.IsDir() && !strings.HasPrefix(f.Name(), ".") && strings.HasSuffix(f.Name(), ".go") }, 0) if err != nil { if errList, ok := err.(scanner.ErrorList); ok { var pos = errList[0].Pos newError := &utils.Error{ SourceType: ".go source", Title: "Go Compilation Error", Path: pos.Filename, Description: errList[0].Msg, Line: pos.Line, Column: pos.Column, SourceLines: utils.MustReadLines(pos.Filename), } errorLink := pc.paths.Config.StringDefault("error.link", "") if errorLink != "" { newError.SetLink(errorLink) } return newError } // This is exception, err already checked above. Here just a print ast.Print(nil, err) utils.Logger.Fatal("Failed to parse dir", "error", err) } // Skip "main" packages. delete(pkgs, "main") // Ignore packages that end with _test // These cannot be included in source code that is not generated specifically as a test for i := range pkgs { if len(i) > 6 { if string(i[len(i)-5:]) == "_test" { delete(pkgs, i) } } } // If there is no code in this directory, skip it. if len(pkgs) == 0 { return nil } // There should be only one package in this directory. if len(pkgs) > 1 { for i := range pkgs { println("Found package ", i) } utils.Logger.Fatal("Most unexpected! Multiple packages in a single directory:", "packages", pkgs) } var pkg *ast.Package for _, v := range pkgs { pkg = v } if pkg != nil { pc.srcInfo = appendSourceInfo(pc.srcInfo, processPackage(fset, pkgImportPath, path, pkg)) } else { utils.Logger.Info("Ignoring package, because it contained no packages", "path", path) } return nil }
go
func (pc *processContainer) processPath(path string, info os.FileInfo, err error) error { if err != nil { utils.Logger.Error("Error scanning app source:", "error", err) return nil } if !info.IsDir() || info.Name() == "tmp" { return nil } // Get the import path of the package. pkgImportPath := pc.rootImportPath if pc.root != path { pkgImportPath = pc.rootImportPath + "/" + filepath.ToSlash(path[len(pc.root)+1:]) } // Parse files within the path. var pkgs map[string]*ast.Package fset := token.NewFileSet() pkgs, err = parser.ParseDir( fset, path, func(f os.FileInfo) bool { return !f.IsDir() && !strings.HasPrefix(f.Name(), ".") && strings.HasSuffix(f.Name(), ".go") }, 0) if err != nil { if errList, ok := err.(scanner.ErrorList); ok { var pos = errList[0].Pos newError := &utils.Error{ SourceType: ".go source", Title: "Go Compilation Error", Path: pos.Filename, Description: errList[0].Msg, Line: pos.Line, Column: pos.Column, SourceLines: utils.MustReadLines(pos.Filename), } errorLink := pc.paths.Config.StringDefault("error.link", "") if errorLink != "" { newError.SetLink(errorLink) } return newError } // This is exception, err already checked above. Here just a print ast.Print(nil, err) utils.Logger.Fatal("Failed to parse dir", "error", err) } // Skip "main" packages. delete(pkgs, "main") // Ignore packages that end with _test // These cannot be included in source code that is not generated specifically as a test for i := range pkgs { if len(i) > 6 { if string(i[len(i)-5:]) == "_test" { delete(pkgs, i) } } } // If there is no code in this directory, skip it. if len(pkgs) == 0 { return nil } // There should be only one package in this directory. if len(pkgs) > 1 { for i := range pkgs { println("Found package ", i) } utils.Logger.Fatal("Most unexpected! Multiple packages in a single directory:", "packages", pkgs) } var pkg *ast.Package for _, v := range pkgs { pkg = v } if pkg != nil { pc.srcInfo = appendSourceInfo(pc.srcInfo, processPackage(fset, pkgImportPath, path, pkg)) } else { utils.Logger.Info("Ignoring package, because it contained no packages", "path", path) } return nil }
[ "func", "(", "pc", "*", "processContainer", ")", "processPath", "(", "path", "string", ",", "info", "os", ".", "FileInfo", ",", "err", "error", ")", "error", "{", "if", "err", "!=", "nil", "{", "utils", ".", "Logger", ".", "Error", "(", "\"", "\"", ",", "\"", "\"", ",", "err", ")", "\n", "return", "nil", "\n", "}", "\n\n", "if", "!", "info", ".", "IsDir", "(", ")", "||", "info", ".", "Name", "(", ")", "==", "\"", "\"", "{", "return", "nil", "\n", "}", "\n\n", "// Get the import path of the package.", "pkgImportPath", ":=", "pc", ".", "rootImportPath", "\n", "if", "pc", ".", "root", "!=", "path", "{", "pkgImportPath", "=", "pc", ".", "rootImportPath", "+", "\"", "\"", "+", "filepath", ".", "ToSlash", "(", "path", "[", "len", "(", "pc", ".", "root", ")", "+", "1", ":", "]", ")", "\n", "}", "\n\n", "// Parse files within the path.", "var", "pkgs", "map", "[", "string", "]", "*", "ast", ".", "Package", "\n", "fset", ":=", "token", ".", "NewFileSet", "(", ")", "\n", "pkgs", ",", "err", "=", "parser", ".", "ParseDir", "(", "fset", ",", "path", ",", "func", "(", "f", "os", ".", "FileInfo", ")", "bool", "{", "return", "!", "f", ".", "IsDir", "(", ")", "&&", "!", "strings", ".", "HasPrefix", "(", "f", ".", "Name", "(", ")", ",", "\"", "\"", ")", "&&", "strings", ".", "HasSuffix", "(", "f", ".", "Name", "(", ")", ",", "\"", "\"", ")", "\n", "}", ",", "0", ")", "\n\n", "if", "err", "!=", "nil", "{", "if", "errList", ",", "ok", ":=", "err", ".", "(", "scanner", ".", "ErrorList", ")", ";", "ok", "{", "var", "pos", "=", "errList", "[", "0", "]", ".", "Pos", "\n", "newError", ":=", "&", "utils", ".", "Error", "{", "SourceType", ":", "\"", "\"", ",", "Title", ":", "\"", "\"", ",", "Path", ":", "pos", ".", "Filename", ",", "Description", ":", "errList", "[", "0", "]", ".", "Msg", ",", "Line", ":", "pos", ".", "Line", ",", "Column", ":", "pos", ".", "Column", ",", "SourceLines", ":", "utils", ".", "MustReadLines", "(", "pos", ".", "Filename", ")", ",", "}", "\n\n", "errorLink", ":=", "pc", ".", "paths", ".", "Config", ".", "StringDefault", "(", "\"", "\"", ",", "\"", "\"", ")", "\n", "if", "errorLink", "!=", "\"", "\"", "{", "newError", ".", "SetLink", "(", "errorLink", ")", "\n", "}", "\n", "return", "newError", "\n", "}", "\n\n", "// This is exception, err already checked above. Here just a print", "ast", ".", "Print", "(", "nil", ",", "err", ")", "\n", "utils", ".", "Logger", ".", "Fatal", "(", "\"", "\"", ",", "\"", "\"", ",", "err", ")", "\n", "}", "\n\n", "// Skip \"main\" packages.", "delete", "(", "pkgs", ",", "\"", "\"", ")", "\n\n", "// Ignore packages that end with _test", "// These cannot be included in source code that is not generated specifically as a test", "for", "i", ":=", "range", "pkgs", "{", "if", "len", "(", "i", ")", ">", "6", "{", "if", "string", "(", "i", "[", "len", "(", "i", ")", "-", "5", ":", "]", ")", "==", "\"", "\"", "{", "delete", "(", "pkgs", ",", "i", ")", "\n", "}", "\n", "}", "\n", "}", "\n\n", "// If there is no code in this directory, skip it.", "if", "len", "(", "pkgs", ")", "==", "0", "{", "return", "nil", "\n", "}", "\n\n", "// There should be only one package in this directory.", "if", "len", "(", "pkgs", ")", ">", "1", "{", "for", "i", ":=", "range", "pkgs", "{", "println", "(", "\"", "\"", ",", "i", ")", "\n", "}", "\n", "utils", ".", "Logger", ".", "Fatal", "(", "\"", "\"", ",", "\"", "\"", ",", "pkgs", ")", "\n", "}", "\n\n", "var", "pkg", "*", "ast", ".", "Package", "\n", "for", "_", ",", "v", ":=", "range", "pkgs", "{", "pkg", "=", "v", "\n", "}", "\n\n", "if", "pkg", "!=", "nil", "{", "pc", ".", "srcInfo", "=", "appendSourceInfo", "(", "pc", ".", "srcInfo", ",", "processPackage", "(", "fset", ",", "pkgImportPath", ",", "path", ",", "pkg", ")", ")", "\n", "}", "else", "{", "utils", ".", "Logger", ".", "Info", "(", "\"", "\"", ",", "\"", "\"", ",", "path", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// Called during the "walk process"
[ "Called", "during", "the", "walk", "process" ]
149f9f992be9b0957fb1ffeda43c14a123ceb43a
https://github.com/revel/cmd/blob/149f9f992be9b0957fb1ffeda43c14a123ceb43a/parser/reflect.go#L58-L147
18,024
revel/cmd
parser/reflect.go
processPackage
func processPackage(fset *token.FileSet, pkgImportPath, pkgPath string, pkg *ast.Package) *model.SourceInfo { var ( structSpecs []*model.TypeInfo initImportPaths []string methodSpecs = make(methodMap) validationKeys = make(map[string]map[int]string) scanControllers = strings.HasSuffix(pkgImportPath, "/controllers") || strings.Contains(pkgImportPath, "/controllers/") scanTests = strings.HasSuffix(pkgImportPath, "/tests") || strings.Contains(pkgImportPath, "/tests/") ) // For each source file in the package... utils.Logger.Info("Exaimining files in path", "package", pkgPath) for fname, file := range pkg.Files { // Imports maps the package key to the full import path. // e.g. import "sample/app/models" => "models": "sample/app/models" imports := map[string]string{} // For each declaration in the source file... for _, decl := range file.Decls { addImports(imports, decl, pkgPath) if scanControllers { // Match and add both structs and methods structSpecs = appendStruct(fname, structSpecs, pkgImportPath, pkg, decl, imports, fset) appendAction(fset, methodSpecs, decl, pkgImportPath, pkg.Name, imports) } else if scanTests { structSpecs = appendStruct(fname, structSpecs, pkgImportPath, pkg, decl, imports, fset) } // If this is a func... (ignore nil for external (non-Go) function) if funcDecl, ok := decl.(*ast.FuncDecl); ok && funcDecl.Body != nil { // Scan it for validation calls lineKeys := GetValidationKeys(fname, fset, funcDecl, imports) if len(lineKeys) > 0 { validationKeys[pkgImportPath+"."+getFuncName(funcDecl)] = lineKeys } // Check if it's an init function. if funcDecl.Name.Name == "init" { initImportPaths = []string{pkgImportPath} } } } } // Add the method specs to the struct specs. for _, spec := range structSpecs { spec.MethodSpecs = methodSpecs[spec.StructName] } return &model.SourceInfo{ StructSpecs: structSpecs, ValidationKeys: validationKeys, InitImportPaths: initImportPaths, } }
go
func processPackage(fset *token.FileSet, pkgImportPath, pkgPath string, pkg *ast.Package) *model.SourceInfo { var ( structSpecs []*model.TypeInfo initImportPaths []string methodSpecs = make(methodMap) validationKeys = make(map[string]map[int]string) scanControllers = strings.HasSuffix(pkgImportPath, "/controllers") || strings.Contains(pkgImportPath, "/controllers/") scanTests = strings.HasSuffix(pkgImportPath, "/tests") || strings.Contains(pkgImportPath, "/tests/") ) // For each source file in the package... utils.Logger.Info("Exaimining files in path", "package", pkgPath) for fname, file := range pkg.Files { // Imports maps the package key to the full import path. // e.g. import "sample/app/models" => "models": "sample/app/models" imports := map[string]string{} // For each declaration in the source file... for _, decl := range file.Decls { addImports(imports, decl, pkgPath) if scanControllers { // Match and add both structs and methods structSpecs = appendStruct(fname, structSpecs, pkgImportPath, pkg, decl, imports, fset) appendAction(fset, methodSpecs, decl, pkgImportPath, pkg.Name, imports) } else if scanTests { structSpecs = appendStruct(fname, structSpecs, pkgImportPath, pkg, decl, imports, fset) } // If this is a func... (ignore nil for external (non-Go) function) if funcDecl, ok := decl.(*ast.FuncDecl); ok && funcDecl.Body != nil { // Scan it for validation calls lineKeys := GetValidationKeys(fname, fset, funcDecl, imports) if len(lineKeys) > 0 { validationKeys[pkgImportPath+"."+getFuncName(funcDecl)] = lineKeys } // Check if it's an init function. if funcDecl.Name.Name == "init" { initImportPaths = []string{pkgImportPath} } } } } // Add the method specs to the struct specs. for _, spec := range structSpecs { spec.MethodSpecs = methodSpecs[spec.StructName] } return &model.SourceInfo{ StructSpecs: structSpecs, ValidationKeys: validationKeys, InitImportPaths: initImportPaths, } }
[ "func", "processPackage", "(", "fset", "*", "token", ".", "FileSet", ",", "pkgImportPath", ",", "pkgPath", "string", ",", "pkg", "*", "ast", ".", "Package", ")", "*", "model", ".", "SourceInfo", "{", "var", "(", "structSpecs", "[", "]", "*", "model", ".", "TypeInfo", "\n", "initImportPaths", "[", "]", "string", "\n\n", "methodSpecs", "=", "make", "(", "methodMap", ")", "\n", "validationKeys", "=", "make", "(", "map", "[", "string", "]", "map", "[", "int", "]", "string", ")", "\n", "scanControllers", "=", "strings", ".", "HasSuffix", "(", "pkgImportPath", ",", "\"", "\"", ")", "||", "strings", ".", "Contains", "(", "pkgImportPath", ",", "\"", "\"", ")", "\n", "scanTests", "=", "strings", ".", "HasSuffix", "(", "pkgImportPath", ",", "\"", "\"", ")", "||", "strings", ".", "Contains", "(", "pkgImportPath", ",", "\"", "\"", ")", "\n", ")", "\n\n", "// For each source file in the package...", "utils", ".", "Logger", ".", "Info", "(", "\"", "\"", ",", "\"", "\"", ",", "pkgPath", ")", "\n", "for", "fname", ",", "file", ":=", "range", "pkg", ".", "Files", "{", "// Imports maps the package key to the full import path.", "// e.g. import \"sample/app/models\" => \"models\": \"sample/app/models\"", "imports", ":=", "map", "[", "string", "]", "string", "{", "}", "\n\n", "// For each declaration in the source file...", "for", "_", ",", "decl", ":=", "range", "file", ".", "Decls", "{", "addImports", "(", "imports", ",", "decl", ",", "pkgPath", ")", "\n\n", "if", "scanControllers", "{", "// Match and add both structs and methods", "structSpecs", "=", "appendStruct", "(", "fname", ",", "structSpecs", ",", "pkgImportPath", ",", "pkg", ",", "decl", ",", "imports", ",", "fset", ")", "\n", "appendAction", "(", "fset", ",", "methodSpecs", ",", "decl", ",", "pkgImportPath", ",", "pkg", ".", "Name", ",", "imports", ")", "\n", "}", "else", "if", "scanTests", "{", "structSpecs", "=", "appendStruct", "(", "fname", ",", "structSpecs", ",", "pkgImportPath", ",", "pkg", ",", "decl", ",", "imports", ",", "fset", ")", "\n", "}", "\n\n", "// If this is a func... (ignore nil for external (non-Go) function)", "if", "funcDecl", ",", "ok", ":=", "decl", ".", "(", "*", "ast", ".", "FuncDecl", ")", ";", "ok", "&&", "funcDecl", ".", "Body", "!=", "nil", "{", "// Scan it for validation calls", "lineKeys", ":=", "GetValidationKeys", "(", "fname", ",", "fset", ",", "funcDecl", ",", "imports", ")", "\n", "if", "len", "(", "lineKeys", ")", ">", "0", "{", "validationKeys", "[", "pkgImportPath", "+", "\"", "\"", "+", "getFuncName", "(", "funcDecl", ")", "]", "=", "lineKeys", "\n", "}", "\n\n", "// Check if it's an init function.", "if", "funcDecl", ".", "Name", ".", "Name", "==", "\"", "\"", "{", "initImportPaths", "=", "[", "]", "string", "{", "pkgImportPath", "}", "\n", "}", "\n", "}", "\n", "}", "\n", "}", "\n\n", "// Add the method specs to the struct specs.", "for", "_", ",", "spec", ":=", "range", "structSpecs", "{", "spec", ".", "MethodSpecs", "=", "methodSpecs", "[", "spec", ".", "StructName", "]", "\n", "}", "\n\n", "return", "&", "model", ".", "SourceInfo", "{", "StructSpecs", ":", "structSpecs", ",", "ValidationKeys", ":", "validationKeys", ",", "InitImportPaths", ":", "initImportPaths", ",", "}", "\n", "}" ]
// Process a single package within a file
[ "Process", "a", "single", "package", "within", "a", "file" ]
149f9f992be9b0957fb1ffeda43c14a123ceb43a
https://github.com/revel/cmd/blob/149f9f992be9b0957fb1ffeda43c14a123ceb43a/parser/reflect.go#L150-L208
18,025
revel/cmd
parser/reflect.go
getStructTypeDecl
func getStructTypeDecl(decl ast.Decl, fset *token.FileSet) (spec *ast.TypeSpec, found bool) { genDecl, ok := decl.(*ast.GenDecl) if !ok { return } if genDecl.Tok != token.TYPE { return } if len(genDecl.Specs) == 0 { utils.Logger.Warn("Warn: Surprising: %s:%d Decl contains no specifications", fset.Position(decl.Pos()).Filename, fset.Position(decl.Pos()).Line) return } spec = genDecl.Specs[0].(*ast.TypeSpec) _, found = spec.Type.(*ast.StructType) return }
go
func getStructTypeDecl(decl ast.Decl, fset *token.FileSet) (spec *ast.TypeSpec, found bool) { genDecl, ok := decl.(*ast.GenDecl) if !ok { return } if genDecl.Tok != token.TYPE { return } if len(genDecl.Specs) == 0 { utils.Logger.Warn("Warn: Surprising: %s:%d Decl contains no specifications", fset.Position(decl.Pos()).Filename, fset.Position(decl.Pos()).Line) return } spec = genDecl.Specs[0].(*ast.TypeSpec) _, found = spec.Type.(*ast.StructType) return }
[ "func", "getStructTypeDecl", "(", "decl", "ast", ".", "Decl", ",", "fset", "*", "token", ".", "FileSet", ")", "(", "spec", "*", "ast", ".", "TypeSpec", ",", "found", "bool", ")", "{", "genDecl", ",", "ok", ":=", "decl", ".", "(", "*", "ast", ".", "GenDecl", ")", "\n", "if", "!", "ok", "{", "return", "\n", "}", "\n\n", "if", "genDecl", ".", "Tok", "!=", "token", ".", "TYPE", "{", "return", "\n", "}", "\n\n", "if", "len", "(", "genDecl", ".", "Specs", ")", "==", "0", "{", "utils", ".", "Logger", ".", "Warn", "(", "\"", "\"", ",", "fset", ".", "Position", "(", "decl", ".", "Pos", "(", ")", ")", ".", "Filename", ",", "fset", ".", "Position", "(", "decl", ".", "Pos", "(", ")", ")", ".", "Line", ")", "\n", "return", "\n", "}", "\n\n", "spec", "=", "genDecl", ".", "Specs", "[", "0", "]", ".", "(", "*", "ast", ".", "TypeSpec", ")", "\n", "_", ",", "found", "=", "spec", ".", "Type", ".", "(", "*", "ast", ".", "StructType", ")", "\n\n", "return", "\n", "}" ]
// getStructTypeDecl checks if the given decl is a type declaration for a // struct. If so, the TypeSpec is returned.
[ "getStructTypeDecl", "checks", "if", "the", "given", "decl", "is", "a", "type", "declaration", "for", "a", "struct", ".", "If", "so", "the", "TypeSpec", "is", "returned", "." ]
149f9f992be9b0957fb1ffeda43c14a123ceb43a
https://github.com/revel/cmd/blob/149f9f992be9b0957fb1ffeda43c14a123ceb43a/parser/reflect.go#L228-L247
18,026
revel/cmd
harness/app.go
NewApp
func NewApp(binPath string, paths *model.RevelContainer) *App { return &App{BinaryPath: binPath, Paths: paths, Port: paths.HTTPPort} }
go
func NewApp(binPath string, paths *model.RevelContainer) *App { return &App{BinaryPath: binPath, Paths: paths, Port: paths.HTTPPort} }
[ "func", "NewApp", "(", "binPath", "string", ",", "paths", "*", "model", ".", "RevelContainer", ")", "*", "App", "{", "return", "&", "App", "{", "BinaryPath", ":", "binPath", ",", "Paths", ":", "paths", ",", "Port", ":", "paths", ".", "HTTPPort", "}", "\n", "}" ]
// NewApp returns app instance with binary path in it
[ "NewApp", "returns", "app", "instance", "with", "binary", "path", "in", "it" ]
149f9f992be9b0957fb1ffeda43c14a123ceb43a
https://github.com/revel/cmd/blob/149f9f992be9b0957fb1ffeda43c14a123ceb43a/harness/app.go#L31-L33
18,027
revel/cmd
harness/app.go
Cmd
func (a *App) Cmd(runMode string) AppCmd { a.cmd = NewAppCmd(a.BinaryPath, a.Port, runMode, a.Paths) return a.cmd }
go
func (a *App) Cmd(runMode string) AppCmd { a.cmd = NewAppCmd(a.BinaryPath, a.Port, runMode, a.Paths) return a.cmd }
[ "func", "(", "a", "*", "App", ")", "Cmd", "(", "runMode", "string", ")", "AppCmd", "{", "a", ".", "cmd", "=", "NewAppCmd", "(", "a", ".", "BinaryPath", ",", "a", ".", "Port", ",", "runMode", ",", "a", ".", "Paths", ")", "\n", "return", "a", ".", "cmd", "\n", "}" ]
// Cmd returns a command to run the app server using the current configuration.
[ "Cmd", "returns", "a", "command", "to", "run", "the", "app", "server", "using", "the", "current", "configuration", "." ]
149f9f992be9b0957fb1ffeda43c14a123ceb43a
https://github.com/revel/cmd/blob/149f9f992be9b0957fb1ffeda43c14a123ceb43a/harness/app.go#L36-L39
18,028
revel/cmd
harness/app.go
NewAppCmd
func NewAppCmd(binPath string, port int, runMode string, paths *model.RevelContainer) AppCmd { cmd := exec.Command(binPath, fmt.Sprintf("-port=%d", port), fmt.Sprintf("-importPath=%s", paths.ImportPath), fmt.Sprintf("-runMode=%s", runMode)) cmd.Stdout, cmd.Stderr = os.Stdout, os.Stderr return AppCmd{cmd} }
go
func NewAppCmd(binPath string, port int, runMode string, paths *model.RevelContainer) AppCmd { cmd := exec.Command(binPath, fmt.Sprintf("-port=%d", port), fmt.Sprintf("-importPath=%s", paths.ImportPath), fmt.Sprintf("-runMode=%s", runMode)) cmd.Stdout, cmd.Stderr = os.Stdout, os.Stderr return AppCmd{cmd} }
[ "func", "NewAppCmd", "(", "binPath", "string", ",", "port", "int", ",", "runMode", "string", ",", "paths", "*", "model", ".", "RevelContainer", ")", "AppCmd", "{", "cmd", ":=", "exec", ".", "Command", "(", "binPath", ",", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "port", ")", ",", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "paths", ".", "ImportPath", ")", ",", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "runMode", ")", ")", "\n", "cmd", ".", "Stdout", ",", "cmd", ".", "Stderr", "=", "os", ".", "Stdout", ",", "os", ".", "Stderr", "\n", "return", "AppCmd", "{", "cmd", "}", "\n", "}" ]
// NewAppCmd returns the AppCmd with parameters initialized for running app
[ "NewAppCmd", "returns", "the", "AppCmd", "with", "parameters", "initialized", "for", "running", "app" ]
149f9f992be9b0957fb1ffeda43c14a123ceb43a
https://github.com/revel/cmd/blob/149f9f992be9b0957fb1ffeda43c14a123ceb43a/harness/app.go#L53-L60
18,029
revel/cmd
harness/app.go
Start
func (cmd AppCmd) Start(c *model.CommandConfig) error { listeningWriter := &startupListeningWriter{os.Stdout, make(chan bool), c, &bytes.Buffer{}} cmd.Stdout = listeningWriter utils.Logger.Info("Exec app:", "path", cmd.Path, "args", cmd.Args, "dir", cmd.Dir, "env", cmd.Env) utils.CmdInit(cmd.Cmd, c.AppPath) if err := cmd.Cmd.Start(); err != nil { utils.Logger.Fatal("Error running:", "error", err) } select { case exitState := <-cmd.waitChan(): fmt.Println("Startup failure view previous messages, \n Proxy is listening :", c.Run.Port) err := utils.NewError("","Revel Run Error", "starting your application there was an exception. See terminal output, " + exitState,"") // TODO pretiffy command line output // err.MetaError = listeningWriter.getLastOutput() return err case <-time.After(60 * time.Second): println("Revel proxy is listening, point your browser to :", c.Run.Port) utils.Logger.Error("Killing revel server process did not respond after wait timeout.", "processid", cmd.Process.Pid) cmd.Kill() return errors.New("revel/harness: app timed out") case <-listeningWriter.notifyReady: println("Revel proxy is listening, point your browser to :", c.Run.Port) return nil } }
go
func (cmd AppCmd) Start(c *model.CommandConfig) error { listeningWriter := &startupListeningWriter{os.Stdout, make(chan bool), c, &bytes.Buffer{}} cmd.Stdout = listeningWriter utils.Logger.Info("Exec app:", "path", cmd.Path, "args", cmd.Args, "dir", cmd.Dir, "env", cmd.Env) utils.CmdInit(cmd.Cmd, c.AppPath) if err := cmd.Cmd.Start(); err != nil { utils.Logger.Fatal("Error running:", "error", err) } select { case exitState := <-cmd.waitChan(): fmt.Println("Startup failure view previous messages, \n Proxy is listening :", c.Run.Port) err := utils.NewError("","Revel Run Error", "starting your application there was an exception. See terminal output, " + exitState,"") // TODO pretiffy command line output // err.MetaError = listeningWriter.getLastOutput() return err case <-time.After(60 * time.Second): println("Revel proxy is listening, point your browser to :", c.Run.Port) utils.Logger.Error("Killing revel server process did not respond after wait timeout.", "processid", cmd.Process.Pid) cmd.Kill() return errors.New("revel/harness: app timed out") case <-listeningWriter.notifyReady: println("Revel proxy is listening, point your browser to :", c.Run.Port) return nil } }
[ "func", "(", "cmd", "AppCmd", ")", "Start", "(", "c", "*", "model", ".", "CommandConfig", ")", "error", "{", "listeningWriter", ":=", "&", "startupListeningWriter", "{", "os", ".", "Stdout", ",", "make", "(", "chan", "bool", ")", ",", "c", ",", "&", "bytes", ".", "Buffer", "{", "}", "}", "\n", "cmd", ".", "Stdout", "=", "listeningWriter", "\n", "utils", ".", "Logger", ".", "Info", "(", "\"", "\"", ",", "\"", "\"", ",", "cmd", ".", "Path", ",", "\"", "\"", ",", "cmd", ".", "Args", ",", "\"", "\"", ",", "cmd", ".", "Dir", ",", "\"", "\"", ",", "cmd", ".", "Env", ")", "\n", "utils", ".", "CmdInit", "(", "cmd", ".", "Cmd", ",", "c", ".", "AppPath", ")", "\n", "if", "err", ":=", "cmd", ".", "Cmd", ".", "Start", "(", ")", ";", "err", "!=", "nil", "{", "utils", ".", "Logger", ".", "Fatal", "(", "\"", "\"", ",", "\"", "\"", ",", "err", ")", "\n", "}", "\n\n", "select", "{", "case", "exitState", ":=", "<-", "cmd", ".", "waitChan", "(", ")", ":", "fmt", ".", "Println", "(", "\"", "\\n", "\"", ",", "c", ".", "Run", ".", "Port", ")", "\n", "err", ":=", "utils", ".", "NewError", "(", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", "+", "exitState", ",", "\"", "\"", ")", "\n", "// TODO pretiffy command line output", "// err.MetaError = listeningWriter.getLastOutput()", "return", "err", "\n\n", "case", "<-", "time", ".", "After", "(", "60", "*", "time", ".", "Second", ")", ":", "println", "(", "\"", "\"", ",", "c", ".", "Run", ".", "Port", ")", "\n", "utils", ".", "Logger", ".", "Error", "(", "\"", "\"", ",", "\"", "\"", ",", "cmd", ".", "Process", ".", "Pid", ")", "\n", "cmd", ".", "Kill", "(", ")", "\n", "return", "errors", ".", "New", "(", "\"", "\"", ")", "\n\n", "case", "<-", "listeningWriter", ".", "notifyReady", ":", "println", "(", "\"", "\"", ",", "c", ".", "Run", ".", "Port", ")", "\n", "return", "nil", "\n", "}", "\n\n", "}" ]
// Start the app server, and wait until it is ready to serve requests.
[ "Start", "the", "app", "server", "and", "wait", "until", "it", "is", "ready", "to", "serve", "requests", "." ]
149f9f992be9b0957fb1ffeda43c14a123ceb43a
https://github.com/revel/cmd/blob/149f9f992be9b0957fb1ffeda43c14a123ceb43a/harness/app.go#L63-L91
18,030
revel/cmd
harness/app.go
Run
func (cmd AppCmd) Run() { utils.Logger.Info("Exec app:", "path", cmd.Path, "args", cmd.Args) if err := cmd.Cmd.Run(); err != nil { utils.Logger.Fatal("Error running:", "error", err) } }
go
func (cmd AppCmd) Run() { utils.Logger.Info("Exec app:", "path", cmd.Path, "args", cmd.Args) if err := cmd.Cmd.Run(); err != nil { utils.Logger.Fatal("Error running:", "error", err) } }
[ "func", "(", "cmd", "AppCmd", ")", "Run", "(", ")", "{", "utils", ".", "Logger", ".", "Info", "(", "\"", "\"", ",", "\"", "\"", ",", "cmd", ".", "Path", ",", "\"", "\"", ",", "cmd", ".", "Args", ")", "\n", "if", "err", ":=", "cmd", ".", "Cmd", ".", "Run", "(", ")", ";", "err", "!=", "nil", "{", "utils", ".", "Logger", ".", "Fatal", "(", "\"", "\"", ",", "\"", "\"", ",", "err", ")", "\n", "}", "\n", "}" ]
// Run the app server inline. Never returns.
[ "Run", "the", "app", "server", "inline", ".", "Never", "returns", "." ]
149f9f992be9b0957fb1ffeda43c14a123ceb43a
https://github.com/revel/cmd/blob/149f9f992be9b0957fb1ffeda43c14a123ceb43a/harness/app.go#L94-L99
18,031
revel/cmd
harness/app.go
Kill
func (cmd AppCmd) Kill() { if cmd.Cmd != nil && (cmd.ProcessState == nil || !cmd.ProcessState.Exited()) { // Windows appears to send the kill to all threads, shutting down the // server before this can, this check will ensure the process is still running if _, err := os.FindProcess(int(cmd.Process.Pid));err!=nil { // Server has already exited utils.Logger.Info("Killing revel server pid", "pid", cmd.Process.Pid) return } // Send an interrupt signal to allow for a graceful shutdown utils.Logger.Info("Killing revel server pid", "pid", cmd.Process.Pid) var err error if runtime.GOOS == "windows" { // os.Interrupt is not available on windows err = cmd.Process.Signal(os.Kill) } else { err = cmd.Process.Signal(os.Interrupt) } if err != nil { utils.Logger.Error( "Revel app failed to kill process.", "processid", cmd.Process.Pid,"error",err, "killerror", cmd.Process.Kill()) return } // Wait for the shutdown ch := make(chan bool, 1) go func() { s, err := cmd.Process.Wait() defer func() { ch <- true }() if err != nil { utils.Logger.Info("Wait failed for process ", "error", err) } if s != nil { utils.Logger.Info("Revel App exited", "state", s.String()) } }() // Use a timer to ensure that the process exits utils.Logger.Info("Waiting to exit") select { case <-ch: return case <-time.After(60 * time.Second): // Kill the process utils.Logger.Error( "Revel app failed to exit in 60 seconds - killing.", "processid", cmd.Process.Pid, "killerror", cmd.Process.Kill()) } utils.Logger.Info("Done Waiting to exit") } }
go
func (cmd AppCmd) Kill() { if cmd.Cmd != nil && (cmd.ProcessState == nil || !cmd.ProcessState.Exited()) { // Windows appears to send the kill to all threads, shutting down the // server before this can, this check will ensure the process is still running if _, err := os.FindProcess(int(cmd.Process.Pid));err!=nil { // Server has already exited utils.Logger.Info("Killing revel server pid", "pid", cmd.Process.Pid) return } // Send an interrupt signal to allow for a graceful shutdown utils.Logger.Info("Killing revel server pid", "pid", cmd.Process.Pid) var err error if runtime.GOOS == "windows" { // os.Interrupt is not available on windows err = cmd.Process.Signal(os.Kill) } else { err = cmd.Process.Signal(os.Interrupt) } if err != nil { utils.Logger.Error( "Revel app failed to kill process.", "processid", cmd.Process.Pid,"error",err, "killerror", cmd.Process.Kill()) return } // Wait for the shutdown ch := make(chan bool, 1) go func() { s, err := cmd.Process.Wait() defer func() { ch <- true }() if err != nil { utils.Logger.Info("Wait failed for process ", "error", err) } if s != nil { utils.Logger.Info("Revel App exited", "state", s.String()) } }() // Use a timer to ensure that the process exits utils.Logger.Info("Waiting to exit") select { case <-ch: return case <-time.After(60 * time.Second): // Kill the process utils.Logger.Error( "Revel app failed to exit in 60 seconds - killing.", "processid", cmd.Process.Pid, "killerror", cmd.Process.Kill()) } utils.Logger.Info("Done Waiting to exit") } }
[ "func", "(", "cmd", "AppCmd", ")", "Kill", "(", ")", "{", "if", "cmd", ".", "Cmd", "!=", "nil", "&&", "(", "cmd", ".", "ProcessState", "==", "nil", "||", "!", "cmd", ".", "ProcessState", ".", "Exited", "(", ")", ")", "{", "// Windows appears to send the kill to all threads, shutting down the", "// server before this can, this check will ensure the process is still running", "if", "_", ",", "err", ":=", "os", ".", "FindProcess", "(", "int", "(", "cmd", ".", "Process", ".", "Pid", ")", ")", ";", "err", "!=", "nil", "{", "// Server has already exited", "utils", ".", "Logger", ".", "Info", "(", "\"", "\"", ",", "\"", "\"", ",", "cmd", ".", "Process", ".", "Pid", ")", "\n", "return", "\n", "}", "\n\n", "// Send an interrupt signal to allow for a graceful shutdown", "utils", ".", "Logger", ".", "Info", "(", "\"", "\"", ",", "\"", "\"", ",", "cmd", ".", "Process", ".", "Pid", ")", "\n", "var", "err", "error", "\n", "if", "runtime", ".", "GOOS", "==", "\"", "\"", "{", "// os.Interrupt is not available on windows", "err", "=", "cmd", ".", "Process", ".", "Signal", "(", "os", ".", "Kill", ")", "\n", "}", "else", "{", "err", "=", "cmd", ".", "Process", ".", "Signal", "(", "os", ".", "Interrupt", ")", "\n", "}", "\n\n", "if", "err", "!=", "nil", "{", "utils", ".", "Logger", ".", "Error", "(", "\"", "\"", ",", "\"", "\"", ",", "cmd", ".", "Process", ".", "Pid", ",", "\"", "\"", ",", "err", ",", "\"", "\"", ",", "cmd", ".", "Process", ".", "Kill", "(", ")", ")", "\n", "return", "\n", "}", "\n\n", "// Wait for the shutdown", "ch", ":=", "make", "(", "chan", "bool", ",", "1", ")", "\n", "go", "func", "(", ")", "{", "s", ",", "err", ":=", "cmd", ".", "Process", ".", "Wait", "(", ")", "\n", "defer", "func", "(", ")", "{", "ch", "<-", "true", "\n", "}", "(", ")", "\n", "if", "err", "!=", "nil", "{", "utils", ".", "Logger", ".", "Info", "(", "\"", "\"", ",", "\"", "\"", ",", "err", ")", "\n", "}", "\n", "if", "s", "!=", "nil", "{", "utils", ".", "Logger", ".", "Info", "(", "\"", "\"", ",", "\"", "\"", ",", "s", ".", "String", "(", ")", ")", "\n", "}", "\n", "}", "(", ")", "\n\n", "// Use a timer to ensure that the process exits", "utils", ".", "Logger", ".", "Info", "(", "\"", "\"", ")", "\n", "select", "{", "case", "<-", "ch", ":", "return", "\n", "case", "<-", "time", ".", "After", "(", "60", "*", "time", ".", "Second", ")", ":", "// Kill the process", "utils", ".", "Logger", ".", "Error", "(", "\"", "\"", ",", "\"", "\"", ",", "cmd", ".", "Process", ".", "Pid", ",", "\"", "\"", ",", "cmd", ".", "Process", ".", "Kill", "(", ")", ")", "\n", "}", "\n\n", "utils", ".", "Logger", ".", "Info", "(", "\"", "\"", ")", "\n", "}", "\n", "}" ]
// Kill terminates the app server if it's running.
[ "Kill", "terminates", "the", "app", "server", "if", "it", "s", "running", "." ]
149f9f992be9b0957fb1ffeda43c14a123ceb43a
https://github.com/revel/cmd/blob/149f9f992be9b0957fb1ffeda43c14a123ceb43a/harness/app.go#L102-L161
18,032
revel/cmd
harness/app.go
Write
func (w *startupListeningWriter) Write(p []byte) (int, error) { if w.notifyReady != nil && bytes.Contains(p, []byte("Revel engine is listening on")) { w.notifyReady <- true w.notifyReady = nil } if w.c.HistoricMode { if w.notifyReady != nil && bytes.Contains(p, []byte("Listening on")) { w.notifyReady <- true w.notifyReady = nil } } if w.notifyReady!=nil { w.buffer.Write(p) } return w.dest.Write(p) }
go
func (w *startupListeningWriter) Write(p []byte) (int, error) { if w.notifyReady != nil && bytes.Contains(p, []byte("Revel engine is listening on")) { w.notifyReady <- true w.notifyReady = nil } if w.c.HistoricMode { if w.notifyReady != nil && bytes.Contains(p, []byte("Listening on")) { w.notifyReady <- true w.notifyReady = nil } } if w.notifyReady!=nil { w.buffer.Write(p) } return w.dest.Write(p) }
[ "func", "(", "w", "*", "startupListeningWriter", ")", "Write", "(", "p", "[", "]", "byte", ")", "(", "int", ",", "error", ")", "{", "if", "w", ".", "notifyReady", "!=", "nil", "&&", "bytes", ".", "Contains", "(", "p", ",", "[", "]", "byte", "(", "\"", "\"", ")", ")", "{", "w", ".", "notifyReady", "<-", "true", "\n", "w", ".", "notifyReady", "=", "nil", "\n", "}", "\n", "if", "w", ".", "c", ".", "HistoricMode", "{", "if", "w", ".", "notifyReady", "!=", "nil", "&&", "bytes", ".", "Contains", "(", "p", ",", "[", "]", "byte", "(", "\"", "\"", ")", ")", "{", "w", ".", "notifyReady", "<-", "true", "\n", "w", ".", "notifyReady", "=", "nil", "\n", "}", "\n", "}", "\n", "if", "w", ".", "notifyReady", "!=", "nil", "{", "w", ".", "buffer", ".", "Write", "(", "p", ")", "\n", "}", "\n", "return", "w", ".", "dest", ".", "Write", "(", "p", ")", "\n", "}" ]
// Writes to this output stream
[ "Writes", "to", "this", "output", "stream" ]
149f9f992be9b0957fb1ffeda43c14a123ceb43a
https://github.com/revel/cmd/blob/149f9f992be9b0957fb1ffeda43c14a123ceb43a/harness/app.go#L190-L205
18,033
revel/cmd
watcher/watcher.go
NewWatcher
func NewWatcher(paths *model.RevelContainer, eagerRefresh bool) *Watcher { return &Watcher{ forceRefresh: true, lastError: -1, paths: paths, refreshTimerMS: time.Duration(paths.Config.IntDefault("watch.rebuild.delay", 10)), eagerRefresh: eagerRefresh || paths.DevMode && paths.Config.BoolDefault("watch", true) && paths.Config.StringDefault("watch.mode", "normal") == "eager", timerMutex: &sync.Mutex{}, refreshChannel: make(chan *utils.Error, 10), refreshChannelCount: 0, } }
go
func NewWatcher(paths *model.RevelContainer, eagerRefresh bool) *Watcher { return &Watcher{ forceRefresh: true, lastError: -1, paths: paths, refreshTimerMS: time.Duration(paths.Config.IntDefault("watch.rebuild.delay", 10)), eagerRefresh: eagerRefresh || paths.DevMode && paths.Config.BoolDefault("watch", true) && paths.Config.StringDefault("watch.mode", "normal") == "eager", timerMutex: &sync.Mutex{}, refreshChannel: make(chan *utils.Error, 10), refreshChannelCount: 0, } }
[ "func", "NewWatcher", "(", "paths", "*", "model", ".", "RevelContainer", ",", "eagerRefresh", "bool", ")", "*", "Watcher", "{", "return", "&", "Watcher", "{", "forceRefresh", ":", "true", ",", "lastError", ":", "-", "1", ",", "paths", ":", "paths", ",", "refreshTimerMS", ":", "time", ".", "Duration", "(", "paths", ".", "Config", ".", "IntDefault", "(", "\"", "\"", ",", "10", ")", ")", ",", "eagerRefresh", ":", "eagerRefresh", "||", "paths", ".", "DevMode", "&&", "paths", ".", "Config", ".", "BoolDefault", "(", "\"", "\"", ",", "true", ")", "&&", "paths", ".", "Config", ".", "StringDefault", "(", "\"", "\"", ",", "\"", "\"", ")", "==", "\"", "\"", ",", "timerMutex", ":", "&", "sync", ".", "Mutex", "{", "}", ",", "refreshChannel", ":", "make", "(", "chan", "*", "utils", ".", "Error", ",", "10", ")", ",", "refreshChannelCount", ":", "0", ",", "}", "\n", "}" ]
// Creates a new watched based on the container
[ "Creates", "a", "new", "watched", "based", "on", "the", "container" ]
149f9f992be9b0957fb1ffeda43c14a123ceb43a
https://github.com/revel/cmd/blob/149f9f992be9b0957fb1ffeda43c14a123ceb43a/watcher/watcher.go#L53-L67
18,034
revel/cmd
watcher/watcher.go
NotifyWhenUpdated
func (w *Watcher) NotifyWhenUpdated(listener Listener, watcher *fsnotify.Watcher) { for { select { case ev := <-watcher.Events: if w.rebuildRequired(ev, listener) { if w.serial { // Serialize listener.Refresh() calls. w.notifyMutex.Lock() if err := listener.Refresh(); err != nil { utils.Logger.Error("Watcher: Listener refresh reported error:", "error", err) } w.notifyMutex.Unlock() } else { // Run refresh in parallel go func() { w.notifyInProcess(listener) }() } } case <-watcher.Errors: continue } } }
go
func (w *Watcher) NotifyWhenUpdated(listener Listener, watcher *fsnotify.Watcher) { for { select { case ev := <-watcher.Events: if w.rebuildRequired(ev, listener) { if w.serial { // Serialize listener.Refresh() calls. w.notifyMutex.Lock() if err := listener.Refresh(); err != nil { utils.Logger.Error("Watcher: Listener refresh reported error:", "error", err) } w.notifyMutex.Unlock() } else { // Run refresh in parallel go func() { w.notifyInProcess(listener) }() } } case <-watcher.Errors: continue } } }
[ "func", "(", "w", "*", "Watcher", ")", "NotifyWhenUpdated", "(", "listener", "Listener", ",", "watcher", "*", "fsnotify", ".", "Watcher", ")", "{", "for", "{", "select", "{", "case", "ev", ":=", "<-", "watcher", ".", "Events", ":", "if", "w", ".", "rebuildRequired", "(", "ev", ",", "listener", ")", "{", "if", "w", ".", "serial", "{", "// Serialize listener.Refresh() calls.", "w", ".", "notifyMutex", ".", "Lock", "(", ")", "\n\n", "if", "err", ":=", "listener", ".", "Refresh", "(", ")", ";", "err", "!=", "nil", "{", "utils", ".", "Logger", ".", "Error", "(", "\"", "\"", ",", "\"", "\"", ",", "err", ")", "\n", "}", "\n", "w", ".", "notifyMutex", ".", "Unlock", "(", ")", "\n", "}", "else", "{", "// Run refresh in parallel", "go", "func", "(", ")", "{", "w", ".", "notifyInProcess", "(", "listener", ")", "\n", "}", "(", ")", "\n", "}", "\n", "}", "\n", "case", "<-", "watcher", ".", "Errors", ":", "continue", "\n", "}", "\n", "}", "\n", "}" ]
// NotifyWhenUpdated notifies the watcher when a file event is received.
[ "NotifyWhenUpdated", "notifies", "the", "watcher", "when", "a", "file", "event", "is", "received", "." ]
149f9f992be9b0957fb1ffeda43c14a123ceb43a
https://github.com/revel/cmd/blob/149f9f992be9b0957fb1ffeda43c14a123ceb43a/watcher/watcher.go#L152-L177
18,035
revel/cmd
watcher/watcher.go
notifyInProcess
func (w *Watcher) notifyInProcess(listener Listener) (err *utils.Error) { shouldReturn := false // This code block ensures that either a timer is created // or that a process would be added the the h.refreshChannel func() { w.timerMutex.Lock() defer w.timerMutex.Unlock() // If we are in the process of a rebuild, forceRefresh will always be true w.forceRefresh = true if w.refreshTimer != nil { utils.Logger.Info("Found existing timer running, resetting") w.refreshTimer.Reset(time.Millisecond * w.refreshTimerMS) shouldReturn = true w.refreshChannelCount++ } else { w.refreshTimer = time.NewTimer(time.Millisecond * w.refreshTimerMS) } }() // If another process is already waiting for the timer this one // only needs to return the output from the channel if shouldReturn { return <-w.refreshChannel } utils.Logger.Info("Waiting for refresh timer to expire") <-w.refreshTimer.C w.timerMutex.Lock() // Ensure the queue is properly dispatched even if a panic occurs defer func() { for x := 0; x < w.refreshChannelCount; x++ { w.refreshChannel <- err } w.refreshChannelCount = 0 w.refreshTimer = nil w.timerMutex.Unlock() }() err = listener.Refresh() if err != nil { utils.Logger.Info("Watcher: Recording error last build, setting rebuild on", "error", err) } else { w.lastError = -1 w.forceRefresh = false } utils.Logger.Info("Rebuilt, result", "error", err) return }
go
func (w *Watcher) notifyInProcess(listener Listener) (err *utils.Error) { shouldReturn := false // This code block ensures that either a timer is created // or that a process would be added the the h.refreshChannel func() { w.timerMutex.Lock() defer w.timerMutex.Unlock() // If we are in the process of a rebuild, forceRefresh will always be true w.forceRefresh = true if w.refreshTimer != nil { utils.Logger.Info("Found existing timer running, resetting") w.refreshTimer.Reset(time.Millisecond * w.refreshTimerMS) shouldReturn = true w.refreshChannelCount++ } else { w.refreshTimer = time.NewTimer(time.Millisecond * w.refreshTimerMS) } }() // If another process is already waiting for the timer this one // only needs to return the output from the channel if shouldReturn { return <-w.refreshChannel } utils.Logger.Info("Waiting for refresh timer to expire") <-w.refreshTimer.C w.timerMutex.Lock() // Ensure the queue is properly dispatched even if a panic occurs defer func() { for x := 0; x < w.refreshChannelCount; x++ { w.refreshChannel <- err } w.refreshChannelCount = 0 w.refreshTimer = nil w.timerMutex.Unlock() }() err = listener.Refresh() if err != nil { utils.Logger.Info("Watcher: Recording error last build, setting rebuild on", "error", err) } else { w.lastError = -1 w.forceRefresh = false } utils.Logger.Info("Rebuilt, result", "error", err) return }
[ "func", "(", "w", "*", "Watcher", ")", "notifyInProcess", "(", "listener", "Listener", ")", "(", "err", "*", "utils", ".", "Error", ")", "{", "shouldReturn", ":=", "false", "\n", "// This code block ensures that either a timer is created", "// or that a process would be added the the h.refreshChannel", "func", "(", ")", "{", "w", ".", "timerMutex", ".", "Lock", "(", ")", "\n", "defer", "w", ".", "timerMutex", ".", "Unlock", "(", ")", "\n", "// If we are in the process of a rebuild, forceRefresh will always be true", "w", ".", "forceRefresh", "=", "true", "\n", "if", "w", ".", "refreshTimer", "!=", "nil", "{", "utils", ".", "Logger", ".", "Info", "(", "\"", "\"", ")", "\n", "w", ".", "refreshTimer", ".", "Reset", "(", "time", ".", "Millisecond", "*", "w", ".", "refreshTimerMS", ")", "\n", "shouldReturn", "=", "true", "\n", "w", ".", "refreshChannelCount", "++", "\n", "}", "else", "{", "w", ".", "refreshTimer", "=", "time", ".", "NewTimer", "(", "time", ".", "Millisecond", "*", "w", ".", "refreshTimerMS", ")", "\n", "}", "\n", "}", "(", ")", "\n\n", "// If another process is already waiting for the timer this one", "// only needs to return the output from the channel", "if", "shouldReturn", "{", "return", "<-", "w", ".", "refreshChannel", "\n", "}", "\n", "utils", ".", "Logger", ".", "Info", "(", "\"", "\"", ")", "\n", "<-", "w", ".", "refreshTimer", ".", "C", "\n", "w", ".", "timerMutex", ".", "Lock", "(", ")", "\n\n", "// Ensure the queue is properly dispatched even if a panic occurs", "defer", "func", "(", ")", "{", "for", "x", ":=", "0", ";", "x", "<", "w", ".", "refreshChannelCount", ";", "x", "++", "{", "w", ".", "refreshChannel", "<-", "err", "\n", "}", "\n", "w", ".", "refreshChannelCount", "=", "0", "\n", "w", ".", "refreshTimer", "=", "nil", "\n", "w", ".", "timerMutex", ".", "Unlock", "(", ")", "\n", "}", "(", ")", "\n\n", "err", "=", "listener", ".", "Refresh", "(", ")", "\n", "if", "err", "!=", "nil", "{", "utils", ".", "Logger", ".", "Info", "(", "\"", "\"", ",", "\"", "\"", ",", "err", ")", "\n", "}", "else", "{", "w", ".", "lastError", "=", "-", "1", "\n", "w", ".", "forceRefresh", "=", "false", "\n", "}", "\n", "utils", ".", "Logger", ".", "Info", "(", "\"", "\"", ",", "\"", "\"", ",", "err", ")", "\n", "return", "\n", "}" ]
// Build a queue for refresh notifications // this will not return until one of the queue completes
[ "Build", "a", "queue", "for", "refresh", "notifications", "this", "will", "not", "return", "until", "one", "of", "the", "queue", "completes" ]
149f9f992be9b0957fb1ffeda43c14a123ceb43a
https://github.com/revel/cmd/blob/149f9f992be9b0957fb1ffeda43c14a123ceb43a/watcher/watcher.go#L232-L279
18,036
revel/cmd
revel/clean.go
updateCleanConfig
func updateCleanConfig(c *model.CommandConfig, args []string) bool { c.Index = model.CLEAN if len(args) == 0 { fmt.Fprintf(os.Stderr, cmdClean.Long) return false } c.Clean.ImportPath = args[0] return true }
go
func updateCleanConfig(c *model.CommandConfig, args []string) bool { c.Index = model.CLEAN if len(args) == 0 { fmt.Fprintf(os.Stderr, cmdClean.Long) return false } c.Clean.ImportPath = args[0] return true }
[ "func", "updateCleanConfig", "(", "c", "*", "model", ".", "CommandConfig", ",", "args", "[", "]", "string", ")", "bool", "{", "c", ".", "Index", "=", "model", ".", "CLEAN", "\n", "if", "len", "(", "args", ")", "==", "0", "{", "fmt", ".", "Fprintf", "(", "os", ".", "Stderr", ",", "cmdClean", ".", "Long", ")", "\n", "return", "false", "\n", "}", "\n", "c", ".", "Clean", ".", "ImportPath", "=", "args", "[", "0", "]", "\n", "return", "true", "\n", "}" ]
// Update the clean command configuration, using old method
[ "Update", "the", "clean", "command", "configuration", "using", "old", "method" ]
149f9f992be9b0957fb1ffeda43c14a123ceb43a
https://github.com/revel/cmd/blob/149f9f992be9b0957fb1ffeda43c14a123ceb43a/revel/clean.go#L38-L46
18,037
revel/cmd
revel/clean.go
cleanApp
func cleanApp(c *model.CommandConfig) (err error) { appPkg, err := build.Import(c.ImportPath, "", build.FindOnly) if err != nil { utils.Logger.Fatal("Abort: Failed to find import path:", "error", err) } purgeDirs := []string{ filepath.Join(appPkg.Dir, "app", "tmp"), filepath.Join(appPkg.Dir, "app", "routes"), } for _, dir := range purgeDirs { fmt.Println("Removing:", dir) err = os.RemoveAll(dir) if err != nil { utils.Logger.Error("Failed to clean dir", "error", err) return } } return err }
go
func cleanApp(c *model.CommandConfig) (err error) { appPkg, err := build.Import(c.ImportPath, "", build.FindOnly) if err != nil { utils.Logger.Fatal("Abort: Failed to find import path:", "error", err) } purgeDirs := []string{ filepath.Join(appPkg.Dir, "app", "tmp"), filepath.Join(appPkg.Dir, "app", "routes"), } for _, dir := range purgeDirs { fmt.Println("Removing:", dir) err = os.RemoveAll(dir) if err != nil { utils.Logger.Error("Failed to clean dir", "error", err) return } } return err }
[ "func", "cleanApp", "(", "c", "*", "model", ".", "CommandConfig", ")", "(", "err", "error", ")", "{", "appPkg", ",", "err", ":=", "build", ".", "Import", "(", "c", ".", "ImportPath", ",", "\"", "\"", ",", "build", ".", "FindOnly", ")", "\n", "if", "err", "!=", "nil", "{", "utils", ".", "Logger", ".", "Fatal", "(", "\"", "\"", ",", "\"", "\"", ",", "err", ")", "\n", "}", "\n\n", "purgeDirs", ":=", "[", "]", "string", "{", "filepath", ".", "Join", "(", "appPkg", ".", "Dir", ",", "\"", "\"", ",", "\"", "\"", ")", ",", "filepath", ".", "Join", "(", "appPkg", ".", "Dir", ",", "\"", "\"", ",", "\"", "\"", ")", ",", "}", "\n\n", "for", "_", ",", "dir", ":=", "range", "purgeDirs", "{", "fmt", ".", "Println", "(", "\"", "\"", ",", "dir", ")", "\n", "err", "=", "os", ".", "RemoveAll", "(", "dir", ")", "\n", "if", "err", "!=", "nil", "{", "utils", ".", "Logger", ".", "Error", "(", "\"", "\"", ",", "\"", "\"", ",", "err", ")", "\n", "return", "\n", "}", "\n", "}", "\n", "return", "err", "\n", "}" ]
// Clean the source directory of generated files
[ "Clean", "the", "source", "directory", "of", "generated", "files" ]
149f9f992be9b0957fb1ffeda43c14a123ceb43a
https://github.com/revel/cmd/blob/149f9f992be9b0957fb1ffeda43c14a123ceb43a/revel/clean.go#L49-L69
18,038
revel/cmd
revel/new.go
generateSecret
func generateSecret() string { chars := make([]byte, 64) for i := 0; i < 64; i++ { chars[i] = alphaNumeric[rand.Intn(len(alphaNumeric))] } return string(chars) }
go
func generateSecret() string { chars := make([]byte, 64) for i := 0; i < 64; i++ { chars[i] = alphaNumeric[rand.Intn(len(alphaNumeric))] } return string(chars) }
[ "func", "generateSecret", "(", ")", "string", "{", "chars", ":=", "make", "(", "[", "]", "byte", ",", "64", ")", "\n", "for", "i", ":=", "0", ";", "i", "<", "64", ";", "i", "++", "{", "chars", "[", "i", "]", "=", "alphaNumeric", "[", "rand", ".", "Intn", "(", "len", "(", "alphaNumeric", ")", ")", "]", "\n", "}", "\n", "return", "string", "(", "chars", ")", "\n", "}" ]
// Generate a secret key
[ "Generate", "a", "secret", "key" ]
149f9f992be9b0957fb1ffeda43c14a123ceb43a
https://github.com/revel/cmd/blob/149f9f992be9b0957fb1ffeda43c14a123ceb43a/revel/new.go#L163-L169
18,039
revel/cmd
revel/new.go
setApplicationPath
func setApplicationPath(c *model.CommandConfig) (err error) { // revel/revel#1014 validate relative path, we cannot use built-in functions // since Go import path is valid relative path too. // so check basic part of the path, which is "." if filepath.IsAbs(c.ImportPath) || strings.HasPrefix(c.ImportPath, ".") { utils.Logger.Fatalf("Abort: '%s' looks like a directory. Please provide a Go import path instead.", c.ImportPath) } // If we are running a vendored version of Revel we do not need to check for it. if !c.New.Vendored { _, err = build.Import(model.RevelImportPath, "", build.FindOnly) if err != nil { //// Go get the revel project err = c.PackageResolver(model.RevelImportPath) if err != nil { return utils.NewBuildIfError(err, "Failed to fetch revel "+model.RevelImportPath) } } } c.AppName = filepath.Base(c.AppPath) return nil }
go
func setApplicationPath(c *model.CommandConfig) (err error) { // revel/revel#1014 validate relative path, we cannot use built-in functions // since Go import path is valid relative path too. // so check basic part of the path, which is "." if filepath.IsAbs(c.ImportPath) || strings.HasPrefix(c.ImportPath, ".") { utils.Logger.Fatalf("Abort: '%s' looks like a directory. Please provide a Go import path instead.", c.ImportPath) } // If we are running a vendored version of Revel we do not need to check for it. if !c.New.Vendored { _, err = build.Import(model.RevelImportPath, "", build.FindOnly) if err != nil { //// Go get the revel project err = c.PackageResolver(model.RevelImportPath) if err != nil { return utils.NewBuildIfError(err, "Failed to fetch revel "+model.RevelImportPath) } } } c.AppName = filepath.Base(c.AppPath) return nil }
[ "func", "setApplicationPath", "(", "c", "*", "model", ".", "CommandConfig", ")", "(", "err", "error", ")", "{", "// revel/revel#1014 validate relative path, we cannot use built-in functions", "// since Go import path is valid relative path too.", "// so check basic part of the path, which is \".\"", "if", "filepath", ".", "IsAbs", "(", "c", ".", "ImportPath", ")", "||", "strings", ".", "HasPrefix", "(", "c", ".", "ImportPath", ",", "\"", "\"", ")", "{", "utils", ".", "Logger", ".", "Fatalf", "(", "\"", "\"", ",", "c", ".", "ImportPath", ")", "\n", "}", "\n\n", "// If we are running a vendored version of Revel we do not need to check for it.", "if", "!", "c", ".", "New", ".", "Vendored", "{", "_", ",", "err", "=", "build", ".", "Import", "(", "model", ".", "RevelImportPath", ",", "\"", "\"", ",", "build", ".", "FindOnly", ")", "\n", "if", "err", "!=", "nil", "{", "//// Go get the revel project", "err", "=", "c", ".", "PackageResolver", "(", "model", ".", "RevelImportPath", ")", "\n", "if", "err", "!=", "nil", "{", "return", "utils", ".", "NewBuildIfError", "(", "err", ",", "\"", "\"", "+", "model", ".", "RevelImportPath", ")", "\n", "}", "\n", "}", "\n", "}", "\n\n", "c", ".", "AppName", "=", "filepath", ".", "Base", "(", "c", ".", "AppPath", ")", "\n\n", "return", "nil", "\n", "}" ]
// Sets the applicaiton path
[ "Sets", "the", "applicaiton", "path" ]
149f9f992be9b0957fb1ffeda43c14a123ceb43a
https://github.com/revel/cmd/blob/149f9f992be9b0957fb1ffeda43c14a123ceb43a/revel/new.go#L172-L197
18,040
revel/cmd
revel/new.go
setSkeletonPath
func setSkeletonPath(c *model.CommandConfig) (err error) { if len(c.New.SkeletonPath) == 0 { c.New.SkeletonPath = "https://" + RevelSkeletonsImportPath + ":basic/bootstrap4" } // First check to see the protocol of the string sp, err := url.Parse(c.New.SkeletonPath) if err == nil { utils.Logger.Info("Detected skeleton path", "path", sp) switch strings.ToLower(sp.Scheme) { // TODO Add support for ftp, sftp, scp ?? case "" : sp.Scheme="file" fallthrough case "file" : fullpath := sp.String()[7:] if !filepath.IsAbs(fullpath) { fullpath, err = filepath.Abs(fullpath) if err!=nil { return } } c.New.SkeletonPath = fullpath utils.Logger.Info("Set skeleton path to ", fullpath) if !utils.DirExists(fullpath) { return fmt.Errorf("Failed to find skeleton in filepath %s %s", fullpath, sp.String()) } case "git": fallthrough case "http": fallthrough case "https": if err := newLoadFromGit(c, sp); err != nil { return err } default: utils.Logger.Fatal("Unsupported skeleton schema ", "path", c.New.SkeletonPath) } // TODO check to see if the path needs to be extracted } else { utils.Logger.Fatal("Invalid skeleton path format", "path", c.New.SkeletonPath) } return }
go
func setSkeletonPath(c *model.CommandConfig) (err error) { if len(c.New.SkeletonPath) == 0 { c.New.SkeletonPath = "https://" + RevelSkeletonsImportPath + ":basic/bootstrap4" } // First check to see the protocol of the string sp, err := url.Parse(c.New.SkeletonPath) if err == nil { utils.Logger.Info("Detected skeleton path", "path", sp) switch strings.ToLower(sp.Scheme) { // TODO Add support for ftp, sftp, scp ?? case "" : sp.Scheme="file" fallthrough case "file" : fullpath := sp.String()[7:] if !filepath.IsAbs(fullpath) { fullpath, err = filepath.Abs(fullpath) if err!=nil { return } } c.New.SkeletonPath = fullpath utils.Logger.Info("Set skeleton path to ", fullpath) if !utils.DirExists(fullpath) { return fmt.Errorf("Failed to find skeleton in filepath %s %s", fullpath, sp.String()) } case "git": fallthrough case "http": fallthrough case "https": if err := newLoadFromGit(c, sp); err != nil { return err } default: utils.Logger.Fatal("Unsupported skeleton schema ", "path", c.New.SkeletonPath) } // TODO check to see if the path needs to be extracted } else { utils.Logger.Fatal("Invalid skeleton path format", "path", c.New.SkeletonPath) } return }
[ "func", "setSkeletonPath", "(", "c", "*", "model", ".", "CommandConfig", ")", "(", "err", "error", ")", "{", "if", "len", "(", "c", ".", "New", ".", "SkeletonPath", ")", "==", "0", "{", "c", ".", "New", ".", "SkeletonPath", "=", "\"", "\"", "+", "RevelSkeletonsImportPath", "+", "\"", "\"", "\n", "}", "\n\n", "// First check to see the protocol of the string", "sp", ",", "err", ":=", "url", ".", "Parse", "(", "c", ".", "New", ".", "SkeletonPath", ")", "\n", "if", "err", "==", "nil", "{", "utils", ".", "Logger", ".", "Info", "(", "\"", "\"", ",", "\"", "\"", ",", "sp", ")", "\n\n", "switch", "strings", ".", "ToLower", "(", "sp", ".", "Scheme", ")", "{", "// TODO Add support for ftp, sftp, scp ??", "case", "\"", "\"", ":", "sp", ".", "Scheme", "=", "\"", "\"", "\n", "fallthrough", "\n", "case", "\"", "\"", ":", "fullpath", ":=", "sp", ".", "String", "(", ")", "[", "7", ":", "]", "\n", "if", "!", "filepath", ".", "IsAbs", "(", "fullpath", ")", "{", "fullpath", ",", "err", "=", "filepath", ".", "Abs", "(", "fullpath", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\n", "}", "\n", "}", "\n", "c", ".", "New", ".", "SkeletonPath", "=", "fullpath", "\n", "utils", ".", "Logger", ".", "Info", "(", "\"", "\"", ",", "fullpath", ")", "\n", "if", "!", "utils", ".", "DirExists", "(", "fullpath", ")", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "fullpath", ",", "sp", ".", "String", "(", ")", ")", "\n", "}", "\n", "case", "\"", "\"", ":", "fallthrough", "\n", "case", "\"", "\"", ":", "fallthrough", "\n", "case", "\"", "\"", ":", "if", "err", ":=", "newLoadFromGit", "(", "c", ",", "sp", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "default", ":", "utils", ".", "Logger", ".", "Fatal", "(", "\"", "\"", ",", "\"", "\"", ",", "c", ".", "New", ".", "SkeletonPath", ")", "\n\n", "}", "\n", "// TODO check to see if the path needs to be extracted", "}", "else", "{", "utils", ".", "Logger", ".", "Fatal", "(", "\"", "\"", ",", "\"", "\"", ",", "c", ".", "New", ".", "SkeletonPath", ")", "\n", "}", "\n", "return", "\n", "}" ]
// Set the skeleton path
[ "Set", "the", "skeleton", "path" ]
149f9f992be9b0957fb1ffeda43c14a123ceb43a
https://github.com/revel/cmd/blob/149f9f992be9b0957fb1ffeda43c14a123ceb43a/revel/new.go#L200-L245
18,041
revel/cmd
revel/new.go
newLoadFromGit
func newLoadFromGit(c *model.CommandConfig, sp *url.URL) (err error) { // This method indicates we need to fetch from a repository using git // Execute "git clone get <pkg>" targetPath := filepath.Join(os.TempDir(), "revel", "skeleton") os.RemoveAll(targetPath) pathpart := strings.Split(sp.Path, ":") getCmd := exec.Command("git", "clone", sp.Scheme+"://"+sp.Host+pathpart[0], targetPath) utils.Logger.Info("Exec:", "args", getCmd.Args) getOutput, err := getCmd.CombinedOutput() if err != nil { utils.Logger.Fatal("Abort: could not clone the Skeleton source code: ","output", string(getOutput), "path", c.New.SkeletonPath) } outputPath := targetPath if len(pathpart) > 1 { outputPath = filepath.Join(targetPath, filepath.Join(strings.Split(pathpart[1], string('/'))...)) } outputPath, _ = filepath.Abs(outputPath) if !strings.HasPrefix(outputPath, targetPath) { utils.Logger.Fatal("Unusual target path outside root path", "target", outputPath, "root", targetPath) } c.New.SkeletonPath = outputPath return }
go
func newLoadFromGit(c *model.CommandConfig, sp *url.URL) (err error) { // This method indicates we need to fetch from a repository using git // Execute "git clone get <pkg>" targetPath := filepath.Join(os.TempDir(), "revel", "skeleton") os.RemoveAll(targetPath) pathpart := strings.Split(sp.Path, ":") getCmd := exec.Command("git", "clone", sp.Scheme+"://"+sp.Host+pathpart[0], targetPath) utils.Logger.Info("Exec:", "args", getCmd.Args) getOutput, err := getCmd.CombinedOutput() if err != nil { utils.Logger.Fatal("Abort: could not clone the Skeleton source code: ","output", string(getOutput), "path", c.New.SkeletonPath) } outputPath := targetPath if len(pathpart) > 1 { outputPath = filepath.Join(targetPath, filepath.Join(strings.Split(pathpart[1], string('/'))...)) } outputPath, _ = filepath.Abs(outputPath) if !strings.HasPrefix(outputPath, targetPath) { utils.Logger.Fatal("Unusual target path outside root path", "target", outputPath, "root", targetPath) } c.New.SkeletonPath = outputPath return }
[ "func", "newLoadFromGit", "(", "c", "*", "model", ".", "CommandConfig", ",", "sp", "*", "url", ".", "URL", ")", "(", "err", "error", ")", "{", "// This method indicates we need to fetch from a repository using git", "// Execute \"git clone get <pkg>\"", "targetPath", ":=", "filepath", ".", "Join", "(", "os", ".", "TempDir", "(", ")", ",", "\"", "\"", ",", "\"", "\"", ")", "\n", "os", ".", "RemoveAll", "(", "targetPath", ")", "\n", "pathpart", ":=", "strings", ".", "Split", "(", "sp", ".", "Path", ",", "\"", "\"", ")", "\n", "getCmd", ":=", "exec", ".", "Command", "(", "\"", "\"", ",", "\"", "\"", ",", "sp", ".", "Scheme", "+", "\"", "\"", "+", "sp", ".", "Host", "+", "pathpart", "[", "0", "]", ",", "targetPath", ")", "\n", "utils", ".", "Logger", ".", "Info", "(", "\"", "\"", ",", "\"", "\"", ",", "getCmd", ".", "Args", ")", "\n", "getOutput", ",", "err", ":=", "getCmd", ".", "CombinedOutput", "(", ")", "\n", "if", "err", "!=", "nil", "{", "utils", ".", "Logger", ".", "Fatal", "(", "\"", "\"", ",", "\"", "\"", ",", "string", "(", "getOutput", ")", ",", "\"", "\"", ",", "c", ".", "New", ".", "SkeletonPath", ")", "\n", "}", "\n", "outputPath", ":=", "targetPath", "\n", "if", "len", "(", "pathpart", ")", ">", "1", "{", "outputPath", "=", "filepath", ".", "Join", "(", "targetPath", ",", "filepath", ".", "Join", "(", "strings", ".", "Split", "(", "pathpart", "[", "1", "]", ",", "string", "(", "'/'", ")", ")", "...", ")", ")", "\n", "}", "\n", "outputPath", ",", "_", "=", "filepath", ".", "Abs", "(", "outputPath", ")", "\n", "if", "!", "strings", ".", "HasPrefix", "(", "outputPath", ",", "targetPath", ")", "{", "utils", ".", "Logger", ".", "Fatal", "(", "\"", "\"", ",", "\"", "\"", ",", "outputPath", ",", "\"", "\"", ",", "targetPath", ")", "\n", "}", "\n\n", "c", ".", "New", ".", "SkeletonPath", "=", "outputPath", "\n", "return", "\n", "}" ]
// Load skeleton from git
[ "Load", "skeleton", "from", "git" ]
149f9f992be9b0957fb1ffeda43c14a123ceb43a
https://github.com/revel/cmd/blob/149f9f992be9b0957fb1ffeda43c14a123ceb43a/revel/new.go#L248-L271
18,042
revel/cmd
utils/log.go
Retry
func Retry(format string, args ...interface{}) { // Ensure the user's command prompt starts on the next line. if !strings.HasSuffix(format, "\n") { format += "\n" } fmt.Fprintf(os.Stderr, format, args...) panic(format) // Panic instead of os.Exit so that deferred will run. }
go
func Retry(format string, args ...interface{}) { // Ensure the user's command prompt starts on the next line. if !strings.HasSuffix(format, "\n") { format += "\n" } fmt.Fprintf(os.Stderr, format, args...) panic(format) // Panic instead of os.Exit so that deferred will run. }
[ "func", "Retry", "(", "format", "string", ",", "args", "...", "interface", "{", "}", ")", "{", "// Ensure the user's command prompt starts on the next line.", "if", "!", "strings", ".", "HasSuffix", "(", "format", ",", "\"", "\\n", "\"", ")", "{", "format", "+=", "\"", "\\n", "\"", "\n", "}", "\n", "fmt", ".", "Fprintf", "(", "os", ".", "Stderr", ",", "format", ",", "args", "...", ")", "\n", "panic", "(", "format", ")", "// Panic instead of os.Exit so that deferred will run.", "\n", "}" ]
// This function is to throw a panic that may be caught by the packger so it can perform the needed // imports
[ "This", "function", "is", "to", "throw", "a", "panic", "that", "may", "be", "caught", "by", "the", "packger", "so", "it", "can", "perform", "the", "needed", "imports" ]
149f9f992be9b0957fb1ffeda43c14a123ceb43a
https://github.com/revel/cmd/blob/149f9f992be9b0957fb1ffeda43c14a123ceb43a/utils/log.go#L35-L42
18,043
segmentio/analytics-go
analytics.go
New
func New(key string) *Client { c := &Client{ Endpoint: Endpoint, Interval: 5 * time.Second, Size: 250, Logger: log.New(os.Stderr, "segment ", log.LstdFlags), Verbose: false, Client: *http.DefaultClient, key: key, msgs: make(chan interface{}, 100), quit: make(chan struct{}), shutdown: make(chan struct{}), now: time.Now, uid: uid, } c.logf("You are currently using the v2 version analytics-go, which is being deprecated. Please update to v3 as soon as you can https://segment.com/docs/sources/server/go/#migrating-from-v2") c.upcond.L = &c.upmtx return c }
go
func New(key string) *Client { c := &Client{ Endpoint: Endpoint, Interval: 5 * time.Second, Size: 250, Logger: log.New(os.Stderr, "segment ", log.LstdFlags), Verbose: false, Client: *http.DefaultClient, key: key, msgs: make(chan interface{}, 100), quit: make(chan struct{}), shutdown: make(chan struct{}), now: time.Now, uid: uid, } c.logf("You are currently using the v2 version analytics-go, which is being deprecated. Please update to v3 as soon as you can https://segment.com/docs/sources/server/go/#migrating-from-v2") c.upcond.L = &c.upmtx return c }
[ "func", "New", "(", "key", "string", ")", "*", "Client", "{", "c", ":=", "&", "Client", "{", "Endpoint", ":", "Endpoint", ",", "Interval", ":", "5", "*", "time", ".", "Second", ",", "Size", ":", "250", ",", "Logger", ":", "log", ".", "New", "(", "os", ".", "Stderr", ",", "\"", "\"", ",", "log", ".", "LstdFlags", ")", ",", "Verbose", ":", "false", ",", "Client", ":", "*", "http", ".", "DefaultClient", ",", "key", ":", "key", ",", "msgs", ":", "make", "(", "chan", "interface", "{", "}", ",", "100", ")", ",", "quit", ":", "make", "(", "chan", "struct", "{", "}", ")", ",", "shutdown", ":", "make", "(", "chan", "struct", "{", "}", ")", ",", "now", ":", "time", ".", "Now", ",", "uid", ":", "uid", ",", "}", "\n\n", "c", ".", "logf", "(", "\"", "\"", ")", "\n\n", "c", ".", "upcond", ".", "L", "=", "&", "c", ".", "upmtx", "\n", "return", "c", "\n", "}" ]
// New client with write key.
[ "New", "client", "with", "write", "key", "." ]
8999d38db33a06d54813976725d47e18b4e3191c
https://github.com/segmentio/analytics-go/blob/8999d38db33a06d54813976725d47e18b4e3191c/analytics.go#L139-L159
18,044
segmentio/analytics-go
analytics.go
Alias
func (c *Client) Alias(msg *Alias) error { if msg.UserId == "" { return errors.New("You must pass a 'userId'.") } if msg.PreviousId == "" { return errors.New("You must pass a 'previousId'.") } msg.Type = "alias" c.queue(msg) return nil }
go
func (c *Client) Alias(msg *Alias) error { if msg.UserId == "" { return errors.New("You must pass a 'userId'.") } if msg.PreviousId == "" { return errors.New("You must pass a 'previousId'.") } msg.Type = "alias" c.queue(msg) return nil }
[ "func", "(", "c", "*", "Client", ")", "Alias", "(", "msg", "*", "Alias", ")", "error", "{", "if", "msg", ".", "UserId", "==", "\"", "\"", "{", "return", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n\n", "if", "msg", ".", "PreviousId", "==", "\"", "\"", "{", "return", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n\n", "msg", ".", "Type", "=", "\"", "\"", "\n", "c", ".", "queue", "(", "msg", ")", "\n\n", "return", "nil", "\n", "}" ]
// Alias buffers an "alias" message.
[ "Alias", "buffers", "an", "alias", "message", "." ]
8999d38db33a06d54813976725d47e18b4e3191c
https://github.com/segmentio/analytics-go/blob/8999d38db33a06d54813976725d47e18b4e3191c/analytics.go#L162-L175
18,045
segmentio/analytics-go
analytics.go
Page
func (c *Client) Page(msg *Page) error { if msg.UserId == "" && msg.AnonymousId == "" { return errors.New("You must pass either an 'anonymousId' or 'userId'.") } msg.Type = "page" c.queue(msg) return nil }
go
func (c *Client) Page(msg *Page) error { if msg.UserId == "" && msg.AnonymousId == "" { return errors.New("You must pass either an 'anonymousId' or 'userId'.") } msg.Type = "page" c.queue(msg) return nil }
[ "func", "(", "c", "*", "Client", ")", "Page", "(", "msg", "*", "Page", ")", "error", "{", "if", "msg", ".", "UserId", "==", "\"", "\"", "&&", "msg", ".", "AnonymousId", "==", "\"", "\"", "{", "return", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n\n", "msg", ".", "Type", "=", "\"", "\"", "\n", "c", ".", "queue", "(", "msg", ")", "\n\n", "return", "nil", "\n", "}" ]
// Page buffers an "page" message.
[ "Page", "buffers", "an", "page", "message", "." ]
8999d38db33a06d54813976725d47e18b4e3191c
https://github.com/segmentio/analytics-go/blob/8999d38db33a06d54813976725d47e18b4e3191c/analytics.go#L178-L187
18,046
segmentio/analytics-go
analytics.go
Group
func (c *Client) Group(msg *Group) error { if msg.GroupId == "" { return errors.New("You must pass a 'groupId'.") } if msg.UserId == "" && msg.AnonymousId == "" { return errors.New("You must pass either an 'anonymousId' or 'userId'.") } msg.Type = "group" c.queue(msg) return nil }
go
func (c *Client) Group(msg *Group) error { if msg.GroupId == "" { return errors.New("You must pass a 'groupId'.") } if msg.UserId == "" && msg.AnonymousId == "" { return errors.New("You must pass either an 'anonymousId' or 'userId'.") } msg.Type = "group" c.queue(msg) return nil }
[ "func", "(", "c", "*", "Client", ")", "Group", "(", "msg", "*", "Group", ")", "error", "{", "if", "msg", ".", "GroupId", "==", "\"", "\"", "{", "return", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n\n", "if", "msg", ".", "UserId", "==", "\"", "\"", "&&", "msg", ".", "AnonymousId", "==", "\"", "\"", "{", "return", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n\n", "msg", ".", "Type", "=", "\"", "\"", "\n", "c", ".", "queue", "(", "msg", ")", "\n\n", "return", "nil", "\n", "}" ]
// Group buffers an "group" message.
[ "Group", "buffers", "an", "group", "message", "." ]
8999d38db33a06d54813976725d47e18b4e3191c
https://github.com/segmentio/analytics-go/blob/8999d38db33a06d54813976725d47e18b4e3191c/analytics.go#L190-L203
18,047
segmentio/analytics-go
analytics.go
Track
func (c *Client) Track(msg *Track) error { if msg.Event == "" { return errors.New("You must pass 'event'.") } if msg.UserId == "" && msg.AnonymousId == "" { return errors.New("You must pass either an 'anonymousId' or 'userId'.") } msg.Type = "track" c.queue(msg) return nil }
go
func (c *Client) Track(msg *Track) error { if msg.Event == "" { return errors.New("You must pass 'event'.") } if msg.UserId == "" && msg.AnonymousId == "" { return errors.New("You must pass either an 'anonymousId' or 'userId'.") } msg.Type = "track" c.queue(msg) return nil }
[ "func", "(", "c", "*", "Client", ")", "Track", "(", "msg", "*", "Track", ")", "error", "{", "if", "msg", ".", "Event", "==", "\"", "\"", "{", "return", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n\n", "if", "msg", ".", "UserId", "==", "\"", "\"", "&&", "msg", ".", "AnonymousId", "==", "\"", "\"", "{", "return", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n\n", "msg", ".", "Type", "=", "\"", "\"", "\n", "c", ".", "queue", "(", "msg", ")", "\n\n", "return", "nil", "\n", "}" ]
// Track buffers an "track" message.
[ "Track", "buffers", "an", "track", "message", "." ]
8999d38db33a06d54813976725d47e18b4e3191c
https://github.com/segmentio/analytics-go/blob/8999d38db33a06d54813976725d47e18b4e3191c/analytics.go#L218-L231
18,048
segmentio/analytics-go
analytics.go
queue
func (c *Client) queue(msg message) { c.once.Do(c.startLoop) msg.setMessageId(c.uid()) msg.setTimestamp(timestamp(c.now())) c.msgs <- msg }
go
func (c *Client) queue(msg message) { c.once.Do(c.startLoop) msg.setMessageId(c.uid()) msg.setTimestamp(timestamp(c.now())) c.msgs <- msg }
[ "func", "(", "c", "*", "Client", ")", "queue", "(", "msg", "message", ")", "{", "c", ".", "once", ".", "Do", "(", "c", ".", "startLoop", ")", "\n", "msg", ".", "setMessageId", "(", "c", ".", "uid", "(", ")", ")", "\n", "msg", ".", "setTimestamp", "(", "timestamp", "(", "c", ".", "now", "(", ")", ")", ")", "\n", "c", ".", "msgs", "<-", "msg", "\n", "}" ]
// Queue message.
[ "Queue", "message", "." ]
8999d38db33a06d54813976725d47e18b4e3191c
https://github.com/segmentio/analytics-go/blob/8999d38db33a06d54813976725d47e18b4e3191c/analytics.go#L238-L243
18,049
segmentio/analytics-go
analytics.go
Close
func (c *Client) Close() error { c.once.Do(c.startLoop) c.quit <- struct{}{} close(c.msgs) <-c.shutdown return nil }
go
func (c *Client) Close() error { c.once.Do(c.startLoop) c.quit <- struct{}{} close(c.msgs) <-c.shutdown return nil }
[ "func", "(", "c", "*", "Client", ")", "Close", "(", ")", "error", "{", "c", ".", "once", ".", "Do", "(", "c", ".", "startLoop", ")", "\n", "c", ".", "quit", "<-", "struct", "{", "}", "{", "}", "\n", "close", "(", "c", ".", "msgs", ")", "\n", "<-", "c", ".", "shutdown", "\n", "return", "nil", "\n", "}" ]
// Close and flush metrics.
[ "Close", "and", "flush", "metrics", "." ]
8999d38db33a06d54813976725d47e18b4e3191c
https://github.com/segmentio/analytics-go/blob/8999d38db33a06d54813976725d47e18b4e3191c/analytics.go#L246-L252
18,050
segmentio/analytics-go
analytics.go
send
func (c *Client) send(msgs []interface{}) error { if len(msgs) == 0 { return nil } batch := new(Batch) batch.Messages = msgs batch.MessageId = c.uid() batch.SentAt = timestamp(c.now()) batch.Context = DefaultContext b, err := json.Marshal(batch) if err != nil { return fmt.Errorf("error marshalling msgs: %s", err) } for i := 0; i < 10; i++ { if err = c.upload(b); err == nil { return nil } Backo.Sleep(i) } return err }
go
func (c *Client) send(msgs []interface{}) error { if len(msgs) == 0 { return nil } batch := new(Batch) batch.Messages = msgs batch.MessageId = c.uid() batch.SentAt = timestamp(c.now()) batch.Context = DefaultContext b, err := json.Marshal(batch) if err != nil { return fmt.Errorf("error marshalling msgs: %s", err) } for i := 0; i < 10; i++ { if err = c.upload(b); err == nil { return nil } Backo.Sleep(i) } return err }
[ "func", "(", "c", "*", "Client", ")", "send", "(", "msgs", "[", "]", "interface", "{", "}", ")", "error", "{", "if", "len", "(", "msgs", ")", "==", "0", "{", "return", "nil", "\n", "}", "\n\n", "batch", ":=", "new", "(", "Batch", ")", "\n", "batch", ".", "Messages", "=", "msgs", "\n", "batch", ".", "MessageId", "=", "c", ".", "uid", "(", ")", "\n", "batch", ".", "SentAt", "=", "timestamp", "(", "c", ".", "now", "(", ")", ")", "\n", "batch", ".", "Context", "=", "DefaultContext", "\n\n", "b", ",", "err", ":=", "json", ".", "Marshal", "(", "batch", ")", "\n", "if", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n\n", "for", "i", ":=", "0", ";", "i", "<", "10", ";", "i", "++", "{", "if", "err", "=", "c", ".", "upload", "(", "b", ")", ";", "err", "==", "nil", "{", "return", "nil", "\n", "}", "\n", "Backo", ".", "Sleep", "(", "i", ")", "\n", "}", "\n\n", "return", "err", "\n", "}" ]
// Send batch request.
[ "Send", "batch", "request", "." ]
8999d38db33a06d54813976725d47e18b4e3191c
https://github.com/segmentio/analytics-go/blob/8999d38db33a06d54813976725d47e18b4e3191c/analytics.go#L276-L300
18,051
segmentio/analytics-go
analytics.go
upload
func (c *Client) upload(b []byte) error { url := c.Endpoint + "/v1/batch" req, err := http.NewRequest("POST", url, bytes.NewReader(b)) if err != nil { return fmt.Errorf("error creating request: %s", err) } req.Header.Add("User-Agent", "analytics-go (version: "+Version+")") req.Header.Add("Content-Type", "application/json") req.Header.Add("Content-Length", string(len(b))) req.SetBasicAuth(c.key, "") res, err := c.Client.Do(req) if err != nil { return fmt.Errorf("error sending request: %s", err) } defer res.Body.Close() if res.StatusCode < 400 { c.verbose("response %s", res.Status) return nil } body, err := ioutil.ReadAll(res.Body) if err != nil { return fmt.Errorf("error reading response body: %s", err) } return fmt.Errorf("response %s: %d – %s", res.Status, res.StatusCode, string(body)) }
go
func (c *Client) upload(b []byte) error { url := c.Endpoint + "/v1/batch" req, err := http.NewRequest("POST", url, bytes.NewReader(b)) if err != nil { return fmt.Errorf("error creating request: %s", err) } req.Header.Add("User-Agent", "analytics-go (version: "+Version+")") req.Header.Add("Content-Type", "application/json") req.Header.Add("Content-Length", string(len(b))) req.SetBasicAuth(c.key, "") res, err := c.Client.Do(req) if err != nil { return fmt.Errorf("error sending request: %s", err) } defer res.Body.Close() if res.StatusCode < 400 { c.verbose("response %s", res.Status) return nil } body, err := ioutil.ReadAll(res.Body) if err != nil { return fmt.Errorf("error reading response body: %s", err) } return fmt.Errorf("response %s: %d – %s", res.Status, res.StatusCode, string(body)) }
[ "func", "(", "c", "*", "Client", ")", "upload", "(", "b", "[", "]", "byte", ")", "error", "{", "url", ":=", "c", ".", "Endpoint", "+", "\"", "\"", "\n", "req", ",", "err", ":=", "http", ".", "NewRequest", "(", "\"", "\"", ",", "url", ",", "bytes", ".", "NewReader", "(", "b", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n\n", "req", ".", "Header", ".", "Add", "(", "\"", "\"", ",", "\"", "\"", "+", "Version", "+", "\"", "\"", ")", "\n", "req", ".", "Header", ".", "Add", "(", "\"", "\"", ",", "\"", "\"", ")", "\n", "req", ".", "Header", ".", "Add", "(", "\"", "\"", ",", "string", "(", "len", "(", "b", ")", ")", ")", "\n", "req", ".", "SetBasicAuth", "(", "c", ".", "key", ",", "\"", "\"", ")", "\n\n", "res", ",", "err", ":=", "c", ".", "Client", ".", "Do", "(", "req", ")", "\n", "if", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n", "defer", "res", ".", "Body", ".", "Close", "(", ")", "\n\n", "if", "res", ".", "StatusCode", "<", "400", "{", "c", ".", "verbose", "(", "\"", "\"", ",", "res", ".", "Status", ")", "\n", "return", "nil", "\n", "}", "\n\n", "body", ",", "err", ":=", "ioutil", ".", "ReadAll", "(", "res", ".", "Body", ")", "\n", "if", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n\n", "return", "fmt", ".", "Errorf", "(", "\"", " ", "r", "s.S", "t", "atus, ", "r", "s.S", "t", "atusCode, ", "s", "ring(b", "o", "dy))", "", "", "\n", "}" ]
// Upload serialized batch message.
[ "Upload", "serialized", "batch", "message", "." ]
8999d38db33a06d54813976725d47e18b4e3191c
https://github.com/segmentio/analytics-go/blob/8999d38db33a06d54813976725d47e18b4e3191c/analytics.go#L303-L332
18,052
segmentio/analytics-go
analytics.go
loop
func (c *Client) loop() { var msgs []interface{} tick := time.NewTicker(c.Interval) for { select { case msg := <-c.msgs: c.verbose("buffer (%d/%d) %v", len(msgs), c.Size, msg) msgs = append(msgs, msg) if len(msgs) == c.Size { c.verbose("exceeded %d messages – flushing", c.Size) c.sendAsync(msgs) msgs = make([]interface{}, 0, c.Size) } case <-tick.C: if len(msgs) > 0 { c.verbose("interval reached - flushing %d", len(msgs)) c.sendAsync(msgs) msgs = make([]interface{}, 0, c.Size) } else { c.verbose("interval reached – nothing to send") } case <-c.quit: tick.Stop() c.verbose("exit requested – draining msgs") // drain the msg channel. for msg := range c.msgs { c.verbose("buffer (%d/%d) %v", len(msgs), c.Size, msg) msgs = append(msgs, msg) } c.verbose("exit requested – flushing %d", len(msgs)) c.sendAsync(msgs) c.wg.Wait() c.verbose("exit") c.shutdown <- struct{}{} return } } }
go
func (c *Client) loop() { var msgs []interface{} tick := time.NewTicker(c.Interval) for { select { case msg := <-c.msgs: c.verbose("buffer (%d/%d) %v", len(msgs), c.Size, msg) msgs = append(msgs, msg) if len(msgs) == c.Size { c.verbose("exceeded %d messages – flushing", c.Size) c.sendAsync(msgs) msgs = make([]interface{}, 0, c.Size) } case <-tick.C: if len(msgs) > 0 { c.verbose("interval reached - flushing %d", len(msgs)) c.sendAsync(msgs) msgs = make([]interface{}, 0, c.Size) } else { c.verbose("interval reached – nothing to send") } case <-c.quit: tick.Stop() c.verbose("exit requested – draining msgs") // drain the msg channel. for msg := range c.msgs { c.verbose("buffer (%d/%d) %v", len(msgs), c.Size, msg) msgs = append(msgs, msg) } c.verbose("exit requested – flushing %d", len(msgs)) c.sendAsync(msgs) c.wg.Wait() c.verbose("exit") c.shutdown <- struct{}{} return } } }
[ "func", "(", "c", "*", "Client", ")", "loop", "(", ")", "{", "var", "msgs", "[", "]", "interface", "{", "}", "\n", "tick", ":=", "time", ".", "NewTicker", "(", "c", ".", "Interval", ")", "\n\n", "for", "{", "select", "{", "case", "msg", ":=", "<-", "c", ".", "msgs", ":", "c", ".", "verbose", "(", "\"", "\"", ",", "len", "(", "msgs", ")", ",", "c", ".", "Size", ",", "msg", ")", "\n", "msgs", "=", "append", "(", "msgs", ",", "msg", ")", "\n", "if", "len", "(", "msgs", ")", "==", "c", ".", "Size", "{", "c", ".", "verbose", "(", "\"", " ", "c", "S", "i", "ze)", "", "\n", "c", ".", "sendAsync", "(", "msgs", ")", "\n", "msgs", "=", "make", "(", "[", "]", "interface", "{", "}", ",", "0", ",", "c", ".", "Size", ")", "\n", "}", "\n", "case", "<-", "tick", ".", "C", ":", "if", "len", "(", "msgs", ")", ">", "0", "{", "c", ".", "verbose", "(", "\"", "\"", ",", "len", "(", "msgs", ")", ")", "\n", "c", ".", "sendAsync", "(", "msgs", ")", "\n", "msgs", "=", "make", "(", "[", "]", "interface", "{", "}", ",", "0", ",", "c", ".", "Size", ")", "\n", "}", "else", "{", "c", ".", "verbose", "(", "\"", "", "", "\n", "}", "\n", "case", "<-", "c", ".", "quit", ":", "tick", ".", "Stop", "(", ")", "\n", "c", ".", "verbose", "(", "\"", "", "", "\n", "// drain the msg channel.", "for", "msg", ":=", "range", "c", ".", "msgs", "{", "c", ".", "verbose", "(", "\"", "\"", ",", "len", "(", "msgs", ")", ",", "c", ".", "Size", ",", "msg", ")", "\n", "msgs", "=", "append", "(", "msgs", ",", "msg", ")", "\n", "}", "\n", "c", ".", "verbose", "(", "\"", " ", "l", "n(m", "s", "gs))", "", "", "\n", "c", ".", "sendAsync", "(", "msgs", ")", "\n", "c", ".", "wg", ".", "Wait", "(", ")", "\n", "c", ".", "verbose", "(", "\"", "\"", ")", "\n", "c", ".", "shutdown", "<-", "struct", "{", "}", "{", "}", "\n", "return", "\n", "}", "\n", "}", "\n", "}" ]
// Batch loop.
[ "Batch", "loop", "." ]
8999d38db33a06d54813976725d47e18b4e3191c
https://github.com/segmentio/analytics-go/blob/8999d38db33a06d54813976725d47e18b4e3191c/analytics.go#L335-L373
18,053
segmentio/analytics-go
analytics.go
verbose
func (c *Client) verbose(msg string, args ...interface{}) { if c.Verbose { c.Logger.Printf(msg, args...) } }
go
func (c *Client) verbose(msg string, args ...interface{}) { if c.Verbose { c.Logger.Printf(msg, args...) } }
[ "func", "(", "c", "*", "Client", ")", "verbose", "(", "msg", "string", ",", "args", "...", "interface", "{", "}", ")", "{", "if", "c", ".", "Verbose", "{", "c", ".", "Logger", ".", "Printf", "(", "msg", ",", "args", "...", ")", "\n", "}", "\n", "}" ]
// Verbose log.
[ "Verbose", "log", "." ]
8999d38db33a06d54813976725d47e18b4e3191c
https://github.com/segmentio/analytics-go/blob/8999d38db33a06d54813976725d47e18b4e3191c/analytics.go#L376-L380
18,054
segmentio/analytics-go
analytics.go
logf
func (c *Client) logf(msg string, args ...interface{}) { c.Logger.Printf(msg, args...) }
go
func (c *Client) logf(msg string, args ...interface{}) { c.Logger.Printf(msg, args...) }
[ "func", "(", "c", "*", "Client", ")", "logf", "(", "msg", "string", ",", "args", "...", "interface", "{", "}", ")", "{", "c", ".", "Logger", ".", "Printf", "(", "msg", ",", "args", "...", ")", "\n", "}" ]
// Unconditional log.
[ "Unconditional", "log", "." ]
8999d38db33a06d54813976725d47e18b4e3191c
https://github.com/segmentio/analytics-go/blob/8999d38db33a06d54813976725d47e18b4e3191c/analytics.go#L383-L385
18,055
segmentio/analytics-go
analytics.go
setTimestamp
func (m *Message) setTimestamp(s string) { if m.Timestamp == "" { m.Timestamp = s } }
go
func (m *Message) setTimestamp(s string) { if m.Timestamp == "" { m.Timestamp = s } }
[ "func", "(", "m", "*", "Message", ")", "setTimestamp", "(", "s", "string", ")", "{", "if", "m", ".", "Timestamp", "==", "\"", "\"", "{", "m", ".", "Timestamp", "=", "s", "\n", "}", "\n", "}" ]
// Set message timestamp if one is not already set.
[ "Set", "message", "timestamp", "if", "one", "is", "not", "already", "set", "." ]
8999d38db33a06d54813976725d47e18b4e3191c
https://github.com/segmentio/analytics-go/blob/8999d38db33a06d54813976725d47e18b4e3191c/analytics.go#L388-L392
18,056
segmentio/analytics-go
analytics.go
setMessageId
func (m *Message) setMessageId(s string) { if m.MessageId == "" { m.MessageId = s } }
go
func (m *Message) setMessageId(s string) { if m.MessageId == "" { m.MessageId = s } }
[ "func", "(", "m", "*", "Message", ")", "setMessageId", "(", "s", "string", ")", "{", "if", "m", ".", "MessageId", "==", "\"", "\"", "{", "m", ".", "MessageId", "=", "s", "\n", "}", "\n", "}" ]
// Set message id.
[ "Set", "message", "id", "." ]
8999d38db33a06d54813976725d47e18b4e3191c
https://github.com/segmentio/analytics-go/blob/8999d38db33a06d54813976725d47e18b4e3191c/analytics.go#L395-L399
18,057
qor/i18n
backends/database/database.go
New
func New(db *gorm.DB) i18n.Backend { db.AutoMigrate(&Translation{}) if err := db.Model(&Translation{}).AddUniqueIndex("idx_translations_key_with_locale", "locale", "key").Error; err != nil { fmt.Printf("Failed to create unique index for translations key & locale, got: %v\n", err.Error()) } return &Backend{DB: db} }
go
func New(db *gorm.DB) i18n.Backend { db.AutoMigrate(&Translation{}) if err := db.Model(&Translation{}).AddUniqueIndex("idx_translations_key_with_locale", "locale", "key").Error; err != nil { fmt.Printf("Failed to create unique index for translations key & locale, got: %v\n", err.Error()) } return &Backend{DB: db} }
[ "func", "New", "(", "db", "*", "gorm", ".", "DB", ")", "i18n", ".", "Backend", "{", "db", ".", "AutoMigrate", "(", "&", "Translation", "{", "}", ")", "\n", "if", "err", ":=", "db", ".", "Model", "(", "&", "Translation", "{", "}", ")", ".", "AddUniqueIndex", "(", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ")", ".", "Error", ";", "err", "!=", "nil", "{", "fmt", ".", "Printf", "(", "\"", "\\n", "\"", ",", "err", ".", "Error", "(", ")", ")", "\n", "}", "\n", "return", "&", "Backend", "{", "DB", ":", "db", "}", "\n", "}" ]
// New new DB backend for I18n
[ "New", "new", "DB", "backend", "for", "I18n" ]
f7206d223bcd503538783d387b61ed5720264b7b
https://github.com/qor/i18n/blob/f7206d223bcd503538783d387b61ed5720264b7b/backends/database/database.go#L18-L24
18,058
qor/i18n
backends/database/database.go
LoadTranslations
func (backend *Backend) LoadTranslations() (translations []*i18n.Translation) { backend.DB.Find(&translations) return translations }
go
func (backend *Backend) LoadTranslations() (translations []*i18n.Translation) { backend.DB.Find(&translations) return translations }
[ "func", "(", "backend", "*", "Backend", ")", "LoadTranslations", "(", ")", "(", "translations", "[", "]", "*", "i18n", ".", "Translation", ")", "{", "backend", ".", "DB", ".", "Find", "(", "&", "translations", ")", "\n", "return", "translations", "\n", "}" ]
// LoadTranslations load translations from DB backend
[ "LoadTranslations", "load", "translations", "from", "DB", "backend" ]
f7206d223bcd503538783d387b61ed5720264b7b
https://github.com/qor/i18n/blob/f7206d223bcd503538783d387b61ed5720264b7b/backends/database/database.go#L32-L35
18,059
qor/i18n
backends/database/database.go
SaveTranslation
func (backend *Backend) SaveTranslation(t *i18n.Translation) error { return backend.DB.Where(Translation{Key: t.Key, Locale: t.Locale}). Assign(Translation{Value: t.Value}). FirstOrCreate(&Translation{}).Error }
go
func (backend *Backend) SaveTranslation(t *i18n.Translation) error { return backend.DB.Where(Translation{Key: t.Key, Locale: t.Locale}). Assign(Translation{Value: t.Value}). FirstOrCreate(&Translation{}).Error }
[ "func", "(", "backend", "*", "Backend", ")", "SaveTranslation", "(", "t", "*", "i18n", ".", "Translation", ")", "error", "{", "return", "backend", ".", "DB", ".", "Where", "(", "Translation", "{", "Key", ":", "t", ".", "Key", ",", "Locale", ":", "t", ".", "Locale", "}", ")", ".", "Assign", "(", "Translation", "{", "Value", ":", "t", ".", "Value", "}", ")", ".", "FirstOrCreate", "(", "&", "Translation", "{", "}", ")", ".", "Error", "\n", "}" ]
// SaveTranslation save translation into DB backend
[ "SaveTranslation", "save", "translation", "into", "DB", "backend" ]
f7206d223bcd503538783d387b61ed5720264b7b
https://github.com/qor/i18n/blob/f7206d223bcd503538783d387b61ed5720264b7b/backends/database/database.go#L38-L42
18,060
qor/i18n
backends/database/database.go
DeleteTranslation
func (backend *Backend) DeleteTranslation(t *i18n.Translation) error { return backend.DB.Where(Translation{Key: t.Key, Locale: t.Locale}).Delete(&Translation{}).Error }
go
func (backend *Backend) DeleteTranslation(t *i18n.Translation) error { return backend.DB.Where(Translation{Key: t.Key, Locale: t.Locale}).Delete(&Translation{}).Error }
[ "func", "(", "backend", "*", "Backend", ")", "DeleteTranslation", "(", "t", "*", "i18n", ".", "Translation", ")", "error", "{", "return", "backend", ".", "DB", ".", "Where", "(", "Translation", "{", "Key", ":", "t", ".", "Key", ",", "Locale", ":", "t", ".", "Locale", "}", ")", ".", "Delete", "(", "&", "Translation", "{", "}", ")", ".", "Error", "\n", "}" ]
// DeleteTranslation delete translation into DB backend
[ "DeleteTranslation", "delete", "translation", "into", "DB", "backend" ]
f7206d223bcd503538783d387b61ed5720264b7b
https://github.com/qor/i18n/blob/f7206d223bcd503538783d387b61ed5720264b7b/backends/database/database.go#L45-L47
18,061
qor/i18n
backends/yaml/yaml.go
New
func New(paths ...string) *Backend { backend := &Backend{} var files []string for _, p := range paths { if file, err := os.Open(p); err == nil { defer file.Close() if fileInfo, err := file.Stat(); err == nil { if fileInfo.IsDir() { yamlFiles, _ := filepath.Glob(filepath.Join(p, "*.yaml")) files = append(files, yamlFiles...) ymlFiles, _ := filepath.Glob(filepath.Join(p, "*.yml")) files = append(files, ymlFiles...) } else if fileInfo.Mode().IsRegular() { files = append(files, p) } } } } for _, file := range files { if content, err := ioutil.ReadFile(file); err == nil { backend.contents = append(backend.contents, content) } } return backend }
go
func New(paths ...string) *Backend { backend := &Backend{} var files []string for _, p := range paths { if file, err := os.Open(p); err == nil { defer file.Close() if fileInfo, err := file.Stat(); err == nil { if fileInfo.IsDir() { yamlFiles, _ := filepath.Glob(filepath.Join(p, "*.yaml")) files = append(files, yamlFiles...) ymlFiles, _ := filepath.Glob(filepath.Join(p, "*.yml")) files = append(files, ymlFiles...) } else if fileInfo.Mode().IsRegular() { files = append(files, p) } } } } for _, file := range files { if content, err := ioutil.ReadFile(file); err == nil { backend.contents = append(backend.contents, content) } } return backend }
[ "func", "New", "(", "paths", "...", "string", ")", "*", "Backend", "{", "backend", ":=", "&", "Backend", "{", "}", "\n\n", "var", "files", "[", "]", "string", "\n", "for", "_", ",", "p", ":=", "range", "paths", "{", "if", "file", ",", "err", ":=", "os", ".", "Open", "(", "p", ")", ";", "err", "==", "nil", "{", "defer", "file", ".", "Close", "(", ")", "\n", "if", "fileInfo", ",", "err", ":=", "file", ".", "Stat", "(", ")", ";", "err", "==", "nil", "{", "if", "fileInfo", ".", "IsDir", "(", ")", "{", "yamlFiles", ",", "_", ":=", "filepath", ".", "Glob", "(", "filepath", ".", "Join", "(", "p", ",", "\"", "\"", ")", ")", "\n", "files", "=", "append", "(", "files", ",", "yamlFiles", "...", ")", "\n\n", "ymlFiles", ",", "_", ":=", "filepath", ".", "Glob", "(", "filepath", ".", "Join", "(", "p", ",", "\"", "\"", ")", ")", "\n", "files", "=", "append", "(", "files", ",", "ymlFiles", "...", ")", "\n", "}", "else", "if", "fileInfo", ".", "Mode", "(", ")", ".", "IsRegular", "(", ")", "{", "files", "=", "append", "(", "files", ",", "p", ")", "\n", "}", "\n", "}", "\n", "}", "\n", "}", "\n", "for", "_", ",", "file", ":=", "range", "files", "{", "if", "content", ",", "err", ":=", "ioutil", ".", "ReadFile", "(", "file", ")", ";", "err", "==", "nil", "{", "backend", ".", "contents", "=", "append", "(", "backend", ".", "contents", ",", "content", ")", "\n", "}", "\n", "}", "\n", "return", "backend", "\n", "}" ]
// New new YAML backend for I18n
[ "New", "new", "YAML", "backend", "for", "I18n" ]
f7206d223bcd503538783d387b61ed5720264b7b
https://github.com/qor/i18n/blob/f7206d223bcd503538783d387b61ed5720264b7b/backends/yaml/yaml.go#L19-L45
18,062
qor/i18n
backends/yaml/yaml.go
NewWithWalk
func NewWithWalk(paths ...string) i18n.Backend { backend := &Backend{} var files []string for _, p := range paths { filepath.Walk(p, func(path string, fileInfo os.FileInfo, err error) error { if isYamlFile(fileInfo) { files = append(files, path) } return nil }) } for _, file := range files { if content, err := ioutil.ReadFile(file); err == nil { backend.contents = append(backend.contents, content) } } return backend }
go
func NewWithWalk(paths ...string) i18n.Backend { backend := &Backend{} var files []string for _, p := range paths { filepath.Walk(p, func(path string, fileInfo os.FileInfo, err error) error { if isYamlFile(fileInfo) { files = append(files, path) } return nil }) } for _, file := range files { if content, err := ioutil.ReadFile(file); err == nil { backend.contents = append(backend.contents, content) } } return backend }
[ "func", "NewWithWalk", "(", "paths", "...", "string", ")", "i18n", ".", "Backend", "{", "backend", ":=", "&", "Backend", "{", "}", "\n\n", "var", "files", "[", "]", "string", "\n", "for", "_", ",", "p", ":=", "range", "paths", "{", "filepath", ".", "Walk", "(", "p", ",", "func", "(", "path", "string", ",", "fileInfo", "os", ".", "FileInfo", ",", "err", "error", ")", "error", "{", "if", "isYamlFile", "(", "fileInfo", ")", "{", "files", "=", "append", "(", "files", ",", "path", ")", "\n", "}", "\n", "return", "nil", "\n", "}", ")", "\n", "}", "\n", "for", "_", ",", "file", ":=", "range", "files", "{", "if", "content", ",", "err", ":=", "ioutil", ".", "ReadFile", "(", "file", ")", ";", "err", "==", "nil", "{", "backend", ".", "contents", "=", "append", "(", "backend", ".", "contents", ",", "content", ")", "\n", "}", "\n", "}", "\n\n", "return", "backend", "\n", "}" ]
// NewWithWalk has the same functionality as New but uses filepath.Walk to find all the translation files recursively.
[ "NewWithWalk", "has", "the", "same", "functionality", "as", "New", "but", "uses", "filepath", ".", "Walk", "to", "find", "all", "the", "translation", "files", "recursively", "." ]
f7206d223bcd503538783d387b61ed5720264b7b
https://github.com/qor/i18n/blob/f7206d223bcd503538783d387b61ed5720264b7b/backends/yaml/yaml.go#L48-L67
18,063
qor/i18n
backends/yaml/yaml.go
NewWithFilesystem
func NewWithFilesystem(fss ...http.FileSystem) i18n.Backend { backend := &Backend{} for _, fs := range fss { backend.contents = append(backend.contents, walkFilesystem(fs, nil, "/")...) } return backend }
go
func NewWithFilesystem(fss ...http.FileSystem) i18n.Backend { backend := &Backend{} for _, fs := range fss { backend.contents = append(backend.contents, walkFilesystem(fs, nil, "/")...) } return backend }
[ "func", "NewWithFilesystem", "(", "fss", "...", "http", ".", "FileSystem", ")", "i18n", ".", "Backend", "{", "backend", ":=", "&", "Backend", "{", "}", "\n\n", "for", "_", ",", "fs", ":=", "range", "fss", "{", "backend", ".", "contents", "=", "append", "(", "backend", ".", "contents", ",", "walkFilesystem", "(", "fs", ",", "nil", ",", "\"", "\"", ")", "...", ")", "\n", "}", "\n", "return", "backend", "\n", "}" ]
// NewWithFilesystem initializes a backend that reads translation files from an http.FileSystem.
[ "NewWithFilesystem", "initializes", "a", "backend", "that", "reads", "translation", "files", "from", "an", "http", ".", "FileSystem", "." ]
f7206d223bcd503538783d387b61ed5720264b7b
https://github.com/qor/i18n/blob/f7206d223bcd503538783d387b61ed5720264b7b/backends/yaml/yaml.go#L114-L121
18,064
qor/i18n
backends/yaml/yaml.go
LoadYAMLContent
func (backend *Backend) LoadYAMLContent(content []byte) (translations []*i18n.Translation, err error) { var slice yaml.MapSlice if err = yaml.Unmarshal(content, &slice); err == nil { for _, item := range slice { translations = append(translations, loadTranslationsFromYaml(item.Key.(string) /* locale */, item.Value, []string{})...) } } return translations, err }
go
func (backend *Backend) LoadYAMLContent(content []byte) (translations []*i18n.Translation, err error) { var slice yaml.MapSlice if err = yaml.Unmarshal(content, &slice); err == nil { for _, item := range slice { translations = append(translations, loadTranslationsFromYaml(item.Key.(string) /* locale */, item.Value, []string{})...) } } return translations, err }
[ "func", "(", "backend", "*", "Backend", ")", "LoadYAMLContent", "(", "content", "[", "]", "byte", ")", "(", "translations", "[", "]", "*", "i18n", ".", "Translation", ",", "err", "error", ")", "{", "var", "slice", "yaml", ".", "MapSlice", "\n\n", "if", "err", "=", "yaml", ".", "Unmarshal", "(", "content", ",", "&", "slice", ")", ";", "err", "==", "nil", "{", "for", "_", ",", "item", ":=", "range", "slice", "{", "translations", "=", "append", "(", "translations", ",", "loadTranslationsFromYaml", "(", "item", ".", "Key", ".", "(", "string", ")", "/* locale */", ",", "item", ".", "Value", ",", "[", "]", "string", "{", "}", ")", "...", ")", "\n", "}", "\n", "}", "\n\n", "return", "translations", ",", "err", "\n", "}" ]
// LoadYAMLContent load YAML content
[ "LoadYAMLContent", "load", "YAML", "content" ]
f7206d223bcd503538783d387b61ed5720264b7b
https://github.com/qor/i18n/blob/f7206d223bcd503538783d387b61ed5720264b7b/backends/yaml/yaml.go#L147-L157
18,065
qor/i18n
backends/yaml/yaml.go
LoadTranslations
func (backend *Backend) LoadTranslations() (translations []*i18n.Translation) { for _, content := range backend.contents { if results, err := backend.LoadYAMLContent(content); err == nil { translations = append(translations, results...) } else { panic(err) } } return translations }
go
func (backend *Backend) LoadTranslations() (translations []*i18n.Translation) { for _, content := range backend.contents { if results, err := backend.LoadYAMLContent(content); err == nil { translations = append(translations, results...) } else { panic(err) } } return translations }
[ "func", "(", "backend", "*", "Backend", ")", "LoadTranslations", "(", ")", "(", "translations", "[", "]", "*", "i18n", ".", "Translation", ")", "{", "for", "_", ",", "content", ":=", "range", "backend", ".", "contents", "{", "if", "results", ",", "err", ":=", "backend", ".", "LoadYAMLContent", "(", "content", ")", ";", "err", "==", "nil", "{", "translations", "=", "append", "(", "translations", ",", "results", "...", ")", "\n", "}", "else", "{", "panic", "(", "err", ")", "\n", "}", "\n", "}", "\n", "return", "translations", "\n", "}" ]
// LoadTranslations load translations from YAML backend
[ "LoadTranslations", "load", "translations", "from", "YAML", "backend" ]
f7206d223bcd503538783d387b61ed5720264b7b
https://github.com/qor/i18n/blob/f7206d223bcd503538783d387b61ed5720264b7b/backends/yaml/yaml.go#L160-L169
18,066
qor/i18n
i18n.go
New
func New(backends ...Backend) *I18n { i18n := &I18n{Backends: backends, cacheStore: memory.New()} i18n.loadToCacheStore() return i18n }
go
func New(backends ...Backend) *I18n { i18n := &I18n{Backends: backends, cacheStore: memory.New()} i18n.loadToCacheStore() return i18n }
[ "func", "New", "(", "backends", "...", "Backend", ")", "*", "I18n", "{", "i18n", ":=", "&", "I18n", "{", "Backends", ":", "backends", ",", "cacheStore", ":", "memory", ".", "New", "(", ")", "}", "\n", "i18n", ".", "loadToCacheStore", "(", ")", "\n", "return", "i18n", "\n", "}" ]
// New initialize I18n with backends
[ "New", "initialize", "I18n", "with", "backends" ]
f7206d223bcd503538783d387b61ed5720264b7b
https://github.com/qor/i18n/blob/f7206d223bcd503538783d387b61ed5720264b7b/i18n.go#L58-L62
18,067
qor/i18n
i18n.go
SetCacheStore
func (i18n *I18n) SetCacheStore(cacheStore cache.CacheStoreInterface) { i18n.cacheStore = cacheStore i18n.loadToCacheStore() }
go
func (i18n *I18n) SetCacheStore(cacheStore cache.CacheStoreInterface) { i18n.cacheStore = cacheStore i18n.loadToCacheStore() }
[ "func", "(", "i18n", "*", "I18n", ")", "SetCacheStore", "(", "cacheStore", "cache", ".", "CacheStoreInterface", ")", "{", "i18n", ".", "cacheStore", "=", "cacheStore", "\n", "i18n", ".", "loadToCacheStore", "(", ")", "\n", "}" ]
// SetCacheStore set i18n's cache store
[ "SetCacheStore", "set", "i18n", "s", "cache", "store" ]
f7206d223bcd503538783d387b61ed5720264b7b
https://github.com/qor/i18n/blob/f7206d223bcd503538783d387b61ed5720264b7b/i18n.go#L65-L68
18,068
qor/i18n
i18n.go
AddTranslation
func (i18n *I18n) AddTranslation(translation *Translation) error { return i18n.cacheStore.Set(cacheKey(translation.Locale, translation.Key), translation) }
go
func (i18n *I18n) AddTranslation(translation *Translation) error { return i18n.cacheStore.Set(cacheKey(translation.Locale, translation.Key), translation) }
[ "func", "(", "i18n", "*", "I18n", ")", "AddTranslation", "(", "translation", "*", "Translation", ")", "error", "{", "return", "i18n", ".", "cacheStore", ".", "Set", "(", "cacheKey", "(", "translation", ".", "Locale", ",", "translation", ".", "Key", ")", ",", "translation", ")", "\n", "}" ]
// AddTranslation add translation
[ "AddTranslation", "add", "translation" ]
f7206d223bcd503538783d387b61ed5720264b7b
https://github.com/qor/i18n/blob/f7206d223bcd503538783d387b61ed5720264b7b/i18n.go#L97-L99
18,069
qor/i18n
i18n.go
SaveTranslation
func (i18n *I18n) SaveTranslation(translation *Translation) error { for _, backend := range i18n.Backends { if backend.SaveTranslation(translation) == nil { i18n.AddTranslation(translation) return nil } } return errors.New("failed to save translation") }
go
func (i18n *I18n) SaveTranslation(translation *Translation) error { for _, backend := range i18n.Backends { if backend.SaveTranslation(translation) == nil { i18n.AddTranslation(translation) return nil } } return errors.New("failed to save translation") }
[ "func", "(", "i18n", "*", "I18n", ")", "SaveTranslation", "(", "translation", "*", "Translation", ")", "error", "{", "for", "_", ",", "backend", ":=", "range", "i18n", ".", "Backends", "{", "if", "backend", ".", "SaveTranslation", "(", "translation", ")", "==", "nil", "{", "i18n", ".", "AddTranslation", "(", "translation", ")", "\n", "return", "nil", "\n", "}", "\n", "}", "\n\n", "return", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}" ]
// SaveTranslation save translation
[ "SaveTranslation", "save", "translation" ]
f7206d223bcd503538783d387b61ed5720264b7b
https://github.com/qor/i18n/blob/f7206d223bcd503538783d387b61ed5720264b7b/i18n.go#L102-L111
18,070
qor/i18n
i18n.go
DeleteTranslation
func (i18n *I18n) DeleteTranslation(translation *Translation) (err error) { for _, backend := range i18n.Backends { backend.DeleteTranslation(translation) } return i18n.cacheStore.Delete(cacheKey(translation.Locale, translation.Key)) }
go
func (i18n *I18n) DeleteTranslation(translation *Translation) (err error) { for _, backend := range i18n.Backends { backend.DeleteTranslation(translation) } return i18n.cacheStore.Delete(cacheKey(translation.Locale, translation.Key)) }
[ "func", "(", "i18n", "*", "I18n", ")", "DeleteTranslation", "(", "translation", "*", "Translation", ")", "(", "err", "error", ")", "{", "for", "_", ",", "backend", ":=", "range", "i18n", ".", "Backends", "{", "backend", ".", "DeleteTranslation", "(", "translation", ")", "\n", "}", "\n\n", "return", "i18n", ".", "cacheStore", ".", "Delete", "(", "cacheKey", "(", "translation", ".", "Locale", ",", "translation", ".", "Key", ")", ")", "\n", "}" ]
// DeleteTranslation delete translation
[ "DeleteTranslation", "delete", "translation" ]
f7206d223bcd503538783d387b61ed5720264b7b
https://github.com/qor/i18n/blob/f7206d223bcd503538783d387b61ed5720264b7b/i18n.go#L114-L120
18,071
qor/i18n
i18n.go
Scope
func (i18n *I18n) Scope(scope string) admin.I18n { return &I18n{cacheStore: i18n.cacheStore, scope: scope, value: i18n.value, Backends: i18n.Backends, Resource: i18n.Resource, FallbackLocales: i18n.FallbackLocales, fallbackLocales: i18n.fallbackLocales} }
go
func (i18n *I18n) Scope(scope string) admin.I18n { return &I18n{cacheStore: i18n.cacheStore, scope: scope, value: i18n.value, Backends: i18n.Backends, Resource: i18n.Resource, FallbackLocales: i18n.FallbackLocales, fallbackLocales: i18n.fallbackLocales} }
[ "func", "(", "i18n", "*", "I18n", ")", "Scope", "(", "scope", "string", ")", "admin", ".", "I18n", "{", "return", "&", "I18n", "{", "cacheStore", ":", "i18n", ".", "cacheStore", ",", "scope", ":", "scope", ",", "value", ":", "i18n", ".", "value", ",", "Backends", ":", "i18n", ".", "Backends", ",", "Resource", ":", "i18n", ".", "Resource", ",", "FallbackLocales", ":", "i18n", ".", "FallbackLocales", ",", "fallbackLocales", ":", "i18n", ".", "fallbackLocales", "}", "\n", "}" ]
// Scope i18n scope
[ "Scope", "i18n", "scope" ]
f7206d223bcd503538783d387b61ed5720264b7b
https://github.com/qor/i18n/blob/f7206d223bcd503538783d387b61ed5720264b7b/i18n.go#L123-L125
18,072
qor/i18n
i18n.go
Fallbacks
func (i18n *I18n) Fallbacks(locale ...string) admin.I18n { return &I18n{cacheStore: i18n.cacheStore, scope: i18n.scope, value: i18n.value, Backends: i18n.Backends, Resource: i18n.Resource, FallbackLocales: i18n.FallbackLocales, fallbackLocales: locale} }
go
func (i18n *I18n) Fallbacks(locale ...string) admin.I18n { return &I18n{cacheStore: i18n.cacheStore, scope: i18n.scope, value: i18n.value, Backends: i18n.Backends, Resource: i18n.Resource, FallbackLocales: i18n.FallbackLocales, fallbackLocales: locale} }
[ "func", "(", "i18n", "*", "I18n", ")", "Fallbacks", "(", "locale", "...", "string", ")", "admin", ".", "I18n", "{", "return", "&", "I18n", "{", "cacheStore", ":", "i18n", ".", "cacheStore", ",", "scope", ":", "i18n", ".", "scope", ",", "value", ":", "i18n", ".", "value", ",", "Backends", ":", "i18n", ".", "Backends", ",", "Resource", ":", "i18n", ".", "Resource", ",", "FallbackLocales", ":", "i18n", ".", "FallbackLocales", ",", "fallbackLocales", ":", "locale", "}", "\n", "}" ]
// Fallbacks fallback to locale if translation doesn't exist in specified locale
[ "Fallbacks", "fallback", "to", "locale", "if", "translation", "doesn", "t", "exist", "in", "specified", "locale" ]
f7206d223bcd503538783d387b61ed5720264b7b
https://github.com/qor/i18n/blob/f7206d223bcd503538783d387b61ed5720264b7b/i18n.go#L133-L135
18,073
qor/i18n
i18n.go
T
func (i18n *I18n) T(locale, key string, args ...interface{}) template.HTML { var ( value = i18n.value translationKey = key fallbackLocales = i18n.fallbackLocales ) if locale == "" { locale = Default } if locales, ok := i18n.FallbackLocales[locale]; ok { fallbackLocales = append(fallbackLocales, locales...) } fallbackLocales = append(fallbackLocales, Default) if i18n.scope != "" { translationKey = strings.Join([]string{i18n.scope, key}, ".") } var translation Translation if err := i18n.cacheStore.Unmarshal(cacheKey(locale, key), &translation); err != nil || translation.Value == "" { for _, fallbackLocale := range fallbackLocales { if err := i18n.cacheStore.Unmarshal(cacheKey(fallbackLocale, key), &translation); err == nil && translation.Value != "" { break } } if translation.Value == "" { // Get default translation if not translated if err := i18n.cacheStore.Unmarshal(cacheKey(Default, key), &translation); err != nil || translation.Value == "" { // If not initialized var defaultBackend Backend if len(i18n.Backends) > 0 { defaultBackend = i18n.Backends[0] } translation = Translation{Key: translationKey, Value: value, Locale: locale, Backend: defaultBackend} // Save translation i18n.SaveTranslation(&translation) } } } if translation.Value != "" { value = translation.Value } else { value = key } if str, err := cldr.Parse(locale, value, args...); err == nil { value = str } return template.HTML(value) }
go
func (i18n *I18n) T(locale, key string, args ...interface{}) template.HTML { var ( value = i18n.value translationKey = key fallbackLocales = i18n.fallbackLocales ) if locale == "" { locale = Default } if locales, ok := i18n.FallbackLocales[locale]; ok { fallbackLocales = append(fallbackLocales, locales...) } fallbackLocales = append(fallbackLocales, Default) if i18n.scope != "" { translationKey = strings.Join([]string{i18n.scope, key}, ".") } var translation Translation if err := i18n.cacheStore.Unmarshal(cacheKey(locale, key), &translation); err != nil || translation.Value == "" { for _, fallbackLocale := range fallbackLocales { if err := i18n.cacheStore.Unmarshal(cacheKey(fallbackLocale, key), &translation); err == nil && translation.Value != "" { break } } if translation.Value == "" { // Get default translation if not translated if err := i18n.cacheStore.Unmarshal(cacheKey(Default, key), &translation); err != nil || translation.Value == "" { // If not initialized var defaultBackend Backend if len(i18n.Backends) > 0 { defaultBackend = i18n.Backends[0] } translation = Translation{Key: translationKey, Value: value, Locale: locale, Backend: defaultBackend} // Save translation i18n.SaveTranslation(&translation) } } } if translation.Value != "" { value = translation.Value } else { value = key } if str, err := cldr.Parse(locale, value, args...); err == nil { value = str } return template.HTML(value) }
[ "func", "(", "i18n", "*", "I18n", ")", "T", "(", "locale", ",", "key", "string", ",", "args", "...", "interface", "{", "}", ")", "template", ".", "HTML", "{", "var", "(", "value", "=", "i18n", ".", "value", "\n", "translationKey", "=", "key", "\n", "fallbackLocales", "=", "i18n", ".", "fallbackLocales", "\n", ")", "\n\n", "if", "locale", "==", "\"", "\"", "{", "locale", "=", "Default", "\n", "}", "\n\n", "if", "locales", ",", "ok", ":=", "i18n", ".", "FallbackLocales", "[", "locale", "]", ";", "ok", "{", "fallbackLocales", "=", "append", "(", "fallbackLocales", ",", "locales", "...", ")", "\n", "}", "\n", "fallbackLocales", "=", "append", "(", "fallbackLocales", ",", "Default", ")", "\n\n", "if", "i18n", ".", "scope", "!=", "\"", "\"", "{", "translationKey", "=", "strings", ".", "Join", "(", "[", "]", "string", "{", "i18n", ".", "scope", ",", "key", "}", ",", "\"", "\"", ")", "\n", "}", "\n\n", "var", "translation", "Translation", "\n", "if", "err", ":=", "i18n", ".", "cacheStore", ".", "Unmarshal", "(", "cacheKey", "(", "locale", ",", "key", ")", ",", "&", "translation", ")", ";", "err", "!=", "nil", "||", "translation", ".", "Value", "==", "\"", "\"", "{", "for", "_", ",", "fallbackLocale", ":=", "range", "fallbackLocales", "{", "if", "err", ":=", "i18n", ".", "cacheStore", ".", "Unmarshal", "(", "cacheKey", "(", "fallbackLocale", ",", "key", ")", ",", "&", "translation", ")", ";", "err", "==", "nil", "&&", "translation", ".", "Value", "!=", "\"", "\"", "{", "break", "\n", "}", "\n", "}", "\n\n", "if", "translation", ".", "Value", "==", "\"", "\"", "{", "// Get default translation if not translated", "if", "err", ":=", "i18n", ".", "cacheStore", ".", "Unmarshal", "(", "cacheKey", "(", "Default", ",", "key", ")", ",", "&", "translation", ")", ";", "err", "!=", "nil", "||", "translation", ".", "Value", "==", "\"", "\"", "{", "// If not initialized", "var", "defaultBackend", "Backend", "\n", "if", "len", "(", "i18n", ".", "Backends", ")", ">", "0", "{", "defaultBackend", "=", "i18n", ".", "Backends", "[", "0", "]", "\n", "}", "\n", "translation", "=", "Translation", "{", "Key", ":", "translationKey", ",", "Value", ":", "value", ",", "Locale", ":", "locale", ",", "Backend", ":", "defaultBackend", "}", "\n\n", "// Save translation", "i18n", ".", "SaveTranslation", "(", "&", "translation", ")", "\n", "}", "\n", "}", "\n", "}", "\n\n", "if", "translation", ".", "Value", "!=", "\"", "\"", "{", "value", "=", "translation", ".", "Value", "\n", "}", "else", "{", "value", "=", "key", "\n", "}", "\n\n", "if", "str", ",", "err", ":=", "cldr", ".", "Parse", "(", "locale", ",", "value", ",", "args", "...", ")", ";", "err", "==", "nil", "{", "value", "=", "str", "\n", "}", "\n\n", "return", "template", ".", "HTML", "(", "value", ")", "\n", "}" ]
// T translate with locale, key and arguments
[ "T", "translate", "with", "locale", "key", "and", "arguments" ]
f7206d223bcd503538783d387b61ed5720264b7b
https://github.com/qor/i18n/blob/f7206d223bcd503538783d387b61ed5720264b7b/i18n.go#L138-L193
18,074
qor/i18n
inline_edit/inline_edit.go
FuncMap
func FuncMap(I18n *i18n.I18n, locale string, enableInlineEdit bool) template.FuncMap { return template.FuncMap{ "t": InlineEdit(I18n, locale, enableInlineEdit), } }
go
func FuncMap(I18n *i18n.I18n, locale string, enableInlineEdit bool) template.FuncMap { return template.FuncMap{ "t": InlineEdit(I18n, locale, enableInlineEdit), } }
[ "func", "FuncMap", "(", "I18n", "*", "i18n", ".", "I18n", ",", "locale", "string", ",", "enableInlineEdit", "bool", ")", "template", ".", "FuncMap", "{", "return", "template", ".", "FuncMap", "{", "\"", "\"", ":", "InlineEdit", "(", "I18n", ",", "locale", ",", "enableInlineEdit", ")", ",", "}", "\n", "}" ]
// FuncMap generate func map for inline edit
[ "FuncMap", "generate", "func", "map", "for", "inline", "edit" ]
f7206d223bcd503538783d387b61ed5720264b7b
https://github.com/qor/i18n/blob/f7206d223bcd503538783d387b61ed5720264b7b/inline_edit/inline_edit.go#L16-L20
18,075
qor/i18n
inline_edit/inline_edit.go
InlineEdit
func InlineEdit(I18n *i18n.I18n, locale string, isInline bool) func(string, ...interface{}) template.HTML { return func(key string, args ...interface{}) template.HTML { // Get Translation Value var value template.HTML var defaultValue string if len(args) > 0 { if args[0] == nil { defaultValue = key } else { defaultValue = fmt.Sprint(args[0]) } value = I18n.Default(defaultValue).T(locale, key, args[1:]...) } else { value = I18n.T(locale, key) } // Append inline-edit script/tag if isInline { var editType string if len(value) > 25 { editType = "data-type=\"textarea\"" } prefix := I18n.Resource.GetAdmin().GetRouter().Prefix assetsTag := fmt.Sprintf("<script data-prefix=\"%v\" src=\"%v/assets/javascripts/i18n-checker.js?theme=i18n\"></script>", prefix, prefix) return template.HTML(fmt.Sprintf("%s<span class=\"qor-i18n-inline\" %s data-locale=\"%s\" data-key=\"%s\">%s</span>", assetsTag, editType, locale, key, string(value))) } return value } }
go
func InlineEdit(I18n *i18n.I18n, locale string, isInline bool) func(string, ...interface{}) template.HTML { return func(key string, args ...interface{}) template.HTML { // Get Translation Value var value template.HTML var defaultValue string if len(args) > 0 { if args[0] == nil { defaultValue = key } else { defaultValue = fmt.Sprint(args[0]) } value = I18n.Default(defaultValue).T(locale, key, args[1:]...) } else { value = I18n.T(locale, key) } // Append inline-edit script/tag if isInline { var editType string if len(value) > 25 { editType = "data-type=\"textarea\"" } prefix := I18n.Resource.GetAdmin().GetRouter().Prefix assetsTag := fmt.Sprintf("<script data-prefix=\"%v\" src=\"%v/assets/javascripts/i18n-checker.js?theme=i18n\"></script>", prefix, prefix) return template.HTML(fmt.Sprintf("%s<span class=\"qor-i18n-inline\" %s data-locale=\"%s\" data-key=\"%s\">%s</span>", assetsTag, editType, locale, key, string(value))) } return value } }
[ "func", "InlineEdit", "(", "I18n", "*", "i18n", ".", "I18n", ",", "locale", "string", ",", "isInline", "bool", ")", "func", "(", "string", ",", "...", "interface", "{", "}", ")", "template", ".", "HTML", "{", "return", "func", "(", "key", "string", ",", "args", "...", "interface", "{", "}", ")", "template", ".", "HTML", "{", "// Get Translation Value", "var", "value", "template", ".", "HTML", "\n", "var", "defaultValue", "string", "\n", "if", "len", "(", "args", ")", ">", "0", "{", "if", "args", "[", "0", "]", "==", "nil", "{", "defaultValue", "=", "key", "\n", "}", "else", "{", "defaultValue", "=", "fmt", ".", "Sprint", "(", "args", "[", "0", "]", ")", "\n", "}", "\n", "value", "=", "I18n", ".", "Default", "(", "defaultValue", ")", ".", "T", "(", "locale", ",", "key", ",", "args", "[", "1", ":", "]", "...", ")", "\n", "}", "else", "{", "value", "=", "I18n", ".", "T", "(", "locale", ",", "key", ")", "\n", "}", "\n\n", "// Append inline-edit script/tag", "if", "isInline", "{", "var", "editType", "string", "\n", "if", "len", "(", "value", ")", ">", "25", "{", "editType", "=", "\"", "\\\"", "\\\"", "\"", "\n", "}", "\n", "prefix", ":=", "I18n", ".", "Resource", ".", "GetAdmin", "(", ")", ".", "GetRouter", "(", ")", ".", "Prefix", "\n", "assetsTag", ":=", "fmt", ".", "Sprintf", "(", "\"", "\\\"", "\\\"", "\\\"", "\\\"", "\"", ",", "prefix", ",", "prefix", ")", "\n", "return", "template", ".", "HTML", "(", "fmt", ".", "Sprintf", "(", "\"", "\\\"", "\\\"", "\\\"", "\\\"", "\\\"", "\\\"", "\"", ",", "assetsTag", ",", "editType", ",", "locale", ",", "key", ",", "string", "(", "value", ")", ")", ")", "\n", "}", "\n", "return", "value", "\n", "}", "\n", "}" ]
// InlineEdit enable inline edit
[ "InlineEdit", "enable", "inline", "edit" ]
f7206d223bcd503538783d387b61ed5720264b7b
https://github.com/qor/i18n/blob/f7206d223bcd503538783d387b61ed5720264b7b/inline_edit/inline_edit.go#L23-L51
18,076
go-audio/audio
pcm_buffer.go
AsFloatBuffer
func (b *PCMBuffer) AsFloatBuffer() *FloatBuffer { newB := &FloatBuffer{} newB.Data = b.AsF64() if b.Format != nil { newB.Format = &Format{ NumChannels: b.Format.NumChannels, SampleRate: b.Format.SampleRate, } } return newB }
go
func (b *PCMBuffer) AsFloatBuffer() *FloatBuffer { newB := &FloatBuffer{} newB.Data = b.AsF64() if b.Format != nil { newB.Format = &Format{ NumChannels: b.Format.NumChannels, SampleRate: b.Format.SampleRate, } } return newB }
[ "func", "(", "b", "*", "PCMBuffer", ")", "AsFloatBuffer", "(", ")", "*", "FloatBuffer", "{", "newB", ":=", "&", "FloatBuffer", "{", "}", "\n", "newB", ".", "Data", "=", "b", ".", "AsF64", "(", ")", "\n", "if", "b", ".", "Format", "!=", "nil", "{", "newB", ".", "Format", "=", "&", "Format", "{", "NumChannels", ":", "b", ".", "Format", ".", "NumChannels", ",", "SampleRate", ":", "b", ".", "Format", ".", "SampleRate", ",", "}", "\n", "}", "\n", "return", "newB", "\n", "}" ]
// AsFloatBuffer returns a copy of this buffer but with data converted to floats.
[ "AsFloatBuffer", "returns", "a", "copy", "of", "this", "buffer", "but", "with", "data", "converted", "to", "floats", "." ]
7b2a6ca214808c64326280ac13268af853543f0b
https://github.com/go-audio/audio/blob/7b2a6ca214808c64326280ac13268af853543f0b/pcm_buffer.go#L96-L106
18,077
go-audio/audio
pcm_buffer.go
AsIntBuffer
func (b *PCMBuffer) AsIntBuffer() *IntBuffer { newB := &IntBuffer{} newB.Data = b.AsInt() if b.Format != nil { newB.Format = &Format{ NumChannels: b.Format.NumChannels, SampleRate: b.Format.SampleRate, } } return newB }
go
func (b *PCMBuffer) AsIntBuffer() *IntBuffer { newB := &IntBuffer{} newB.Data = b.AsInt() if b.Format != nil { newB.Format = &Format{ NumChannels: b.Format.NumChannels, SampleRate: b.Format.SampleRate, } } return newB }
[ "func", "(", "b", "*", "PCMBuffer", ")", "AsIntBuffer", "(", ")", "*", "IntBuffer", "{", "newB", ":=", "&", "IntBuffer", "{", "}", "\n", "newB", ".", "Data", "=", "b", ".", "AsInt", "(", ")", "\n", "if", "b", ".", "Format", "!=", "nil", "{", "newB", ".", "Format", "=", "&", "Format", "{", "NumChannels", ":", "b", ".", "Format", ".", "NumChannels", ",", "SampleRate", ":", "b", ".", "Format", ".", "SampleRate", ",", "}", "\n", "}", "\n", "return", "newB", "\n", "}" ]
// AsIntBuffer returns a copy of this buffer but with data truncated to Ints.
[ "AsIntBuffer", "returns", "a", "copy", "of", "this", "buffer", "but", "with", "data", "truncated", "to", "Ints", "." ]
7b2a6ca214808c64326280ac13268af853543f0b
https://github.com/go-audio/audio/blob/7b2a6ca214808c64326280ac13268af853543f0b/pcm_buffer.go#L122-L132
18,078
go-audio/audio
pcm_buffer.go
AsI8
func (b *PCMBuffer) AsI8() (out []int8) { if b == nil { return nil } switch b.DataType { case DataTypeI8: return b.I8 case DataTypeI16: out = make([]int8, len(b.I16)) for i := 0; i < len(b.I16); i++ { out[i] = int8(b.I16[i]) } case DataTypeI32: out = make([]int8, len(b.I32)) for i := 0; i < len(b.I32); i++ { out[i] = int8(b.I32[i]) } case DataTypeF32: out = make([]int8, len(b.F32)) for i := 0; i < len(b.F32); i++ { out[i] = int8(b.F32[i]) } case DataTypeF64: out = make([]int8, len(b.F64)) for i := 0; i < len(b.F64); i++ { out[i] = int8(b.F64[i]) } } return out }
go
func (b *PCMBuffer) AsI8() (out []int8) { if b == nil { return nil } switch b.DataType { case DataTypeI8: return b.I8 case DataTypeI16: out = make([]int8, len(b.I16)) for i := 0; i < len(b.I16); i++ { out[i] = int8(b.I16[i]) } case DataTypeI32: out = make([]int8, len(b.I32)) for i := 0; i < len(b.I32); i++ { out[i] = int8(b.I32[i]) } case DataTypeF32: out = make([]int8, len(b.F32)) for i := 0; i < len(b.F32); i++ { out[i] = int8(b.F32[i]) } case DataTypeF64: out = make([]int8, len(b.F64)) for i := 0; i < len(b.F64); i++ { out[i] = int8(b.F64[i]) } } return out }
[ "func", "(", "b", "*", "PCMBuffer", ")", "AsI8", "(", ")", "(", "out", "[", "]", "int8", ")", "{", "if", "b", "==", "nil", "{", "return", "nil", "\n", "}", "\n", "switch", "b", ".", "DataType", "{", "case", "DataTypeI8", ":", "return", "b", ".", "I8", "\n", "case", "DataTypeI16", ":", "out", "=", "make", "(", "[", "]", "int8", ",", "len", "(", "b", ".", "I16", ")", ")", "\n", "for", "i", ":=", "0", ";", "i", "<", "len", "(", "b", ".", "I16", ")", ";", "i", "++", "{", "out", "[", "i", "]", "=", "int8", "(", "b", ".", "I16", "[", "i", "]", ")", "\n", "}", "\n", "case", "DataTypeI32", ":", "out", "=", "make", "(", "[", "]", "int8", ",", "len", "(", "b", ".", "I32", ")", ")", "\n", "for", "i", ":=", "0", ";", "i", "<", "len", "(", "b", ".", "I32", ")", ";", "i", "++", "{", "out", "[", "i", "]", "=", "int8", "(", "b", ".", "I32", "[", "i", "]", ")", "\n", "}", "\n", "case", "DataTypeF32", ":", "out", "=", "make", "(", "[", "]", "int8", ",", "len", "(", "b", ".", "F32", ")", ")", "\n", "for", "i", ":=", "0", ";", "i", "<", "len", "(", "b", ".", "F32", ")", ";", "i", "++", "{", "out", "[", "i", "]", "=", "int8", "(", "b", ".", "F32", "[", "i", "]", ")", "\n", "}", "\n", "case", "DataTypeF64", ":", "out", "=", "make", "(", "[", "]", "int8", ",", "len", "(", "b", ".", "F64", ")", ")", "\n", "for", "i", ":=", "0", ";", "i", "<", "len", "(", "b", ".", "F64", ")", ";", "i", "++", "{", "out", "[", "i", "]", "=", "int8", "(", "b", ".", "F64", "[", "i", "]", ")", "\n", "}", "\n", "}", "\n", "return", "out", "\n", "}" ]
// AsI8 returns the buffer's samples as int8 sample values. // If the buffer isn't in this format, a copy is created and converted. // Note that converting might result in loss of resolution.
[ "AsI8", "returns", "the", "buffer", "s", "samples", "as", "int8", "sample", "values", ".", "If", "the", "buffer", "isn", "t", "in", "this", "format", "a", "copy", "is", "created", "and", "converted", ".", "Note", "that", "converting", "might", "result", "in", "loss", "of", "resolution", "." ]
7b2a6ca214808c64326280ac13268af853543f0b
https://github.com/go-audio/audio/blob/7b2a6ca214808c64326280ac13268af853543f0b/pcm_buffer.go#L137-L166
18,079
go-audio/audio
pcm_buffer.go
AsF64
func (b *PCMBuffer) AsF64() (out []float64) { if b == nil { return nil } switch b.DataType { case DataTypeI8: bitDepth := b.calculateIntBitDepth() factor := math.Pow(2, 8*float64(bitDepth/8)-1) out = make([]float64, len(b.I8)) for i := 0; i < len(b.I8); i++ { out[i] = float64(int64(b.I8[i])) / factor } case DataTypeI16: bitDepth := b.calculateIntBitDepth() factor := math.Pow(2, 8*float64(bitDepth/8)-1) out = make([]float64, len(b.I16)) for i := 0; i < len(b.I16); i++ { out[i] = float64(int64(b.I16[i])) / factor } case DataTypeI32: bitDepth := b.calculateIntBitDepth() factor := math.Pow(2, 8*float64(bitDepth/8)-1) out = make([]float64, len(b.I16)) for i := 0; i < len(b.I16); i++ { out[i] = float64(int64(b.I16[i])) / factor } case DataTypeF32: out = make([]float64, len(b.F32)) for i := 0; i < len(b.F32); i++ { out[i] = float64(b.F32[i]) } case DataTypeF64: return b.F64 } return out }
go
func (b *PCMBuffer) AsF64() (out []float64) { if b == nil { return nil } switch b.DataType { case DataTypeI8: bitDepth := b.calculateIntBitDepth() factor := math.Pow(2, 8*float64(bitDepth/8)-1) out = make([]float64, len(b.I8)) for i := 0; i < len(b.I8); i++ { out[i] = float64(int64(b.I8[i])) / factor } case DataTypeI16: bitDepth := b.calculateIntBitDepth() factor := math.Pow(2, 8*float64(bitDepth/8)-1) out = make([]float64, len(b.I16)) for i := 0; i < len(b.I16); i++ { out[i] = float64(int64(b.I16[i])) / factor } case DataTypeI32: bitDepth := b.calculateIntBitDepth() factor := math.Pow(2, 8*float64(bitDepth/8)-1) out = make([]float64, len(b.I16)) for i := 0; i < len(b.I16); i++ { out[i] = float64(int64(b.I16[i])) / factor } case DataTypeF32: out = make([]float64, len(b.F32)) for i := 0; i < len(b.F32); i++ { out[i] = float64(b.F32[i]) } case DataTypeF64: return b.F64 } return out }
[ "func", "(", "b", "*", "PCMBuffer", ")", "AsF64", "(", ")", "(", "out", "[", "]", "float64", ")", "{", "if", "b", "==", "nil", "{", "return", "nil", "\n", "}", "\n", "switch", "b", ".", "DataType", "{", "case", "DataTypeI8", ":", "bitDepth", ":=", "b", ".", "calculateIntBitDepth", "(", ")", "\n", "factor", ":=", "math", ".", "Pow", "(", "2", ",", "8", "*", "float64", "(", "bitDepth", "/", "8", ")", "-", "1", ")", "\n", "out", "=", "make", "(", "[", "]", "float64", ",", "len", "(", "b", ".", "I8", ")", ")", "\n", "for", "i", ":=", "0", ";", "i", "<", "len", "(", "b", ".", "I8", ")", ";", "i", "++", "{", "out", "[", "i", "]", "=", "float64", "(", "int64", "(", "b", ".", "I8", "[", "i", "]", ")", ")", "/", "factor", "\n", "}", "\n", "case", "DataTypeI16", ":", "bitDepth", ":=", "b", ".", "calculateIntBitDepth", "(", ")", "\n", "factor", ":=", "math", ".", "Pow", "(", "2", ",", "8", "*", "float64", "(", "bitDepth", "/", "8", ")", "-", "1", ")", "\n", "out", "=", "make", "(", "[", "]", "float64", ",", "len", "(", "b", ".", "I16", ")", ")", "\n", "for", "i", ":=", "0", ";", "i", "<", "len", "(", "b", ".", "I16", ")", ";", "i", "++", "{", "out", "[", "i", "]", "=", "float64", "(", "int64", "(", "b", ".", "I16", "[", "i", "]", ")", ")", "/", "factor", "\n", "}", "\n", "case", "DataTypeI32", ":", "bitDepth", ":=", "b", ".", "calculateIntBitDepth", "(", ")", "\n", "factor", ":=", "math", ".", "Pow", "(", "2", ",", "8", "*", "float64", "(", "bitDepth", "/", "8", ")", "-", "1", ")", "\n", "out", "=", "make", "(", "[", "]", "float64", ",", "len", "(", "b", ".", "I16", ")", ")", "\n", "for", "i", ":=", "0", ";", "i", "<", "len", "(", "b", ".", "I16", ")", ";", "i", "++", "{", "out", "[", "i", "]", "=", "float64", "(", "int64", "(", "b", ".", "I16", "[", "i", "]", ")", ")", "/", "factor", "\n", "}", "\n", "case", "DataTypeF32", ":", "out", "=", "make", "(", "[", "]", "float64", ",", "len", "(", "b", ".", "F32", ")", ")", "\n", "for", "i", ":=", "0", ";", "i", "<", "len", "(", "b", ".", "F32", ")", ";", "i", "++", "{", "out", "[", "i", "]", "=", "float64", "(", "b", ".", "F32", "[", "i", "]", ")", "\n", "}", "\n", "case", "DataTypeF64", ":", "return", "b", ".", "F64", "\n", "}", "\n", "return", "out", "\n", "}" ]
// AsF64 returns the buffer's samples as float64 sample values. // If the buffer isn't in this format, a copy is created and converted. // Note that converting might result in unexpected truncations.
[ "AsF64", "returns", "the", "buffer", "s", "samples", "as", "float64", "sample", "values", ".", "If", "the", "buffer", "isn", "t", "in", "this", "format", "a", "copy", "is", "created", "and", "converted", ".", "Note", "that", "converting", "might", "result", "in", "unexpected", "truncations", "." ]
7b2a6ca214808c64326280ac13268af853543f0b
https://github.com/go-audio/audio/blob/7b2a6ca214808c64326280ac13268af853543f0b/pcm_buffer.go#L291-L326
18,080
go-audio/audio
pcm_buffer.go
calculateIntBitDepth
func (b *PCMBuffer) calculateIntBitDepth() uint8 { if b == nil { return 0 } bitDepth := b.SourceBitDepth if bitDepth != 0 { return bitDepth } var max int64 switch b.DataType { case DataTypeI8: var i8max int8 for _, s := range b.I8 { if s > i8max { i8max = s } } max = int64(i8max) case DataTypeI16: var i16max int16 for _, s := range b.I16 { if s > i16max { i16max = s } } max = int64(i16max) case DataTypeI32: var i32max int32 for _, s := range b.I32 { if s > i32max { i32max = s } } max = int64(i32max) default: // This method is only meant to be used on int buffers. return bitDepth } bitDepth = 8 if max > 127 { bitDepth = 16 } // greater than int16, expecting int24 if max > 32767 { bitDepth = 24 } // int 32 if max > 8388607 { bitDepth = 32 } // int 64 if max > 4294967295 { bitDepth = 64 } return bitDepth }
go
func (b *PCMBuffer) calculateIntBitDepth() uint8 { if b == nil { return 0 } bitDepth := b.SourceBitDepth if bitDepth != 0 { return bitDepth } var max int64 switch b.DataType { case DataTypeI8: var i8max int8 for _, s := range b.I8 { if s > i8max { i8max = s } } max = int64(i8max) case DataTypeI16: var i16max int16 for _, s := range b.I16 { if s > i16max { i16max = s } } max = int64(i16max) case DataTypeI32: var i32max int32 for _, s := range b.I32 { if s > i32max { i32max = s } } max = int64(i32max) default: // This method is only meant to be used on int buffers. return bitDepth } bitDepth = 8 if max > 127 { bitDepth = 16 } // greater than int16, expecting int24 if max > 32767 { bitDepth = 24 } // int 32 if max > 8388607 { bitDepth = 32 } // int 64 if max > 4294967295 { bitDepth = 64 } return bitDepth }
[ "func", "(", "b", "*", "PCMBuffer", ")", "calculateIntBitDepth", "(", ")", "uint8", "{", "if", "b", "==", "nil", "{", "return", "0", "\n", "}", "\n", "bitDepth", ":=", "b", ".", "SourceBitDepth", "\n", "if", "bitDepth", "!=", "0", "{", "return", "bitDepth", "\n", "}", "\n", "var", "max", "int64", "\n", "switch", "b", ".", "DataType", "{", "case", "DataTypeI8", ":", "var", "i8max", "int8", "\n", "for", "_", ",", "s", ":=", "range", "b", ".", "I8", "{", "if", "s", ">", "i8max", "{", "i8max", "=", "s", "\n", "}", "\n", "}", "\n", "max", "=", "int64", "(", "i8max", ")", "\n", "case", "DataTypeI16", ":", "var", "i16max", "int16", "\n", "for", "_", ",", "s", ":=", "range", "b", ".", "I16", "{", "if", "s", ">", "i16max", "{", "i16max", "=", "s", "\n", "}", "\n", "}", "\n", "max", "=", "int64", "(", "i16max", ")", "\n", "case", "DataTypeI32", ":", "var", "i32max", "int32", "\n", "for", "_", ",", "s", ":=", "range", "b", ".", "I32", "{", "if", "s", ">", "i32max", "{", "i32max", "=", "s", "\n", "}", "\n", "}", "\n", "max", "=", "int64", "(", "i32max", ")", "\n", "default", ":", "// This method is only meant to be used on int buffers.", "return", "bitDepth", "\n", "}", "\n", "bitDepth", "=", "8", "\n", "if", "max", ">", "127", "{", "bitDepth", "=", "16", "\n", "}", "\n", "// greater than int16, expecting int24", "if", "max", ">", "32767", "{", "bitDepth", "=", "24", "\n", "}", "\n", "// int 32", "if", "max", ">", "8388607", "{", "bitDepth", "=", "32", "\n", "}", "\n", "// int 64", "if", "max", ">", "4294967295", "{", "bitDepth", "=", "64", "\n", "}", "\n\n", "return", "bitDepth", "\n", "}" ]
// calculateIntBithDepth looks at the int values in the buffer and returns // the required lowest bit depth.
[ "calculateIntBithDepth", "looks", "at", "the", "int", "values", "in", "the", "buffer", "and", "returns", "the", "required", "lowest", "bit", "depth", "." ]
7b2a6ca214808c64326280ac13268af853543f0b
https://github.com/go-audio/audio/blob/7b2a6ca214808c64326280ac13268af853543f0b/pcm_buffer.go#L405-L461
18,081
go-audio/audio
int_buffer.go
AsFloat32Buffer
func (buf *IntBuffer) AsFloat32Buffer() *Float32Buffer { newB := &Float32Buffer{} newB.Data = make([]float32, len(buf.Data)) max := int64(0) // try to guess the bit depths without knowing the source if buf.SourceBitDepth == 0 { for _, s := range buf.Data { if int64(s) > max { max = int64(s) } } buf.SourceBitDepth = 8 if max > 127 { buf.SourceBitDepth = 16 } // greater than int16, expecting int24 if max > 32767 { buf.SourceBitDepth = 24 } // int 32 if max > 8388607 { buf.SourceBitDepth = 32 } // int 64 if max > 4294967295 { buf.SourceBitDepth = 64 } } newB.SourceBitDepth = buf.SourceBitDepth factor := math.Pow(2, float64(buf.SourceBitDepth)-1) for i := 0; i < len(buf.Data); i++ { newB.Data[i] = float32(float64(buf.Data[i]) / factor) } newB.Format = &Format{ NumChannels: buf.Format.NumChannels, SampleRate: buf.Format.SampleRate, } return newB }
go
func (buf *IntBuffer) AsFloat32Buffer() *Float32Buffer { newB := &Float32Buffer{} newB.Data = make([]float32, len(buf.Data)) max := int64(0) // try to guess the bit depths without knowing the source if buf.SourceBitDepth == 0 { for _, s := range buf.Data { if int64(s) > max { max = int64(s) } } buf.SourceBitDepth = 8 if max > 127 { buf.SourceBitDepth = 16 } // greater than int16, expecting int24 if max > 32767 { buf.SourceBitDepth = 24 } // int 32 if max > 8388607 { buf.SourceBitDepth = 32 } // int 64 if max > 4294967295 { buf.SourceBitDepth = 64 } } newB.SourceBitDepth = buf.SourceBitDepth factor := math.Pow(2, float64(buf.SourceBitDepth)-1) for i := 0; i < len(buf.Data); i++ { newB.Data[i] = float32(float64(buf.Data[i]) / factor) } newB.Format = &Format{ NumChannels: buf.Format.NumChannels, SampleRate: buf.Format.SampleRate, } return newB }
[ "func", "(", "buf", "*", "IntBuffer", ")", "AsFloat32Buffer", "(", ")", "*", "Float32Buffer", "{", "newB", ":=", "&", "Float32Buffer", "{", "}", "\n", "newB", ".", "Data", "=", "make", "(", "[", "]", "float32", ",", "len", "(", "buf", ".", "Data", ")", ")", "\n", "max", ":=", "int64", "(", "0", ")", "\n", "// try to guess the bit depths without knowing the source", "if", "buf", ".", "SourceBitDepth", "==", "0", "{", "for", "_", ",", "s", ":=", "range", "buf", ".", "Data", "{", "if", "int64", "(", "s", ")", ">", "max", "{", "max", "=", "int64", "(", "s", ")", "\n", "}", "\n", "}", "\n", "buf", ".", "SourceBitDepth", "=", "8", "\n", "if", "max", ">", "127", "{", "buf", ".", "SourceBitDepth", "=", "16", "\n", "}", "\n", "// greater than int16, expecting int24", "if", "max", ">", "32767", "{", "buf", ".", "SourceBitDepth", "=", "24", "\n", "}", "\n", "// int 32", "if", "max", ">", "8388607", "{", "buf", ".", "SourceBitDepth", "=", "32", "\n", "}", "\n", "// int 64", "if", "max", ">", "4294967295", "{", "buf", ".", "SourceBitDepth", "=", "64", "\n", "}", "\n", "}", "\n", "newB", ".", "SourceBitDepth", "=", "buf", ".", "SourceBitDepth", "\n", "factor", ":=", "math", ".", "Pow", "(", "2", ",", "float64", "(", "buf", ".", "SourceBitDepth", ")", "-", "1", ")", "\n", "for", "i", ":=", "0", ";", "i", "<", "len", "(", "buf", ".", "Data", ")", ";", "i", "++", "{", "newB", ".", "Data", "[", "i", "]", "=", "float32", "(", "float64", "(", "buf", ".", "Data", "[", "i", "]", ")", "/", "factor", ")", "\n", "}", "\n", "newB", ".", "Format", "=", "&", "Format", "{", "NumChannels", ":", "buf", ".", "Format", ".", "NumChannels", ",", "SampleRate", ":", "buf", ".", "Format", ".", "SampleRate", ",", "}", "\n", "return", "newB", "\n", "}" ]
// AsFloat32Buffer returns a copy of this buffer but with data converted to float 32.
[ "AsFloat32Buffer", "returns", "a", "copy", "of", "this", "buffer", "but", "with", "data", "converted", "to", "float", "32", "." ]
7b2a6ca214808c64326280ac13268af853543f0b
https://github.com/go-audio/audio/blob/7b2a6ca214808c64326280ac13268af853543f0b/int_buffer.go#L36-L74
18,082
go-audio/audio
conv.go
IEEEFloatToInt
func IEEEFloatToInt(b [10]byte) int { var i uint32 // Negative number if (b[0] & 0x80) == 1 { return 0 } // Less than 1 if b[0] <= 0x3F { return 1 } // Too big if b[0] > 0x40 { return 67108864 } // Still too big if b[0] == 0x40 && b[1] > 0x1C { return 800000000 } i = (uint32(b[2]) << 23) | (uint32(b[3]) << 15) | (uint32(b[4]) << 7) | (uint32(b[5]) >> 1) i >>= (29 - uint32(b[1])) return int(i) }
go
func IEEEFloatToInt(b [10]byte) int { var i uint32 // Negative number if (b[0] & 0x80) == 1 { return 0 } // Less than 1 if b[0] <= 0x3F { return 1 } // Too big if b[0] > 0x40 { return 67108864 } // Still too big if b[0] == 0x40 && b[1] > 0x1C { return 800000000 } i = (uint32(b[2]) << 23) | (uint32(b[3]) << 15) | (uint32(b[4]) << 7) | (uint32(b[5]) >> 1) i >>= (29 - uint32(b[1])) return int(i) }
[ "func", "IEEEFloatToInt", "(", "b", "[", "10", "]", "byte", ")", "int", "{", "var", "i", "uint32", "\n", "// Negative number", "if", "(", "b", "[", "0", "]", "&", "0x80", ")", "==", "1", "{", "return", "0", "\n", "}", "\n\n", "// Less than 1", "if", "b", "[", "0", "]", "<=", "0x3F", "{", "return", "1", "\n", "}", "\n\n", "// Too big", "if", "b", "[", "0", "]", ">", "0x40", "{", "return", "67108864", "\n", "}", "\n\n", "// Still too big", "if", "b", "[", "0", "]", "==", "0x40", "&&", "b", "[", "1", "]", ">", "0x1C", "{", "return", "800000000", "\n", "}", "\n\n", "i", "=", "(", "uint32", "(", "b", "[", "2", "]", ")", "<<", "23", ")", "|", "(", "uint32", "(", "b", "[", "3", "]", ")", "<<", "15", ")", "|", "(", "uint32", "(", "b", "[", "4", "]", ")", "<<", "7", ")", "|", "(", "uint32", "(", "b", "[", "5", "]", ")", ">>", "1", ")", "\n", "i", ">>=", "(", "29", "-", "uint32", "(", "b", "[", "1", "]", ")", ")", "\n\n", "return", "int", "(", "i", ")", "\n", "}" ]
// IEEEFloatToInt converts a 10 byte IEEE float into an int.
[ "IEEEFloatToInt", "converts", "a", "10", "byte", "IEEE", "float", "into", "an", "int", "." ]
7b2a6ca214808c64326280ac13268af853543f0b
https://github.com/go-audio/audio/blob/7b2a6ca214808c64326280ac13268af853543f0b/conv.go#L23-L49
18,083
go-audio/audio
conv.go
IntToIEEEFloat
func IntToIEEEFloat(i int) [10]byte { b := [10]byte{} num := float64(i) var sign int var expon int var fMant, fsMant float64 var hiMant, loMant uint if num < 0 { sign = 0x8000 } else { sign = 0 } if num == 0 { expon = 0 hiMant = 0 loMant = 0 } else { fMant, expon = math.Frexp(num) if (expon > 16384) || !(fMant < 1) { /* Infinity or NaN */ expon = sign | 0x7FFF hiMant = 0 loMant = 0 /* infinity */ } else { /* Finite */ expon += 16382 if expon < 0 { /* denormalized */ fMant = math.Ldexp(fMant, expon) expon = 0 } expon |= sign fMant = math.Ldexp(fMant, 32) fsMant = math.Floor(fMant) hiMant = uint(fsMant) fMant = math.Ldexp(fMant-fsMant, 32) fsMant = math.Floor(fMant) loMant = uint(fsMant) } } b[0] = byte(expon >> 8) b[1] = byte(expon) b[2] = byte(hiMant >> 24) b[3] = byte(hiMant >> 16) b[4] = byte(hiMant >> 8) b[5] = byte(hiMant) b[6] = byte(loMant >> 24) b[7] = byte(loMant >> 16) b[8] = byte(loMant >> 8) b[9] = byte(loMant) return b }
go
func IntToIEEEFloat(i int) [10]byte { b := [10]byte{} num := float64(i) var sign int var expon int var fMant, fsMant float64 var hiMant, loMant uint if num < 0 { sign = 0x8000 } else { sign = 0 } if num == 0 { expon = 0 hiMant = 0 loMant = 0 } else { fMant, expon = math.Frexp(num) if (expon > 16384) || !(fMant < 1) { /* Infinity or NaN */ expon = sign | 0x7FFF hiMant = 0 loMant = 0 /* infinity */ } else { /* Finite */ expon += 16382 if expon < 0 { /* denormalized */ fMant = math.Ldexp(fMant, expon) expon = 0 } expon |= sign fMant = math.Ldexp(fMant, 32) fsMant = math.Floor(fMant) hiMant = uint(fsMant) fMant = math.Ldexp(fMant-fsMant, 32) fsMant = math.Floor(fMant) loMant = uint(fsMant) } } b[0] = byte(expon >> 8) b[1] = byte(expon) b[2] = byte(hiMant >> 24) b[3] = byte(hiMant >> 16) b[4] = byte(hiMant >> 8) b[5] = byte(hiMant) b[6] = byte(loMant >> 24) b[7] = byte(loMant >> 16) b[8] = byte(loMant >> 8) b[9] = byte(loMant) return b }
[ "func", "IntToIEEEFloat", "(", "i", "int", ")", "[", "10", "]", "byte", "{", "b", ":=", "[", "10", "]", "byte", "{", "}", "\n", "num", ":=", "float64", "(", "i", ")", "\n\n", "var", "sign", "int", "\n", "var", "expon", "int", "\n", "var", "fMant", ",", "fsMant", "float64", "\n", "var", "hiMant", ",", "loMant", "uint", "\n\n", "if", "num", "<", "0", "{", "sign", "=", "0x8000", "\n", "}", "else", "{", "sign", "=", "0", "\n", "}", "\n\n", "if", "num", "==", "0", "{", "expon", "=", "0", "\n", "hiMant", "=", "0", "\n", "loMant", "=", "0", "\n", "}", "else", "{", "fMant", ",", "expon", "=", "math", ".", "Frexp", "(", "num", ")", "\n", "if", "(", "expon", ">", "16384", ")", "||", "!", "(", "fMant", "<", "1", ")", "{", "/* Infinity or NaN */", "expon", "=", "sign", "|", "0x7FFF", "\n", "hiMant", "=", "0", "\n", "loMant", "=", "0", "/* infinity */", "\n", "}", "else", "{", "/* Finite */", "expon", "+=", "16382", "\n", "if", "expon", "<", "0", "{", "/* denormalized */", "fMant", "=", "math", ".", "Ldexp", "(", "fMant", ",", "expon", ")", "\n", "expon", "=", "0", "\n", "}", "\n", "expon", "|=", "sign", "\n", "fMant", "=", "math", ".", "Ldexp", "(", "fMant", ",", "32", ")", "\n", "fsMant", "=", "math", ".", "Floor", "(", "fMant", ")", "\n", "hiMant", "=", "uint", "(", "fsMant", ")", "\n", "fMant", "=", "math", ".", "Ldexp", "(", "fMant", "-", "fsMant", ",", "32", ")", "\n", "fsMant", "=", "math", ".", "Floor", "(", "fMant", ")", "\n", "loMant", "=", "uint", "(", "fsMant", ")", "\n", "}", "\n", "}", "\n\n", "b", "[", "0", "]", "=", "byte", "(", "expon", ">>", "8", ")", "\n", "b", "[", "1", "]", "=", "byte", "(", "expon", ")", "\n", "b", "[", "2", "]", "=", "byte", "(", "hiMant", ">>", "24", ")", "\n", "b", "[", "3", "]", "=", "byte", "(", "hiMant", ">>", "16", ")", "\n", "b", "[", "4", "]", "=", "byte", "(", "hiMant", ">>", "8", ")", "\n", "b", "[", "5", "]", "=", "byte", "(", "hiMant", ")", "\n", "b", "[", "6", "]", "=", "byte", "(", "loMant", ">>", "24", ")", "\n", "b", "[", "7", "]", "=", "byte", "(", "loMant", ">>", "16", ")", "\n", "b", "[", "8", "]", "=", "byte", "(", "loMant", ">>", "8", ")", "\n", "b", "[", "9", "]", "=", "byte", "(", "loMant", ")", "\n\n", "return", "b", "\n", "}" ]
// IntToIEEEFloat converts an int into a 10 byte IEEE float.
[ "IntToIEEEFloat", "converts", "an", "int", "into", "a", "10", "byte", "IEEE", "float", "." ]
7b2a6ca214808c64326280ac13268af853543f0b
https://github.com/go-audio/audio/blob/7b2a6ca214808c64326280ac13268af853543f0b/conv.go#L52-L105
18,084
go-audio/audio
conv.go
Uint24to32
func Uint24to32(bytes []byte) uint32 { var output uint32 output |= uint32(bytes[2]) << 0 output |= uint32(bytes[1]) << 8 output |= uint32(bytes[0]) << 16 return output }
go
func Uint24to32(bytes []byte) uint32 { var output uint32 output |= uint32(bytes[2]) << 0 output |= uint32(bytes[1]) << 8 output |= uint32(bytes[0]) << 16 return output }
[ "func", "Uint24to32", "(", "bytes", "[", "]", "byte", ")", "uint32", "{", "var", "output", "uint32", "\n", "output", "|=", "uint32", "(", "bytes", "[", "2", "]", ")", "<<", "0", "\n", "output", "|=", "uint32", "(", "bytes", "[", "1", "]", ")", "<<", "8", "\n", "output", "|=", "uint32", "(", "bytes", "[", "0", "]", ")", "<<", "16", "\n\n", "return", "output", "\n", "}" ]
// Uint24to32 converts a 3 byte uint23 into a uint32 // BigEndian!
[ "Uint24to32", "converts", "a", "3", "byte", "uint23", "into", "a", "uint32", "BigEndian!" ]
7b2a6ca214808c64326280ac13268af853543f0b
https://github.com/go-audio/audio/blob/7b2a6ca214808c64326280ac13268af853543f0b/conv.go#L109-L116
18,085
go-audio/audio
conv.go
Int24BETo32
func Int24BETo32(bytes []byte) int32 { if len(bytes) < 3 { return 0 } ss := int32(0xFF&bytes[0])<<16 | int32(0xFF&bytes[1])<<8 | int32(0xFF&bytes[2]) if (ss & 0x800000) > 0 { ss |= ^0xffffff } return ss }
go
func Int24BETo32(bytes []byte) int32 { if len(bytes) < 3 { return 0 } ss := int32(0xFF&bytes[0])<<16 | int32(0xFF&bytes[1])<<8 | int32(0xFF&bytes[2]) if (ss & 0x800000) > 0 { ss |= ^0xffffff } return ss }
[ "func", "Int24BETo32", "(", "bytes", "[", "]", "byte", ")", "int32", "{", "if", "len", "(", "bytes", ")", "<", "3", "{", "return", "0", "\n", "}", "\n", "ss", ":=", "int32", "(", "0xFF", "&", "bytes", "[", "0", "]", ")", "<<", "16", "|", "int32", "(", "0xFF", "&", "bytes", "[", "1", "]", ")", "<<", "8", "|", "int32", "(", "0xFF", "&", "bytes", "[", "2", "]", ")", "\n", "if", "(", "ss", "&", "0x800000", ")", ">", "0", "{", "ss", "|=", "^", "0xffffff", "\n", "}", "\n\n", "return", "ss", "\n", "}" ]
// Int24BETo32 converts an int24 value from 3 bytes into an int32 value
[ "Int24BETo32", "converts", "an", "int24", "value", "from", "3", "bytes", "into", "an", "int32", "value" ]
7b2a6ca214808c64326280ac13268af853543f0b
https://github.com/go-audio/audio/blob/7b2a6ca214808c64326280ac13268af853543f0b/conv.go#L119-L129
18,086
go-audio/audio
conv.go
Int24LETo32
func Int24LETo32(bytes []byte) int32 { if len(bytes) < 3 { return 0 } ss := int32(bytes[0]) | int32(bytes[1])<<8 | int32(bytes[2])<<16 if (ss & 0x800000) > 0 { ss |= ^0xffffff } return ss }
go
func Int24LETo32(bytes []byte) int32 { if len(bytes) < 3 { return 0 } ss := int32(bytes[0]) | int32(bytes[1])<<8 | int32(bytes[2])<<16 if (ss & 0x800000) > 0 { ss |= ^0xffffff } return ss }
[ "func", "Int24LETo32", "(", "bytes", "[", "]", "byte", ")", "int32", "{", "if", "len", "(", "bytes", ")", "<", "3", "{", "return", "0", "\n", "}", "\n", "ss", ":=", "int32", "(", "bytes", "[", "0", "]", ")", "|", "int32", "(", "bytes", "[", "1", "]", ")", "<<", "8", "|", "int32", "(", "bytes", "[", "2", "]", ")", "<<", "16", "\n", "if", "(", "ss", "&", "0x800000", ")", ">", "0", "{", "ss", "|=", "^", "0xffffff", "\n", "}", "\n\n", "return", "ss", "\n", "}" ]
// Int24LETo32 converts an int24 value from 3 bytes into an int32 value
[ "Int24LETo32", "converts", "an", "int24", "value", "from", "3", "bytes", "into", "an", "int32", "value" ]
7b2a6ca214808c64326280ac13268af853543f0b
https://github.com/go-audio/audio/blob/7b2a6ca214808c64326280ac13268af853543f0b/conv.go#L132-L142
18,087
go-audio/audio
conv.go
Uint32toUint24Bytes
func Uint32toUint24Bytes(n uint32) []byte { bytes := make([]byte, 3) bytes[0] = byte(n >> 16) bytes[1] = byte(n >> 8) bytes[2] = byte(n >> 0) return bytes }
go
func Uint32toUint24Bytes(n uint32) []byte { bytes := make([]byte, 3) bytes[0] = byte(n >> 16) bytes[1] = byte(n >> 8) bytes[2] = byte(n >> 0) return bytes }
[ "func", "Uint32toUint24Bytes", "(", "n", "uint32", ")", "[", "]", "byte", "{", "bytes", ":=", "make", "(", "[", "]", "byte", ",", "3", ")", "\n", "bytes", "[", "0", "]", "=", "byte", "(", "n", ">>", "16", ")", "\n", "bytes", "[", "1", "]", "=", "byte", "(", "n", ">>", "8", ")", "\n", "bytes", "[", "2", "]", "=", "byte", "(", "n", ">>", "0", ")", "\n\n", "return", "bytes", "\n", "}" ]
// Uint32toUint24Bytes converts a uint32 into a 3 byte uint24 representation
[ "Uint32toUint24Bytes", "converts", "a", "uint32", "into", "a", "3", "byte", "uint24", "representation" ]
7b2a6ca214808c64326280ac13268af853543f0b
https://github.com/go-audio/audio/blob/7b2a6ca214808c64326280ac13268af853543f0b/conv.go#L145-L152
18,088
go-audio/audio
conv.go
Int32toInt24LEBytes
func Int32toInt24LEBytes(n int32) []byte { bytes := make([]byte, 3) if (n & 0x800000) > 0 { n |= ^0xffffff } bytes[2] = byte(n >> 16) bytes[1] = byte(n >> 8) bytes[0] = byte(n >> 0) return bytes }
go
func Int32toInt24LEBytes(n int32) []byte { bytes := make([]byte, 3) if (n & 0x800000) > 0 { n |= ^0xffffff } bytes[2] = byte(n >> 16) bytes[1] = byte(n >> 8) bytes[0] = byte(n >> 0) return bytes }
[ "func", "Int32toInt24LEBytes", "(", "n", "int32", ")", "[", "]", "byte", "{", "bytes", ":=", "make", "(", "[", "]", "byte", ",", "3", ")", "\n", "if", "(", "n", "&", "0x800000", ")", ">", "0", "{", "n", "|=", "^", "0xffffff", "\n", "}", "\n", "bytes", "[", "2", "]", "=", "byte", "(", "n", ">>", "16", ")", "\n", "bytes", "[", "1", "]", "=", "byte", "(", "n", ">>", "8", ")", "\n", "bytes", "[", "0", "]", "=", "byte", "(", "n", ">>", "0", ")", "\n", "return", "bytes", "\n", "}" ]
// Int32toInt24LEBytes converts an int32 into a little endian 3 byte int24 representation
[ "Int32toInt24LEBytes", "converts", "an", "int32", "into", "a", "little", "endian", "3", "byte", "int24", "representation" ]
7b2a6ca214808c64326280ac13268af853543f0b
https://github.com/go-audio/audio/blob/7b2a6ca214808c64326280ac13268af853543f0b/conv.go#L155-L164
18,089
go-audio/audio
conv.go
Int32toInt24BEBytes
func Int32toInt24BEBytes(n int32) []byte { bytes := make([]byte, 3) if (n & 0x800000) > 0 { n |= ^0xffffff } bytes[0] = byte(n >> 16) bytes[1] = byte(n >> 8) bytes[2] = byte(n >> 0) return bytes }
go
func Int32toInt24BEBytes(n int32) []byte { bytes := make([]byte, 3) if (n & 0x800000) > 0 { n |= ^0xffffff } bytes[0] = byte(n >> 16) bytes[1] = byte(n >> 8) bytes[2] = byte(n >> 0) return bytes }
[ "func", "Int32toInt24BEBytes", "(", "n", "int32", ")", "[", "]", "byte", "{", "bytes", ":=", "make", "(", "[", "]", "byte", ",", "3", ")", "\n", "if", "(", "n", "&", "0x800000", ")", ">", "0", "{", "n", "|=", "^", "0xffffff", "\n", "}", "\n", "bytes", "[", "0", "]", "=", "byte", "(", "n", ">>", "16", ")", "\n", "bytes", "[", "1", "]", "=", "byte", "(", "n", ">>", "8", ")", "\n", "bytes", "[", "2", "]", "=", "byte", "(", "n", ">>", "0", ")", "\n\n", "return", "bytes", "\n", "}" ]
// Int32toInt24BEBytes converts an int32 into a big endian 3 byte int24 representation
[ "Int32toInt24BEBytes", "converts", "an", "int32", "into", "a", "big", "endian", "3", "byte", "int24", "representation" ]
7b2a6ca214808c64326280ac13268af853543f0b
https://github.com/go-audio/audio/blob/7b2a6ca214808c64326280ac13268af853543f0b/conv.go#L167-L177
18,090
go-audio/audio
float_buffer.go
AsFloatBuffer
func (buf *Float32Buffer) AsFloatBuffer() *FloatBuffer { newB := &FloatBuffer{} newB.Data = make([]float64, len(buf.Data)) for i := 0; i < len(buf.Data); i++ { newB.Data[i] = float64(buf.Data[i]) } newB.Format = &Format{ NumChannels: buf.Format.NumChannels, SampleRate: buf.Format.SampleRate, } return newB }
go
func (buf *Float32Buffer) AsFloatBuffer() *FloatBuffer { newB := &FloatBuffer{} newB.Data = make([]float64, len(buf.Data)) for i := 0; i < len(buf.Data); i++ { newB.Data[i] = float64(buf.Data[i]) } newB.Format = &Format{ NumChannels: buf.Format.NumChannels, SampleRate: buf.Format.SampleRate, } return newB }
[ "func", "(", "buf", "*", "Float32Buffer", ")", "AsFloatBuffer", "(", ")", "*", "FloatBuffer", "{", "newB", ":=", "&", "FloatBuffer", "{", "}", "\n", "newB", ".", "Data", "=", "make", "(", "[", "]", "float64", ",", "len", "(", "buf", ".", "Data", ")", ")", "\n", "for", "i", ":=", "0", ";", "i", "<", "len", "(", "buf", ".", "Data", ")", ";", "i", "++", "{", "newB", ".", "Data", "[", "i", "]", "=", "float64", "(", "buf", ".", "Data", "[", "i", "]", ")", "\n", "}", "\n", "newB", ".", "Format", "=", "&", "Format", "{", "NumChannels", ":", "buf", ".", "Format", ".", "NumChannels", ",", "SampleRate", ":", "buf", ".", "Format", ".", "SampleRate", ",", "}", "\n", "return", "newB", "\n", "}" ]
// AsFloatBuffer implements the Buffer interface and returns a float64 version of itself.
[ "AsFloatBuffer", "implements", "the", "Buffer", "interface", "and", "returns", "a", "float64", "version", "of", "itself", "." ]
7b2a6ca214808c64326280ac13268af853543f0b
https://github.com/go-audio/audio/blob/7b2a6ca214808c64326280ac13268af853543f0b/float_buffer.go#L92-L103
18,091
instana/go-sensor
adapters.go
TraceHandler
func (s *Sensor) TraceHandler(name, pattern string, handler http.HandlerFunc) (string, http.HandlerFunc) { return pattern, s.TracingHandler(name, handler) }
go
func (s *Sensor) TraceHandler(name, pattern string, handler http.HandlerFunc) (string, http.HandlerFunc) { return pattern, s.TracingHandler(name, handler) }
[ "func", "(", "s", "*", "Sensor", ")", "TraceHandler", "(", "name", ",", "pattern", "string", ",", "handler", "http", ".", "HandlerFunc", ")", "(", "string", ",", "http", ".", "HandlerFunc", ")", "{", "return", "pattern", ",", "s", ".", "TracingHandler", "(", "name", ",", "handler", ")", "\n", "}" ]
// It is similar to TracingHandler in regards, that it wraps an existing http.HandlerFunc // into a named instance to support capturing tracing information and data. It, however, // provides a neater way to register the handler with existing frameworks by returning // not only the wrapper, but also the URL-pattern to react on.
[ "It", "is", "similar", "to", "TracingHandler", "in", "regards", "that", "it", "wraps", "an", "existing", "http", ".", "HandlerFunc", "into", "a", "named", "instance", "to", "support", "capturing", "tracing", "information", "and", "data", ".", "It", "however", "provides", "a", "neater", "way", "to", "register", "the", "handler", "with", "existing", "frameworks", "by", "returning", "not", "only", "the", "wrapper", "but", "also", "the", "URL", "-", "pattern", "to", "react", "on", "." ]
9854c6e5d3e8c264693416ef9ee0646fa89cdc18
https://github.com/instana/go-sensor/blob/9854c6e5d3e8c264693416ef9ee0646fa89cdc18/adapters.go#L36-L38
18,092
instana/go-sensor
adapters.go
TracingHandler
func (s *Sensor) TracingHandler(name string, handler http.HandlerFunc) http.HandlerFunc { return func(w http.ResponseWriter, req *http.Request) { s.WithTracingContext(name, w, req, func(span ot.Span, ctx context.Context) { // Capture response code for span hooks := httpsnoop.Hooks{ WriteHeader: func(next httpsnoop.WriteHeaderFunc) httpsnoop.WriteHeaderFunc { return func(code int) { next(code) span.SetTag(string(ext.HTTPStatusCode), code) } }, } // Add hooks to response writer wrappedWriter := httpsnoop.Wrap(w, hooks) // Serve original handler handler.ServeHTTP(wrappedWriter, req.WithContext(ctx)) }) } }
go
func (s *Sensor) TracingHandler(name string, handler http.HandlerFunc) http.HandlerFunc { return func(w http.ResponseWriter, req *http.Request) { s.WithTracingContext(name, w, req, func(span ot.Span, ctx context.Context) { // Capture response code for span hooks := httpsnoop.Hooks{ WriteHeader: func(next httpsnoop.WriteHeaderFunc) httpsnoop.WriteHeaderFunc { return func(code int) { next(code) span.SetTag(string(ext.HTTPStatusCode), code) } }, } // Add hooks to response writer wrappedWriter := httpsnoop.Wrap(w, hooks) // Serve original handler handler.ServeHTTP(wrappedWriter, req.WithContext(ctx)) }) } }
[ "func", "(", "s", "*", "Sensor", ")", "TracingHandler", "(", "name", "string", ",", "handler", "http", ".", "HandlerFunc", ")", "http", ".", "HandlerFunc", "{", "return", "func", "(", "w", "http", ".", "ResponseWriter", ",", "req", "*", "http", ".", "Request", ")", "{", "s", ".", "WithTracingContext", "(", "name", ",", "w", ",", "req", ",", "func", "(", "span", "ot", ".", "Span", ",", "ctx", "context", ".", "Context", ")", "{", "// Capture response code for span", "hooks", ":=", "httpsnoop", ".", "Hooks", "{", "WriteHeader", ":", "func", "(", "next", "httpsnoop", ".", "WriteHeaderFunc", ")", "httpsnoop", ".", "WriteHeaderFunc", "{", "return", "func", "(", "code", "int", ")", "{", "next", "(", "code", ")", "\n", "span", ".", "SetTag", "(", "string", "(", "ext", ".", "HTTPStatusCode", ")", ",", "code", ")", "\n", "}", "\n", "}", ",", "}", "\n\n", "// Add hooks to response writer", "wrappedWriter", ":=", "httpsnoop", ".", "Wrap", "(", "w", ",", "hooks", ")", "\n\n", "// Serve original handler", "handler", ".", "ServeHTTP", "(", "wrappedWriter", ",", "req", ".", "WithContext", "(", "ctx", ")", ")", "\n", "}", ")", "\n", "}", "\n", "}" ]
// Wraps an existing http.HandlerFunc into a named instance to support capturing tracing // information and response data.
[ "Wraps", "an", "existing", "http", ".", "HandlerFunc", "into", "a", "named", "instance", "to", "support", "capturing", "tracing", "information", "and", "response", "data", "." ]
9854c6e5d3e8c264693416ef9ee0646fa89cdc18
https://github.com/instana/go-sensor/blob/9854c6e5d3e8c264693416ef9ee0646fa89cdc18/adapters.go#L42-L62
18,093
instana/go-sensor
adapters.go
TracingHttpRequest
func (s *Sensor) TracingHttpRequest(name string, parent, req *http.Request, client http.Client) (res *http.Response, err error) { var span ot.Span if parentSpan, ok := parent.Context().Value("parentSpan").(ot.Span); ok { span = s.tracer.StartSpan("client", ot.ChildOf(parentSpan.Context())) } else { span = s.tracer.StartSpan("client") } defer span.Finish() headersCarrier := ot.HTTPHeadersCarrier(req.Header) if err := s.tracer.Inject(span.Context(), ot.HTTPHeaders, headersCarrier); err != nil { return nil, err } res, err = client.Do(req.WithContext(context.Background())) span.SetTag(string(ext.SpanKind), string(ext.SpanKindRPCClientEnum)) span.SetTag(string(ext.PeerHostname), req.Host) span.SetTag(string(ext.HTTPUrl), req.URL.String()) span.SetTag(string(ext.HTTPMethod), req.Method) span.SetTag(string(ext.HTTPStatusCode), res.StatusCode) if err != nil { if e, ok := err.(error); ok { span.LogFields(otlog.Error(e)) } else { span.LogFields(otlog.Object("error", err)) } } return }
go
func (s *Sensor) TracingHttpRequest(name string, parent, req *http.Request, client http.Client) (res *http.Response, err error) { var span ot.Span if parentSpan, ok := parent.Context().Value("parentSpan").(ot.Span); ok { span = s.tracer.StartSpan("client", ot.ChildOf(parentSpan.Context())) } else { span = s.tracer.StartSpan("client") } defer span.Finish() headersCarrier := ot.HTTPHeadersCarrier(req.Header) if err := s.tracer.Inject(span.Context(), ot.HTTPHeaders, headersCarrier); err != nil { return nil, err } res, err = client.Do(req.WithContext(context.Background())) span.SetTag(string(ext.SpanKind), string(ext.SpanKindRPCClientEnum)) span.SetTag(string(ext.PeerHostname), req.Host) span.SetTag(string(ext.HTTPUrl), req.URL.String()) span.SetTag(string(ext.HTTPMethod), req.Method) span.SetTag(string(ext.HTTPStatusCode), res.StatusCode) if err != nil { if e, ok := err.(error); ok { span.LogFields(otlog.Error(e)) } else { span.LogFields(otlog.Object("error", err)) } } return }
[ "func", "(", "s", "*", "Sensor", ")", "TracingHttpRequest", "(", "name", "string", ",", "parent", ",", "req", "*", "http", ".", "Request", ",", "client", "http", ".", "Client", ")", "(", "res", "*", "http", ".", "Response", ",", "err", "error", ")", "{", "var", "span", "ot", ".", "Span", "\n", "if", "parentSpan", ",", "ok", ":=", "parent", ".", "Context", "(", ")", ".", "Value", "(", "\"", "\"", ")", ".", "(", "ot", ".", "Span", ")", ";", "ok", "{", "span", "=", "s", ".", "tracer", ".", "StartSpan", "(", "\"", "\"", ",", "ot", ".", "ChildOf", "(", "parentSpan", ".", "Context", "(", ")", ")", ")", "\n", "}", "else", "{", "span", "=", "s", ".", "tracer", ".", "StartSpan", "(", "\"", "\"", ")", "\n", "}", "\n", "defer", "span", ".", "Finish", "(", ")", "\n\n", "headersCarrier", ":=", "ot", ".", "HTTPHeadersCarrier", "(", "req", ".", "Header", ")", "\n", "if", "err", ":=", "s", ".", "tracer", ".", "Inject", "(", "span", ".", "Context", "(", ")", ",", "ot", ".", "HTTPHeaders", ",", "headersCarrier", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "res", ",", "err", "=", "client", ".", "Do", "(", "req", ".", "WithContext", "(", "context", ".", "Background", "(", ")", ")", ")", "\n\n", "span", ".", "SetTag", "(", "string", "(", "ext", ".", "SpanKind", ")", ",", "string", "(", "ext", ".", "SpanKindRPCClientEnum", ")", ")", "\n", "span", ".", "SetTag", "(", "string", "(", "ext", ".", "PeerHostname", ")", ",", "req", ".", "Host", ")", "\n", "span", ".", "SetTag", "(", "string", "(", "ext", ".", "HTTPUrl", ")", ",", "req", ".", "URL", ".", "String", "(", ")", ")", "\n", "span", ".", "SetTag", "(", "string", "(", "ext", ".", "HTTPMethod", ")", ",", "req", ".", "Method", ")", "\n", "span", ".", "SetTag", "(", "string", "(", "ext", ".", "HTTPStatusCode", ")", ",", "res", ".", "StatusCode", ")", "\n\n", "if", "err", "!=", "nil", "{", "if", "e", ",", "ok", ":=", "err", ".", "(", "error", ")", ";", "ok", "{", "span", ".", "LogFields", "(", "otlog", ".", "Error", "(", "e", ")", ")", "\n", "}", "else", "{", "span", ".", "LogFields", "(", "otlog", ".", "Object", "(", "\"", "\"", ",", "err", ")", ")", "\n", "}", "\n", "}", "\n", "return", "\n", "}" ]
// Wraps an existing http.Request instance into a named instance to inject tracing and span // header information into the actual HTTP wire transfer.
[ "Wraps", "an", "existing", "http", ".", "Request", "instance", "into", "a", "named", "instance", "to", "inject", "tracing", "and", "span", "header", "information", "into", "the", "actual", "HTTP", "wire", "transfer", "." ]
9854c6e5d3e8c264693416ef9ee0646fa89cdc18
https://github.com/instana/go-sensor/blob/9854c6e5d3e8c264693416ef9ee0646fa89cdc18/adapters.go#L66-L96
18,094
instana/go-sensor
adapters.go
WithTracingContext
func (s *Sensor) WithTracingContext(name string, w http.ResponseWriter, req *http.Request, f ContextSensitiveFunc) { s.WithTracingSpan(name, w, req, func(span ot.Span) { ctx := context.WithValue(req.Context(), "parentSpan", span) f(span, ctx) }) }
go
func (s *Sensor) WithTracingContext(name string, w http.ResponseWriter, req *http.Request, f ContextSensitiveFunc) { s.WithTracingSpan(name, w, req, func(span ot.Span) { ctx := context.WithValue(req.Context(), "parentSpan", span) f(span, ctx) }) }
[ "func", "(", "s", "*", "Sensor", ")", "WithTracingContext", "(", "name", "string", ",", "w", "http", ".", "ResponseWriter", ",", "req", "*", "http", ".", "Request", ",", "f", "ContextSensitiveFunc", ")", "{", "s", ".", "WithTracingSpan", "(", "name", ",", "w", ",", "req", ",", "func", "(", "span", "ot", ".", "Span", ")", "{", "ctx", ":=", "context", ".", "WithValue", "(", "req", ".", "Context", "(", ")", ",", "\"", "\"", ",", "span", ")", "\n", "f", "(", "span", ",", "ctx", ")", "\n", "}", ")", "\n", "}" ]
// Executes the given ContextSensitiveFunc and executes it under the scope of a newly created context.Context, // that provides access to the parent span as 'parentSpan'.
[ "Executes", "the", "given", "ContextSensitiveFunc", "and", "executes", "it", "under", "the", "scope", "of", "a", "newly", "created", "context", ".", "Context", "that", "provides", "access", "to", "the", "parent", "span", "as", "parentSpan", "." ]
9854c6e5d3e8c264693416ef9ee0646fa89cdc18
https://github.com/instana/go-sensor/blob/9854c6e5d3e8c264693416ef9ee0646fa89cdc18/adapters.go#L152-L157
18,095
instana/go-sensor
eum.go
EumSnippet
func EumSnippet(apiKey string, traceID string, meta map[string]string) string { if len(apiKey) == 0 || len(traceID) == 0 { return "" } b, err := ioutil.ReadFile(eumTemplate) if err != nil { return "" } var snippet = string(b) var metaBuffer bytes.Buffer snippet = strings.Replace(snippet, "$apiKey", apiKey, -1) snippet = strings.Replace(snippet, "$traceId", traceID, -1) for key, value := range meta { metaBuffer.WriteString(" ineum('meta', '" + key + "', '" + value + "');\n") } snippet = strings.Replace(snippet, "$meta", metaBuffer.String(), -1) return snippet }
go
func EumSnippet(apiKey string, traceID string, meta map[string]string) string { if len(apiKey) == 0 || len(traceID) == 0 { return "" } b, err := ioutil.ReadFile(eumTemplate) if err != nil { return "" } var snippet = string(b) var metaBuffer bytes.Buffer snippet = strings.Replace(snippet, "$apiKey", apiKey, -1) snippet = strings.Replace(snippet, "$traceId", traceID, -1) for key, value := range meta { metaBuffer.WriteString(" ineum('meta', '" + key + "', '" + value + "');\n") } snippet = strings.Replace(snippet, "$meta", metaBuffer.String(), -1) return snippet }
[ "func", "EumSnippet", "(", "apiKey", "string", ",", "traceID", "string", ",", "meta", "map", "[", "string", "]", "string", ")", "string", "{", "if", "len", "(", "apiKey", ")", "==", "0", "||", "len", "(", "traceID", ")", "==", "0", "{", "return", "\"", "\"", "\n", "}", "\n\n", "b", ",", "err", ":=", "ioutil", ".", "ReadFile", "(", "eumTemplate", ")", "\n\n", "if", "err", "!=", "nil", "{", "return", "\"", "\"", "\n", "}", "\n\n", "var", "snippet", "=", "string", "(", "b", ")", "\n", "var", "metaBuffer", "bytes", ".", "Buffer", "\n\n", "snippet", "=", "strings", ".", "Replace", "(", "snippet", ",", "\"", "\"", ",", "apiKey", ",", "-", "1", ")", "\n", "snippet", "=", "strings", ".", "Replace", "(", "snippet", ",", "\"", "\"", ",", "traceID", ",", "-", "1", ")", "\n\n", "for", "key", ",", "value", ":=", "range", "meta", "{", "metaBuffer", ".", "WriteString", "(", "\"", "\"", "+", "key", "+", "\"", "\"", "+", "value", "+", "\"", "\\n", "\"", ")", "\n", "}", "\n\n", "snippet", "=", "strings", ".", "Replace", "(", "snippet", ",", "\"", "\"", ",", "metaBuffer", ".", "String", "(", ")", ",", "-", "1", ")", "\n\n", "return", "snippet", "\n", "}" ]
// EumSnippet generates javascript code to initialize JavaScript agent
[ "EumSnippet", "generates", "javascript", "code", "to", "initialize", "JavaScript", "agent" ]
9854c6e5d3e8c264693416ef9ee0646fa89cdc18
https://github.com/instana/go-sensor/blob/9854c6e5d3e8c264693416ef9ee0646fa89cdc18/eum.go#L12-L37
18,096
instana/go-sensor
util.go
Header2ID
func Header2ID(header string) (int64, error) { // FIXME: We're assuming LittleEndian here // Parse unsigned 64 bit hex string into unsigned 64 bit base 10 integer if unsignedID, err := strconv.ParseUint(header, 16, 64); err == nil { // Write out _unsigned_ 64bit integer to byte buffer buf := new(bytes.Buffer) if err = binary.Write(buf, binary.LittleEndian, unsignedID); err == nil { // Read bytes back into _signed_ 64 bit integer var signedID int64 if err = binary.Read(buf, binary.LittleEndian, &signedID); err == nil { // The success case return signedID, nil } log.debug(err) } else { log.debug(err) } } else { log.debug(err) } return int64(0), errors.New("context corrupted; could not convert value") }
go
func Header2ID(header string) (int64, error) { // FIXME: We're assuming LittleEndian here // Parse unsigned 64 bit hex string into unsigned 64 bit base 10 integer if unsignedID, err := strconv.ParseUint(header, 16, 64); err == nil { // Write out _unsigned_ 64bit integer to byte buffer buf := new(bytes.Buffer) if err = binary.Write(buf, binary.LittleEndian, unsignedID); err == nil { // Read bytes back into _signed_ 64 bit integer var signedID int64 if err = binary.Read(buf, binary.LittleEndian, &signedID); err == nil { // The success case return signedID, nil } log.debug(err) } else { log.debug(err) } } else { log.debug(err) } return int64(0), errors.New("context corrupted; could not convert value") }
[ "func", "Header2ID", "(", "header", "string", ")", "(", "int64", ",", "error", ")", "{", "// FIXME: We're assuming LittleEndian here", "// Parse unsigned 64 bit hex string into unsigned 64 bit base 10 integer", "if", "unsignedID", ",", "err", ":=", "strconv", ".", "ParseUint", "(", "header", ",", "16", ",", "64", ")", ";", "err", "==", "nil", "{", "// Write out _unsigned_ 64bit integer to byte buffer", "buf", ":=", "new", "(", "bytes", ".", "Buffer", ")", "\n", "if", "err", "=", "binary", ".", "Write", "(", "buf", ",", "binary", ".", "LittleEndian", ",", "unsignedID", ")", ";", "err", "==", "nil", "{", "// Read bytes back into _signed_ 64 bit integer", "var", "signedID", "int64", "\n", "if", "err", "=", "binary", ".", "Read", "(", "buf", ",", "binary", ".", "LittleEndian", ",", "&", "signedID", ")", ";", "err", "==", "nil", "{", "// The success case", "return", "signedID", ",", "nil", "\n", "}", "\n", "log", ".", "debug", "(", "err", ")", "\n", "}", "else", "{", "log", ".", "debug", "(", "err", ")", "\n", "}", "\n", "}", "else", "{", "log", ".", "debug", "(", "err", ")", "\n", "}", "\n", "return", "int64", "(", "0", ")", ",", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}" ]
// Header2ID converts an header context value into an Instana ID. More // specifically, this converts an unsigned 64 bit hex value into a signed // 64bit integer.
[ "Header2ID", "converts", "an", "header", "context", "value", "into", "an", "Instana", "ID", ".", "More", "specifically", "this", "converts", "an", "unsigned", "64", "bit", "hex", "value", "into", "a", "signed", "64bit", "integer", "." ]
9854c6e5d3e8c264693416ef9ee0646fa89cdc18
https://github.com/instana/go-sensor/blob/9854c6e5d3e8c264693416ef9ee0646fa89cdc18/util.go#L54-L76
18,097
instana/go-sensor
util.go
hexGatewayToAddr
func hexGatewayToAddr(gateway []rune) (string, error) { // gateway address is encoded in reverse order in hex if len(gateway) != 8 { return "", errors.New("invalid gateway length") } var octets [4]uint8 for i, hexOctet := range [4]string{ string(gateway[6:8]), // first octet of IP Address string(gateway[4:6]), // second octet string(gateway[2:4]), // third octet string(gateway[0:2]), // last octet } { octet, err := strconv.ParseUint(hexOctet, 16, 8) if err != nil { return "", err } octets[i] = uint8(octet) } return fmt.Sprintf("%v.%v.%v.%v", octets[0], octets[1], octets[2], octets[3]), nil }
go
func hexGatewayToAddr(gateway []rune) (string, error) { // gateway address is encoded in reverse order in hex if len(gateway) != 8 { return "", errors.New("invalid gateway length") } var octets [4]uint8 for i, hexOctet := range [4]string{ string(gateway[6:8]), // first octet of IP Address string(gateway[4:6]), // second octet string(gateway[2:4]), // third octet string(gateway[0:2]), // last octet } { octet, err := strconv.ParseUint(hexOctet, 16, 8) if err != nil { return "", err } octets[i] = uint8(octet) } return fmt.Sprintf("%v.%v.%v.%v", octets[0], octets[1], octets[2], octets[3]), nil }
[ "func", "hexGatewayToAddr", "(", "gateway", "[", "]", "rune", ")", "(", "string", ",", "error", ")", "{", "// gateway address is encoded in reverse order in hex", "if", "len", "(", "gateway", ")", "!=", "8", "{", "return", "\"", "\"", ",", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n\n", "var", "octets", "[", "4", "]", "uint8", "\n", "for", "i", ",", "hexOctet", ":=", "range", "[", "4", "]", "string", "{", "string", "(", "gateway", "[", "6", ":", "8", "]", ")", ",", "// first octet of IP Address", "string", "(", "gateway", "[", "4", ":", "6", "]", ")", ",", "// second octet", "string", "(", "gateway", "[", "2", ":", "4", "]", ")", ",", "// third octet", "string", "(", "gateway", "[", "0", ":", "2", "]", ")", ",", "// last octet", "}", "{", "octet", ",", "err", ":=", "strconv", ".", "ParseUint", "(", "hexOctet", ",", "16", ",", "8", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "err", "\n", "}", "\n\n", "octets", "[", "i", "]", "=", "uint8", "(", "octet", ")", "\n", "}", "\n\n", "return", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "octets", "[", "0", "]", ",", "octets", "[", "1", "]", ",", "octets", "[", "2", "]", ",", "octets", "[", "3", "]", ")", ",", "nil", "\n", "}" ]
// hexGatewayToAddr converts the hex representation of the gateway address to string.
[ "hexGatewayToAddr", "converts", "the", "hex", "representation", "of", "the", "gateway", "address", "to", "string", "." ]
9854c6e5d3e8c264693416ef9ee0646fa89cdc18
https://github.com/instana/go-sensor/blob/9854c6e5d3e8c264693416ef9ee0646fa89cdc18/util.go#L142-L164
18,098
instana/go-sensor
event.go
SendDefaultServiceEvent
func SendDefaultServiceEvent(title string, text string, sev severity, duration time.Duration) { if sensor == nil { // Since no sensor was initialized, there is no default service (as // configured on the sensor) so we send blank. SendServiceEvent("", title, text, sev, duration) } else { SendServiceEvent(sensor.serviceName, title, text, sev, duration) } }
go
func SendDefaultServiceEvent(title string, text string, sev severity, duration time.Duration) { if sensor == nil { // Since no sensor was initialized, there is no default service (as // configured on the sensor) so we send blank. SendServiceEvent("", title, text, sev, duration) } else { SendServiceEvent(sensor.serviceName, title, text, sev, duration) } }
[ "func", "SendDefaultServiceEvent", "(", "title", "string", ",", "text", "string", ",", "sev", "severity", ",", "duration", "time", ".", "Duration", ")", "{", "if", "sensor", "==", "nil", "{", "// Since no sensor was initialized, there is no default service (as", "// configured on the sensor) so we send blank.", "SendServiceEvent", "(", "\"", "\"", ",", "title", ",", "text", ",", "sev", ",", "duration", ")", "\n", "}", "else", "{", "SendServiceEvent", "(", "sensor", ".", "serviceName", ",", "title", ",", "text", ",", "sev", ",", "duration", ")", "\n", "}", "\n", "}" ]
// SendDefaultServiceEvent sends a default event which already contains the service and host
[ "SendDefaultServiceEvent", "sends", "a", "default", "event", "which", "already", "contains", "the", "service", "and", "host" ]
9854c6e5d3e8c264693416ef9ee0646fa89cdc18
https://github.com/instana/go-sensor/blob/9854c6e5d3e8c264693416ef9ee0646fa89cdc18/event.go#L36-L44
18,099
instana/go-sensor
event.go
SendServiceEvent
func SendServiceEvent(service string, title string, text string, sev severity, duration time.Duration) { sendEvent(&EventData{ Title: title, Text: text, Severity: int(sev), Plugin: ServicePlugin, ID: service, Host: ServiceHost, Duration: int(duration / time.Millisecond), }) }
go
func SendServiceEvent(service string, title string, text string, sev severity, duration time.Duration) { sendEvent(&EventData{ Title: title, Text: text, Severity: int(sev), Plugin: ServicePlugin, ID: service, Host: ServiceHost, Duration: int(duration / time.Millisecond), }) }
[ "func", "SendServiceEvent", "(", "service", "string", ",", "title", "string", ",", "text", "string", ",", "sev", "severity", ",", "duration", "time", ".", "Duration", ")", "{", "sendEvent", "(", "&", "EventData", "{", "Title", ":", "title", ",", "Text", ":", "text", ",", "Severity", ":", "int", "(", "sev", ")", ",", "Plugin", ":", "ServicePlugin", ",", "ID", ":", "service", ",", "Host", ":", "ServiceHost", ",", "Duration", ":", "int", "(", "duration", "/", "time", ".", "Millisecond", ")", ",", "}", ")", "\n", "}" ]
// SendServiceEvent send an event on a specific service
[ "SendServiceEvent", "send", "an", "event", "on", "a", "specific", "service" ]
9854c6e5d3e8c264693416ef9ee0646fa89cdc18
https://github.com/instana/go-sensor/blob/9854c6e5d3e8c264693416ef9ee0646fa89cdc18/event.go#L47-L57