func bdd(t *testing.T, lead string, args ...interface{}) { var msg bytes.Buffer fmt.Fprint(&msg, color.Sprintf("@{g}%s ", lead)) for i, each := range args { if i%2 == 0 { fmt.Fprint(&msg, color.Sprintf("@{g}%v ", each)) } else { fmt.Fprint(&msg, color.Sprintf("@{m}%v ", each)) } } t.Log(msg.String()) }
func getProjectIssues(gitlab *gogitlab.Gitlab, projectId int) { events := gitlab.ProjectEvents(projectId) for _, event := range events { var iconName string switch event.TargetType { case "Issue": iconName = ":beer:" default: iconName = ":punch:" } //fmt.Printf("ProjectID[%d] action[%s] targetId[%d] targetType[%s] targetTitle[%s]\n", event.ProductId, event.ActionName,event.TargetId, event.TargetType, event.TargetTitle) if event.TargetId != 0 { actionText := color.Sprintf("@y[%s]", event.ActionName) repositoriesText := color.Sprintf("@c%s(%d)", event.TargetType, event.TargetId) userText := color.Sprintf("@c%s", event.Data.UserName) titleText := color.Sprintf("@g%s", event.TargetTitle) emoji.Println("@{"+iconName+"}", actionText, repositoriesText, userText, titleText) } else if event.TargetId == 0 { actionText := color.Sprintf("@y[%s]", event.ActionName) repositoriesText := color.Sprintf("@c%s", event.Data.Repository.Name) userText := color.Sprintf("@c%s", event.Data.UserName) var titleText string if event.Data.TotalCommitsCount > 0 { commitMessage := event.Data.Commits[0].Message commitMessage = strings.Replace(commitMessage, "\n\n", "\t", -1) titleText = color.Sprintf("@g%s", commitMessage) } else if event.Data.Before == "0000000000000000000000000000000000000000" { titleText = color.Sprintf("@g%s %s", emoji.Sprint("@{:fire:}"), "create New branch") } emoji.Println("@{"+iconName+"}", actionText, repositoriesText, userText, titleText) // fmt.Println(" \t user -> ", event.Data.UserName, event.Data.UserId) // fmt.Println(" \t author -> ", event.Data.AuthorId) // // fmt.Println(" \t\t name -> ", event.Data.Repository.Name) // fmt.Println(" \t\t description -> ", event.Data.Repository.Description) // fmt.Println(" \t\t gitUrl -> ", event.Data.Repository.GitUrl) // fmt.Println(" \t\t pageUrl -> ", event.Data.Repository.PageUrl) // // fmt.Println(" \t\t totalCount -> ", event.Data.TotalCommitsCount) // // if event.Data.TotalCommitsCount > 0 { // fmt.Println(" \t\t message -> ", event.Data.Commits[0].Message) // fmt.Println(" \t\t time -> ", event.Data.Commits[0].Timestamp) // } } } // // for _, event := range events { // // } }
func TODO(t *testing.T, comment string, args ...interface{}) { if PrintColorsEnabled { t.Log(append(append([]interface{}{}, fmt.Sprintf(" ")+color.Sprintf("@{R}%s", "TODO:"+" "+comment)), args...)...) } else { t.Log(append(append([]interface{}{}, "Comment:"+" "+comment), args...)...) } }
// ColoredPrintf does printf in colored way + newline func (p *Progress) ColoredPrintf(msg string, a ...interface{}) { if RunningOnTerminal() { p.queue <- printTask{code: codePrint, message: color.Sprintf(msg, a...) + "\n"} } else { // stip color marks var prev rune msg = strings.Map(func(r rune) rune { if prev == '@' { prev = 0 if r == '@' { return r } return -1 } prev = r if r == '@' { return -1 } return r }, msg) p.Printf(msg+"\n", a...) } }
func (p *Printer) Sprintf(fmtstr string, args ...interface{}) string { if p.NoColors { fmtstr = removeMeta.ReplaceAllLiteralString(fmtstr, "") return fmt.Sprintf(fmtstr, args...) } else { return color.Sprintf(fmtstr, args...) } }
// Scolorf returns a string colorized for terminal output using the syntaxCode (unless that's empty). // Requires the syntax defined on https://github.com/wsxiaoys/terminal/blob/master/color/color.go . func Scolorf(syntaxCode string, format string, args ...interface{}) string { plainFormatted := fmt.Sprintf(format, args...) if len(syntaxCode) > 0 && TerminalColorsEnabled { // cannot pass the code as a string param return color.Sprintf(syntaxCode+"%s%s", FailMessagePrefix, plainFormatted) } return FailMessagePrefix + plainFormatted }
// Scolorf returns a string colorized for terminal output using the syntaxCode (unless that's empty). // Requires the syntax defined on https://github.com/wsxiaoys/terminal/blob/master/color/color.go . func Scolorf(syntaxCode string, format string, args ...interface{}) string { plainFormatted := fmt.Sprintf(format, args...) if len(syntaxCode) > 0 && AssertColorsEnabled { // cannot pass the code as a string param return color.Sprintf(syntaxCode+"%s", plainFormatted) } return plainFormatted }
func output(hostname, servicename, v interface{}) { // define quick color/graphic view of output var s, m, a string if state(v) == 0 { s = color.Sprintf("@{g}%-10s", "[OK]") } else if state(v) == 1 { s = color.Sprintf("@{y}%-10s", "[WARNING]") } else if state(v) == 2 { s = color.Sprintf("@{r}%-10s", "[CRITICAL]") } if notifications(v) { m = color.Sprintf("@{g} %v ", ` `) } else { m = color.Sprintf("@{r} %v ", `Ø`) } if acknowledged(v) { a = color.Sprintf("@{g} %v ", `√`) } else { a = color.Sprintf("@{g} %v ", ` `) } // this just incase if change mind use different syntax switch v := v.(type) { default: case *nagiosToJson.Hoststatus: // color.Printf("%-10s: %v %v %v %v %v\n", hostname, m, s, a, v.Plugin_output, time.Since(str2time(v.Last_check))) color.Printf("%-10s: %-10v %v %v %v %v %v\n", hostname, servicename, m, s, a, v.Plugin_output, time.Since(str2time(v.Last_check))) case *nagiosToJson.Servicestatus: color.Printf("%-10s: %-10v %v %v %v %v %v\n", hostname, servicename, m, s, a, v.Plugin_output, time.Since(str2time(v.Last_check))) } }
func (p *Printer) Sprintf(colorfmt, plainfmt string, args ...interface{}) string { if p.NoColors { return fmt.Sprintf(plainfmt, args...) } else { return color.Sprintf(colorfmt, args...) } }
func (v *GRVisitor) SearchFileName(fn string) { if !v.pattern.MatchString(fn) { return } colored := v.pattern.ReplaceAllStringFunc(fn, func(wrap string) string { return color.Sprintf("@Y%s", wrap) }) fmt.Println(colored) }
func (s *LoggingServer) ServeHTTP(w http.ResponseWriter, req *http.Request) { s.mu.RLock() defer s.mu.RUnlock() if i := sort.SearchStrings(s.ExcludePaths, req.URL.Path); i < len(s.ExcludePaths) && req.URL.Path == s.ExcludePaths[i] { return } req.ParseForm() // Log request var data string for key, _ := range req.Form { data += "\n " if value := req.Form.Get(key); value != "" { data += color.Sprintf("@.%s@|@w = @|%s", key, value) } else { data += color.Sprintf("%s", key) } } log.Print(color.Sprintf("@c%s @{!y}%s", req.Method, req.RequestURI)) if data != "" { color.Printf(" @bRequest@|%s\n", data) } // Find matcher matcher := s.findMatcher(req) if matcher != nil { matcher.Write(w, req) // TODO Better response logging response := matcher.Response color.Printf(" @gResponse@|\n %+v\n", response) } else { color.Print(" @rUnmatched@|\n") w.WriteHeader(http.StatusNotFound) w.Header().Set("Content-Type", "text/html") io.WriteString(w, "<html><body>Unmatched request, please configure a mock request for path "+req.URL.Path+" and method "+req.Method+"</body></html>\n") } }
func (v *GRVisitor) SearchFile(fn string, content []byte) { lines := IntList([]int{}) binary := false if bytes.IndexByte(content, 0) != -1 { binary = true } for _, info := range v.FindAllIndex(content) { if lines.Contains(info.num) { continue } if v.prependNewLine { fmt.Println("") v.prependNewLine = false } first := len(lines) == 0 lines = append(lines, info.num) if first { if binary && !*onlyName { fmt.Printf("Binary file %s matches\n", fn) break } else { color.Printf("@g%s\n", fn) } } if *onlyName { return } color.Printf("@!@y%d:", info.num) coloredLine := v.pattern.ReplaceAllStringFunc(string(info.line), func(wrap string) string { return color.Sprintf("@Y%s", wrap) }) fmt.Printf("%s\n", coloredLine) } if len(lines) > 0 { v.prependNewLine = true } }
func TestUpdateProject(t *testing.T) { ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { r.Header.Set("Content-Type", "application/json") jsonOutput := `{ "slug": "gemnasium/API_project", "name: "API_project", "description": "This is a brief description of a project on Gemnasium" "origin": "github", "private": false, "color": "green", "monitored": true, "unmonitored_reason": "" }` fmt.Fprintln(w, jsonOutput) })) defer ts.Close() old := os.Stdout // keep backup of the real stdout r, w, _ := os.Pipe() os.Stdout = w config.APIEndpoint = ts.URL var name, desc *string var monitored *bool nameStr := "API_project" name = &nameStr descStr := "A desc" desc = &descStr monitoredBool := false monitored = &monitoredBool p := &Project{Slug: "blah"} err := p.Update(name, desc, monitored) if err != nil { t.Fatal(err) } w.Close() var buf bytes.Buffer io.Copy(&buf, r) os.Stdout = old // restoring the real stdout expectedOutput := color.Sprintf("@gProject %s updated succesfully\n", "blah") if buf.String() != expectedOutput { t.Errorf("Expected ouput:\n%s\n\nGot:\n%s", expectedOutput, buf.String()) } }
// 絵文字付きターミナル用のコメント作成(Activiyベース) func createFeedCommentText(currentUser *gogitlab.User, feedCommit *gogitlab.FeedCommit) string { var iconName string if strings.Contains(feedCommit.Title, "commented") { iconName = ":speech_balloon:" } else if strings.Contains(feedCommit.Title, "pushed") { iconName = ":punch:" } else if strings.Contains(feedCommit.Title, "closed") { iconName = ":white_check_mark:" } else if strings.Contains(feedCommit.Title, "opened") { iconName = ":fire:" } else if strings.Contains(feedCommit.Title, "accepted") { iconName = ":atm:" } else { iconName = ":beer:" } if currentUser.Name == feedCommit.Author.Name { return emoji.Sprint("@{"+iconName+"}", color.Sprintf("@y[%s] %s", feedCommit.Updated.Format(time.ANSIC), feedCommit.Title)) } else { return emoji.Sprint("@{"+iconName+"}", fmt.Sprintf("[%s] %s", feedCommit.Updated.Format(time.ANSIC), feedCommit.Title)) } }
// ColoredPrintf does printf in colored way + newline func (p *Progress) ColoredPrintf(msg string, a ...interface{}) { if RunningOnTerminal() { p.queue <- printTask{code: codePrint, message: color.Sprintf(msg, a...) + "\n"} } else { // stip color marks var inColorMark, inCurly bool msg = strings.Map(func(r rune) rune { if inColorMark { if inCurly { if r == '}' { inCurly = false inColorMark = false return -1 } } else { if r == '{' { inCurly = true } else if r == '@' { return '@' } else { inColorMark = false } } return -1 } if r == '@' { inColorMark = true return -1 } return r }, msg) p.Printf(msg+"\n", a...) } }
// Panicf is equivalent to Printf() followed by a call to panic(). func Panicf(format string, v ...interface{}) { s := color.Sprintf(format, v...) std.Output(2, s) panic(s) }
func bluePrint(text string) string { return color.Sprintf("@b%s", text) }
func yellowPrint(text string) string { return color.Sprintf("@y%s", text) }
func greenPrint(text string) string { return color.Sprintf("@g%s", text) }
func redPrint(text string) string { return color.Sprintf("@r%s", text) }
func blackPrint(text string) string { return color.Sprintf("@k%s", text) }
func whitePrint(text string) string { return color.Sprintf("@w%s", text) }
func cyanPrint(text string) string { return color.Sprintf("@c%s", text) }
func magentaPrint(text string) string { return color.Sprintf("@m%s", text) }
func main() { runtime.GOMAXPROCS(runtime.NumCPU()) if *testFile { go byteCounter() } mux := http.NewServeMux() mux.HandleFunc("/", func(w http.ResponseWriter, req *http.Request) { if stop { return } wg.Add(1) t1 := time.Now() if *veryverbose { dumpRequest(req, true, true) } defer wg.Done() defer func() { var res string if proxyMethod { res = fmt.Sprintf("%v %v %v %v %v", req.RemoteAddr, req.Method, req.URL.String(), NanoToSecond(time.Since(t1)), w.Header().Get("X-Upstream-Response-Time")) } else { res = fmt.Sprintf("%v %v %v %v %v", req.RemoteAddr, req.Method, req.URL.String(), NanoToSecond(time.Since(t1)), "-") } if *colors { log.Println(color.Sprintf("@{g}%s", res)) } else { log.Println(res) } }() ch <- true if proxyMethod { if isbridge { scheme := "https" if req.TLS == nil { scheme = "http" } proxyHandler(w, req, fmt.Sprintf("%s://%s", scheme, bridgeIp)) } else { proxyHandler(w, req, *upstream) } return } // if not just return code if *rt != -1 { w.WriteHeader(*rt) dumpRequest(req, true, true) return } // w.Header().Add("Cache-Control", "no-cache") w.Header().Add("Connection", "Keep-Alive") if req.Method == "GET" && !*uploadonly && !*testFile { w.Header().Add("Cache-Control", "no-cache") f := &fileHandler{http.Dir(*fdir)} f.ServeHTTP(w, req) } else if *testFile { testFileHandler(w, req) } else if req.Method == "POST" || req.Method == "PUT" { uploadHandler(w, req) } }) log.Println("Listening on", getips()) if proxyMethod { log.Println("Upstream", *upstream, "tcp", tcp) } if *testFile { log.SetOutput(ioutil.Discard) } done := make(chan bool) if *sock { go func() { conf := &socks5.Config{} conf.Resolver = new(Resolver) conf.Rewriter = new(Rewriter) server, err := socks5.New(conf) if err != nil { panic(err) } if err := server.ListenAndServe("tcp", *fport); err != nil { panic(err) } }() } else if tcp { go tcpProxy() } else { if !isbridge { if len(*crt) > 0 && len(*key) > 0 { go func() { if err := http.ListenAndServeTLS(*fport, *crt, *key, mux); err != nil { panic(err) } }() } else { go func() { if err := http.ListenAndServe(*fport, mux); err != nil { panic(err) } }() } } else { go func() { if err := http.ListenAndServe(":80", mux); err != nil { panic(err) } }() if len(*crt) > 0 && len(*key) > 0 { go func() { if err := http.ListenAndServeTLS(":443", *crt, *key, mux); err != nil { panic(err) } }() } } } if *notimeout { *timeout = time.Duration(time.Hour * 24 * 365 * 10) } t := time.Tick(*timeout) go func() { for { select { case <-t: log.Println(os.Args[0], "auto stop, no more request accessable") stop = true wg.Wait() done <- true case <-ch: t = time.Tick(*timeout) } } }() if <-done { log.Println("stop") os.Exit(0) } }
// Printf calls Output to print to the standard logger. // Arguments are handled in the manner of fmt.Printf. func Printf(format string, v ...interface{}) { std.Output(2, color.Sprintf(format, v...)) }
// Fatalf is equivalent to Printf() followed by a call to os.Exit(1). func Fatalf(format string, v ...interface{}) { std.Output(2, color.Sprintf(format, v...)) os.Exit(1) }
func TODO(t *testing.T, comment string, args ...interface{}) { t.Log(append(append([]interface{}{}, fmt.Sprintf(" ")+color.Sprintf("@{R}%s", "TODO:"+" "+comment)), args...)...) }
func (w *TerminalWriter) Colorf(format string, a ...interface{}) *TerminalWriter { w.checkOutput(color.Sprintf(format, a...)) return w }
func debugLog(s string, v ...interface{}) { if AccessLog { log.Println(color.Sprintf("@{kw}"+s, v...)) } }