repo
stringlengths
5
67
sha
stringlengths
40
40
path
stringlengths
4
234
url
stringlengths
85
339
language
stringclasses
6 values
split
stringclasses
3 values
doc
stringlengths
3
51.2k
sign
stringlengths
5
8.01k
problem
stringlengths
13
51.2k
output
stringlengths
0
3.87M
beego/bee
6a86284cec9a17f9aae6fe82ecf3c436aafed68d
generate/g_appcode.go
https://github.com/beego/bee/blob/6a86284cec9a17f9aae6fe82ecf3c436aafed68d/generate/g_appcode.go#L803-L842
go
train
// writeControllerFiles generates controller files
func writeControllerFiles(tables []*Table, cPath string, pkgPath string)
// writeControllerFiles generates controller files func writeControllerFiles(tables []*Table, cPath string, pkgPath string)
{ w := colors.NewColorWriter(os.Stdout) for _, tb := range tables { if tb.Pk == "" { continue } filename := getFileName(tb.Name) fpath := path.Join(cPath, filename+".go") var f *os.File var err error if utils.IsExist(fpath) { beeLogger.Log.Warnf("'%s' already exists. Do you want to overwrite it? [Yes|No] ", fpath) if utils.AskForConfirmation() { f, err = os.OpenFile(fpath, os.O_RDWR|os.O_TRUNC, 0666) if err != nil { beeLogger.Log.Warnf("%s", err) continue } } else { beeLogger.Log.Warnf("Skipped create file '%s'", fpath) continue } } else { f, err = os.OpenFile(fpath, os.O_CREATE|os.O_RDWR, 0666) if err != nil { beeLogger.Log.Warnf("%s", err) continue } } fileStr := strings.Replace(CtrlTPL, "{{ctrlName}}", utils.CamelCase(tb.Name), -1) fileStr = strings.Replace(fileStr, "{{pkgPath}}", pkgPath, -1) if _, err := f.WriteString(fileStr); err != nil { beeLogger.Log.Fatalf("Could not write controller file to '%s': %s", fpath, err) } utils.CloseFile(f) fmt.Fprintf(w, "\t%s%screate%s\t %s%s\n", "\x1b[32m", "\x1b[1m", "\x1b[21m", fpath, "\x1b[0m") utils.FormatSourceCode(fpath) } }
beego/bee
6a86284cec9a17f9aae6fe82ecf3c436aafed68d
generate/g_appcode.go
https://github.com/beego/bee/blob/6a86284cec9a17f9aae6fe82ecf3c436aafed68d/generate/g_appcode.go#L845-L889
go
train
// writeRouterFile generates router file
func writeRouterFile(tables []*Table, rPath string, pkgPath string)
// writeRouterFile generates router file func writeRouterFile(tables []*Table, rPath string, pkgPath string)
{ w := colors.NewColorWriter(os.Stdout) var nameSpaces []string for _, tb := range tables { if tb.Pk == "" { continue } // Add namespaces nameSpace := strings.Replace(NamespaceTPL, "{{nameSpace}}", tb.Name, -1) nameSpace = strings.Replace(nameSpace, "{{ctrlName}}", utils.CamelCase(tb.Name), -1) nameSpaces = append(nameSpaces, nameSpace) } // Add export controller fpath := filepath.Join(rPath, "router.go") routerStr := strings.Replace(RouterTPL, "{{nameSpaces}}", strings.Join(nameSpaces, ""), 1) routerStr = strings.Replace(routerStr, "{{pkgPath}}", pkgPath, 1) var f *os.File var err error if utils.IsExist(fpath) { beeLogger.Log.Warnf("'%s' already exists. Do you want to overwrite it? [Yes|No] ", fpath) if utils.AskForConfirmation() { f, err = os.OpenFile(fpath, os.O_RDWR|os.O_TRUNC, 0666) if err != nil { beeLogger.Log.Warnf("%s", err) return } } else { beeLogger.Log.Warnf("Skipped create file '%s'", fpath) return } } else { f, err = os.OpenFile(fpath, os.O_CREATE|os.O_RDWR, 0666) if err != nil { beeLogger.Log.Warnf("%s", err) return } } if _, err := f.WriteString(routerStr); err != nil { beeLogger.Log.Fatalf("Could not write router file to '%s': %s", fpath, err) } utils.CloseFile(f) fmt.Fprintf(w, "\t%s%screate%s\t %s%s\n", "\x1b[32m", "\x1b[1m", "\x1b[21m", fpath, "\x1b[0m") utils.FormatSourceCode(fpath) }
beego/bee
6a86284cec9a17f9aae6fe82ecf3c436aafed68d
generate/g_appcode.go
https://github.com/beego/bee/blob/6a86284cec9a17f9aae6fe82ecf3c436aafed68d/generate/g_appcode.go#L919-L923
go
train
// extractColSize extracts field size: e.g. varchar(255) => 255
func extractColSize(colType string) string
// extractColSize extracts field size: e.g. varchar(255) => 255 func extractColSize(colType string) string
{ regex := regexp.MustCompile(`^[a-z]+\(([0-9]+)\)$`) size := regex.FindStringSubmatch(colType) return size[1] }
beego/bee
6a86284cec9a17f9aae6fe82ecf3c436aafed68d
generate/g_hproseappcode.go
https://github.com/beego/bee/blob/6a86284cec9a17f9aae6fe82ecf3c436aafed68d/generate/g_hproseappcode.go#L308-L326
go
train
// Generate takes table, column and foreign key information from database connection // and generate corresponding golang source files
func genHprose(dbms, connStr string, mode byte, selectedTableNames map[string]bool, currpath string)
// Generate takes table, column and foreign key information from database connection // and generate corresponding golang source files func genHprose(dbms, connStr string, mode byte, selectedTableNames map[string]bool, currpath string)
{ db, err := sql.Open(dbms, connStr) if err != nil { beeLogger.Log.Fatalf("Could not connect to '%s' database using '%s': %s", dbms, connStr, err) } defer db.Close() if trans, ok := dbDriver[dbms]; ok { beeLogger.Log.Info("Analyzing database tables...") tableNames := trans.GetTableNames(db) tables := getTableObjects(tableNames, db, trans) mvcPath := new(MvcPath) mvcPath.ModelPath = path.Join(currpath, "models") createPaths(mode, mvcPath) pkgPath := getPackagePath(currpath) writeHproseSourceFiles(pkgPath, tables, mode, mvcPath, selectedTableNames) } else { beeLogger.Log.Fatalf("Generating app code from '%s' database is not supported yet", dbms) } }
beego/bee
6a86284cec9a17f9aae6fe82ecf3c436aafed68d
generate/g_hproseappcode.go
https://github.com/beego/bee/blob/6a86284cec9a17f9aae6fe82ecf3c436aafed68d/generate/g_hproseappcode.go#L331-L336
go
train
// writeHproseSourceFiles generates source files for model/controller/router // It will wipe the following directories and recreate them:./models, ./controllers, ./routers // Newly geneated files will be inside these folders.
func writeHproseSourceFiles(pkgPath string, tables []*Table, mode byte, paths *MvcPath, selectedTables map[string]bool)
// writeHproseSourceFiles generates source files for model/controller/router // It will wipe the following directories and recreate them:./models, ./controllers, ./routers // Newly geneated files will be inside these folders. func writeHproseSourceFiles(pkgPath string, tables []*Table, mode byte, paths *MvcPath, selectedTables map[string]bool)
{ if (OModel & mode) == OModel { beeLogger.Log.Info("Creating model files...") writeHproseModelFiles(tables, paths.ModelPath, selectedTables) } }
beego/bee
6a86284cec9a17f9aae6fe82ecf3c436aafed68d
generate/g_views.go
https://github.com/beego/bee/blob/6a86284cec9a17f9aae6fe82ecf3c436aafed68d/generate/g_views.go#L29-L75
go
train
// recipe // admin/recipe
func GenerateView(viewpath, currpath string)
// recipe // admin/recipe func GenerateView(viewpath, currpath string)
{ w := colors.NewColorWriter(os.Stdout) beeLogger.Log.Info("Generating view...") absViewPath := path.Join(currpath, "views", viewpath) err := os.MkdirAll(absViewPath, os.ModePerm) if err != nil { beeLogger.Log.Fatalf("Could not create '%s' view: %s", viewpath, err) } cfile := path.Join(absViewPath, "index.tpl") if f, err := os.OpenFile(cfile, os.O_CREATE|os.O_EXCL|os.O_RDWR, 0666); err == nil { defer utils.CloseFile(f) f.WriteString(cfile) fmt.Fprintf(w, "\t%s%screate%s\t %s%s\n", "\x1b[32m", "\x1b[1m", "\x1b[21m", cfile, "\x1b[0m") } else { beeLogger.Log.Fatalf("Could not create view file: %s", err) } cfile = path.Join(absViewPath, "show.tpl") if f, err := os.OpenFile(cfile, os.O_CREATE|os.O_EXCL|os.O_RDWR, 0666); err == nil { defer utils.CloseFile(f) f.WriteString(cfile) fmt.Fprintf(w, "\t%s%screate%s\t %s%s\n", "\x1b[32m", "\x1b[1m", "\x1b[21m", cfile, "\x1b[0m") } else { beeLogger.Log.Fatalf("Could not create view file: %s", err) } cfile = path.Join(absViewPath, "create.tpl") if f, err := os.OpenFile(cfile, os.O_CREATE|os.O_EXCL|os.O_RDWR, 0666); err == nil { defer utils.CloseFile(f) f.WriteString(cfile) fmt.Fprintf(w, "\t%s%screate%s\t %s%s\n", "\x1b[32m", "\x1b[1m", "\x1b[21m", cfile, "\x1b[0m") } else { beeLogger.Log.Fatalf("Could not create view file: %s", err) } cfile = path.Join(absViewPath, "edit.tpl") if f, err := os.OpenFile(cfile, os.O_CREATE|os.O_EXCL|os.O_RDWR, 0666); err == nil { defer utils.CloseFile(f) f.WriteString(cfile) fmt.Fprintf(w, "\t%s%screate%s\t %s%s\n", "\x1b[32m", "\x1b[1m", "\x1b[21m", cfile, "\x1b[0m") } else { beeLogger.Log.Fatalf("Could not create view file: %s", err) } }
beego/bee
6a86284cec9a17f9aae6fe82ecf3c436aafed68d
cmd/commands/version/banner.go
https://github.com/beego/bee/blob/6a86284cec9a17f9aae6fe82ecf3c436aafed68d/cmd/commands/version/banner.go#L31-L42
go
train
// InitBanner loads the banner and prints it to output // All errors are ignored, the application will not // print the banner in case of error.
func InitBanner(out io.Writer, in io.Reader)
// InitBanner loads the banner and prints it to output // All errors are ignored, the application will not // print the banner in case of error. func InitBanner(out io.Writer, in io.Reader)
{ if in == nil { beeLogger.Log.Fatal("The input is nil") } banner, err := ioutil.ReadAll(in) if err != nil { beeLogger.Log.Fatalf("Error while trying to read the banner: %s", err) } show(out, string(banner)) }
beego/bee
6a86284cec9a17f9aae6fe82ecf3c436aafed68d
cmd/commands/command.go
https://github.com/beego/bee/blob/6a86284cec9a17f9aae6fe82ecf3c436aafed68d/cmd/commands/command.go#L64-L69
go
train
// Out returns the out writer of the current command. // If cmd.output is nil, os.Stderr is used.
func (c *Command) Out() io.Writer
// Out returns the out writer of the current command. // If cmd.output is nil, os.Stderr is used. func (c *Command) Out() io.Writer
{ if c.output != nil { return *c.output } return colors.NewColorWriter(os.Stderr) }
beego/bee
6a86284cec9a17f9aae6fe82ecf3c436aafed68d
cmd/commands/run/reload.go
https://github.com/beego/bee/blob/6a86284cec9a17f9aae6fe82ecf3c436aafed68d/cmd/commands/run/reload.go#L64-L79
go
train
// readPump pumps messages from the websocket connection to the broker.
func (c *wsClient) readPump()
// readPump pumps messages from the websocket connection to the broker. func (c *wsClient) readPump()
{ defer func() { c.broker.unregister <- c c.conn.Close() }() for { _, _, err := c.conn.ReadMessage() if err != nil { if websocket.IsUnexpectedCloseError(err, websocket.CloseGoingAway) { beeLogger.Log.Errorf("An error happened when reading from the Websocket client: %v", err) } break } } }
beego/bee
6a86284cec9a17f9aae6fe82ecf3c436aafed68d
cmd/commands/run/reload.go
https://github.com/beego/bee/blob/6a86284cec9a17f9aae6fe82ecf3c436aafed68d/cmd/commands/run/reload.go#L82-L85
go
train
// write writes a message with the given message type and payload.
func (c *wsClient) write(mt int, payload []byte) error
// write writes a message with the given message type and payload. func (c *wsClient) write(mt int, payload []byte) error
{ c.conn.SetWriteDeadline(time.Now().Add(writeWait)) return c.conn.WriteMessage(mt, payload) }
beego/bee
6a86284cec9a17f9aae6fe82ecf3c436aafed68d
cmd/commands/run/reload.go
https://github.com/beego/bee/blob/6a86284cec9a17f9aae6fe82ecf3c436aafed68d/cmd/commands/run/reload.go#L176-L192
go
train
// handleWsRequest handles websocket requests from the peer.
func handleWsRequest(broker *wsBroker, w http.ResponseWriter, r *http.Request)
// handleWsRequest handles websocket requests from the peer. func handleWsRequest(broker *wsBroker, w http.ResponseWriter, r *http.Request)
{ conn, err := upgrader.Upgrade(w, r, nil) if err != nil { beeLogger.Log.Errorf("error while upgrading server connection: %v", err) return } client := &wsClient{ broker: broker, conn: conn, send: make(chan []byte, 256), } client.broker.register <- client go client.writePump() client.readPump() }
beego/bee
6a86284cec9a17f9aae6fe82ecf3c436aafed68d
config/conf.go
https://github.com/beego/bee/blob/6a86284cec9a17f9aae6fe82ecf3c436aafed68d/config/conf.go#L86-L138
go
train
// LoadConfig loads the bee tool configuration. // It looks for Beefile or bee.json in the current path, // and falls back to default configuration in case not found.
func LoadConfig()
// LoadConfig loads the bee tool configuration. // It looks for Beefile or bee.json in the current path, // and falls back to default configuration in case not found. func LoadConfig()
{ currentPath, err := os.Getwd() if err != nil { beeLogger.Log.Error(err.Error()) } dir, err := os.Open(currentPath) if err != nil { beeLogger.Log.Error(err.Error()) } defer dir.Close() files, err := dir.Readdir(-1) if err != nil { beeLogger.Log.Error(err.Error()) } for _, file := range files { switch file.Name() { case "bee.json": { err = parseJSON(filepath.Join(currentPath, file.Name()), &Conf) if err != nil { beeLogger.Log.Errorf("Failed to parse JSON file: %s", err) } break } case "Beefile": { err = parseYAML(filepath.Join(currentPath, file.Name()), &Conf) if err != nil { beeLogger.Log.Errorf("Failed to parse YAML file: %s", err) } break } } } // Check format version if Conf.Version != confVer { beeLogger.Log.Warn("Your configuration file is outdated. Please do consider updating it.") beeLogger.Log.Hint("Check the latest version of bee's configuration file.") } // Set variables if len(Conf.DirStruct.Controllers) == 0 { Conf.DirStruct.Controllers = "controllers" } if len(Conf.DirStruct.Models) == 0 { Conf.DirStruct.Models = "models" } }
beego/bee
6a86284cec9a17f9aae6fe82ecf3c436aafed68d
utils/utils.go
https://github.com/beego/bee/blob/6a86284cec9a17f9aae6fe82ecf3c436aafed68d/utils/utils.go#L38-L44
go
train
// Go is a basic promise implementation: it wraps calls a function in a goroutine // and returns a channel which will later return the function's return value.
func Go(f func() error) chan error
// Go is a basic promise implementation: it wraps calls a function in a goroutine // and returns a channel which will later return the function's return value. func Go(f func() error) chan error
{ ch := make(chan error) go func() { ch <- f() }() return ch }
beego/bee
6a86284cec9a17f9aae6fe82ecf3c436aafed68d
utils/utils.go
https://github.com/beego/bee/blob/6a86284cec9a17f9aae6fe82ecf3c436aafed68d/utils/utils.go#L53-L59
go
train
// GetGOPATHs returns all paths in GOPATH variable.
func GetGOPATHs() []string
// GetGOPATHs returns all paths in GOPATH variable. func GetGOPATHs() []string
{ gopath := os.Getenv("GOPATH") if gopath == "" && strings.Compare(runtime.Version(), "go1.8") >= 0 { gopath = defaultGOPATH() } return filepath.SplitList(gopath) }
beego/bee
6a86284cec9a17f9aae6fe82ecf3c436aafed68d
utils/utils.go
https://github.com/beego/bee/blob/6a86284cec9a17f9aae6fe82ecf3c436aafed68d/utils/utils.go#L62-L69
go
train
// IsInGOPATH checks whether the path is inside of any GOPATH or not
func IsInGOPATH(thePath string) bool
// IsInGOPATH checks whether the path is inside of any GOPATH or not func IsInGOPATH(thePath string) bool
{ for _, gopath := range GetGOPATHs() { if strings.Contains(thePath, filepath.Join(gopath, "src")) { return true } } return false }
beego/bee
6a86284cec9a17f9aae6fe82ecf3c436aafed68d
utils/utils.go
https://github.com/beego/bee/blob/6a86284cec9a17f9aae6fe82ecf3c436aafed68d/utils/utils.go#L72-L109
go
train
// IsBeegoProject checks whether the current path is a Beego application or not
func IsBeegoProject(thePath string) bool
// IsBeegoProject checks whether the current path is a Beego application or not func IsBeegoProject(thePath string) bool
{ mainFiles := []string{} hasBeegoRegex := regexp.MustCompile(`(?s)package main.*?import.*?\(.*?github.com/astaxie/beego".*?\).*func main()`) c := make(chan error) // Walk the application path tree to look for main files. // Main files must satisfy the 'hasBeegoRegex' regular expression. go func() { filepath.Walk(thePath, func(fpath string, f os.FileInfo, err error) error { if err != nil { return nil } // Skip sub-directories if !f.IsDir() { var data []byte data, err = ioutil.ReadFile(fpath) if err != nil { c <- err return nil } if len(hasBeegoRegex.Find(data)) > 0 { mainFiles = append(mainFiles, fpath) } } return nil }) close(c) }() if err := <-c; err != nil { beeLogger.Log.Fatalf("Unable to walk '%s' tree: %s", thePath, err) } if len(mainFiles) > 0 { return true } return false }
beego/bee
6a86284cec9a17f9aae6fe82ecf3c436aafed68d
utils/utils.go
https://github.com/beego/bee/blob/6a86284cec9a17f9aae6fe82ecf3c436aafed68d/utils/utils.go#L113-L135
go
train
// SearchGOPATHs searchs the user GOPATH(s) for the specified application name. // It returns a boolean, the application's GOPATH and its full path.
func SearchGOPATHs(app string) (bool, string, string)
// SearchGOPATHs searchs the user GOPATH(s) for the specified application name. // It returns a boolean, the application's GOPATH and its full path. func SearchGOPATHs(app string) (bool, string, string)
{ gps := GetGOPATHs() if len(gps) == 0 { beeLogger.Log.Fatal("GOPATH environment variable is not set or empty") } // Lookup the application inside the user workspace(s) for _, gopath := range gps { var currentPath string if !strings.Contains(app, "src") { gopathsrc := path.Join(gopath, "src") currentPath = path.Join(gopathsrc, app) } else { currentPath = app } if IsExist(currentPath) { return true, gopath, currentPath } } return false, "", "" }
beego/bee
6a86284cec9a17f9aae6fe82ecf3c436aafed68d
utils/utils.go
https://github.com/beego/bee/blob/6a86284cec9a17f9aae6fe82ecf3c436aafed68d/utils/utils.go#L142-L158
go
train
// askForConfirmation uses Scanln to parse user input. A user must type in "yes" or "no" and // then press enter. It has fuzzy matching, so "y", "Y", "yes", "YES", and "Yes" all count as // confirmations. If the input is not recognized, it will ask again. The function does not return // until it gets a valid response from the user. Typically, you should use fmt to print out a question // before calling askForConfirmation. E.g. fmt.Println("WARNING: Are you sure? (yes/no)")
func AskForConfirmation() bool
// askForConfirmation uses Scanln to parse user input. A user must type in "yes" or "no" and // then press enter. It has fuzzy matching, so "y", "Y", "yes", "YES", and "Yes" all count as // confirmations. If the input is not recognized, it will ask again. The function does not return // until it gets a valid response from the user. Typically, you should use fmt to print out a question // before calling askForConfirmation. E.g. fmt.Println("WARNING: Are you sure? (yes/no)") func AskForConfirmation() bool
{ var response string _, err := fmt.Scanln(&response) if err != nil { beeLogger.Log.Fatalf("%s", err) } okayResponses := []string{"y", "Y", "yes", "Yes", "YES"} nokayResponses := []string{"n", "N", "no", "No", "NO"} if containsString(okayResponses, response) { return true } else if containsString(nokayResponses, response) { return false } else { fmt.Println("Please type yes or no and then press enter:") return AskForConfirmation() } }
beego/bee
6a86284cec9a17f9aae6fe82ecf3c436aafed68d
utils/utils.go
https://github.com/beego/bee/blob/6a86284cec9a17f9aae6fe82ecf3c436aafed68d/utils/utils.go#L170-L185
go
train
// snake string, XxYy to xx_yy
func SnakeString(s string) string
// snake string, XxYy to xx_yy func SnakeString(s string) string
{ data := make([]byte, 0, len(s)*2) j := false num := len(s) for i := 0; i < num; i++ { d := s[i] if i > 0 && d >= 'A' && d <= 'Z' && j { data = append(data, '_') } if d != '_' { j = true } data = append(data, d) } return strings.ToLower(string(data[:])) }
beego/bee
6a86284cec9a17f9aae6fe82ecf3c436aafed68d
utils/utils.go
https://github.com/beego/bee/blob/6a86284cec9a17f9aae6fe82ecf3c436aafed68d/utils/utils.go#L213-L219
go
train
// camelCase converts a _ delimited string to camel case // e.g. very_important_person => VeryImportantPerson
func CamelCase(in string) string
// camelCase converts a _ delimited string to camel case // e.g. very_important_person => VeryImportantPerson func CamelCase(in string) string
{ tokens := strings.Split(in, "_") for i := range tokens { tokens[i] = strings.Title(strings.Trim(tokens[i], " ")) } return strings.Join(tokens, "") }
beego/bee
6a86284cec9a17f9aae6fe82ecf3c436aafed68d
utils/utils.go
https://github.com/beego/bee/blob/6a86284cec9a17f9aae6fe82ecf3c436aafed68d/utils/utils.go#L222-L227
go
train
// formatSourceCode formats source files
func FormatSourceCode(filename string)
// formatSourceCode formats source files func FormatSourceCode(filename string)
{ cmd := exec.Command("gofmt", "-w", filename) if err := cmd.Run(); err != nil { beeLogger.Log.Warnf("Error while running gofmt: %s", err) } }
beego/bee
6a86284cec9a17f9aae6fe82ecf3c436aafed68d
utils/utils.go
https://github.com/beego/bee/blob/6a86284cec9a17f9aae6fe82ecf3c436aafed68d/utils/utils.go#L244-L250
go
train
// WriteToFile creates a file and writes content to it
func WriteToFile(filename, content string)
// WriteToFile creates a file and writes content to it func WriteToFile(filename, content string)
{ f, err := os.Create(filename) MustCheck(err) defer CloseFile(f) _, err = f.WriteString(content) MustCheck(err) }
beego/bee
6a86284cec9a17f9aae6fe82ecf3c436aafed68d
utils/utils.go
https://github.com/beego/bee/blob/6a86284cec9a17f9aae6fe82ecf3c436aafed68d/utils/utils.go#L265-L274
go
train
// BeeFuncMap returns a FuncMap of functions used in different templates.
func BeeFuncMap() template.FuncMap
// BeeFuncMap returns a FuncMap of functions used in different templates. func BeeFuncMap() template.FuncMap
{ return template.FuncMap{ "trim": strings.TrimSpace, "bold": colors.Bold, "headline": colors.MagentaBold, "foldername": colors.RedBold, "endline": EndLine, "tmpltostr": TmplToString, } }
beego/bee
6a86284cec9a17f9aae6fe82ecf3c436aafed68d
utils/utils.go
https://github.com/beego/bee/blob/6a86284cec9a17f9aae6fe82ecf3c436aafed68d/utils/utils.go#L277-L286
go
train
// TmplToString parses a text template and return the result as a string.
func TmplToString(tmpl string, data interface{}) string
// TmplToString parses a text template and return the result as a string. func TmplToString(tmpl string, data interface{}) string
{ t := template.New("tmpl").Funcs(BeeFuncMap()) template.Must(t.Parse(tmpl)) var doc bytes.Buffer err := t.Execute(&doc, data) MustCheck(err) return doc.String() }
beego/bee
6a86284cec9a17f9aae6fe82ecf3c436aafed68d
utils/utils.go
https://github.com/beego/bee/blob/6a86284cec9a17f9aae6fe82ecf3c436aafed68d/utils/utils.go#L356-L408
go
train
// SplitQuotedFields is like strings.Fields but ignores spaces // inside areas surrounded by single quotes. // To specify a single quote use backslash to escape it: '\''
func SplitQuotedFields(in string) []string
// SplitQuotedFields is like strings.Fields but ignores spaces // inside areas surrounded by single quotes. // To specify a single quote use backslash to escape it: '\'' func SplitQuotedFields(in string) []string
{ type stateEnum int const ( inSpace stateEnum = iota inField inQuote inQuoteEscaped ) state := inSpace r := []string{} var buf bytes.Buffer for _, ch := range in { switch state { case inSpace: if ch == '\'' { state = inQuote } else if !unicode.IsSpace(ch) { buf.WriteRune(ch) state = inField } case inField: if ch == '\'' { state = inQuote } else if unicode.IsSpace(ch) { r = append(r, buf.String()) buf.Reset() } else { buf.WriteRune(ch) } case inQuote: if ch == '\'' { state = inField } else if ch == '\\' { state = inQuoteEscaped } else { buf.WriteRune(ch) } case inQuoteEscaped: buf.WriteRune(ch) state = inQuote } } if buf.Len() != 0 { r = append(r, buf.String()) } return r }
beego/bee
6a86284cec9a17f9aae6fe82ecf3c436aafed68d
utils/utils.go
https://github.com/beego/bee/blob/6a86284cec9a17f9aae6fe82ecf3c436aafed68d/utils/utils.go#L411-L427
go
train
// GetFileModTime returns unix timestamp of `os.File.ModTime` for the given path.
func GetFileModTime(path string) int64
// GetFileModTime returns unix timestamp of `os.File.ModTime` for the given path. func GetFileModTime(path string) int64
{ path = strings.Replace(path, "\\", "/", -1) f, err := os.Open(path) if err != nil { beeLogger.Log.Errorf("Failed to open file on '%s': %s", path, err) return time.Now().Unix() } defer f.Close() fi, err := f.Stat() if err != nil { beeLogger.Log.Errorf("Failed to get file stats: %s", err) return time.Now().Unix() } return fi.ModTime().Unix() }
beego/bee
6a86284cec9a17f9aae6fe82ecf3c436aafed68d
cmd/commands/migrate/migrate.go
https://github.com/beego/bee/blob/6a86284cec9a17f9aae6fe82ecf3c436aafed68d/cmd/commands/migrate/migrate.go#L71-L140
go
train
// runMigration is the entry point for starting a migration
func RunMigration(cmd *commands.Command, args []string) int
// runMigration is the entry point for starting a migration func RunMigration(cmd *commands.Command, args []string) int
{ currpath, _ := os.Getwd() gps := utils.GetGOPATHs() if len(gps) == 0 { beeLogger.Log.Fatal("GOPATH environment variable is not set or empty") } gopath := gps[0] beeLogger.Log.Debugf("GOPATH: %s", utils.FILE(), utils.LINE(), gopath) // Getting command line arguments if len(args) != 0 { cmd.Flag.Parse(args[1:]) } if mDriver == "" { mDriver = utils.DocValue(config.Conf.Database.Driver) if mDriver == "" { mDriver = "mysql" } } if mConn == "" { mConn = utils.DocValue(config.Conf.Database.Conn) if mConn == "" { mConn = "root:@tcp(127.0.0.1:3306)/test" } } if mDir == "" { mDir = utils.DocValue(config.Conf.Database.Dir) if mDir == "" { mDir = utils.DocValue(path.Join(currpath, "database", "migrations")) } } beeLogger.Log.Infof("Using '%s' as 'driver'", mDriver) //Log sensitive connection information only when DEBUG is set to true. beeLogger.Log.Debugf("Conn: %s", utils.FILE(), utils.LINE(), mConn) beeLogger.Log.Infof("Using '%s' as 'dir'", mDir) driverStr, connStr, dirStr := string(mDriver), string(mConn), string(mDir) dirRune := []rune(dirStr) if dirRune[0] != '/' && dirRune[1] != ':' { dirStr = path.Join(currpath, dirStr) } if len(args) == 0 { // run all outstanding migrations beeLogger.Log.Info("Running all outstanding migrations") MigrateUpdate(currpath, driverStr, connStr, dirStr) } else { mcmd := args[0] switch mcmd { case "rollback": beeLogger.Log.Info("Rolling back the last migration operation") MigrateRollback(currpath, driverStr, connStr, dirStr) case "reset": beeLogger.Log.Info("Reseting all migrations") MigrateReset(currpath, driverStr, connStr, dirStr) case "refresh": beeLogger.Log.Info("Refreshing all migrations") MigrateRefresh(currpath, driverStr, connStr, dirStr) default: beeLogger.Log.Fatal("Command is missing") } } beeLogger.Log.Success("Migration successful!") return 0 }
beego/bee
6a86284cec9a17f9aae6fe82ecf3c436aafed68d
cmd/commands/migrate/migrate.go
https://github.com/beego/bee/blob/6a86284cec9a17f9aae6fe82ecf3c436aafed68d/cmd/commands/migrate/migrate.go#L143-L168
go
train
// migrate generates source code, build it, and invoke the binary who does the actual migration
func migrate(goal, currpath, driver, connStr, dir string)
// migrate generates source code, build it, and invoke the binary who does the actual migration func migrate(goal, currpath, driver, connStr, dir string)
{ if dir == "" { dir = path.Join(currpath, "database", "migrations") } postfix := "" if runtime.GOOS == "windows" { postfix = ".exe" } binary := "m" + postfix source := binary + ".go" // Connect to database db, err := sql.Open(driver, connStr) if err != nil { beeLogger.Log.Fatalf("Could not connect to database using '%s': %s", connStr, err) } defer db.Close() checkForSchemaUpdateTable(db, driver) latestName, latestTime := getLatestMigration(db, goal) writeMigrationSourceFile(dir, source, driver, connStr, latestTime, latestName, goal) buildMigrationBinary(dir, binary) runMigrationBinary(dir, binary) removeTempFile(dir, source) removeTempFile(dir, binary) }
beego/bee
6a86284cec9a17f9aae6fe82ecf3c436aafed68d
cmd/commands/migrate/migrate.go
https://github.com/beego/bee/blob/6a86284cec9a17f9aae6fe82ecf3c436aafed68d/cmd/commands/migrate/migrate.go#L172-L217
go
train
// checkForSchemaUpdateTable checks the existence of migrations table. // It checks for the proper table structures and creates the table using MYSQL_MIGRATION_DDL if it does not exist.
func checkForSchemaUpdateTable(db *sql.DB, driver string)
// checkForSchemaUpdateTable checks the existence of migrations table. // It checks for the proper table structures and creates the table using MYSQL_MIGRATION_DDL if it does not exist. func checkForSchemaUpdateTable(db *sql.DB, driver string)
{ showTableSQL := showMigrationsTableSQL(driver) if rows, err := db.Query(showTableSQL); err != nil { beeLogger.Log.Fatalf("Could not show migrations table: %s", err) } else if !rows.Next() { // No migrations table, create new ones createTableSQL := createMigrationsTableSQL(driver) beeLogger.Log.Infof("Creating 'migrations' table...") if _, err := db.Query(createTableSQL); err != nil { beeLogger.Log.Fatalf("Could not create migrations table: %s", err) } } // Checking that migrations table schema are expected selectTableSQL := selectMigrationsTableSQL(driver) if rows, err := db.Query(selectTableSQL); err != nil { beeLogger.Log.Fatalf("Could not show columns of migrations table: %s", err) } else { for rows.Next() { var fieldBytes, typeBytes, nullBytes, keyBytes, defaultBytes, extraBytes []byte if err := rows.Scan(&fieldBytes, &typeBytes, &nullBytes, &keyBytes, &defaultBytes, &extraBytes); err != nil { beeLogger.Log.Fatalf("Could not read column information: %s", err) } fieldStr, typeStr, nullStr, keyStr, defaultStr, extraStr := string(fieldBytes), string(typeBytes), string(nullBytes), string(keyBytes), string(defaultBytes), string(extraBytes) if fieldStr == "id_migration" { if keyStr != "PRI" || extraStr != "auto_increment" { beeLogger.Log.Hint("Expecting KEY: PRI, EXTRA: auto_increment") beeLogger.Log.Fatalf("Column migration.id_migration type mismatch: KEY: %s, EXTRA: %s", keyStr, extraStr) } } else if fieldStr == "name" { if !strings.HasPrefix(typeStr, "varchar") || nullStr != "YES" { beeLogger.Log.Hint("Expecting TYPE: varchar, NULL: YES") beeLogger.Log.Fatalf("Column migration.name type mismatch: TYPE: %s, NULL: %s", typeStr, nullStr) } } else if fieldStr == "created_at" { if typeStr != "timestamp" || defaultStr != "CURRENT_TIMESTAMP" { beeLogger.Log.Hint("Expecting TYPE: timestamp, DEFAULT: CURRENT_TIMESTAMP") beeLogger.Log.Fatalf("Column migration.timestamp type mismatch: TYPE: %s, DEFAULT: %s", typeStr, defaultStr) } } } } }
beego/bee
6a86284cec9a17f9aae6fe82ecf3c436aafed68d
cmd/commands/migrate/migrate.go
https://github.com/beego/bee/blob/6a86284cec9a17f9aae6fe82ecf3c436aafed68d/cmd/commands/migrate/migrate.go#L291-L307
go
train
// writeMigrationSourceFile create the source file based on MIGRATION_MAIN_TPL
func writeMigrationSourceFile(dir, source, driver, connStr string, latestTime int64, latestName string, task string)
// writeMigrationSourceFile create the source file based on MIGRATION_MAIN_TPL func writeMigrationSourceFile(dir, source, driver, connStr string, latestTime int64, latestName string, task string)
{ changeDir(dir) if f, err := os.OpenFile(source, os.O_CREATE|os.O_EXCL|os.O_RDWR, 0666); err != nil { beeLogger.Log.Fatalf("Could not create file: %s", err) } else { content := strings.Replace(MigrationMainTPL, "{{DBDriver}}", driver, -1) content = strings.Replace(content, "{{DriverRepo}}", driverImportStatement(driver), -1) content = strings.Replace(content, "{{ConnStr}}", connStr, -1) content = strings.Replace(content, "{{LatestTime}}", strconv.FormatInt(latestTime, 10), -1) content = strings.Replace(content, "{{LatestName}}", latestName, -1) content = strings.Replace(content, "{{Task}}", task, -1) if _, err := f.WriteString(content); err != nil { beeLogger.Log.Fatalf("Could not write to file: %s", err) } utils.CloseFile(f) } }
beego/bee
6a86284cec9a17f9aae6fe82ecf3c436aafed68d
cmd/commands/migrate/migrate.go
https://github.com/beego/bee/blob/6a86284cec9a17f9aae6fe82ecf3c436aafed68d/cmd/commands/migrate/migrate.go#L310-L320
go
train
// buildMigrationBinary changes directory to database/migrations folder and go-build the source
func buildMigrationBinary(dir, binary string)
// buildMigrationBinary changes directory to database/migrations folder and go-build the source func buildMigrationBinary(dir, binary string)
{ changeDir(dir) cmd := exec.Command("go", "build", "-o", binary) if out, err := cmd.CombinedOutput(); err != nil { beeLogger.Log.Errorf("Could not build migration binary: %s", err) formatShellErrOutput(string(out)) removeTempFile(dir, binary) removeTempFile(dir, binary+".go") os.Exit(2) } }
beego/bee
6a86284cec9a17f9aae6fe82ecf3c436aafed68d
cmd/commands/migrate/migrate.go
https://github.com/beego/bee/blob/6a86284cec9a17f9aae6fe82ecf3c436aafed68d/cmd/commands/migrate/migrate.go#L339-L343
go
train
// changeDir changes working directory to dir. // It exits the system when encouter an error
func changeDir(dir string)
// changeDir changes working directory to dir. // It exits the system when encouter an error func changeDir(dir string)
{ if err := os.Chdir(dir); err != nil { beeLogger.Log.Fatalf("Could not find migration directory: %s", err) } }
beego/bee
6a86284cec9a17f9aae6fe82ecf3c436aafed68d
cmd/commands/migrate/migrate.go
https://github.com/beego/bee/blob/6a86284cec9a17f9aae6fe82ecf3c436aafed68d/cmd/commands/migrate/migrate.go#L346-L351
go
train
// removeTempFile removes a file in dir
func removeTempFile(dir, file string)
// removeTempFile removes a file in dir func removeTempFile(dir, file string)
{ changeDir(dir) if err := os.Remove(file); err != nil { beeLogger.Log.Warnf("Could not remove temporary file: %s", err) } }
beego/bee
6a86284cec9a17f9aae6fe82ecf3c436aafed68d
cmd/commands/migrate/migrate.go
https://github.com/beego/bee/blob/6a86284cec9a17f9aae6fe82ecf3c436aafed68d/cmd/commands/migrate/migrate.go#L354-L360
go
train
// formatShellErrOutput formats the error shell output
func formatShellErrOutput(o string)
// formatShellErrOutput formats the error shell output func formatShellErrOutput(o string)
{ for _, line := range strings.Split(o, "\n") { if line != "" { beeLogger.Log.Errorf("|> %s", line) } } }
beego/bee
6a86284cec9a17f9aae6fe82ecf3c436aafed68d
cmd/commands/migrate/migrate.go
https://github.com/beego/bee/blob/6a86284cec9a17f9aae6fe82ecf3c436aafed68d/cmd/commands/migrate/migrate.go#L363-L369
go
train
// formatShellOutput formats the normal shell output
func formatShellOutput(o string)
// formatShellOutput formats the normal shell output func formatShellOutput(o string)
{ for _, line := range strings.Split(o, "\n") { if line != "" { beeLogger.Log.Infof("|> %s", line) } } }
beego/bee
6a86284cec9a17f9aae6fe82ecf3c436aafed68d
cmd/commands/migrate/migrate.go
https://github.com/beego/bee/blob/6a86284cec9a17f9aae6fe82ecf3c436aafed68d/cmd/commands/migrate/migrate.go#L438-L440
go
train
// MigrateUpdate does the schema update
func MigrateUpdate(currpath, driver, connStr, dir string)
// MigrateUpdate does the schema update func MigrateUpdate(currpath, driver, connStr, dir string)
{ migrate("upgrade", currpath, driver, connStr, dir) }
beego/bee
6a86284cec9a17f9aae6fe82ecf3c436aafed68d
cmd/commands/migrate/migrate.go
https://github.com/beego/bee/blob/6a86284cec9a17f9aae6fe82ecf3c436aafed68d/cmd/commands/migrate/migrate.go#L443-L445
go
train
// MigrateRollback rolls back the latest migration
func MigrateRollback(currpath, driver, connStr, dir string)
// MigrateRollback rolls back the latest migration func MigrateRollback(currpath, driver, connStr, dir string)
{ migrate("rollback", currpath, driver, connStr, dir) }
beego/bee
6a86284cec9a17f9aae6fe82ecf3c436aafed68d
cmd/commands/migrate/migrate.go
https://github.com/beego/bee/blob/6a86284cec9a17f9aae6fe82ecf3c436aafed68d/cmd/commands/migrate/migrate.go#L448-L450
go
train
// MigrateReset rolls back all migrations
func MigrateReset(currpath, driver, connStr, dir string)
// MigrateReset rolls back all migrations func MigrateReset(currpath, driver, connStr, dir string)
{ migrate("reset", currpath, driver, connStr, dir) }
beego/bee
6a86284cec9a17f9aae6fe82ecf3c436aafed68d
cmd/commands/migrate/migrate.go
https://github.com/beego/bee/blob/6a86284cec9a17f9aae6fe82ecf3c436aafed68d/cmd/commands/migrate/migrate.go#L453-L455
go
train
// MigrateRefresh rolls back all migrations and start over again
func MigrateRefresh(currpath, driver, connStr, dir string)
// MigrateRefresh rolls back all migrations and start over again func MigrateRefresh(currpath, driver, connStr, dir string)
{ migrate("refresh", currpath, driver, connStr, dir) }
beego/bee
6a86284cec9a17f9aae6fe82ecf3c436aafed68d
cmd/commands/run/run.go
https://github.com/beego/bee/blob/6a86284cec9a17f9aae6fe82ecf3c436aafed68d/cmd/commands/run/run.go#L83-L193
go
train
// RunApp locates files to watch, and starts the beego application
func RunApp(cmd *commands.Command, args []string) int
// RunApp locates files to watch, and starts the beego application func RunApp(cmd *commands.Command, args []string) int
{ // The default app path is the current working directory appPath, _ := os.Getwd() // If an argument is presented, we use it as the app path if len(args) != 0 && args[0] != "watchall" { if path.IsAbs(args[0]) { appPath = args[0] } else { appPath = path.Join(appPath, args[0]) } } if utils.IsInGOPATH(appPath) { if found, _gopath, _path := utils.SearchGOPATHs(appPath); found { appPath = _path appname = path.Base(appPath) currentGoPath = _gopath } else { beeLogger.Log.Fatalf("No application '%s' found in your GOPATH", appPath) } if strings.HasSuffix(appname, ".go") && utils.IsExist(appPath) { beeLogger.Log.Warnf("The appname is in conflict with file's current path. Do you want to build appname as '%s'", appname) beeLogger.Log.Info("Do you want to overwrite it? [yes|no] ") if !utils.AskForConfirmation() { return 0 } } } else { beeLogger.Log.Warn("Running application outside of GOPATH") appname = path.Base(appPath) currentGoPath = appPath } beeLogger.Log.Infof("Using '%s' as 'appname'", appname) beeLogger.Log.Debugf("Current path: %s", utils.FILE(), utils.LINE(), appPath) if runmode == "prod" || runmode == "dev" { os.Setenv("BEEGO_RUNMODE", runmode) beeLogger.Log.Infof("Using '%s' as 'runmode'", os.Getenv("BEEGO_RUNMODE")) } else if runmode != "" { os.Setenv("BEEGO_RUNMODE", runmode) beeLogger.Log.Warnf("Using '%s' as 'runmode'", os.Getenv("BEEGO_RUNMODE")) } else if os.Getenv("BEEGO_RUNMODE") != "" { beeLogger.Log.Warnf("Using '%s' as 'runmode'", os.Getenv("BEEGO_RUNMODE")) } var paths []string readAppDirectories(appPath, &paths) // Because monitor files has some issues, we watch current directory // and ignore non-go files. for _, p := range config.Conf.DirStruct.Others { paths = append(paths, strings.Replace(p, "$GOPATH", currentGoPath, -1)) } if len(extraPackages) > 0 { // get the full path for _, packagePath := range extraPackages { if found, _, _fullPath := utils.SearchGOPATHs(packagePath); found { readAppDirectories(_fullPath, &paths) } else { beeLogger.Log.Warnf("No extra package '%s' found in your GOPATH", packagePath) } } // let paths unique strSet := make(map[string]struct{}) for _, p := range paths { strSet[p] = struct{}{} } paths = make([]string, len(strSet)) index := 0 for i := range strSet { paths[index] = i index++ } } files := []string{} for _, arg := range mainFiles { if len(arg) > 0 { files = append(files, arg) } } if downdoc == "true" { if _, err := os.Stat(path.Join(appPath, "swagger", "index.html")); err != nil { if os.IsNotExist(err) { downloadFromURL(swaggerlink, "swagger.zip") unzipAndDelete("swagger.zip") } } } // Start the Reload server (if enabled) if config.Conf.EnableReload { startReloadServer() } if gendoc == "true" { NewWatcher(paths, files, true) AutoBuild(files, true) } else { NewWatcher(paths, files, false) AutoBuild(files, false) } for { <-exit runtime.Goexit() } }
beego/bee
6a86284cec9a17f9aae6fe82ecf3c436aafed68d
cmd/commands/run/run.go
https://github.com/beego/bee/blob/6a86284cec9a17f9aae6fe82ecf3c436aafed68d/cmd/commands/run/run.go#L235-L253
go
train
// If a file is excluded
func isExcluded(filePath string) bool
// If a file is excluded func isExcluded(filePath string) bool
{ for _, p := range excludedPaths { absP, err := path.Abs(p) if err != nil { beeLogger.Log.Errorf("Cannot get absolute path of '%s'", p) continue } absFilePath, err := path.Abs(filePath) if err != nil { beeLogger.Log.Errorf("Cannot get absolute path of '%s'", filePath) break } if strings.HasPrefix(absFilePath, absP) { beeLogger.Log.Infof("'%s' is not being watched", filePath) return true } } return false }
beego/bee
6a86284cec9a17f9aae6fe82ecf3c436aafed68d
logger/colors/color.go
https://github.com/beego/bee/blob/6a86284cec9a17f9aae6fe82ecf3c436aafed68d/logger/colors/color.go#L46-L54
go
train
// NewModeColorWriter create and initializes a new ansiColorWriter // by specifying the outputMode.
func NewModeColorWriter(w io.Writer, mode outputMode) io.Writer
// NewModeColorWriter create and initializes a new ansiColorWriter // by specifying the outputMode. func NewModeColorWriter(w io.Writer, mode outputMode) io.Writer
{ if _, ok := w.(*colorWriter); !ok { return &colorWriter{ w: w, mode: mode, } } return w }
beego/bee
6a86284cec9a17f9aae6fe82ecf3c436aafed68d
cmd/commands/version/version.go
https://github.com/beego/bee/blob/6a86284cec9a17f9aae6fe82ecf3c436aafed68d/cmd/commands/version/version.go#L115-L118
go
train
// ShowShortVersionBanner prints the short version banner.
func ShowShortVersionBanner()
// ShowShortVersionBanner prints the short version banner. func ShowShortVersionBanner()
{ output := colors.NewColorWriter(os.Stdout) InitBanner(output, bytes.NewBufferString(colors.MagentaBold(shortVersionBanner))) }
beego/bee
6a86284cec9a17f9aae6fe82ecf3c436aafed68d
cmd/commands/run/watch.go
https://github.com/beego/bee/blob/6a86284cec9a17f9aae6fe82ecf3c436aafed68d/cmd/commands/run/watch.go#L51-L112
go
train
// NewWatcher starts an fsnotify Watcher on the specified paths
func NewWatcher(paths []string, files []string, isgenerate bool)
// NewWatcher starts an fsnotify Watcher on the specified paths func NewWatcher(paths []string, files []string, isgenerate bool)
{ watcher, err := fsnotify.NewWatcher() if err != nil { beeLogger.Log.Fatalf("Failed to create watcher: %s", err) } go func() { for { select { case e := <-watcher.Events: isBuild := true if ifStaticFile(e.Name) && config.Conf.EnableReload { sendReload(e.String()) continue } // Skip ignored files if shouldIgnoreFile(e.Name) { continue } if !shouldWatchFileWithExtension(e.Name) { continue } mt := utils.GetFileModTime(e.Name) if t := eventTime[e.Name]; mt == t { beeLogger.Log.Hintf(colors.Bold("Skipping: ")+"%s", e.String()) isBuild = false } eventTime[e.Name] = mt if isBuild { beeLogger.Log.Hintf("Event fired: %s", e) go func() { // Wait 1s before autobuild until there is no file change. scheduleTime = time.Now().Add(1 * time.Second) time.Sleep(time.Until(scheduleTime)) AutoBuild(files, isgenerate) if config.Conf.EnableReload { // Wait 100ms more before refreshing the browser time.Sleep(100 * time.Millisecond) sendReload(e.String()) } }() } case err := <-watcher.Errors: beeLogger.Log.Warnf("Watcher error: %s", err.Error()) // No need to exit here } } }() beeLogger.Log.Info("Initializing watcher...") for _, path := range paths { beeLogger.Log.Hintf(colors.Bold("Watching: ")+"%s", path) err = watcher.Add(path) if err != nil { beeLogger.Log.Fatalf("Failed to watch directory: %s", err) } } }
beego/bee
6a86284cec9a17f9aae6fe82ecf3c436aafed68d
cmd/commands/run/watch.go
https://github.com/beego/bee/blob/6a86284cec9a17f9aae6fe82ecf3c436aafed68d/cmd/commands/run/watch.go#L115-L176
go
train
// AutoBuild builds the specified set of files
func AutoBuild(files []string, isgenerate bool)
// AutoBuild builds the specified set of files func AutoBuild(files []string, isgenerate bool)
{ state.Lock() defer state.Unlock() os.Chdir(currpath) cmdName := "go" var ( err error stderr bytes.Buffer ) // For applications use full import path like "github.com/.../.." // are able to use "go install" to reduce build time. if config.Conf.GoInstall { icmd := exec.Command(cmdName, "install", "-v") icmd.Stdout = os.Stdout icmd.Stderr = os.Stderr icmd.Env = append(os.Environ(), "GOGC=off") icmd.Run() } if isgenerate { beeLogger.Log.Info("Generating the docs...") icmd := exec.Command("bee", "generate", "docs") icmd.Env = append(os.Environ(), "GOGC=off") err = icmd.Run() if err != nil { utils.Notify("", "Failed to generate the docs.") beeLogger.Log.Errorf("Failed to generate the docs.") return } beeLogger.Log.Success("Docs generated!") } appName := appname if err == nil { if runtime.GOOS == "windows" { appName += ".exe" } args := []string{"build"} args = append(args, "-o", appName) if buildTags != "" { args = append(args, "-tags", buildTags) } args = append(args, files...) bcmd := exec.Command(cmdName, args...) bcmd.Env = append(os.Environ(), "GOGC=off") bcmd.Stderr = &stderr err = bcmd.Run() if err != nil { utils.Notify(stderr.String(), "Build Failed") beeLogger.Log.Errorf("Failed to build the application: %s", stderr.String()) return } } beeLogger.Log.Success("Built Successfully!") Restart(appName) }
beego/bee
6a86284cec9a17f9aae6fe82ecf3c436aafed68d
cmd/commands/run/watch.go
https://github.com/beego/bee/blob/6a86284cec9a17f9aae6fe82ecf3c436aafed68d/cmd/commands/run/watch.go#L179-L211
go
train
// Kill kills the running command process
func Kill()
// Kill kills the running command process func Kill()
{ defer func() { if e := recover(); e != nil { beeLogger.Log.Infof("Kill recover: %s", e) } }() if cmd != nil && cmd.Process != nil { // Windows does not support Interrupt if runtime.GOOS == "windows" { cmd.Process.Signal(os.Kill) } else { cmd.Process.Signal(os.Interrupt) } ch := make(chan struct{}, 1) go func() { cmd.Wait() ch <- struct{}{} }() select { case <-ch: return case <-time.After(10 * time.Second): beeLogger.Log.Info("Timeout. Force kill cmd process") err := cmd.Process.Kill() if err != nil { beeLogger.Log.Errorf("Error while killing cmd process: %s", err) } return } } }
beego/bee
6a86284cec9a17f9aae6fe82ecf3c436aafed68d
cmd/commands/run/watch.go
https://github.com/beego/bee/blob/6a86284cec9a17f9aae6fe82ecf3c436aafed68d/cmd/commands/run/watch.go#L214-L218
go
train
// Restart kills the running command process and starts it again
func Restart(appname string)
// Restart kills the running command process and starts it again func Restart(appname string)
{ beeLogger.Log.Debugf("Kill running process", utils.FILE(), utils.LINE()) Kill() go Start(appname) }
beego/bee
6a86284cec9a17f9aae6fe82ecf3c436aafed68d
cmd/commands/run/watch.go
https://github.com/beego/bee/blob/6a86284cec9a17f9aae6fe82ecf3c436aafed68d/cmd/commands/run/watch.go#L221-L242
go
train
// Start starts the command process
func Start(appname string)
// Start starts the command process func Start(appname string)
{ beeLogger.Log.Infof("Restarting '%s'...", appname) if !strings.Contains(appname, "./") { appname = "./" + appname } cmd = exec.Command(appname) cmd.Stdout = os.Stdout cmd.Stderr = os.Stderr if runargs != "" { r := regexp.MustCompile("'.+'|\".+\"|\\S+") m := r.FindAllString(runargs, -1) cmd.Args = append([]string{appname}, m...) } else { cmd.Args = append([]string{appname}, config.Conf.CmdArgs...) } cmd.Env = append(os.Environ(), config.Conf.Envs...) go cmd.Run() beeLogger.Log.Successf("'%s' is running...", appname) started <- true }
beego/bee
6a86284cec9a17f9aae6fe82ecf3c436aafed68d
cmd/commands/run/watch.go
https://github.com/beego/bee/blob/6a86284cec9a17f9aae6fe82ecf3c436aafed68d/cmd/commands/run/watch.go#L255-L267
go
train
// shouldIgnoreFile ignores filenames generated by Emacs, Vim or SublimeText. // It returns true if the file should be ignored, false otherwise.
func shouldIgnoreFile(filename string) bool
// shouldIgnoreFile ignores filenames generated by Emacs, Vim or SublimeText. // It returns true if the file should be ignored, false otherwise. func shouldIgnoreFile(filename string) bool
{ for _, regex := range ignoredFilesRegExps { r, err := regexp.Compile(regex) if err != nil { beeLogger.Log.Fatalf("Could not compile regular expression: %s", err) } if r.MatchString(filename) { return true } continue } return false }
beego/bee
6a86284cec9a17f9aae6fe82ecf3c436aafed68d
cmd/commands/run/watch.go
https://github.com/beego/bee/blob/6a86284cec9a17f9aae6fe82ecf3c436aafed68d/cmd/commands/run/watch.go#L271-L278
go
train
// shouldWatchFileWithExtension returns true if the name of the file // hash a suffix that should be watched.
func shouldWatchFileWithExtension(name string) bool
// shouldWatchFileWithExtension returns true if the name of the file // hash a suffix that should be watched. func shouldWatchFileWithExtension(name string) bool
{ for _, s := range watchExts { if strings.HasSuffix(name, s) { return true } } return false }
beego/bee
6a86284cec9a17f9aae6fe82ecf3c436aafed68d
logger/logger.go
https://github.com/beego/bee/blob/6a86284cec9a17f9aae6fe82ecf3c436aafed68d/logger/logger.go#L77-L102
go
train
// GetBeeLogger initializes the logger instance with a NewColorWriter output // and returns a singleton
func GetBeeLogger(w io.Writer) *BeeLogger
// GetBeeLogger initializes the logger instance with a NewColorWriter output // and returns a singleton func GetBeeLogger(w io.Writer) *BeeLogger
{ once.Do(func() { var ( err error simpleLogFormat = `{{Now "2006/01/02 15:04:05"}} {{.Level}} ▶ {{.ID}} {{.Message}}{{EndLine}}` debugLogFormat = `{{Now "2006/01/02 15:04:05"}} {{.Level}} ▶ {{.ID}} {{.Filename}}:{{.LineNo}} {{.Message}}{{EndLine}}` ) // Initialize and parse logging templates funcs := template.FuncMap{ "Now": Now, "EndLine": EndLine, } logRecordTemplate, err = template.New("simpleLogFormat").Funcs(funcs).Parse(simpleLogFormat) if err != nil { panic(err) } debugLogRecordTemplate, err = template.New("debugLogFormat").Funcs(funcs).Parse(debugLogFormat) if err != nil { panic(err) } instance = &BeeLogger{output: colors.NewColorWriter(w)} }) return instance }
beego/bee
6a86284cec9a17f9aae6fe82ecf3c436aafed68d
logger/logger.go
https://github.com/beego/bee/blob/6a86284cec9a17f9aae6fe82ecf3c436aafed68d/logger/logger.go#L105-L109
go
train
// SetOutput sets the logger output destination
func (l *BeeLogger) SetOutput(w io.Writer)
// SetOutput sets the logger output destination func (l *BeeLogger) SetOutput(w io.Writer)
{ l.mu.Lock() defer l.mu.Unlock() l.output = colors.NewColorWriter(w) }
beego/bee
6a86284cec9a17f9aae6fe82ecf3c436aafed68d
logger/logger.go
https://github.com/beego/bee/blob/6a86284cec9a17f9aae6fe82ecf3c436aafed68d/logger/logger.go#L169-L188
go
train
// mustLog logs the message according to the specified level and arguments. // It panics in case of an error.
func (l *BeeLogger) mustLog(level int, message string, args ...interface{})
// mustLog logs the message according to the specified level and arguments. // It panics in case of an error. func (l *BeeLogger) mustLog(level int, message string, args ...interface{})
{ if level > logLevel { return } // Acquire the lock l.mu.Lock() defer l.mu.Unlock() // Create the logging record and pass into the output record := LogRecord{ ID: fmt.Sprintf("%04d", atomic.AddUint64(&sequenceNo, 1)), Level: l.getColorLevel(level), Message: fmt.Sprintf(message, args...), } err := logRecordTemplate.Execute(l.output, record) if err != nil { panic(err) } }
beego/bee
6a86284cec9a17f9aae6fe82ecf3c436aafed68d
logger/logger.go
https://github.com/beego/bee/blob/6a86284cec9a17f9aae6fe82ecf3c436aafed68d/logger/logger.go#L192-L212
go
train
// mustLogDebug logs a debug message only if debug mode // is enabled. i.e. DEBUG_ENABLED="1"
func (l *BeeLogger) mustLogDebug(message string, file string, line int, args ...interface{})
// mustLogDebug logs a debug message only if debug mode // is enabled. i.e. DEBUG_ENABLED="1" func (l *BeeLogger) mustLogDebug(message string, file string, line int, args ...interface{})
{ if !debugMode { return } // Change the output to Stderr l.SetOutput(os.Stderr) // Create the log record record := LogRecord{ ID: fmt.Sprintf("%04d", atomic.AddUint64(&sequenceNo, 1)), Level: l.getColorLevel(levelDebug), Message: fmt.Sprintf(message, args...), LineNo: line, Filename: filepath.Base(file), } err := debugLogRecordTemplate.Execute(l.output, record) if err != nil { panic(err) } }
beego/bee
6a86284cec9a17f9aae6fe82ecf3c436aafed68d
logger/logger.go
https://github.com/beego/bee/blob/6a86284cec9a17f9aae6fe82ecf3c436aafed68d/logger/logger.go#L215-L217
go
train
// Debug outputs a debug log message
func (l *BeeLogger) Debug(message string, file string, line int)
// Debug outputs a debug log message func (l *BeeLogger) Debug(message string, file string, line int)
{ l.mustLogDebug(message, file, line) }
beego/bee
6a86284cec9a17f9aae6fe82ecf3c436aafed68d
logger/logger.go
https://github.com/beego/bee/blob/6a86284cec9a17f9aae6fe82ecf3c436aafed68d/logger/logger.go#L220-L222
go
train
// Debugf outputs a formatted debug log message
func (l *BeeLogger) Debugf(message string, file string, line int, vars ...interface{})
// Debugf outputs a formatted debug log message func (l *BeeLogger) Debugf(message string, file string, line int, vars ...interface{})
{ l.mustLogDebug(message, file, line, vars...) }
beego/bee
6a86284cec9a17f9aae6fe82ecf3c436aafed68d
logger/logger.go
https://github.com/beego/bee/blob/6a86284cec9a17f9aae6fe82ecf3c436aafed68d/logger/logger.go#L230-L232
go
train
// Infof outputs a formatted information log message
func (l *BeeLogger) Infof(message string, vars ...interface{})
// Infof outputs a formatted information log message func (l *BeeLogger) Infof(message string, vars ...interface{})
{ l.mustLog(levelInfo, message, vars...) }
beego/bee
6a86284cec9a17f9aae6fe82ecf3c436aafed68d
logger/logger.go
https://github.com/beego/bee/blob/6a86284cec9a17f9aae6fe82ecf3c436aafed68d/logger/logger.go#L240-L242
go
train
// Warnf outputs a formatted warning log message
func (l *BeeLogger) Warnf(message string, vars ...interface{})
// Warnf outputs a formatted warning log message func (l *BeeLogger) Warnf(message string, vars ...interface{})
{ l.mustLog(levelWarn, message, vars...) }
beego/bee
6a86284cec9a17f9aae6fe82ecf3c436aafed68d
logger/logger.go
https://github.com/beego/bee/blob/6a86284cec9a17f9aae6fe82ecf3c436aafed68d/logger/logger.go#L250-L252
go
train
// Errorf outputs a formatted error log message
func (l *BeeLogger) Errorf(message string, vars ...interface{})
// Errorf outputs a formatted error log message func (l *BeeLogger) Errorf(message string, vars ...interface{})
{ l.mustLog(levelError, message, vars...) }
beego/bee
6a86284cec9a17f9aae6fe82ecf3c436aafed68d
logger/logger.go
https://github.com/beego/bee/blob/6a86284cec9a17f9aae6fe82ecf3c436aafed68d/logger/logger.go#L255-L258
go
train
// Fatal outputs a fatal log message and exists
func (l *BeeLogger) Fatal(message string)
// Fatal outputs a fatal log message and exists func (l *BeeLogger) Fatal(message string)
{ l.mustLog(levelFatal, message) os.Exit(255) }
beego/bee
6a86284cec9a17f9aae6fe82ecf3c436aafed68d
logger/logger.go
https://github.com/beego/bee/blob/6a86284cec9a17f9aae6fe82ecf3c436aafed68d/logger/logger.go#L261-L264
go
train
// Fatalf outputs a formatted log message and exists
func (l *BeeLogger) Fatalf(message string, vars ...interface{})
// Fatalf outputs a formatted log message and exists func (l *BeeLogger) Fatalf(message string, vars ...interface{})
{ l.mustLog(levelFatal, message, vars...) os.Exit(255) }
beego/bee
6a86284cec9a17f9aae6fe82ecf3c436aafed68d
logger/logger.go
https://github.com/beego/bee/blob/6a86284cec9a17f9aae6fe82ecf3c436aafed68d/logger/logger.go#L272-L274
go
train
// Successf outputs a formatted success log message
func (l *BeeLogger) Successf(message string, vars ...interface{})
// Successf outputs a formatted success log message func (l *BeeLogger) Successf(message string, vars ...interface{})
{ l.mustLog(levelSuccess, message, vars...) }
beego/bee
6a86284cec9a17f9aae6fe82ecf3c436aafed68d
logger/logger.go
https://github.com/beego/bee/blob/6a86284cec9a17f9aae6fe82ecf3c436aafed68d/logger/logger.go#L282-L284
go
train
// Hintf outputs a formatted hint log message
func (l *BeeLogger) Hintf(message string, vars ...interface{})
// Hintf outputs a formatted hint log message func (l *BeeLogger) Hintf(message string, vars ...interface{})
{ l.mustLog(levelHint, message, vars...) }
beego/bee
6a86284cec9a17f9aae6fe82ecf3c436aafed68d
logger/logger.go
https://github.com/beego/bee/blob/6a86284cec9a17f9aae6fe82ecf3c436aafed68d/logger/logger.go#L292-L294
go
train
// Criticalf outputs a formatted critical log message
func (l *BeeLogger) Criticalf(message string, vars ...interface{})
// Criticalf outputs a formatted critical log message func (l *BeeLogger) Criticalf(message string, vars ...interface{})
{ l.mustLog(levelCritical, message, vars...) }
cloudfoundry/cli
5010c000047f246b870475e2c299556078cdad30
actor/v3action/organization.go
https://github.com/cloudfoundry/cli/blob/5010c000047f246b870475e2c299556078cdad30/actor/v3action/organization.go#L14-L27
go
train
// GetOrganizationByName returns the organization with the given name.
func (actor Actor) GetOrganizationByName(name string) (Organization, Warnings, error)
// GetOrganizationByName returns the organization with the given name. func (actor Actor) GetOrganizationByName(name string) (Organization, Warnings, error)
{ orgs, warnings, err := actor.CloudControllerClient.GetOrganizations( ccv3.Query{Key: ccv3.NameFilter, Values: []string{name}}, ) if err != nil { return Organization{}, Warnings(warnings), err } if len(orgs) == 0 { return Organization{}, Warnings(warnings), actionerror.OrganizationNotFoundError{Name: name} } return Organization(orgs[0]), Warnings(warnings), nil }
cloudfoundry/cli
5010c000047f246b870475e2c299556078cdad30
util/configv3/json_config.go
https://github.com/cloudfoundry/cli/blob/5010c000047f246b870475e2c299556078cdad30/util/configv3/json_config.go#L85-L91
go
train
// CurrentUserName returns the name of a user as returned by CurrentUser()
func (config *Config) CurrentUserName() (string, error)
// CurrentUserName returns the name of a user as returned by CurrentUser() func (config *Config) CurrentUserName() (string, error)
{ user, err := config.CurrentUser() if err != nil { return "", err } return user.Name, nil }
cloudfoundry/cli
5010c000047f246b870475e2c299556078cdad30
util/configv3/json_config.go
https://github.com/cloudfoundry/cli/blob/5010c000047f246b870475e2c299556078cdad30/util/configv3/json_config.go#L112-L117
go
train
// OverallPollingTimeout returns the overall polling timeout for async // operations. The time is based off of: // 1. The config file's AsyncTimeout value (integer) is > 0 // 2. Defaults to the DefaultOverallPollingTimeout
func (config *Config) OverallPollingTimeout() time.Duration
// OverallPollingTimeout returns the overall polling timeout for async // operations. The time is based off of: // 1. The config file's AsyncTimeout value (integer) is > 0 // 2. Defaults to the DefaultOverallPollingTimeout func (config *Config) OverallPollingTimeout() time.Duration
{ if config.ConfigFile.AsyncTimeout == 0 { return DefaultOverallPollingTimeout } return time.Duration(config.ConfigFile.AsyncTimeout) * time.Minute }
cloudfoundry/cli
5010c000047f246b870475e2c299556078cdad30
util/configv3/json_config.go
https://github.com/cloudfoundry/cli/blob/5010c000047f246b870475e2c299556078cdad30/util/configv3/json_config.go#L140-L144
go
train
// SetOrganizationInformation sets the currently targeted organization.
func (config *Config) SetOrganizationInformation(guid string, name string)
// SetOrganizationInformation sets the currently targeted organization. func (config *Config) SetOrganizationInformation(guid string, name string)
{ config.ConfigFile.TargetedOrganization.GUID = guid config.ConfigFile.TargetedOrganization.Name = name config.ConfigFile.TargetedOrganization.QuotaDefinition = QuotaDefinition{} }
cloudfoundry/cli
5010c000047f246b870475e2c299556078cdad30
util/configv3/json_config.go
https://github.com/cloudfoundry/cli/blob/5010c000047f246b870475e2c299556078cdad30/util/configv3/json_config.go#L152-L155
go
train
// SetSpaceInformation sets the currently targeted space.
func (config *Config) SetSpaceInformation(guid string, name string, allowSSH bool)
// SetSpaceInformation sets the currently targeted space. func (config *Config) SetSpaceInformation(guid string, name string, allowSSH bool)
{ config.V7SetSpaceInformation(guid, name) config.ConfigFile.TargetedSpace.AllowSSH = allowSSH }
cloudfoundry/cli
5010c000047f246b870475e2c299556078cdad30
util/configv3/json_config.go
https://github.com/cloudfoundry/cli/blob/5010c000047f246b870475e2c299556078cdad30/util/configv3/json_config.go#L159-L169
go
train
// SetTargetInformation sets the currently targeted CC API and related other // related API URLs.
func (config *Config) SetTargetInformation(api string, apiVersion string, auth string, minCLIVersion string, doppler string, routing string, skipSSLValidation bool)
// SetTargetInformation sets the currently targeted CC API and related other // related API URLs. func (config *Config) SetTargetInformation(api string, apiVersion string, auth string, minCLIVersion string, doppler string, routing string, skipSSLValidation bool)
{ config.ConfigFile.Target = api config.ConfigFile.APIVersion = apiVersion config.ConfigFile.AuthorizationEndpoint = auth config.SetMinCLIVersion(minCLIVersion) config.ConfigFile.DopplerEndpoint = doppler config.ConfigFile.RoutingEndpoint = routing config.ConfigFile.SkipSSLValidation = skipSSLValidation config.UnsetOrganizationAndSpaceInformation() }
cloudfoundry/cli
5010c000047f246b870475e2c299556078cdad30
util/configv3/json_config.go
https://github.com/cloudfoundry/cli/blob/5010c000047f246b870475e2c299556078cdad30/util/configv3/json_config.go#L172-L176
go
train
// SetTokenInformation sets the current token/user information.
func (config *Config) SetTokenInformation(accessToken string, refreshToken string, sshOAuthClient string)
// SetTokenInformation sets the current token/user information. func (config *Config) SetTokenInformation(accessToken string, refreshToken string, sshOAuthClient string)
{ config.ConfigFile.AccessToken = accessToken config.ConfigFile.RefreshToken = refreshToken config.ConfigFile.SSHOAuthClient = sshOAuthClient }
cloudfoundry/cli
5010c000047f246b870475e2c299556078cdad30
util/configv3/json_config.go
https://github.com/cloudfoundry/cli/blob/5010c000047f246b870475e2c299556078cdad30/util/configv3/json_config.go#L179-L182
go
train
// SetUAAClientCredentials sets the client credentials.
func (config *Config) SetUAAClientCredentials(client string, clientSecret string)
// SetUAAClientCredentials sets the client credentials. func (config *Config) SetUAAClientCredentials(client string, clientSecret string)
{ config.ConfigFile.UAAOAuthClient = client config.ConfigFile.UAAOAuthClientSecret = clientSecret }
cloudfoundry/cli
5010c000047f246b870475e2c299556078cdad30
util/configv3/json_config.go
https://github.com/cloudfoundry/cli/blob/5010c000047f246b870475e2c299556078cdad30/util/configv3/json_config.go#L257-L265
go
train
// UnsetUserInformation resets the access token, refresh token, UAA grant type, // UAA client credentials, and targeted org/space information.
func (config *Config) UnsetUserInformation()
// UnsetUserInformation resets the access token, refresh token, UAA grant type, // UAA client credentials, and targeted org/space information. func (config *Config) UnsetUserInformation()
{ config.SetAccessToken("") config.SetRefreshToken("") config.SetUAAGrantType("") config.SetUAAClientCredentials(DefaultUAAOAuthClient, DefaultUAAOAuthClientSecret) config.UnsetOrganizationAndSpaceInformation() }
cloudfoundry/cli
5010c000047f246b870475e2c299556078cdad30
util/configv3/json_config.go
https://github.com/cloudfoundry/cli/blob/5010c000047f246b870475e2c299556078cdad30/util/configv3/json_config.go#L268-L271
go
train
// V7SetSpaceInformation sets the currently targeted space.
func (config *Config) V7SetSpaceInformation(guid string, name string)
// V7SetSpaceInformation sets the currently targeted space. func (config *Config) V7SetSpaceInformation(guid string, name string)
{ config.ConfigFile.TargetedSpace.GUID = guid config.ConfigFile.TargetedSpace.Name = name }
cloudfoundry/cli
5010c000047f246b870475e2c299556078cdad30
actor/v3action/actor.go
https://github.com/cloudfoundry/cli/blob/5010c000047f246b870475e2c299556078cdad30/actor/v3action/actor.go#L24-L31
go
train
// NewActor returns a new V3 actor.
func NewActor(client CloudControllerClient, config Config, sharedActor SharedActor, uaaClient UAAClient) *Actor
// NewActor returns a new V3 actor. func NewActor(client CloudControllerClient, config Config, sharedActor SharedActor, uaaClient UAAClient) *Actor
{ return &Actor{ CloudControllerClient: client, Config: config, SharedActor: sharedActor, UAAClient: uaaClient, } }
cloudfoundry/cli
5010c000047f246b870475e2c299556078cdad30
api/cloudcontroller/ccv3/target.go
https://github.com/cloudfoundry/cli/blob/5010c000047f246b870475e2c299556078cdad30/api/cloudcontroller/ccv3/target.go#L32-L58
go
train
// TargetCF sets the client to use the Cloud Controller specified in the // configuration. Any other configuration is also applied to the client.
func (client *Client) TargetCF(settings TargetSettings) (Warnings, error)
// TargetCF sets the client to use the Cloud Controller specified in the // configuration. Any other configuration is also applied to the client. func (client *Client) TargetCF(settings TargetSettings) (Warnings, error)
{ client.cloudControllerURL = settings.URL client.connection = cloudcontroller.NewConnection(cloudcontroller.Config{ DialTimeout: settings.DialTimeout, SkipSSLValidation: settings.SkipSSLValidation, }) for _, wrapper := range client.wrappers { client.connection = wrapper.Wrap(client.connection) } apiInfo, resourceLinks, warnings, err := client.GetInfo() if err != nil { return warnings, err } client.Info = apiInfo resources := map[string]string{} for resource, link := range resourceLinks { resources[resource] = link.HREF } client.router = internal.NewRouter(internal.APIRoutes, resources) return warnings, nil }
cloudfoundry/cli
5010c000047f246b870475e2c299556078cdad30
api/cloudcontroller/ccv2/info.go
https://github.com/cloudfoundry/cli/blob/5010c000047f246b870475e2c299556078cdad30/api/cloudcontroller/ccv2/info.go#L67-L85
go
train
// Info returns back endpoint and API information from /v2/info.
func (client *Client) Info() (APIInformation, Warnings, error)
// Info returns back endpoint and API information from /v2/info. func (client *Client) Info() (APIInformation, Warnings, error)
{ request, err := client.newHTTPRequest(requestOptions{ RequestName: internal.GetInfoRequest, }) if err != nil { return APIInformation{}, nil, err } var info APIInformation response := cloudcontroller.Response{ DecodeJSONResponseInto: &info, } err = client.connection.Make(request, &response) if unknownSourceErr, ok := err.(ccerror.UnknownHTTPSourceError); ok && unknownSourceErr.StatusCode == http.StatusNotFound { return APIInformation{}, nil, ccerror.APINotFoundError{URL: client.cloudControllerURL} } return info, response.Warnings, err }
cloudfoundry/cli
5010c000047f246b870475e2c299556078cdad30
api/cloudcontroller/ccv2/service_binding.go
https://github.com/cloudfoundry/cli/blob/5010c000047f246b870475e2c299556078cdad30/api/cloudcontroller/ccv2/service_binding.go#L29-L50
go
train
// UnmarshalJSON helps unmarshal a Cloud Controller Service Binding response.
func (serviceBinding *ServiceBinding) UnmarshalJSON(data []byte) error
// UnmarshalJSON helps unmarshal a Cloud Controller Service Binding response. func (serviceBinding *ServiceBinding) UnmarshalJSON(data []byte) error
{ var ccServiceBinding struct { Metadata internal.Metadata Entity struct { AppGUID string `json:"app_guid"` ServiceInstanceGUID string `json:"service_instance_guid"` Name string `json:"name"` LastOperation LastOperation `json:"last_operation"` } `json:"entity"` } err := cloudcontroller.DecodeJSON(data, &ccServiceBinding) if err != nil { return err } serviceBinding.AppGUID = ccServiceBinding.Entity.AppGUID serviceBinding.GUID = ccServiceBinding.Metadata.GUID serviceBinding.ServiceInstanceGUID = ccServiceBinding.Entity.ServiceInstanceGUID serviceBinding.Name = ccServiceBinding.Entity.Name serviceBinding.LastOperation = ccServiceBinding.Entity.LastOperation return nil }
cloudfoundry/cli
5010c000047f246b870475e2c299556078cdad30
api/cloudcontroller/ccv2/service_binding.go
https://github.com/cloudfoundry/cli/blob/5010c000047f246b870475e2c299556078cdad30/api/cloudcontroller/ccv2/service_binding.go#L98-L118
go
train
// DeleteServiceBinding deletes the specified Service Binding. An updated // service binding is returned only if acceptsIncomplete is true.
func (client *Client) DeleteServiceBinding(serviceBindingGUID string, acceptsIncomplete bool) (ServiceBinding, Warnings, error)
// DeleteServiceBinding deletes the specified Service Binding. An updated // service binding is returned only if acceptsIncomplete is true. func (client *Client) DeleteServiceBinding(serviceBindingGUID string, acceptsIncomplete bool) (ServiceBinding, Warnings, error)
{ request, err := client.newHTTPRequest(requestOptions{ RequestName: internal.DeleteServiceBindingRequest, URIParams: map[string]string{"service_binding_guid": serviceBindingGUID}, Query: url.Values{"accepts_incomplete": {fmt.Sprint(acceptsIncomplete)}}, }) if err != nil { return ServiceBinding{}, nil, err } var response cloudcontroller.Response var serviceBinding ServiceBinding if acceptsIncomplete { response = cloudcontroller.Response{ DecodeJSONResponseInto: &serviceBinding, } } err = client.connection.Make(request, &response) return serviceBinding, response.Warnings, err }
cloudfoundry/cli
5010c000047f246b870475e2c299556078cdad30
api/cloudcontroller/ccv2/service_binding.go
https://github.com/cloudfoundry/cli/blob/5010c000047f246b870475e2c299556078cdad30/api/cloudcontroller/ccv2/service_binding.go#L121-L137
go
train
// GetServiceBinding returns back a service binding with the provided GUID.
func (client *Client) GetServiceBinding(guid string) (ServiceBinding, Warnings, error)
// GetServiceBinding returns back a service binding with the provided GUID. func (client *Client) GetServiceBinding(guid string) (ServiceBinding, Warnings, error)
{ request, err := client.newHTTPRequest(requestOptions{ RequestName: internal.GetServiceBindingRequest, URIParams: Params{"service_binding_guid": guid}, }) if err != nil { return ServiceBinding{}, nil, err } var serviceBinding ServiceBinding response := cloudcontroller.Response{ DecodeJSONResponseInto: &serviceBinding, } err = client.connection.Make(request, &response) return serviceBinding, response.Warnings, err }
cloudfoundry/cli
5010c000047f246b870475e2c299556078cdad30
api/cloudcontroller/ccv2/service_binding.go
https://github.com/cloudfoundry/cli/blob/5010c000047f246b870475e2c299556078cdad30/api/cloudcontroller/ccv2/service_binding.go#L141-L164
go
train
// GetServiceBindings returns back a list of Service Bindings based off of the // provided filters.
func (client *Client) GetServiceBindings(filters ...Filter) ([]ServiceBinding, Warnings, error)
// GetServiceBindings returns back a list of Service Bindings based off of the // provided filters. func (client *Client) GetServiceBindings(filters ...Filter) ([]ServiceBinding, Warnings, error)
{ request, err := client.newHTTPRequest(requestOptions{ RequestName: internal.GetServiceBindingsRequest, Query: ConvertFilterParameters(filters), }) if err != nil { return nil, nil, err } var fullBindingsList []ServiceBinding warnings, err := client.paginate(request, ServiceBinding{}, func(item interface{}) error { if binding, ok := item.(ServiceBinding); ok { fullBindingsList = append(fullBindingsList, binding) } else { return ccerror.UnknownObjectInListError{ Expected: ServiceBinding{}, Unexpected: item, } } return nil }) return fullBindingsList, warnings, err }
cloudfoundry/cli
5010c000047f246b870475e2c299556078cdad30
api/cloudcontroller/ccv2/service_binding.go
https://github.com/cloudfoundry/cli/blob/5010c000047f246b870475e2c299556078cdad30/api/cloudcontroller/ccv2/service_binding.go#L167-L190
go
train
// GetServiceInstanceServiceBindings returns back a list of Service Bindings for the provided service instance GUID.
func (client *Client) GetServiceInstanceServiceBindings(serviceInstanceGUID string) ([]ServiceBinding, Warnings, error)
// GetServiceInstanceServiceBindings returns back a list of Service Bindings for the provided service instance GUID. func (client *Client) GetServiceInstanceServiceBindings(serviceInstanceGUID string) ([]ServiceBinding, Warnings, error)
{ request, err := client.newHTTPRequest(requestOptions{ RequestName: internal.GetServiceInstanceServiceBindingsRequest, URIParams: map[string]string{"service_instance_guid": serviceInstanceGUID}, }) if err != nil { return nil, nil, err } var fullBindingsList []ServiceBinding warnings, err := client.paginate(request, ServiceBinding{}, func(item interface{}) error { if binding, ok := item.(ServiceBinding); ok { fullBindingsList = append(fullBindingsList, binding) } else { return ccerror.UnknownObjectInListError{ Expected: ServiceBinding{}, Unexpected: item, } } return nil }) return fullBindingsList, warnings, err }
cloudfoundry/cli
5010c000047f246b870475e2c299556078cdad30
api/cloudcontroller/ccv2/feature_flag.go
https://github.com/cloudfoundry/cli/blob/5010c000047f246b870475e2c299556078cdad30/api/cloudcontroller/ccv2/feature_flag.go#L21-L36
go
train
// GetConfigFeatureFlags retrieves a list of FeatureFlag from the Cloud // Controller.
func (client Client) GetConfigFeatureFlags() ([]FeatureFlag, Warnings, error)
// GetConfigFeatureFlags retrieves a list of FeatureFlag from the Cloud // Controller. func (client Client) GetConfigFeatureFlags() ([]FeatureFlag, Warnings, error)
{ request, err := client.newHTTPRequest(requestOptions{ RequestName: internal.GetConfigFeatureFlagsRequest, }) if err != nil { return nil, nil, err } var featureFlags []FeatureFlag response := cloudcontroller.Response{ DecodeJSONResponseInto: &featureFlags, } err = client.connection.Make(request, &response) return featureFlags, response.Warnings, err }
cloudfoundry/cli
5010c000047f246b870475e2c299556078cdad30
api/router/connection_wrapper.go
https://github.com/cloudfoundry/cli/blob/5010c000047f246b870475e2c299556078cdad30/api/router/connection_wrapper.go#L13-L15
go
train
// WrapConnection wraps the current Client connection in the wrapper.
func (client *Client) WrapConnection(wrapper ConnectionWrapper)
// WrapConnection wraps the current Client connection in the wrapper. func (client *Client) WrapConnection(wrapper ConnectionWrapper)
{ client.connection = wrapper.Wrap(client.connection) }
cloudfoundry/cli
5010c000047f246b870475e2c299556078cdad30
actor/v3action/target.go
https://github.com/cloudfoundry/cli/blob/5010c000047f246b870475e2c299556078cdad30/actor/v3action/target.go#L11-L40
go
train
// SetTarget targets the Cloud Controller using the client and sets target // information in the actor based on the response.
func (actor Actor) SetTarget(settings TargetSettings) (Warnings, error)
// SetTarget targets the Cloud Controller using the client and sets target // information in the actor based on the response. func (actor Actor) SetTarget(settings TargetSettings) (Warnings, error)
{ if actor.Config.Target() == settings.URL && actor.Config.SkipSSLValidation() == settings.SkipSSLValidation { return nil, nil } var allWarnings Warnings warnings, err := actor.CloudControllerClient.TargetCF(ccv3.TargetSettings(settings)) if err != nil { return Warnings(warnings), err } allWarnings = Warnings(warnings) var info ccv3.Info info, _, warnings, err = actor.CloudControllerClient.GetInfo() allWarnings = append(allWarnings, Warnings(warnings)...) if err != nil { return allWarnings, err } actor.Config.SetTargetInformation(settings.URL, info.CloudControllerAPIVersion(), info.UAA(), "", // Oldest supported V3 version should be OK info.Logging(), info.Routing(), settings.SkipSSLValidation, ) actor.Config.SetTokenInformation("", "", "") return Warnings(warnings), nil }
cloudfoundry/cli
5010c000047f246b870475e2c299556078cdad30
actor/v3action/target.go
https://github.com/cloudfoundry/cli/blob/5010c000047f246b870475e2c299556078cdad30/actor/v3action/target.go#L43-L46
go
train
// ClearTarget clears target information from the actor.
func (actor Actor) ClearTarget()
// ClearTarget clears target information from the actor. func (actor Actor) ClearTarget()
{ actor.Config.SetTargetInformation("", "", "", "", "", "", false) actor.Config.SetTokenInformation("", "", "") }
cloudfoundry/cli
5010c000047f246b870475e2c299556078cdad30
api/cloudcontroller/ccv2/space.go
https://github.com/cloudfoundry/cli/blob/5010c000047f246b870475e2c299556078cdad30/api/cloudcontroller/ccv2/space.go#L34-L55
go
train
// UnmarshalJSON helps unmarshal a Cloud Controller Space response.
func (space *Space) UnmarshalJSON(data []byte) error
// UnmarshalJSON helps unmarshal a Cloud Controller Space response. func (space *Space) UnmarshalJSON(data []byte) error
{ var ccSpace struct { Metadata internal.Metadata `json:"metadata"` Entity struct { Name string `json:"name"` AllowSSH bool `json:"allow_ssh"` SpaceQuotaDefinitionGUID string `json:"space_quota_definition_guid"` OrganizationGUID string `json:"organization_guid"` } `json:"entity"` } err := cloudcontroller.DecodeJSON(data, &ccSpace) if err != nil { return err } space.GUID = ccSpace.Metadata.GUID space.Name = ccSpace.Entity.Name space.AllowSSH = ccSpace.Entity.AllowSSH space.SpaceQuotaDefinitionGUID = ccSpace.Entity.SpaceQuotaDefinitionGUID space.OrganizationGUID = ccSpace.Entity.OrganizationGUID return nil }
cloudfoundry/cli
5010c000047f246b870475e2c299556078cdad30
api/cloudcontroller/ccv2/space.go
https://github.com/cloudfoundry/cli/blob/5010c000047f246b870475e2c299556078cdad30/api/cloudcontroller/ccv2/space.go#L64-L89
go
train
// CreateSpace creates a new space with the provided spaceName in the org with // the provided orgGUID.
func (client *Client) CreateSpace(spaceName string, orgGUID string) (Space, Warnings, error)
// CreateSpace creates a new space with the provided spaceName in the org with // the provided orgGUID. func (client *Client) CreateSpace(spaceName string, orgGUID string) (Space, Warnings, error)
{ requestBody := createSpaceRequestBody{ Name: spaceName, OrganizationGUID: orgGUID, } bodyBytes, _ := json.Marshal(requestBody) request, err := client.newHTTPRequest(requestOptions{ RequestName: internal.PostSpaceRequest, Body: bytes.NewReader(bodyBytes), }) if err != nil { return Space{}, nil, err } var space Space response := cloudcontroller.Response{ DecodeJSONResponseInto: &space, } err = client.connection.Make(request, &response) return space, response.Warnings, err }
cloudfoundry/cli
5010c000047f246b870475e2c299556078cdad30
api/cloudcontroller/ccv2/space.go
https://github.com/cloudfoundry/cli/blob/5010c000047f246b870475e2c299556078cdad30/api/cloudcontroller/ccv2/space.go#L94-L114
go
train
// DeleteSpace deletes the Space associated with the provided // GUID. It will return the Cloud Controller job that is assigned to the // Space deletion.
func (client *Client) DeleteSpace(guid string) (Job, Warnings, error)
// DeleteSpace deletes the Space associated with the provided // GUID. It will return the Cloud Controller job that is assigned to the // Space deletion. func (client *Client) DeleteSpace(guid string) (Job, Warnings, error)
{ request, err := client.newHTTPRequest(requestOptions{ RequestName: internal.DeleteSpaceRequest, URIParams: Params{"space_guid": guid}, Query: url.Values{ "recursive": {"true"}, "async": {"true"}, }, }) if err != nil { return Job{}, nil, err } var job Job response := cloudcontroller.Response{ DecodeJSONResponseInto: &job, } err = client.connection.Make(request, &response) return job, response.Warnings, err }
cloudfoundry/cli
5010c000047f246b870475e2c299556078cdad30
api/cloudcontroller/ccv2/space.go
https://github.com/cloudfoundry/cli/blob/5010c000047f246b870475e2c299556078cdad30/api/cloudcontroller/ccv2/space.go#L118-L141
go
train
// GetSecurityGroupSpaces returns a list of Spaces based on the provided // SecurityGroup GUID.
func (client *Client) GetSecurityGroupSpaces(securityGroupGUID string) ([]Space, Warnings, error)
// GetSecurityGroupSpaces returns a list of Spaces based on the provided // SecurityGroup GUID. func (client *Client) GetSecurityGroupSpaces(securityGroupGUID string) ([]Space, Warnings, error)
{ request, err := client.newHTTPRequest(requestOptions{ RequestName: internal.GetSecurityGroupSpacesRequest, URIParams: map[string]string{"security_group_guid": securityGroupGUID}, }) if err != nil { return nil, nil, err } var fullSpacesList []Space warnings, err := client.paginate(request, Space{}, func(item interface{}) error { if space, ok := item.(Space); ok { fullSpacesList = append(fullSpacesList, space) } else { return ccerror.UnknownObjectInListError{ Expected: Space{}, Unexpected: item, } } return nil }) return fullSpacesList, warnings, err }
cloudfoundry/cli
5010c000047f246b870475e2c299556078cdad30
api/cloudcontroller/ccv2/space.go
https://github.com/cloudfoundry/cli/blob/5010c000047f246b870475e2c299556078cdad30/api/cloudcontroller/ccv2/space.go#L171-L196
go
train
// GetSpaces returns a list of Spaces based off of the provided filters.
func (client *Client) GetSpaces(filters ...Filter) ([]Space, Warnings, error)
// GetSpaces returns a list of Spaces based off of the provided filters. func (client *Client) GetSpaces(filters ...Filter) ([]Space, Warnings, error)
{ params := ConvertFilterParameters(filters) params.Add("order-by", "name") request, err := client.newHTTPRequest(requestOptions{ RequestName: internal.GetSpacesRequest, Query: params, }) if err != nil { return nil, nil, err } var fullSpacesList []Space warnings, err := client.paginate(request, Space{}, func(item interface{}) error { if space, ok := item.(Space); ok { fullSpacesList = append(fullSpacesList, space) } else { return ccerror.UnknownObjectInListError{ Expected: Space{}, Unexpected: item, } } return nil }) return fullSpacesList, warnings, err }
cloudfoundry/cli
5010c000047f246b870475e2c299556078cdad30
api/cloudcontroller/ccv2/space.go
https://github.com/cloudfoundry/cli/blob/5010c000047f246b870475e2c299556078cdad30/api/cloudcontroller/ccv2/space.go#L200-L215
go
train
// UpdateSpaceDeveloper grants the space developer role to the user or client // associated with the given UAA ID.
func (client *Client) UpdateSpaceDeveloper(spaceGUID string, uaaID string) (Warnings, error)
// UpdateSpaceDeveloper grants the space developer role to the user or client // associated with the given UAA ID. func (client *Client) UpdateSpaceDeveloper(spaceGUID string, uaaID string) (Warnings, error)
{ request, err := client.newHTTPRequest(requestOptions{ RequestName: internal.PutSpaceDeveloperRequest, URIParams: map[string]string{ "space_guid": spaceGUID, "developer_guid": uaaID, }, }) if err != nil { return Warnings{}, err } response := cloudcontroller.Response{} err = client.connection.Make(request, &response) return response.Warnings, err }
cloudfoundry/cli
5010c000047f246b870475e2c299556078cdad30
api/cloudcontroller/ccv2/space.go
https://github.com/cloudfoundry/cli/blob/5010c000047f246b870475e2c299556078cdad30/api/cloudcontroller/ccv2/space.go#L267-L291
go
train
// UpdateSpaceManagerByUsername grants the given username the space manager role.
func (client *Client) UpdateSpaceManagerByUsername(spaceGUID string, username string) (Warnings, error)
// UpdateSpaceManagerByUsername grants the given username the space manager role. func (client *Client) UpdateSpaceManagerByUsername(spaceGUID string, username string) (Warnings, error)
{ requestBody := updateRoleRequestBody{ Username: username, } bodyBytes, err := json.Marshal(requestBody) if err != nil { return Warnings{}, err } request, err := client.newHTTPRequest(requestOptions{ RequestName: internal.PutSpaceManagerByUsernameRequest, URIParams: map[string]string{"space_guid": spaceGUID}, Body: bytes.NewReader(bodyBytes), }) if err != nil { return nil, err } response := cloudcontroller.Response{} err = client.connection.Make(request, &response) return response.Warnings, err }
cloudfoundry/cli
5010c000047f246b870475e2c299556078cdad30
actor/v2v3action/actor.go
https://github.com/cloudfoundry/cli/blob/5010c000047f246b870475e2c299556078cdad30/actor/v2v3action/actor.go#L15-L20
go
train
// NewActor returns a new actor.
func NewActor(v2Actor V2Actor, v3Actor V3Actor) *Actor
// NewActor returns a new actor. func NewActor(v2Actor V2Actor, v3Actor V3Actor) *Actor
{ return &Actor{ V2Actor: v2Actor, V3Actor: v3Actor, } }
cloudfoundry/cli
5010c000047f246b870475e2c299556078cdad30
api/uaa/info.go
https://github.com/cloudfoundry/cli/blob/5010c000047f246b870475e2c299556078cdad30/api/uaa/info.go#L35-L40
go
train
// NewInfo returns back a new
func NewInfo(link string) Info
// NewInfo returns back a new func NewInfo(link string) Info
{ var info Info info.Links.Login = link info.Links.UAA = link return info }
cloudfoundry/cli
5010c000047f246b870475e2c299556078cdad30
api/cloudcontroller/ccv2/service_key.go
https://github.com/cloudfoundry/cli/blob/5010c000047f246b870475e2c299556078cdad30/api/cloudcontroller/ccv2/service_key.go#L56-L83
go
train
// CreateServiceKey creates a new service key using the provided name and // parameters for the requested service instance.
func (client *Client) CreateServiceKey(serviceInstanceGUID string, keyName string, parameters map[string]interface{}) (ServiceKey, Warnings, error)
// CreateServiceKey creates a new service key using the provided name and // parameters for the requested service instance. func (client *Client) CreateServiceKey(serviceInstanceGUID string, keyName string, parameters map[string]interface{}) (ServiceKey, Warnings, error)
{ requestBody := serviceKeyRequestBody{ ServiceInstanceGUID: serviceInstanceGUID, Name: keyName, Parameters: parameters, } bodyBytes, err := json.Marshal(requestBody) if err != nil { return ServiceKey{}, nil, err } request, err := client.newHTTPRequest(requestOptions{ RequestName: internal.PostServiceKeyRequest, Body: bytes.NewReader(bodyBytes), }) if err != nil { return ServiceKey{}, nil, err } var serviceKey ServiceKey response := cloudcontroller.Response{ DecodeJSONResponseInto: &serviceKey, } err = client.connection.Make(request, &response) return serviceKey, response.Warnings, err }
cloudfoundry/cli
5010c000047f246b870475e2c299556078cdad30
actor/pluginaction/install.go
https://github.com/cloudfoundry/cli/blob/5010c000047f246b870475e2c299556078cdad30/actor/pluginaction/install.go#L35-L59
go
train
// CreateExecutableCopy makes a temporary copy of a plugin binary and makes it // executable. // // config.PluginHome() + /temp is used as the temp dir instead of the system // temp for security reasons.
func (actor Actor) CreateExecutableCopy(path string, tempPluginDir string) (string, error)
// CreateExecutableCopy makes a temporary copy of a plugin binary and makes it // executable. // // config.PluginHome() + /temp is used as the temp dir instead of the system // temp for security reasons. func (actor Actor) CreateExecutableCopy(path string, tempPluginDir string) (string, error)
{ tempFile, err := makeTempFile(tempPluginDir) if err != nil { return "", err } // add '.exe' to the temp file if on Windows executablePath := generic.ExecutableFilename(tempFile.Name()) err = os.Rename(tempFile.Name(), executablePath) if err != nil { return "", err } err = fileutils.CopyPathToPath(path, executablePath) if err != nil { return "", err } err = os.Chmod(executablePath, 0700) if err != nil { return "", err } return executablePath, nil }
cloudfoundry/cli
5010c000047f246b870475e2c299556078cdad30
actor/pluginaction/install.go
https://github.com/cloudfoundry/cli/blob/5010c000047f246b870475e2c299556078cdad30/actor/pluginaction/install.go#L63-L75
go
train
// DownloadExecutableBinaryFromURL fetches a plugin binary from the specified // URL, if it exists.
func (actor Actor) DownloadExecutableBinaryFromURL(pluginURL string, tempPluginDir string, proxyReader plugin.ProxyReader) (string, error)
// DownloadExecutableBinaryFromURL fetches a plugin binary from the specified // URL, if it exists. func (actor Actor) DownloadExecutableBinaryFromURL(pluginURL string, tempPluginDir string, proxyReader plugin.ProxyReader) (string, error)
{ tempFile, err := makeTempFile(tempPluginDir) if err != nil { return "", err } err = actor.client.DownloadPlugin(pluginURL, tempFile.Name(), proxyReader) if err != nil { return "", err } return tempFile.Name(), nil }
cloudfoundry/cli
5010c000047f246b870475e2c299556078cdad30
actor/pluginaction/install.go
https://github.com/cloudfoundry/cli/blob/5010c000047f246b870475e2c299556078cdad30/actor/pluginaction/install.go#L79-L82
go
train
// FileExists returns true if the file exists. It returns false if the file // doesn't exist or there is an error checking.
func (actor Actor) FileExists(path string) bool
// FileExists returns true if the file exists. It returns false if the file // doesn't exist or there is an error checking. func (actor Actor) FileExists(path string) bool
{ _, err := os.Stat(path) return err == nil }
cloudfoundry/cli
5010c000047f246b870475e2c299556078cdad30
util/configv3/plugins_config.go
https://github.com/cloudfoundry/cli/blob/5010c000047f246b870475e2c299556078cdad30/util/configv3/plugins_config.go#L32-L40
go
train
// CalculateSHA1 returns the SHA1 value of the plugin executable. If an error // is encountered calculating SHA1, N/A is returned
func (p Plugin) CalculateSHA1() string
// CalculateSHA1 returns the SHA1 value of the plugin executable. If an error // is encountered calculating SHA1, N/A is returned func (p Plugin) CalculateSHA1() string
{ fileSHA, err := util.NewSha1Checksum(p.Location).ComputeFileSha1() if err != nil { return notApplicable } return fmt.Sprintf("%x", fileSHA) }