Beispiel #1
0
func showResult(commits []*commit, keyword string) {

	repoWidth := maxRepoWidth(commits)
	repoFmt := fmt.Sprintf("%%-%ds", repoWidth)

	urlWidth := maxURLWidth(commits)
	urlFmt := fmt.Sprintf("%%-%ds", urlWidth)

	msgWidth := maxMessageWidth(commits)

	fmt.Printf(" %s | %s | %s | message \n",
		color.BlueString(repoFmt, "Repository"),
		color.CyanString("%-7s", "sha1"),
		fmt.Sprintf(urlFmt, "url"),
	)
	fmt.Println(strings.Repeat("-", repoWidth+msgWidth+urlWidth+18))

	for _, c := range commits {
		fmt.Printf(" %s | %7s | %s | %s\n",
			color.BlueString(repoFmt, c.Repo),
			color.CyanString(c.Sha1),
			fmt.Sprintf(urlFmt, c.CommitURL),
			highlightWords(c.Message, keyword),
		)
	}
}
Beispiel #2
0
func (obj *Decorator) replacePlaceholders(
	str string,
	placeholders map[string]interface{},
) string {
	r := regexp.MustCompile(":\\w+")
	for _, key := range r.FindAllString(str, -1) {
		name := strings.Replace(key, ":", "", -1)

		if value, ok := placeholders[name]; ok {
			switch reflect.TypeOf(value).String() {
			case "string":
				value = color.CyanString(fmt.Sprint(value))
				break
			case "int64":
				value = color.BlueString(fmt.Sprintf("%d", value))
			case "float64":
				if regexp.MustCompile("^[0-9]+(.[0]+)?").MatchString(fmt.Sprintf("%f", value)) {
					value = fmt.Sprintf("%d", int64(value.(float64)))
				} else {
					value = fmt.Sprintf("%f", value)
				}

				value = color.BlueString(value.(string))
				break
			default:
				value = fmt.Sprint(value)
			}

			str = strings.Replace(str, key, value.(string), -1)
		}
	}

	return str
}
Beispiel #3
0
// isIndexStatic returns true if a block does not have a modify-index Phi.
func (fa *FairnessAnalysis) isIndexStatic(blk *ssa.BasicBlock) bool {
	for _, instr := range blk.Instrs {
		switch instr := instr.(type) {
		case *ssa.DebugRef:
		case *ssa.Phi:
			if len(instr.Comment) > 0 {
				fa.logger.Println(color.BlueString("  note: Index var %s", instr.Comment))
				return false
			}
		}
	}
	fa.logger.Println(color.BlueString("  note: Index var not found"))
	return true
}
Beispiel #4
0
func (f *Fissile) reportHashDiffs(hashDiffs *HashDiffs) {
	if len(hashDiffs.DeletedKeys) > 0 {
		f.UI.Println(color.RedString("Dropped keys:"))
		sort.Strings(hashDiffs.DeletedKeys)
		for _, v := range hashDiffs.DeletedKeys {
			f.UI.Printf("  %s\n", v)
		}
	}
	if len(hashDiffs.AddedKeys) > 0 {
		f.UI.Println(color.GreenString("Added keys:"))
		sort.Strings(hashDiffs.AddedKeys)
		for _, v := range hashDiffs.AddedKeys {
			f.UI.Printf("  %s\n", v)
		}
	}
	if len(hashDiffs.ChangedValues) > 0 {
		f.UI.Println(color.BlueString("Changed values:"))
		sortedKeys := make([]string, len(hashDiffs.ChangedValues))
		i := 0
		for k := range hashDiffs.ChangedValues {
			sortedKeys[i] = k
			i++
		}
		sort.Strings(sortedKeys)
		for _, k := range sortedKeys {
			v := hashDiffs.ChangedValues[k]
			f.UI.Printf("  %s: %s => %s\n", k, v[0], v[1])
		}
	}
}
Beispiel #5
0
func (rl *ResponseLogWriter) logCode(code int, status string) {
	var codestr string
	switch {
	case code >= 200 && code < 300:
		codestr = color.GreenString("%d %s", code, status)
	case code >= 300 && code < 400:
		codestr = color.BlueString("%d %s", code, status)
	case code >= 400 && code < 500:
		codestr = color.YellowString("%d %s", code, status)
	case code >= 500 && code < 600:
		codestr = color.RedString("%d %s", code, status)
	default:
		codestr = fmt.Sprintf("%d %s", code, status)
	}
	cl := rl.Header().Get("content-length")
	if cl != "" {
		cli, err := strconv.Atoi(cl)
		if err != nil {
			cl = "invalid content length header"
		} else {
			cl = fmt.Sprintf("%s", humanize.Bytes(uint64(cli)))
		}
	}
	rl.Log.Say("<- %s %s", codestr, cl)
}
Beispiel #6
0
func main() {
	l := termlog.NewLog()
	testpatt(l)

	g := l.Group()
	g.Say("This is a group...")
	testpatt(g)
	g.Done()

	g = l.Group()
	g.Say("Here are some composed colours...")
	g.Say(
		"%s %s %s",
		color.RedString("red"),
		color.GreenString("green"),
		color.BlueString("blue"),
	)
	g.Done()

	l.Enable("demo")
	g = l.Group()
	g.SayAs("disabled", "These don't show...")
	g.SayAs("demo", "Some named log entries...")
	g.SayAs("demo", "This is a test")
	g.SayAs("disabled", "This is a test")
	g.Done()

	g = l.Group()
	g.Say("Disabled colour output...")
	l.NoColor()
	testpatt(g)
	g.Done()
}
Beispiel #7
0
func New(separator string) *tree {
	return &tree{
		separator,
		&node{},
		color.BlueString("%%s"),
		true,
	}
}
Beispiel #8
0
func (a Samidare) Do() error {
	fmt.Fprintf(color.Output, "TestName : %s \n", color.GreenString("%s", a.Name))

	for idx, testCase := range a.GetTestCases() {
		fmt.Fprintf(color.Output, "TestCaseName: [%d] %s\n", idx+1, color.GreenString("%s", testCase.Name))

		req, err := testCase.Request.BuildRequest()
		if err != nil {
			fmt.Fprintf(color.Output, "%s\n", color.RedString("%s", err.Error()))
			continue
		}
		resp, err := a.client.Do(req)
		if err != nil {
			fmt.Fprintf(color.Output, "%s\n", color.RedString("%s", err.Error()))
			continue
		}

		if resp.StatusCode != testCase.Response.Status {
			fmt.Fprintf(color.Output, "NG status: %s\n", color.RedString("%d != %d", resp.StatusCode, testCase.Response.Status))
		} else {
			fmt.Fprintf(color.Output, "OK status: %s\n", color.BlueString("%d == %d", resp.StatusCode, testCase.Response.Status))
		}

		for k, v := range testCase.Response.Headers {
			if resp.Header[k][0] != fmt.Sprintf("%v", v) {
				fmt.Fprintf(color.Output, "OK %s: %s\n", k, color.RedString("%v != %v", resp.Header[k][0], v))
			} else {
				fmt.Fprintf(color.Output, "OK %s: %s\n", k, color.BlueString("%v == %v", resp.Header[k][0], v))
			}
		}

		data, err := ioutil.ReadAll(resp.Body)
		defer resp.Body.Close()
		if err != nil {
			log.Println(err)
		} else {
			// TODO: Option
			//			fmt.Println(string(data))
			_ = data
		}
	}

	return nil
}
func testFiles(t *testing.T, files []string, loader *Loader) {
	var passing, total, schemaErrors int
	for _, file := range files {
		f, err := os.Open(file)
		if err != nil {
			t.Fatalf("Failed to open %q: %s", file, err)
		}
		v, err := json.Parse(f)
		f.Close()
		if err != nil {
			t.Fatalf("Failed to parse %q: %s", file, err)
		}

		tests, ok := v.(*json.Array)
		if !ok {
			t.Fatalf("Content of %q is not an array: %T", file, v)
		}
		for i, tt := range tests.Value {
			test, ok := tt.(*json.Object)
			if !ok {
				t.Fatalf("Test %d in %q is not an object", i, file)
			}
			t.Logf(color.BlueString("=====> Testing %s, case %d: %s", file, i, test.Find("description")))
			schema := test.Find("schema")
			err := ValidateDraft04Schema(schema)
			if err != nil {
				t.Errorf(color.RedString("schema does not pass validation: %s", err))
				schemaErrors++
			}
			v, _ := NewValidator(schema, loader) // not checking the error since schema is already validated
			cases := test.Find("tests").(*json.Array)
			for _, c := range cases.Value {
				total++
				case_ := c.(*json.Object)
				valid := case_.Find("valid").(*json.Bool).Value
				err := v.Validate(case_.Find("data"))
				switch {
				case err == nil && valid:
					passing++
					t.Logf("%s %s", color.GreenString("PASSED"), case_.Find("description"))
				case err != nil && !valid:
					passing++
					t.Logf("%s %s: %s", color.GreenString("PASSED"), case_.Find("description"), err)
				case err != nil && valid:
					t.Errorf("%s %s: %s", color.RedString("FAILED"), case_.Find("description"), err)
				case err == nil && !valid:
					t.Errorf("%s %s", color.RedString("FAILED"), case_.Find("description"))
				}
			}
		}
	}
	t.Logf("Passing %d out of %d tests (%g%%)", passing, total, float64(passing)/float64(total)*100)
	if schemaErrors > 0 {
		t.Logf("%d schemas failed validation", schemaErrors)
	}
}
Beispiel #10
0
func (c container) updateCache(hash string, body string, backendURL string, async bool) (string, error) {
	var response string
	var err error

	if c.lockUpdate(hash) == false {
		if async == true {
			log.Debug(fmt.Sprintf("%s %s", hash, color.RedString("LOCKED")))
			return response, err
		}
	}

	redisConn := c.pool.Get()
	defer redisConn.Close()

	log.Debug("%s %s", hash, color.BlueString("UPDATE"))

	httpClient := http.Client{Timeout: time.Duration(600 * time.Second)}
	resp, httperror := httpClient.Post(backendURL, "application/JSON", strings.NewReader(body))

	if httperror == nil {
		if resp.StatusCode != 200 {
			log.Error(fmt.Sprintf("Backend error code: %v ", resp.StatusCode))
			return response, err
		}

		requestBody, err := ioutil.ReadAll(resp.Body)
		if err != nil {
			log.Error(fmt.Sprintf("body read failed: %s : %s", hash, err.Error()))
		}

		response = string(requestBody)
		if response != "" {
			_, err = redisConn.Do("SET", hash, string(requestBody))
			if err != nil {
				log.Error(fmt.Sprintf("key set failed: %s : %s", hash, err.Error()))
				return response, err
			}
			log.Debug(fmt.Sprintf("%s %s", hash, color.GreenString("SET")))
			_, err = redisConn.Do("EXPIRE", hash, config.expire)
			if err != nil {
				log.Error(fmt.Sprintf("key expire set failed: %s : %s", hash, err.Error()))
				return response, err
			}
		} else {
			log.Error("Empty backend response")
			fmt.Println(resp)
		}

	} else {
		log.Error(fmt.Sprintf("Backend request failure: %s", httperror.Error()))
	}

	c.unlockUpdate(hash)

	return response, err
}
Beispiel #11
0
func (app *App) Interactive() {
	rl, err := readline.NewEx(&readline.Config{
		Prompt:      color.BlueString("say » "),
		HistoryFile: app.Config.HistoryFile,
	})
	if err != nil {
		log.Fatal(err)
	}
	defer rl.Close()
	app.Log.SetOutput(rl.Stderr())
	log.SetOutput(rl.Stderr())
	color.Output = ansicolor.NewAnsiColorWriter(rl.Stderr())

	pings := make(map[string]time.Time)

	// Subscribe to all replies and print them to stdout
	app.Client.Subscribe("", "self", func(msg sarif.Message) {
		text := msg.Text
		if text == "" {
			text = msg.Action + " from " + msg.Source
		}
		if msg.IsAction("err") {
			text = color.RedString(text)
		}

		if sent, ok := pings[msg.CorrId]; ok {
			text += color.YellowString("[%.1fms]", time.Since(sent).Seconds()*1e3)
		}
		log.Println(color.GreenString(" « ") + strings.Replace(text, "\n", "\n   ", -1))
	})

	// Interactive mode sends all lines from stdin.
	for {
		line, err := rl.Readline()
		if err != nil {
			if err == io.EOF {
				return
			}
			log.Fatal(err)
		}
		if len(line) == 0 {
			continue
		}

		// Publish natural message
		msg := sarif.Message{
			Id:     sarif.GenerateId(),
			Action: "natural/handle",
			Text:   line,
		}
		if *profile {
			pings[msg.Id] = time.Now()
		}
		app.Client.Publish(msg)
	}
}
Beispiel #12
0
func (e *Entry) Row() []string {
	y, m, d := e.Time.Date()
	date := color.BlueString("%d/%d/%d", m, d, y)
	ip := color.RedString("%s", e.Ip)
	attempts := color.GreenString("%d", e.Attempts)
	user := color.YellowString("%s", e.User)
	auth := color.WhiteString("%s", e.AuthType)
	proto := color.CyanString("%s", e.Protocol)
	port := e.Port
	server := e.Server
	return []string{date, ip, attempts, user, auth, proto, port, server}
}
Beispiel #13
0
// Logo with color
func Logo() string {
	var logo string

	logo += "\n\n"
	logo += color.GreenString("  ██╗  ██╗ ██████╗ ███╗   ███╗ █████╗ ███╗   ██╗██████╗  █████╗\n")
	logo += color.MagentaString("  ██║ ██╔╝██╔═══██╗████╗ ████║██╔══██╗████╗  ██║██╔══██╗██╔══██╗\n")
	logo += color.YellowString("  █████╔╝ ██║   ██║██╔████╔██║███████║██╔██╗ ██║██║  ██║███████║\n")
	logo += color.CyanString("  ██╔═██╗ ██║   ██║██║╚██╔╝██║██╔══██║██║╚██╗██║██║  ██║██╔══██║\n")
	logo += color.BlueString("  ██║  ██╗╚██████╔╝██║ ╚═╝ ██║██║  ██║██║ ╚████║██████╔╝██║  ██║\n")
	logo += color.RedString("  ╚═╝  ╚═╝ ╚═════╝ ╚═╝     ╚═╝╚═╝  ╚═╝╚═╝  ╚═══╝╚═════╝ ╚═╝  ╚═╝")

	return logo
}
Beispiel #14
0
func showResult(result QueryResult, url, keyword string, page int) {
	commits := result.Commits
	if len(commits) == 0 {
		fmt.Println("No Results Found.")
		fmt.Printf("  url: %s\n\n", url)
		return
	}
	fmt.Printf("Search Result : %s : %d/%s pages\n",
		result.ResultCount,
		page,
		result.TotalPages,
	)
	fmt.Printf("  url: %s\n\n", url)

	repoWidth := maxRepoWidth(commits)
	repoFmt := fmt.Sprintf("%%-%ds", repoWidth)

	urlWidth := maxURLWidth(commits)
	urlFmt := fmt.Sprintf("%%-%ds", urlWidth)

	msgWidth := maxMessageWidth(commits)

	fmt.Fprintf(color.Output, " %s | %s | %s | message \n",
		color.BlueString(repoFmt, "Repository"),
		color.CyanString("%-7s", "sha1"),
		fmt.Sprintf(urlFmt, "url"),
	)
	fmt.Println(strings.Repeat("-", repoWidth+msgWidth+urlWidth+18))

	for _, c := range commits {
		fmt.Fprintf(color.Output, " %s | %7s | %s | %s\n",
			color.BlueString(repoFmt, c.Repo),
			color.CyanString(c.Sha1),
			fmt.Sprintf(urlFmt, c.CommitURL),
			highlightWords(c.Message, keyword),
		)
	}
}
Beispiel #15
0
// runListSecretsCommand retrieves a listing of the secrets under one or more paths
func runListSecretsCommand(cx *cli.Context, factory *commandFactory) error {
	bucket := cx.String("bucket")
	suffix := cx.GlobalString("suffix")
	longListing := cx.Bool("long")
	recursive := cx.Bool("recursive")
	paths := cx.Args()

	if bucket == "" {
		return fmt.Errorf("you have not specified a bucket to list files")
	}

	if len(paths) <= 0 {
		paths = append(paths, "")
	}

	// step: iterate the paths specified and list the secrets
	for _, path := range paths {
		path := filterPath(path)

		files, err := factory.s3.listObjects(bucket, path, recursive)
		if err != nil {
			return fmt.Errorf("failed to retrieve a list of files from bucket: %s, path: %s, error: %s", bucket, path, err)
		}

		fmt.Printf("total: %d\n", len(files))
		for _, file := range files {
			filename := file.path
			if strings.HasSuffix(filename, "/") {
				filename = fmt.Sprintf("%s", color.BlueString(filename))
			}
			if !strings.HasSuffix(filename, suffix) {
				filename = fmt.Sprintf("%s", color.RedString(filename))
			}

			switch longListing {
			case true:
				lastModified := "dir"
				if !file.directory {
					lastModified = file.lastModified.Format("Oct 02 15:04")
				}
				fmt.Printf("%-20s %5d %-15s  %s\n", file.owner, file.size, lastModified, filename)
			default:
				fmt.Printf("%s\n", filename)
			}
		}
	}

	return nil
}
Beispiel #16
0
// LogHeader logs a header
func LogHeader(log termlog.Logger, h http.Header) {
	max := 0
	for k := range h {
		if len(k) > max {
			max = len(k)
		}
	}
	for k, vals := range h {
		for _, v := range vals {
			pad := fmt.Sprintf(fmt.Sprintf("%%%ds", max-len(k)+1), " ")
			log.Say(
				"\t%s%s%s",
				color.BlueString(k)+":",
				pad,
				v,
			)
		}
	}
}
Beispiel #17
0
func (rl *ResponseLogWriter) logCode(code int, status string) {
	var codestr string
	switch {
	case code >= 200 && code < 300:
		codestr = color.GreenString("%d %s", code, status)
	case code >= 300 && code < 400:
		codestr = color.BlueString("%d %s", code, status)
	case code >= 400 && code < 500:
		codestr = color.YellowString("%d %s", code, status)
	case code >= 500 && code < 600:
		codestr = color.RedString("%d %s", code, status)
	default:
		codestr = fmt.Sprintf("%d %s", code, status)
	}
	cl := rl.Header().Get("content-length")
	if cl != "" {
		cl = fmt.Sprintf("(%s bytes)", cl)
	}
	rl.log.Say("<- %s %s", codestr, cl)
}
Beispiel #18
0
func (o *Decorator) DecorateList(list []log.Log, placeholders bool) {
	for _, entity := range list {
		date := entity.Time.Format(time.Stamp)
		fmt.Printf("%s ", color.BlueString(date))

		fmt.Printf("%s ", color.GreenString(entity.Id))

		level := o.colorizeLevel(entity.Level)
		fmt.Printf("%s ", level)

		message := entity.Message
		if placeholders {
			message = o.replacePlaceholders(message, entity.Source)
		}

		fmt.Printf("%s ", message)

		fmt.Println()
	}
}
Beispiel #19
0
func colorize(guess string) string {
	var result string

	for _, s := range strings.Split(guess, "") {
		switch s {
		default:
			result += s
		case "r":
			result += color.RedString(s)
		case "g":
			result += color.GreenString(s)
		case "y":
			result += color.YellowString(s)
		case "b":
			result += color.BlueString(s)
		}
	}

	return result
}
Beispiel #20
0
func (obj *Decorator) colorizeLevel(level log.LogLevel) string {
	var str string

	switch level.Code {
	case log.DEBUG_CODE:
		str = color.BlackString(log.DEBUG_SHORT_STRING)
		break
	case log.INFO_CODE:
		str = color.BlueString(log.INFO_SHORT_STRING)
		break
	case log.NOTICE_CODE:
		str = color.CyanString(log.NOTICE_SHORT_STRING)
		break
	case log.WARNING_CODE:
		str = color.YellowString(log.WARNING_SHORT_STRING)
		break
	case log.ERROR_CODE:
		str = color.RedString(log.ERROR_SHORT_STRING)
		break
	case log.CRITICAL_CODE:
		s := color.New(color.FgWhite, color.BgRed).SprintFunc()
		str = fmt.Sprint(s(log.CRITICAL_SHORT_STRING))
		break
	case log.ALERT_CODE:
		s := color.New(color.FgWhite, color.BgRed).SprintFunc()
		str = fmt.Sprint(s(log.ALERT_SHORT_STRING))
		break
	case log.EMERGENCY_CODE:
		s := color.New(color.FgWhite, color.Bold, color.BgHiRed).SprintFunc()
		str = fmt.Sprint(s(log.EMERGENCY_SHORT_STRING))
		break
	default:
		str = string(level.Code)
	}

	return str
}
Beispiel #21
0
// Stumped appends (;¬_¬) in blue
func Stumped(text string) string {
	text += color.BlueString(" (;¬_¬)")
	return text
}
Beispiel #22
0
// Uncertain appends (,,◕ ⋏ ◕,,) in blue
func Uncertain(text string) string {
	text += color.BlueString(" (,,◕ ⋏ ◕,,)")
	return text
}
Beispiel #23
0
func (o *Decorator) DecorateDetails(entity log.Log) {
	fmt.Println()
	c := color.New(color.FgGreen, color.Bold)
	c.Println("Response")

	fmt.Printf(" • Id: %s", color.GreenString(entity.Id))
	fmt.Println()

	level := o.colorizeLevel(entity.Level)
	fmt.Printf(" • Level: %s", level)
	fmt.Println()

	date := entity.Time.Format(time.Stamp)
	fmt.Printf(" • Time: %s", color.WhiteString(date))
	fmt.Println()

	fmt.Printf(" • Host: %s", color.WhiteString(entity.Host))
	fmt.Println()

	if len(entity.SessionId) > 0 {
		fmt.Printf(" • Session id: %s", color.GreenString(entity.SessionId))
		fmt.Println()
	}

	message := o.replacePlaceholders(entity.Message, entity.Source)
	fmt.Printf(" • Message: %s", color.CyanString(message))
	fmt.Println()

	fmt.Printf(" • Script id: %s", color.YellowString(entity.ScriptId))
	fmt.Println()

	fmt.Printf(" • Object: %s", (entity.Object))
	fmt.Println()

	fmt.Println(" • Source:")
	for key, value := range entity.Source {
		if value == nil || key == "log-level" || key == "message" ||
			key == "script-id" || key == "@version" || key == "@timestamp" ||
			key == "object" || key == "type" || key == "host" {
			continue
		}

		switch reflect.TypeOf(value).String() {
		case "string":
			value = color.CyanString(fmt.Sprint(value))
			break
		case "int64":
			value = color.BlueString(fmt.Sprintf("%d", value))
		case "float64":
			if regexp.MustCompile("^[0-9]+(.[0]+)?").MatchString(fmt.Sprintf("%f", value)) {
				value = fmt.Sprintf("%d", int64(value.(float64)))
			} else {
				value = fmt.Sprintf("%f", value)
			}

			value = color.BlueString(value.(string))
			break
		default:
			value = fmt.Sprint(value)
		}

		fmt.Printf("   • %s: %s", color.MagentaString(key), value)
		fmt.Println()
	}

	if entity.Exception != nil && entity.Exception.Code != 0 {
		fmt.Println(" • Exception:")
		style1 := color.New(color.FgWhite, color.BgBlack)

		style1.Printf("   • Message: %s", entity.Exception.Message)
		style1.Println()
		style1.Printf("   • Code: %d", entity.Exception.Code)
		style1.Println()

		for _, trace := range entity.Exception.Trace {
			style1.Printf("   • File: %s:%d", trace.File, trace.Line)
			style1.Println()
		}
	}

	fmt.Println()
}
Beispiel #24
0
func main() {
	trend := trending.NewTrending()

	optTime := trending.TimeToday
	switch *fTime {
	case "today":
		optTime = trending.TimeToday
	case "week":
		optTime = trending.TimeWeek
	case "month":
		optTime = trending.TimeMonth
	default:
		fmt.Printf("time(%s) is unknown.\n", *fTime)
		os.Exit(1)
	}

	var optLang = *fLang
	var optItem = *fItem

	switch optItem {
	case "proj":
		fmt.Println(color.RedString("Projects"), optTime, optLang)

		projects, err := trend.GetProjects(optTime, optLang)
		if err != nil {
			log.Fatal(err)
		}
		for index, project := range projects {
			no := index + 1
			if len(project.Language) > 0 {
				fmt.Printf("%d: %s (written in %s with %d ★ ) %v\n", no, color.BlueString(project.Name), color.YellowString(project.Language), project.Stars, project.URL)
			} else {
				fmt.Printf("%d: %s (with %d ★ ) %v\n", no, color.BlueString(project.Name), project.Stars, project.URL)
			}
		}

	case "dev":
		fmt.Println(color.RedString("Developers"), optTime, optLang)

		developers, err := trend.GetDevelopers(optTime, optLang)
		if err != nil {
			log.Fatal(err)
		}
		for index, developer := range developers {
			no := index + 1
			fmt.Printf("%d: %s (%s)\n", no, color.BlueString(developer.DisplayName), developer.FullName)
		}

	case "lang":
		fmt.Println(color.RedString("Languages"))

		languages, err := trend.GetLanguages()
		if err != nil {
			log.Fatal(err)
		}
		for index, language := range languages {
			no := index + 1
			fmt.Printf("%d: %s (%s)\n", no, color.BlueString(language.Name), language.URLName)
		}
	}
}
Beispiel #25
0
// Do makes request and returns response.
// It also logs and records them and checks that response status code is equal to one of the provided.
// Request and response Body fields are filled, inner *http.(Request|Response).Body fields
// are replaced by stubs.
// In case of error it fails test.
func (c *Client) Do(t TestingT, req *Request, expectedStatuses ...int) *Response {
	status, headers, body, err := dumpRequest(req.Request)
	if err != nil {
		t.Fatalf("can't dump request: %s", err)
	}

	repr := bodyRepr(req.Header.Get("Content-Type"), body)

	colorF := func(b []byte) string { return color.BlueString("%s", string(b)) }
	if config.Default.Verbose {
		t.Logf("\n%s\n%s\n\n%s\n", colorF(status), colorF(headers), colorF(repr))
	} else {
		t.Logf("%s\n", colorF(status))
	}

	if req.Recorder != nil && req.RequestWC != nil {
		err = req.Recorder.RecordRequest(req.Request, status, headers, repr, req.RequestWC)
		if err != nil {
			t.Fatalf("can't record request: %s", err)
		}
		if f, ok := req.RequestWC.(*os.File); ok {
			t.Logf("request recorded to %s", f.Name())
		} else {
			t.Logf("request recorded")
		}
	}

	r, err := c.HTTPClient.Do(req.Request)
	if r != nil {
		origBody := r.Body
		defer func() {
			err = origBody.Close()
			if err != nil {
				t.Fatalf("can't close response body: %s", err)
			}
		}()
	}
	if err != nil {
		t.Fatalf("can't make request: %s", err)
	}

	// put dumped request body back
	req.Body = body
	req.Request.Body = errorReadCloser{}

	resp := &Response{Response: r}

	status, headers, body, err = dumpResponse(resp.Response)
	if err != nil {
		t.Fatalf("can't dump response: %s", err)
	}

	// put dumped response body back
	resp.Body = body
	resp.Response.Body = errorReadCloser{}

	repr = bodyRepr(resp.Header.Get("Content-Type"), body)

	switch {
	case resp.StatusCode >= 400:
		colorF = func(b []byte) string { return color.RedString("%s", string(b)) }
	case resp.StatusCode >= 300:
		colorF = func(b []byte) string { return color.YellowString("%s", string(b)) }
	default:
		colorF = func(b []byte) string { return color.GreenString("%s", string(b)) }
	}

	if config.Default.Verbose {
		t.Logf("\n%s\n%s\n\n%s\n", colorF(status), colorF(headers), colorF(repr))
	} else {
		t.Logf("%s\n", colorF(status))
	}

	if req.Recorder != nil && req.ResponseWC != nil {
		err = req.Recorder.RecordResponse(resp.Response, status, headers, repr, req.ResponseWC)
		if err != nil {
			t.Fatalf("can't record response: %s", err)
		}
		if f, ok := req.ResponseWC.(*os.File); ok {
			t.Logf("response recorded to %s", f.Name())
		} else {
			t.Logf("response recorded")
		}
	}

	if len(expectedStatuses) > 0 {
		var found bool
		for _, s := range expectedStatuses {
			if resp.StatusCode == s {
				found = true
				break
			}
		}

		if !found {
			t.Errorf("%s %s: expected status code to be in %v, got %s", req.Method, req.URL.String(), expectedStatuses, resp.Status)
		}
	}
	return resp
}
Beispiel #26
0
// Do makes request and returns response.
// It also logs and records them and checks response status code.
// In case of error if fails test.
func (c *Client) Do(t TestingTB, req *Request, expectedStatusCode int) *Response {
	status, headers, body, err := dumpRequest(req.Request)
	if err != nil {
		t.Fatalf("can't dump request: %s", err)
	}

	colorF := func(b []byte) string { return color.BlueString(string(b)) }
	if *vF {
		t.Logf("\n%s\n%s\n\n%s\n", colorF(status), colorF(headers), colorF(body))
	} else {
		t.Logf("\n%s\n", colorF(status))
	}

	if req.Recorder != nil && req.RequestWC != nil {
		err = req.Recorder.RecordRequest(req.Request, status, headers, body, req.RequestWC)
		if err != nil {
			t.Fatalf("failed to record request: %s", err)
		}
		if f, ok := req.RequestWC.(*os.File); ok {
			t.Logf("request recorded to %s", f.Name())
		} else {
			t.Logf("request recorded")
		}
	}

	r, err := c.HTTPClient.Do(req.Request)
	if r != nil {
		defer r.Body.Close()
	}
	if err != nil {
		t.Fatalf("can't make request: %s", err)
	}

	resp := &Response{Response: r}

	status, headers, body, err = dumpResponse(resp.Response)
	if err != nil {
		t.Fatalf("can't dump response: %s", err)
	}

	switch {
	case resp.StatusCode >= 400:
		colorF = func(b []byte) string { return color.RedString(string(b)) }
	case resp.StatusCode >= 300:
		colorF = func(b []byte) string { return color.YellowString(string(b)) }
	default:
		colorF = func(b []byte) string { return color.GreenString(string(b)) }
	}

	if *vF {
		t.Logf("\n%s\n%s\n\n%s\n", colorF(status), colorF(headers), colorF(body))
	} else {
		t.Logf("\n%s\n", colorF(status))
	}

	if req.Recorder != nil && req.ResponseWC != nil {
		err = req.Recorder.RecordResponse(resp.Response, status, headers, body, req.ResponseWC)
		if err != nil {
			t.Fatalf("failed to record response: %s", err)
		}
		if f, ok := req.ResponseWC.(*os.File); ok {
			t.Logf("response recorded to %s", f.Name())
		} else {
			t.Logf("response recorded")
		}
	}

	if resp.StatusCode != expectedStatusCode {
		t.Errorf("%s %s: expected %d, got %s", req.Method, req.URL.String(), expectedStatusCode, resp.Status)
	}
	return resp
}
package lion

import (
	"bytes"
	"time"
	"unicode"

	"github.com/fatih/color"
)

var (
	levelToColorString = map[Level]string{
		LevelNone:  color.BlueString(LevelNone.String()),
		LevelDebug: color.WhiteString(LevelDebug.String()),
		LevelInfo:  color.BlueString(LevelInfo.String()),
		LevelWarn:  color.YellowString(LevelWarn.String()),
		LevelError: color.RedString(LevelError.String()),
		LevelFatal: color.RedString(LevelFatal.String()),
		LevelPanic: color.RedString(LevelPanic.String()),
	}
	// TODO(pedge): clean up
	fourLetterLevels = map[Level]bool{
		LevelNone: true,
		LevelInfo: true,
		LevelWarn: true,
	}
)

type textMarshaller struct {
	disableTime     bool
	disableLevel    bool
Beispiel #28
0
func formatJoinedAlert(alertSet *alertSet, colorize bool) string {
	const layout = "2006-01-02 15:04:05"

	host := alertSet.Host
	monitor := alertSet.Monitor
	alert := alertSet.Alert

	hostMsg := ""
	if host != nil {
		statusMsg := host.Status
		if host.IsRetired == true {
			statusMsg = "retired"
		}
		if colorize {
			switch statusMsg {
			case "working":
				statusMsg = color.BlueString("working")
			case "standby":
				statusMsg = color.GreenString("standby")
			case "poweroff":
				statusMsg = "poweroff"
			case "maintenance":
				statusMsg = color.YellowString("maintenance")
			}
		}
		hostMsg = fmt.Sprintf(" %s %s", host.Name, statusMsg)
		roleMsgs := []string{}
		for service, roles := range host.Roles {
			roleMsgs = append(roleMsgs, fmt.Sprintf("%s:%s", service, strings.Join(roles, ",")))
		}
		hostMsg += " [" + strings.Join(roleMsgs, ", ") + "]"
	}

	monitorMsg := ""
	if monitor != nil {
		switch monitor.Type {
		case "connectivity":
			monitorMsg = fmt.Sprintf("%s", monitor.Type)
		case "host":
			switch alert.Status {
			case "CRITICAL":
				monitorMsg = fmt.Sprintf("%s %.2f %s %.2f", monitor.Metric, alert.Value, monitor.Operator, monitor.Critical)
			case "WARNING":
				monitorMsg = fmt.Sprintf("%s %.2f %s %.2f", monitor.Metric, alert.Value, monitor.Operator, monitor.Warning)
			default:
				monitorMsg = fmt.Sprintf("%s %.2f %s %.2f", monitor.Metric, alert.Value, monitor.Operator, monitor.Critical)
			}
		case "service":
			switch alert.Status {
			case "CRITICAL":
				monitorMsg = fmt.Sprintf("%s %s %.2f %s %.2f", monitor.Service, monitor.Metric, alert.Value, monitor.Operator, monitor.Critical)
			case "WARNING":
				monitorMsg = fmt.Sprintf("%s %s %.2f %s %.2f", monitor.Service, monitor.Metric, alert.Value, monitor.Operator, monitor.Warning)
			default:
				monitorMsg = fmt.Sprintf("%s %s %.2f %s %.2f", monitor.Service, monitor.Metric, alert.Value, monitor.Operator, monitor.Critical)
			}
		case "external":
			statusRegexp, _ := regexp.Compile("^[2345][0-9][0-9]$")
			switch alert.Status {
			case "CRITICAL":
				if statusRegexp.MatchString(alert.Message) {
					monitorMsg = fmt.Sprintf("%s %s %.2f > %.2f msec, status:%s", monitor.Name, monitor.URL, alert.Value, monitor.ResponseTimeCritical, alert.Message)
				} else {
					monitorMsg = fmt.Sprintf("%s %s %.2f msec, %s", monitor.Name, monitor.URL, alert.Value, alert.Message)
				}
			case "WARNING":
				if statusRegexp.MatchString(alert.Message) {
					monitorMsg = fmt.Sprintf("%s %.2f > %.2f msec, status:%s", monitor.Name, alert.Value, monitor.ResponseTimeWarning, alert.Message)
				} else {
					monitorMsg = fmt.Sprintf("%s %.2f msec, %s", monitor.Name, alert.Value, alert.Message)
				}
			default:
				monitorMsg = fmt.Sprintf("%s %.2f > %.2f msec, status:%s", monitor.Name, alert.Value, monitor.ResponseTimeCritical, alert.Message)
			}
		case "check":
			monitorMsg = fmt.Sprintf("%s", monitor.Type)
		default:
			monitorMsg = fmt.Sprintf("%s", monitor.Type)
		}
	}
	statusMsg := alert.Status
	if colorize {
		switch alert.Status {
		case "CRITICAL":
			statusMsg = color.RedString("CRITICAL")
		case "WARNING":
			statusMsg = color.YellowString("WARNING ")
		}
	}
	return fmt.Sprintf("%s %s %s %s%s", alert.ID, time.Unix(alert.OpenedAt, 0).Format(layout), statusMsg, monitorMsg, hostMsg)
}