Exemple #1
1
func parseGauges(info string) map[string]int64 {
	gauges_with_values := map[string]int64{
		"blocked_clients":           0,
		"connected_clients":         0,
		"instantaneous_ops_per_sec": 0,
		"latest_fork_usec":          0,
		"mem_fragmentation_ratio":   0,
		"migrate_cached_sockets":    0,
		"pubsub_channels":           0,
		"pubsub_patterns":           0,
		"uptime_in_seconds":         0,
		"used_memory":               0,
		"used_memory_lua":           0,
		"used_memory_peak":          0,
		"used_memory_rss":           0,
	}
	color.White("-------------------")
	color.White("GAUGES:")
	for gauge, _ := range gauges_with_values {
		r, _ := regexp.Compile(fmt.Sprint(gauge, ":([0-9]*)"))
		matches := r.FindStringSubmatch(info)
		if matches == nil {
			color.Yellow(fmt.Sprint("WARN: ", gauge, "is not displayed in redis info"))
		} else {
			value := matches[len(matches)-1]
			color.Cyan(fmt.Sprint(gauge, ": ", value))
			v, _ := strconv.ParseInt(value, 10, 64)
			gauges_with_values[gauge] = v
		}
	}
	return gauges_with_values
}
Exemple #2
0
func getClientCredentials(c *cli.Context) []string {
	credentials := []string{c.GlobalString("client-id"), c.GlobalString("client-secret")}

	if credentials[0] == "" || credentials[1] == "" {
		color.Yellow("No client credentials given. Fallback to builtin default...")
		color.Yellow("Keep in mind that your document might be visible to other users.")
		color.Yellow("Your unique user-id is the only secret to protect your data.\n\n")

		superSecretSecret := []byte("V;4nJvuANmoywKNYk.yewNhqwmAQctc3BvByxeozQVpiK")

		// Decode HEX default credentials
		credentialsBytes, err := hex.DecodeString(defaultClientCredentials)
		if err != nil {
			color.Red("Error: client-id and client-secret missing and fallback decoding (step 1) failed: %s\n\n", err)
			cli.ShowCommandHelp(c, c.Command.FullName())
			os.Exit(1)
		}

		decodedCredentials := strings.Split(string(xorBytes(credentialsBytes, superSecretSecret)), ":")

		if len(decodedCredentials) < 2 {
			color.Red("Error: client-id and client-secret missing and fallback decoding (step 2) failed: %s\n\n", err)
			cli.ShowCommandHelp(c, c.Command.FullName())
			os.Exit(1)
		}
		credentials = decodedCredentials
	}

	return credentials
}
Exemple #3
0
func copyfile() {
	color.Yellow("开始执行文件发送:")
	info, err := os.Lstat(all_ssh.ArgsInfo.File)
	if err != nil || info.IsDir() {
		color.Blue("检查要发送的文件.")
		return
	}
	for _, v := range all_ssh.ServerList {
		go func() {
			client := all_ssh.Connection(v)
			if client != nil {
				all_ssh.CopyFile(client, all_ssh.ArgsInfo.File, all_ssh.ArgsInfo.Dir)
			}
		}()
	}
	var num int
	var Over chan os.Signal = make(chan os.Signal, 1)
	go signal.Notify(Over, os.Interrupt, os.Kill)
	go result(&num, Over)
	<-Over
	color.Yellow("一共有%d条错误.\n", len(all_ssh.ErrorList))
	for _, v := range all_ssh.ErrorList {
		color.Red(v)
	}
	color.Red("收到结果:%d条\n", num)
}
Exemple #4
0
func DisplayInfo() {

	color.Yellow("\n\n******* GO WORKER INFORMATION *******\n\n")

	infoObj := GetInfoObj()

	color.Green("%+v", infoObj)

	color.Yellow("\n\n*************************************\n\n")

}
func handleInteractiveMode() {
	reader := bufio.NewReader(os.Stdin)
	for {
		red := color.New(color.FgCyan)
		red.Printf("%s %s %s => ", time.Now().Format("15:04:05"), *serverFlag, *executorFlag)

		line, err := reader.ReadString('\n')
		if err != nil {
			log.Fatal(color.RedString("ERROR reading string: %s", err.Error()))
		}
		line = strings.Trim(line, "\r\n")

		if strings.EqualFold(line, "exit") {
			color.Green("Exit command received. Good bye.")
			os.Exit(0)
		}

		exeAndArgs, err := parsecommand.Parse(line)
		if err != nil {
			color.Red("Cannot parse line '%s', error: %s", line, err.Error())
			continue
		}

		var exe string
		var args []string = []string{}

		exe = exeAndArgs[0]
		if len(exeAndArgs) > 1 {
			args = exeAndArgs[1:]
		}

		onFeedback := func(fb string) {
			fmt.Println(fb)
		}

		color.Green("Exe '%s' and args '%#v'", exe, args)
		color.Yellow("-------------------------------------")
		println()
		err = execute(false, onFeedback, *serverFlag, *executorFlag, *clientPemFlag, exe, args...)
		if err != nil {
			color.Red("Execute failed with error: %s", err.Error())
			continue
		}
		println()
		color.Yellow("-------------------------------------")
		println()
		println()
	}
}
Exemple #6
0
func main() {
	if all_ssh.ArgsInfo.IP != "" {
		color.Yellow("开始登录:%s\n", all_ssh.ArgsInfo.IP)
		var v all_ssh.ConnetctionInfo
		for _, v = range all_ssh.ServerList {
			if v.IP == all_ssh.ArgsInfo.IP {
				break
			}
		}
		v.IP = all_ssh.ArgsInfo.IP
		client := all_ssh.Connection(v)
		if client == nil {
			return
		}
		err := all_ssh.TtyClient(client)
		if err != nil {
			println(err.Error())
		}
		if len(all_ssh.ErrorList) >= 1 {
			color.Red(all_ssh.ErrorList[0])
		}
		return
	}
	if all_ssh.ArgsInfo.File != "" {
		copyfile()
		return
	}
	if all_ssh.ArgsInfo.Cmd != "" {
		runcmd()
		return
	}
	color.Blue("使用%s -h查看帮助.\n", os.Args[0])
}
Exemple #7
0
func (n *Notifier) Run(message string) {
	switch n.Name {
	case "slack":
		if slack_api == nil {
			color.Red("[!] Slack used as a notifier, but not configured with ENV vars.")
			return
		}
		err = slack_api.ChatPostMessage(slack_channel.Id, message, &slack.ChatPostMessageOpt{IconEmoji: ":fire:"})
		if err != nil {
			color.Red(fmt.Sprintf("[!] Error posting to Slack: %s", err))
		}
	case "hipchat":
		if hipchat_api == nil {
			color.Red("[!] HipChat used as a notifier, but not configured with ENV vars.")
			return
		}
		_, err = hipchat_api.Room.Notification(os.Getenv("HIPCHAT_ROOM_ID"), &hipchat.NotificationRequest{Message: "Testing", Color: "red"})
		if err != nil {
			color.Red(fmt.Sprintf("[!] Error posting to HipChat: %s", err))
		}
	case n.Name: // default
		color.Yellow(fmt.Sprintf("[>] Unknown notifier: %s", n.Name))
	}

}
Exemple #8
0
func TestPlugin(t *testing.T) {
	color.NoColor = false

	casses := map[string]testrunnerTestCase{
		"simple": {
			first:  map[string]interface{}{"name": "value"},
			second: map[string]interface{}{"name": "value"},
			expect: make(map[string]interface{}),
		},
		"diff": {
			first:  map[string]interface{}{"name1": "value"},
			second: map[string]interface{}{"name": "value"},
			expect: map[string]interface{}{"name": "<nil> != value", "name1": "value != <nil>"},
		},
	}

	for name, test := range casses {
		if d := diff(test.first, test.second); !reflect.DeepEqual(d, test.expect) {
			color.Red("\n\nTest `%s` failed!", name)
			color.Yellow("\n\nexpected:  %v\n\ngiven: %v\n\n", test.expect, d)
			t.Fail()
		} else {
			color.Green("\n%s: OK\n", name)
		}
	}

}
Exemple #9
0
// Warn is a convenience method appending a warning message to the logger
func Warn(obj interface{}) {
	// Get the line number and calling func sig
	_, fn, line, _ := runtime.Caller(1)
	msg := fmt.Sprintf("%+v\n%s:%d\n\n", obj, fn, line)
	formattedMessage := formattedLogMessage("WARN", msg)
	color.Yellow(formattedMessage)
}
Exemple #10
0
func writeWarning(format string, a ...interface{}) {
	if silent {
		return
	}

	color.Yellow(format, a...)
}
Exemple #11
0
func parseCounters(info string) map[string]int64 {
	counters := map[string]int64{
		"evicted_keys":               0,
		"expired_keys":               0,
		"keyspace_hits":              0,
		"keyspace_misses":            0,
		"rejected_connections":       0,
		"sync_full":                  0,
		"sync_partial_err":           0,
		"sync_partial_ok":            0,
		"total_commands_processed":   0,
		"total_connections_received": 0,
	}
	color.White("-------------------")
	color.White("COUNTERS:")
	for counter, _ := range counters {
		r, _ := regexp.Compile(fmt.Sprint(counter, ":([0-9]*)"))
		matches := r.FindStringSubmatch(info)
		if matches == nil {
			color.Yellow(fmt.Sprint("ERROR: ", counter, "is not displayed in redis info"))
		} else {
			value := matches[len(matches)-1]
			color.Cyan(fmt.Sprint(counter, ": ", value))
			v, _ := strconv.ParseInt(value, 10, 64)
			counters[counter] = v
		}
	}
	return counters
}
Exemple #12
0
// Warnf is a convenience method appending a warning message to the logger
func Warnf(msg string, a ...interface{}) {
	_, fn, line, _ := runtime.Caller(1)
	msg = fmt.Sprintf(msg, a...)
	msg = fmt.Sprintf("%+v%s:%d\n\n", msg, fn, line)
	formattedMessage := formattedLogMessage("WARN", msg)
	color.Yellow(formattedMessage)
}
Exemple #13
0
func isWatching(channel string, name string) (bool, error) {
	chanName := strings.Replace(channel, "#", "", 1)
	if k+60 <= time.Now().Unix() {
		var err error
		url := "http://tmi.twitch.tv/group/user/" + chanName + "/chatters"
		response, err := http.Get(url)
		if err != nil {
			log.Printf("Cannot get URL response: %s\n", err.Error())
			return false, err
		}
		defer response.Body.Close()
		dec := json.NewDecoder(response.Body)
		if err := dec.Decode(&v); err != nil {
			log.Printf("Parse error: %s\n", err.Error())
			return false, err
		}
		k = time.Now().Unix()
		color.Yellow("Updating chatters")
	}
	//fmt.Printf("%q\n", v)
	chats := v["chatters"].(map[string]interface{})
	views := chats["viewers"].([]interface{})
	mods := chats["moderators"].([]interface{})
	for _, b := range views {
		if b == strings.ToLower(name) {
			return true, nil
		}
	}
	for _, b := range mods {
		if b == strings.ToLower(name) {
			return true, nil
		}
	}
	return false, nil
}
Exemple #14
0
func writeLevelDB(channel string, userName string, userMessage string, levelId string) {
	chanId := channels[channel]
	//Check for duplicate LevelId for this channel
	var duplicateLevel string
	checkDuplicate := db.QueryRow("SELECT Level FROM Levels WHERE Level=? AND StreamID=?;", levelId, chanId).Scan(&duplicateLevel)
	switch {
	case checkDuplicate == sql.ErrNoRows:
		color.Green("No such level, Adding...\n")
		insertLevel, dberr := db.Prepare("INSERT Levels SET StreamID=?,Nick=?,Level=?,Message=?,Added=?;")
		if dberr != nil {
			log.Fatalf("Cannot prepare insertLevel on %s: %s\n", channel, dberr.Error())
		}
		defer insertLevel.Close()
		timeNow := time.Now().Format(time.RFC3339)
		execLevel, dberr := insertLevel.Exec(chanId, userName, levelId, userMessage, timeNow)
		if dberr != nil {
			log.Fatalf("Cannot exec insertLevel on %s: %s\n", channel, dberr.Error())
		}
		rowsAff, dberr := execLevel.RowsAffected()
		if dberr != nil {
			log.Fatalf("No rows changed on %s: %s\n", channel, dberr.Error())
		}
		lastId, dberr := execLevel.LastInsertId()
		if dberr != nil {
			log.Fatalf("No last id on %s: %s\n", channel, dberr.Error())
		}
		color.Green("Added level %s by %s for %d %s. Row|#: %d|%d\n", levelId, userName, chanId, channel, rowsAff, lastId)
	case checkDuplicate != nil:
		log.Fatalf("Checking duplicate level failed, error: %s\n", checkDuplicate.Error())
	default:
		color.Yellow("Duplicate level, not adding...\n")
	}
}
Exemple #15
0
func main() {

	color.Yellow("Job Worker Client")

	jobworker.Run()

}
Exemple #16
0
func main() {

	argsWithoutProg := os.Args[1:]

	if len(argsWithoutProg) == 0 {
		fmt.Println("Usage: go run sum.go filter")
		return
	}
	filter := strings.Join(argsWithoutProg, " ")

	file, err := os.Open("diff.txt")
	check(err)
	defer file.Close()

	var added, removed uint64

	re, err := regexp.Compile(`(.+)\:`)

	scanner := bufio.NewScanner(file)
	for scanner.Scan() {
		line := scanner.Text()
		if len(line) > 3 && strings.Contains(line[3:], filter) {
			if line[0:3] == "Inc" || line[0:3] == "New" {
				res := re.FindStringSubmatch(line[4:])
				if len(res) > 0 {
					added += SizeInBytes(res[1])
				}
			} else if line[0:3] == "Dec" || line[0:3] == "Rem" {
				res := re.FindStringSubmatch(line[4:])
				if len(res) > 0 {
					removed += SizeInBytes(res[1])
				}
			}

		}
	}

	color.Green("Added: " + bytefmt.ByteSize(added))
	color.Yellow("Removed: " + bytefmt.ByteSize(removed))

	diff := int64(added) - int64(removed)
	if diff < 0 {
		color.Yellow("= Net total: -" + bytefmt.ByteSize(uint64(-diff)))
	} else {
		color.Green("= Net total: " + bytefmt.ByteSize(uint64(diff)))
	}
}
Exemple #17
0
func writeLevelDB(channel string, userName string, userMessage string, levelID string) {
	chanID := channels[channel]
	//Check for duplicate LevelId for this channel
	var duplicateLevel string
	var info map[string]string
	var exist bool
	info = make(map[string]string)
	err := try.Do(func(attempt int) (bool, error) {
		var err error
		info, exist, err = fetchInfo(levelID)
		return attempt < 5, err // try 5 times
	})
	if err != nil {
		log.Println("Error: " + err.Error())
	} else if exist {
		checkDuplicate := db.QueryRow("SELECT Level FROM Levels WHERE Level=? AND StreamID=?;", levelID, chanID).Scan(&duplicateLevel)
		switch {
		case checkDuplicate == sql.ErrNoRows:
			color.Green("No such level, Adding...\n")
			insertLevel, dberr := db.Prepare("INSERT Levels SET StreamID=?,Nick=?,Level=?,Message=?,Added=?,Removed=?,Title=?,Difficulty=?,Style=?,Creator=?,Flag=?,Created=?,Tags=?,Image=?,ImageFull=?;")
			if dberr != nil {
				log.Fatalf("Cannot prepare insertLevel on %s: %s\n", channel, dberr.Error())
			}
			defer insertLevel.Close()
			timeNow := time.Now().Format(time.RFC3339)
			execLevel, dberr := insertLevel.Exec(chanID, userName, levelID, userMessage, timeNow, 0, info["title"], info["diff"], info["style"], info["name"], info["flag"], info["created"], info["tags"], info["img"], info["imgfull"])
			if dberr != nil {
				log.Fatalf("Cannot exec insertLevel on %s: %s\n", channel, dberr.Error())
			}
			rowsAff, dberr := execLevel.RowsAffected()
			if dberr != nil {
				log.Fatalf("No rows changed on %s: %s\n", channel, dberr.Error())
			}
			lastID, dberr := execLevel.LastInsertId()
			if dberr != nil {
				log.Fatalf("No lastID on %s: %s\n", channel, dberr.Error())
			}
			color.Green("Added level %s by %s for %d %s. Row|#: %d|%d\n", levelID, userName, chanID, channel, rowsAff, lastID)
		case checkDuplicate != nil:
			log.Fatalf("Checking duplicate level failed, error: %s\n", checkDuplicate.Error())
		default:
			color.Yellow("Duplicate level, not adding...\n")
		}
	} else {
		color.Yellow("Level doesn't exist...\n")
	}
}
func monitorHosts(interval int, execute string) {
	color.Yellow("Monitoring %d hosts every %d seconds. Will invoke '%s' if any change.", flag.NArg(), interval, execute)
	changes := make(chan string)
	for _, hostname := range flag.Args() {
		go monitor(hostname, interval, changes)
		go react(hostname, execute, changes)
	}
}
Exemple #19
0
func check4ForgeUpdate(moduleName string, currentVersion string, latestVersion string) {
	Verbosef("found currently deployed Forge module " + moduleName + " in version: " + currentVersion)
	Verbosef("found latest Forge module of " + moduleName + " in version: " + latestVersion)
	if currentVersion != latestVersion {
		color.Yellow("ATTENTION: Forge module: " + moduleName + " latest: " + latestVersion + " currently deployed: " + currentVersion)
		needSyncForgeCount++
	}
}
Exemple #20
0
func setupPagerduty() {
	if len(os.Getenv("PAGERDUTY_API_TOKEN")) == 0 ||
		len(os.Getenv("PAGERDUTY_SERVICE_KEY")) == 0 {
		color.Yellow("[>] Skipping Pagerduty setup, missing PAGERDUTY_API_TOKEN and PAGERDUTY_SERVICE_KEY")
		return
	}

	pagerduty_api_token = os.Getenv("PAGERDUTY_API_TOKEN")
	pagerduty_service_key = os.Getenv("PAGERDUTY_SERVICE_KEY")
}
Exemple #21
0
//Connect connects to twitch irc
func Connect() {
	var err error
	color.Yellow("Connecting...\n")
	conn, err = net.Dial("tcp", server+":"+port)
	if err != nil {
		color.Red("Unable to connect to Twitch IRC server! Reconnecting in 10 seconds...\n")
		time.Sleep(10 * time.Second)
		Connect()
	}
	color.Green("Connected to IRC server %s\n", server)
}
Exemple #22
0
func errHandler(err kinesumer.IError) {
	switch err.Severity() {
	case kinesumer.ECrit:
		fallthrough
	case kinesumer.EError:
		color.Red("%s:%s\n", err.Severity(), err.Error())
		panic(err)
	default:
		color.Yellow("%s:%s\n", err.Severity(), err.Error())
	}
}
Exemple #23
0
func InitDB() {
	db, dberr = sql.Open("mysql", database)
	if dberr != nil {
		log.Fatalf("Error on initializing database connection: %s", dberr.Error())
	}
	//[MySQL] packets.go:118: write unix /var/lib/mysql/mysql.sock: broken pipe
	db.SetMaxIdleConns(0)

	//Create tables
	_, dberr = db.Exec("CREATE TABLE IF NOT EXISTS Streamers ( StreamID MEDIUMINT NOT NULL, Name VARCHAR(25) NOT NULL UNIQUE, PRIMARY KEY (StreamID) ) ENGINE=MyISAM DEFAULT CHARSET=utf8;")
	if dberr != nil {
		log.Fatalf("Error on initializing table Streamers: %s", dberr.Error())
	}
	_, dberr = db.Exec("CREATE TABLE IF NOT EXISTS Levels ( LevelID MEDIUMINT NOT NULL AUTO_INCREMENT, StreamID MEDIUMINT NOT NULL, Nick VARCHAR(25) NOT NULL, Level VARCHAR(22) NOT NULL, Message VARCHAR(255) NOT NULL, Comment VARCHAR(255) NOT NULL, Played BOOLEAN NOT NULL, Skipped BOOLEAN NOT NULL, Added DATETIME NOT NULL, Passed DATETIME NOT NULL,PRIMARY KEY (LevelID) ) ENGINE=MyISAM DEFAULT CHARSET=utf8;")
	if dberr != nil {
		log.Fatalf("Error on initializing table Levels: %s", dberr.Error())
	}
	_, dberr = db.Exec("CREATE TABLE IF NOT EXISTS Subscribers ( SubID MEDIUMINT NOT NULL AUTO_INCREMENT, StreamID MEDIUMINT NOT NULL, Nick VARCHAR(25) NOT NULL, MonthsInRow TINYINT NOT NULL, MonthsTotal TINYINT NOT NULL, Lastsub DATETIME NOT NULL,PRIMARY KEY (SubID) ) ENGINE=MyISAM DEFAULT CHARSET=utf8;")
	if dberr != nil {
		log.Fatalf("Error on initializing table Subscribers: %s", dberr.Error())
	}

	blue := color.New(color.FgBlue).SprintFunc()
	var Streamer int
	fmt.Printf("dbStreamers: ")
	for k, i := range channels {
		chanName := strings.Replace(k, "#", "", 1)
		checkStream := db.QueryRow("SELECT StreamID FROM Streamers WHERE Name=?;", chanName).Scan(&Streamer)
		switch {
		case checkStream == sql.ErrNoRows:
			color.Yellow("No streamer ID, Adding...\n")
			insertStream, dberr := db.Prepare("INSERT Streamers SET Name=?,StreamID=?;")
			if dberr != nil {
				log.Fatalf("Cannot prepare streamer %s, error: %s\n", chanName, dberr.Error())
			}
			defer insertStream.Close()
			execStream, dberr := insertStream.Exec(chanName, i)
			if dberr != nil {
				log.Fatalf("Cannot add streamer %s, error: %s\n", chanName, dberr.Error())
			}
			lastId, dberr := execStream.LastInsertId()
			if dberr != nil {
				log.Fatalf("Last id error with streamer %s, error: %s\n", chanName, dberr.Error())
			}
			color.Green("New streamId for %s is #%d, ID = %d\n", k, i, lastId)
		case checkStream != nil:
			log.Fatalf("Database query to Streamers table error: %s\n", checkStream.Error())
		default:
			fmt.Printf("#%d: %s, ", Streamer, blue(k))
		}
	}
	fmt.Printf("\n")
}
Exemple #24
0
func quit() {
	color.Green("Cleany closy worky worky...")
	// Close database.
	err := DB.Close()
	if err != nil {
		color.Red("Could not close DB ", err)
	}
	color.Yellow("Quiting programm")

	// Exit programm
	os.Exit(0)
}
func TesTProcessingRequest(t *testing.T) {

	j := initReq()
	resChan := make(chan jobworker.JobResult)
	j.ResultsChannel = resChan

	go j.ProcessRequest()

	jr := <-resChan

	color.Yellow("%v", jr)
}
Exemple #26
0
func (n *Notifier) Run(message string, isAlert bool) {
	switch n.Name {
	case "slack":
		if slack_api == nil {
			color.Red("[!] Slack used as a notifier, but not configured with ENV vars.")
			return
		}
		if isAlert {
			err = slack_api.ChatPostMessage(slack_channel.Id, message, &slack.ChatPostMessageOpt{IconEmoji: ":fire:"})
		} else {
			err = slack_api.ChatPostMessage(slack_channel.Id, message, &slack.ChatPostMessageOpt{IconEmoji: ":success:"})
		}
		if err != nil {
			color.Red(fmt.Sprintf("[!] Error posting to Slack: %s", err))
		}
	case "pagerduty":
		if pagerduty_api_token == "" || pagerduty_service_key == "" {
			color.Red("[!] PagerDuty used as a notifier, but not configured with ENV vars.")
		}

		if isAlert {
			event := pagerduty.Event{
				Type:        "trigger",
				ServiceKey:  pagerduty_service_key,
				Description: message,
			}
			resp, err := pagerduty.CreateEvent(event)
			if err != nil {
				fmt.Println(resp)
				color.Red(fmt.Sprintf("[!] Error posting to PagerDuty: %s", err))
			}
		} else {
			color.Green("[>] PagerDuty incident should be resolved now.")
		}

	case "hipchat":
		if hipchat_api == nil {
			color.Red("[!] HipChat used as a notifier, but not configured with ENV vars.")
			return
		}
		if isAlert {
			_, err = hipchat_api.Room.Notification(os.Getenv("HIPCHAT_ROOM_ID"), &hipchat.NotificationRequest{Message: message, Color: "red"})
		} else {
			_, err = hipchat_api.Room.Notification(os.Getenv("HIPCHAT_ROOM_ID"), &hipchat.NotificationRequest{Message: message, Color: "green"})
		}
		if err != nil {
			color.Red(fmt.Sprintf("[!] Error posting to HipChat: %s", err))
		}
	case n.Name: // default
		color.Yellow(fmt.Sprintf("[>] Unknown notifier: %s", n.Name))
	}

}
Exemple #27
0
func (m *Manager) printListOfPossibleStatuses() {
	req, err := http.NewRequest("GET", m.URL+"/statuses", nil)
	req.Header.Add("X-AUTH-TOKEN", "token")

	client := &http.Client{}
	resp, err := client.Do(req)

	if err != nil {
		color.Red("Couldn't connect to the server")
		return
	}
	defer resp.Body.Close()
	body, err := ioutil.ReadAll(resp.Body)
	statuses := []string{}
	json.Unmarshal(body, &statuses)
	color.Yellow("You should provide a valid status to move your issue")
	color.Yellow("valid statuses for this project are:")
	for _, val := range statuses {
		color.Yellow(" - " + val)
	}
}
Exemple #28
0
func promptUserToChooseBranches(branches []*gitBranch) (local, remote []string, err error) {
	// Go through the branches and ask the user for confirmation.
	var (
		localToDelete  = make([]string, 0, len(branches))
		remoteToDelete = make([]string, 0, len(branches))
	)

	defer fmt.Println()

	for _, branch := range branches {
		tip := branch.tip
		isLocal := tip.BranchName != ""
		isRemote := tip.RemoteBranchName != ""

		var msg string
		switch {
		case isLocal && isRemote:
			msg = fmt.Sprintf(
				"Processing local branch '%v' and its remote counterpart", tip.BranchName)
		case isLocal:
			msg = fmt.Sprintf(
				"Processing local branch '%v'", tip.BranchName)
		case isRemote:
			msg = fmt.Sprintf(
				"Processing remote branch '%v'", tip.FullRemoteBranchName())
		default:
			panic("bullshit")
		}
		fmt.Println()
		fmt.Println(msg)

		if branch.reason != "merged" {
			color.Yellow("Careful now, the branch has not been merged into trunk yet.")
		}

		confirmed, err := prompt.Confirm("Are you sure you want to delete the branch?", false)
		if err != nil {
			return nil, nil, err
		}
		if !confirmed {
			continue
		}

		if isLocal {
			localToDelete = append(localToDelete, tip.BranchName)
		}
		if isRemote {
			remoteToDelete = append(remoteToDelete, tip.RemoteBranchName)
		}
	}
	return localToDelete, remoteToDelete, nil
}
Exemple #29
0
func show(dict Dict) {
	for _, ps := range dict.Ps {
		color.Green(ps)
	}
	for index, pos := range dict.Pos {
		color.Red(strings.TrimSpace(pos))
		color.Yellow(strings.TrimSpace(dict.Acceptation[index]))
	}
	for _, sent := range dict.SentList {
		color.Blue("ex. %s", strings.TrimSpace(sent.Orig))
		color.Cyan("    %s", strings.TrimSpace(sent.Trans))
	}
}
Exemple #30
0
func setupSlack() {
	if len(os.Getenv("SLACK_API_TOKEN")) == 0 ||
		len(os.Getenv("SLACK_ROOM")) == 0 {
		color.Yellow("[>] Skipping Slack setup, missing SLACK_API_TOKEN and SLACK_ROOM")
		return
	}
	slack_api = slack.New(os.Getenv("SLACK_API_TOKEN"))

	slack_channel, err = slack_api.FindChannelByName(os.Getenv("SLACK_ROOM"))
	if err != nil {
		panic(err)
	}
}